aboutsummaryrefslogtreecommitdiff
path: root/internal
diff options
context:
space:
mode:
Diffstat (limited to 'internal')
-rw-r--r--internal/api/api_test.go46
-rw-r--r--internal/api/new.go5
-rw-r--r--internal/api/reload.go25
-rw-r--r--internal/service/gallery.go6
-rw-r--r--internal/service/gallery_service.go3
-rw-r--r--internal/service/photo.go3
-rw-r--r--internal/service/reload.go (renamed from internal/service/load.go)6
-rw-r--r--internal/service/reload_test.go125
-rw-r--r--internal/service/service.go4
-rw-r--r--internal/watcher/config.go11
-rw-r--r--internal/watcher/debounce.go62
-rw-r--r--internal/watcher/debounce_test.go79
-rw-r--r--internal/watcher/doc.go7
-rw-r--r--internal/watcher/fsnotify.go72
-rw-r--r--internal/watcher/watch.go26
-rw-r--r--internal/watcher/watcher.go20
-rw-r--r--internal/watcher/watcher_test.go31
17 files changed, 522 insertions, 9 deletions
diff --git a/internal/api/api_test.go b/internal/api/api_test.go
index c1980fd..dce42e4 100644
--- a/internal/api/api_test.go
+++ b/internal/api/api_test.go
@@ -17,6 +17,9 @@ import (
type fakeGalleryService struct {
photos []gallery.Photo
err error
+
+ reloadCalls int
+ reloadErr error
}
type fakeThumbnailGenerator struct {
@@ -37,8 +40,9 @@ func (f fakeThumbnailGenerator) Generate(
}, nil
}
-func (f fakeGalleryService) Load(ctx context.Context) error {
- return nil
+func (f *fakeGalleryService) Reload(ctx context.Context) error {
+ f.reloadCalls++
+ return f.reloadErr
}
func (f fakeGalleryService) Gallery(ctx context.Context) ([]gallery.Photo, error) {
@@ -62,7 +66,7 @@ func TestPhotos(t *testing.T) {
srv := New(Config{
Address: ":0",
- Gallery: fakeGalleryService{
+ Gallery: &fakeGalleryService{
photos: []gallery.Photo{
{
ID: "abc123",
@@ -146,7 +150,7 @@ func TestThumbnail(t *testing.T) {
srv := New(Config{
Address: ":0",
- Gallery: fakeGalleryService{
+ Gallery: &fakeGalleryService{
photos: []gallery.Photo{
{
ID: "abc123",
@@ -184,3 +188,37 @@ func TestThumbnail(t *testing.T) {
)
}
}
+
+func TestReload(t *testing.T) {
+ gallery := &fakeGalleryService{}
+
+ srv := New(Config{
+ Address: ":0",
+ Gallery: gallery,
+ })
+
+ req := httptest.NewRequest(
+ http.MethodPost,
+ "/api/reload",
+ nil,
+ )
+
+ rec := httptest.NewRecorder()
+
+ srv.mux.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusNoContent {
+ t.Fatalf(
+ "expected %d, got %d",
+ http.StatusNoContent,
+ rec.Code,
+ )
+ }
+
+ if gallery.reloadCalls != 1 {
+ t.Fatalf(
+ "expected Reload() to be called once, got %d",
+ gallery.reloadCalls,
+ )
+ }
+}
diff --git a/internal/api/new.go b/internal/api/new.go
index 7febfe7..b95a909 100644
--- a/internal/api/new.go
+++ b/internal/api/new.go
@@ -40,5 +40,10 @@ func New(config Config) *Server {
srv.handlePhoto,
)
+ srv.mux.HandleFunc(
+ "POST /api/reload",
+ srv.handleReload,
+ )
+
return srv
}
diff --git a/internal/api/reload.go b/internal/api/reload.go
new file mode 100644
index 0000000..bd3cffb
--- /dev/null
+++ b/internal/api/reload.go
@@ -0,0 +1,25 @@
+package api
+
+import (
+ "log"
+ "net/http"
+)
+
+func (s *Server) handleReload(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+ if err := s.gallery.Reload(r.Context()); err != nil {
+ log.Printf("reload gallery: %v", err)
+
+ writeError(
+ w,
+ http.StatusInternalServerError,
+ "failed to reload gallery",
+ )
+
+ return
+ }
+
+ w.WriteHeader(http.StatusNoContent)
+}
diff --git a/internal/service/gallery.go b/internal/service/gallery.go
index 30abefe..0d1e760 100644
--- a/internal/service/gallery.go
+++ b/internal/service/gallery.go
@@ -1,14 +1,18 @@
package service
import (
+ "sync"
+
"github.com/RanXom/galleryd/internal/gallery"
"github.com/RanXom/galleryd/internal/scanner"
)
-// GalleryService builds gallery photos
+// galleryService implements GalleryService.
type galleryService struct {
scanner *scanner.Scanner
builder *gallery.Builder
+ mu sync.RWMutex
+
index galleryIndex
}
diff --git a/internal/service/gallery_service.go b/internal/service/gallery_service.go
index e500bec..23a8e85 100644
--- a/internal/service/gallery_service.go
+++ b/internal/service/gallery_service.go
@@ -9,6 +9,9 @@ import (
// Gallery scans the configured roots and builds the gallery.
func (s *galleryService) Gallery(ctx context.Context) ([]gallery.Photo, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
select {
case <-ctx.Done():
return nil, ctx.Err()
diff --git a/internal/service/photo.go b/internal/service/photo.go
index 018ba6b..7242d8e 100644
--- a/internal/service/photo.go
+++ b/internal/service/photo.go
@@ -14,6 +14,9 @@ func (s *galleryService) Photo(
ctx context.Context,
id string,
) (gallery.Photo, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
select {
case <-ctx.Done():
return gallery.Photo{}, ctx.Err()
diff --git a/internal/service/load.go b/internal/service/reload.go
index 09bbc20..9460dbc 100644
--- a/internal/service/load.go
+++ b/internal/service/reload.go
@@ -6,8 +6,8 @@ import (
"github.com/RanXom/galleryd/internal/gallery"
)
-// Load scans the configured roots and rebuilds the in-memory gallery.
-func (s *galleryService) Load(ctx context.Context) error {
+// Reload scans the configured roots and rebuilds the in-memory gallery.
+func (s *galleryService) Reload(ctx context.Context) error {
files, err := s.scanner.Scan(ctx)
if err != nil {
return err
@@ -27,7 +27,9 @@ func (s *galleryService) Load(ctx context.Context) error {
index.byID[photo.ID] = photo
}
+ s.mu.Lock()
s.index = index
+ s.mu.Unlock()
return nil
}
diff --git a/internal/service/reload_test.go b/internal/service/reload_test.go
new file mode 100644
index 0000000..c8326ca
--- /dev/null
+++ b/internal/service/reload_test.go
@@ -0,0 +1,125 @@
+package service
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/RanXom/galleryd/internal/gallery"
+ "github.com/RanXom/galleryd/internal/metadata"
+ "github.com/RanXom/galleryd/internal/scanner"
+ "github.com/RanXom/galleryd/internal/testfixtures"
+)
+
+func TestReloadInitialLoad(t *testing.T) {
+ ctx := context.Background()
+
+ sc := scanner.New(scanner.Config{
+ Roots: []string{
+ "../scanner/testdata/gallery",
+ },
+ })
+
+ builder := gallery.New(metadata.New())
+
+ service := New(sc, builder)
+
+ if err := service.Reload(ctx); err != nil {
+ t.Fatalf("reload gallery: %v", err)
+ }
+
+ photos, err := service.Gallery(ctx)
+ if err != nil {
+ t.Fatalf("gallery: %v", err)
+ }
+
+ if len(photos) == 0 {
+ t.Fatal("expected gallery to contain photos")
+ }
+
+ for _, photo := range photos {
+ got, err := service.Photo(ctx, photo.ID)
+ if err != nil {
+ t.Fatalf("lookup photo %q: %v", photo.ID, err)
+ }
+
+ if got.ID != photo.ID {
+ t.Fatalf("expected id %q, got %q", photo.ID, got.ID)
+ }
+ }
+}
+
+func TestReloadReplacesGallery(t *testing.T) {
+ ctx := context.Background()
+
+ root := t.TempDir()
+
+ copyFile := func(src, dst string) {
+ t.Helper()
+
+ data, err := os.ReadFile(src)
+ if err != nil {
+ t.Fatalf("read fixture: %v", err)
+ }
+
+ if err := os.WriteFile(dst, data, 0o644); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ }
+
+ first := filepath.Join(root, "first.jpg")
+ second := filepath.Join(root, "second.jpg")
+
+ copyFile(testfixtures.Canon40D(), first)
+
+ sc := scanner.New(scanner.Config{
+ Roots: []string{root},
+ })
+
+ builder := gallery.New(metadata.New())
+
+ service := New(sc, builder)
+
+ if err := service.Reload(ctx); err != nil {
+ t.Fatalf("first reload: %v", err)
+ }
+
+ before, err := service.Gallery(ctx)
+ if err != nil {
+ t.Fatalf("gallery: %v", err)
+ }
+
+ if len(before) != 1 {
+ t.Fatalf("expected 1 photo, got %d", len(before))
+ }
+
+ oldID := before[0].ID
+
+ if err := os.Remove(first); err != nil {
+ t.Fatalf("remove first image: %v", err)
+ }
+
+ copyFile(testfixtures.NikonD70(), second)
+
+ if err := service.Reload(ctx); err != nil {
+ t.Fatalf("second reload: %v", err)
+ }
+
+ after, err := service.Gallery(ctx)
+ if err != nil {
+ t.Fatalf("gallery: %v", err)
+ }
+
+ if len(after) != 1 {
+ t.Fatalf("expected 1 photo, got %d", len(after))
+ }
+
+ if after[0].ID == oldID {
+ t.Fatal("gallery snapshot was not replaced")
+ }
+
+ if _, err := service.Photo(ctx, oldID); err != ErrPhotoNotFound {
+ t.Fatalf("expected ErrPhotoNotFound, got %v", err)
+ }
+}
diff --git a/internal/service/service.go b/internal/service/service.go
index 68a764e..0b9b253 100644
--- a/internal/service/service.go
+++ b/internal/service/service.go
@@ -8,8 +8,8 @@ import (
// GalleryService provides gallery operations.
type GalleryService interface {
- // Load scans the configured roots and builds the in-memory gallery.
- Load(ctx context.Context) error
+ // Reload scans the configured roots and rebuilds the in-memory gallery.
+ Reload(ctx context.Context) error
// Gallery returns the currently loaded gallery.
Gallery(ctx context.Context) ([]gallery.Photo, error)
diff --git a/internal/watcher/config.go b/internal/watcher/config.go
new file mode 100644
index 0000000..a59474f
--- /dev/null
+++ b/internal/watcher/config.go
@@ -0,0 +1,11 @@
+package watcher
+
+import "time"
+
+// Config configures a filesystem watcher
+type Config struct {
+ Roots []string
+
+ Debounce time.Duration
+ OnChange func()
+}
diff --git a/internal/watcher/debounce.go b/internal/watcher/debounce.go
new file mode 100644
index 0000000..b2961bd
--- /dev/null
+++ b/internal/watcher/debounce.go
@@ -0,0 +1,62 @@
+package watcher
+
+import (
+ "context"
+ "time"
+)
+
+// notify schedules a debounced notification.
+//
+// Multiple filesystem events collapse into a single callback.
+func (w *Watcher) notify() {
+ if w.config.OnChange == nil {
+ return
+ }
+
+ select {
+ case w.debounce <- struct{}{}:
+ default:
+ }
+}
+
+func (w *Watcher) debounceLoop(ctx context.Context) {
+ if w.config.OnChange == nil {
+ return
+ }
+
+ timer := time.NewTimer(time.Hour)
+
+ if !timer.Stop() {
+ select {
+ case <-timer.C:
+ default:
+ }
+ }
+
+ var pending bool
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+
+ case <-w.debounce:
+ pending = true
+
+ if !timer.Stop() {
+ select {
+ case <-timer.C:
+ default:
+ }
+ }
+
+ timer.Reset(w.config.Debounce)
+
+ case <-timer.C:
+ if pending {
+ pending = false
+ w.config.OnChange()
+ }
+ }
+ }
+}
diff --git a/internal/watcher/debounce_test.go b/internal/watcher/debounce_test.go
new file mode 100644
index 0000000..007dbd4
--- /dev/null
+++ b/internal/watcher/debounce_test.go
@@ -0,0 +1,79 @@
+package watcher
+
+import (
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestDebounceCollapsesNotifications(t *testing.T) {
+ done := make(chan struct{}, 1)
+ var calls atomic.Int32
+
+ w := New(Config{
+ Debounce: 25 * time.Millisecond,
+ OnChange: func() {
+ calls.Add(1)
+
+ select {
+ case done <- struct{}{}:
+ default:
+ }
+ },
+ })
+
+ go w.debounceLoop(t.Context())
+
+ for range 10 {
+ w.notify()
+ }
+
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for callback")
+ }
+
+ if got := calls.Load(); got != 1 {
+ t.Fatalf("expected 1 callback, got %d", got)
+ }
+}
+
+func TestDebounceSeparateBursts(t *testing.T) {
+ done := make(chan struct{}, 2)
+ var calls atomic.Int32
+
+ w := New(Config{
+ Debounce: 20 * time.Millisecond,
+ OnChange: func() {
+ calls.Add(1)
+
+ select {
+ case done <- struct{}{}:
+ default:
+ }
+ },
+ })
+
+ go w.debounceLoop(t.Context())
+
+ w.notify()
+
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for first callback")
+ }
+
+ w.notify()
+
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ t.Fatal("timed out waiting for second callback")
+ }
+
+ if got := calls.Load(); got != 2 {
+ t.Fatalf("expected 2 callbacks, got %d", got)
+ }
+}
diff --git a/internal/watcher/doc.go b/internal/watcher/doc.go
new file mode 100644
index 0000000..95801aa
--- /dev/null
+++ b/internal/watcher/doc.go
@@ -0,0 +1,7 @@
+// Package watcher watches configured directories for filesystem changes.
+//
+// The package is intentionally unaware of galleries, thumbnails and HTTP.
+//
+// Its sole responsibility is detecting filesystem changes and notifying
+// the caller through a callback.
+package watcher
diff --git a/internal/watcher/fsnotify.go b/internal/watcher/fsnotify.go
new file mode 100644
index 0000000..b759c50
--- /dev/null
+++ b/internal/watcher/fsnotify.go
@@ -0,0 +1,72 @@
+package watcher
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "os"
+
+ "github.com/fsnotify/fsnotify"
+)
+
+// Run starts watching the configured roots.
+//
+// Filesystem events are currently logged for debugging.
+// Future commits will debounce these events and invoke OnChange.
+func (w *Watcher) Run(ctx context.Context) error {
+ fswatcher, err := fsnotify.NewWatcher()
+ if err != nil {
+ return fmt.Errorf("create watcher: %w", err)
+ }
+ defer func() {
+ _ = fswatcher.Close()
+ }()
+
+ go w.debounceLoop(ctx)
+
+ for _, root := range w.config.Roots {
+ if err := watchTree(fswatcher, root); err != nil {
+ return err
+ }
+ }
+
+ for {
+ select {
+ case <-ctx.Done():
+ return nil
+
+ case event, ok := <-fswatcher.Events:
+ if !ok {
+ return nil
+ }
+
+ log.Printf("watcher: %v %s", event.Op, event.Name)
+
+ w.notify()
+
+ if !event.Has(fsnotify.Create) {
+ continue
+ }
+
+ info, err := os.Stat(event.Name)
+ if err != nil {
+ continue
+ }
+
+ if !info.IsDir() {
+ continue
+ }
+
+ if err := watchTree(fswatcher, event.Name); err != nil {
+ log.Printf("watch new directory: %v", err)
+ }
+
+ case err, ok := <-fswatcher.Errors:
+ if !ok {
+ return nil
+ }
+
+ log.Printf("watcher error: %v", err)
+ }
+ }
+}
diff --git a/internal/watcher/watch.go b/internal/watcher/watch.go
new file mode 100644
index 0000000..95146ce
--- /dev/null
+++ b/internal/watcher/watch.go
@@ -0,0 +1,26 @@
+package watcher
+
+import (
+ "io/fs"
+ "path/filepath"
+
+ "github.com/fsnotify/fsnotify"
+)
+
+// watchTree recursively watches root and all of its subdirectories.
+func watchTree(
+ w *fsnotify.Watcher,
+ root string,
+) error {
+ return filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+
+ if !d.IsDir() {
+ return nil
+ }
+
+ return w.Add(path)
+ })
+}
diff --git a/internal/watcher/watcher.go b/internal/watcher/watcher.go
new file mode 100644
index 0000000..303eced
--- /dev/null
+++ b/internal/watcher/watcher.go
@@ -0,0 +1,20 @@
+package watcher
+
+import "time"
+
+type Watcher struct {
+ config Config
+
+ debounce chan struct{}
+}
+
+func New(config Config) *Watcher {
+ if config.Debounce <= 0 {
+ config.Debounce = 500 * time.Millisecond
+ }
+
+ return &Watcher{
+ config: config,
+ debounce: make(chan struct{}, 1),
+ }
+}
diff --git a/internal/watcher/watcher_test.go b/internal/watcher/watcher_test.go
new file mode 100644
index 0000000..53c0baa
--- /dev/null
+++ b/internal/watcher/watcher_test.go
@@ -0,0 +1,31 @@
+package watcher
+
+import (
+ "context"
+ "testing"
+ "time"
+)
+
+func TestRunReturnsOnContextCancellation(t *testing.T) {
+ w := New(Config{})
+
+ ctx, cancel := context.WithCancel(context.Background())
+
+ done := make(chan error, 1)
+
+ go func() {
+ done <- w.Run(ctx)
+ }()
+
+ cancel()
+
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("expected nil, got %v", err)
+ }
+
+ case <-time.After(time.Second):
+ t.Fatal("watcher did not exit")
+ }
+}