Add e2e test harness for testing editor logic without Gio display
- internal/test/e2e/: FrameCapture, Harness, ElementAssertions, helpers - internal/editor/logic.go: Add done channel and Done() method for graceful shutdown - internal/editor/mock_setup.go: Mock filesystem for tests - internal/browser/: Browser layout and search logic - internal/io/: Worker pool for async tasks - Update architecture docs and spec
This commit is contained in:
@@ -0,0 +1,319 @@
|
||||
package pool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pad/internal/io/pool/mock"
|
||||
)
|
||||
|
||||
// cancelTask is a task that respects context cancellation.
|
||||
type cancelTask struct {
|
||||
id string
|
||||
taskType TaskType
|
||||
priority Priority
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
delay time.Duration
|
||||
called atomic.Bool
|
||||
}
|
||||
|
||||
func newCancelTask(id string, delay time.Duration) *cancelTask {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &cancelTask{
|
||||
id: id,
|
||||
taskType: TypeReadFile,
|
||||
priority: HighPriority,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
delay: delay,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *cancelTask) Execute() Result {
|
||||
t.called.Store(true)
|
||||
select {
|
||||
case <-t.ctx.Done():
|
||||
return Result{
|
||||
TaskID: t.id,
|
||||
TaskType: t.taskType,
|
||||
Success: false,
|
||||
Error: t.ctx.Err(),
|
||||
}
|
||||
case <-time.After(t.delay):
|
||||
return Result{
|
||||
TaskID: t.id,
|
||||
TaskType: t.taskType,
|
||||
Success: true,
|
||||
Data: "completed",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *cancelTask) Priority() Priority { return t.priority }
|
||||
func (t *cancelTask) TaskID() string { return t.id }
|
||||
func (t *cancelTask) TaskType() TaskType { return t.taskType }
|
||||
func (t *cancelTask) DirPath() string { return "/test" }
|
||||
func (t *cancelTask) Context() context.Context { return t.ctx }
|
||||
func (t *cancelTask) Cancel() { t.cancel() }
|
||||
func (t *cancelTask) Timeout() time.Duration { return 0 }
|
||||
|
||||
// timeoutTask is a task that respects timeout.
|
||||
type timeoutTask struct {
|
||||
id string
|
||||
taskType TaskType
|
||||
priority Priority
|
||||
delay time.Duration
|
||||
}
|
||||
|
||||
func (t *timeoutTask) Execute() Result {
|
||||
time.Sleep(t.delay)
|
||||
return Result{
|
||||
TaskID: t.id,
|
||||
TaskType: t.taskType,
|
||||
Success: true,
|
||||
Data: "completed",
|
||||
}
|
||||
}
|
||||
|
||||
func (t *timeoutTask) Priority() Priority { return t.priority }
|
||||
func (t *timeoutTask) TaskID() string { return t.id }
|
||||
func (t *timeoutTask) TaskType() TaskType { return t.taskType }
|
||||
func (t *timeoutTask) DirPath() string { return "/test" }
|
||||
func (t *timeoutTask) Context() context.Context { return context.Background() }
|
||||
func (t *timeoutTask) Cancel() {}
|
||||
func (t *timeoutTask) Timeout() time.Duration { return 50 * time.Millisecond }
|
||||
|
||||
func TestTaskContextCancellation(t *testing.T) {
|
||||
task := newCancelTask("test-cancel", 1*time.Second)
|
||||
|
||||
// Cancel the task
|
||||
task.Cancel()
|
||||
|
||||
// Execute should return error
|
||||
result := task.Execute()
|
||||
if result.IsSuccess() {
|
||||
t.Error("Task should not succeed after cancellation")
|
||||
}
|
||||
if result.Error == nil {
|
||||
t.Error("Task should have error after cancellation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskTimeoutMethod(t *testing.T) {
|
||||
task := &timeoutTask{id: "test-timeout"}
|
||||
if task.Timeout() != 50*time.Millisecond {
|
||||
t.Errorf("Timeout = %v, want %v", task.Timeout(), 50*time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ContextCancellation(t *testing.T) {
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// Create a task that will be cancelled
|
||||
task := newCancelTask("cancel-test", 500*time.Millisecond)
|
||||
|
||||
// Dispatch the task
|
||||
pool.Dispatch(task)
|
||||
|
||||
// Cancel after a short delay
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
task.Cancel()
|
||||
|
||||
// Wait for result
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
// Should complete with error due to cancellation
|
||||
if result.IsSuccess() {
|
||||
t.Log("Task completed before cancellation - acceptable")
|
||||
} else {
|
||||
t.Logf("Task cancelled as expected: %v", result.Error)
|
||||
}
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("Timed out waiting for result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_TaskTimeout(t *testing.T) {
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// Create a task with a short timeout that will sleep longer
|
||||
task := &timeoutTask{
|
||||
id: "timeout-test",
|
||||
taskType: TypeReadFile,
|
||||
priority: HighPriority,
|
||||
delay: 5 * time.Second, // Much longer than timeout
|
||||
}
|
||||
|
||||
pool.Dispatch(task)
|
||||
|
||||
// Should complete with timeout error
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
if result.IsSuccess() {
|
||||
t.Error("Task should have timed out")
|
||||
}
|
||||
if result.Error == nil {
|
||||
t.Error("Task should have error after timeout")
|
||||
}
|
||||
t.Logf("Task timed out as expected: %v", result.Error)
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Timed out waiting for result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_CancelByDirPath(t *testing.T) {
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// Create tasks for different directories
|
||||
task1 := newCancelTask("dir1-task", 500*time.Millisecond)
|
||||
task2 := newCancelTask("dir2-task", 500*time.Millisecond)
|
||||
|
||||
// Set DirPath for task1
|
||||
// Note: We need to modify the task to return specific DirPath
|
||||
// For now, we'll test the CancelPendingTasks method
|
||||
|
||||
pool.Dispatch(task1)
|
||||
pool.Dispatch(task2)
|
||||
|
||||
// Cancel tasks for "/test" directory (both tasks use this)
|
||||
pool.CancelPendingTasks("/test")
|
||||
|
||||
// Wait for results
|
||||
for i := 0; i < 2; i++ {
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
t.Logf("Got result for task %s: success=%v, error=%v", result.TaskID, result.IsSuccess(), result.Error)
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatalf("Timed out waiting for result %d", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_CancelPendingTasks_NoEffect(t *testing.T) {
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// Cancel tasks for non-existent directory
|
||||
pool.CancelPendingTasks("/nonexistent")
|
||||
|
||||
// Should not panic or cause issues
|
||||
if !pool.IsRunning() {
|
||||
t.Error("Pool should still be running")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ContextPropagation(t *testing.T) {
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// Create a task that uses context
|
||||
task := newCancelTask("ctx-prop", 100*time.Millisecond)
|
||||
|
||||
pool.Dispatch(task)
|
||||
|
||||
// Wait for result
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
if !result.IsSuccess() {
|
||||
t.Errorf("Task failed: %v", result.Error)
|
||||
}
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("Timed out waiting for result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_DirPathInResult(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.CreateDir("/test/dir1")
|
||||
fs.CreateFile("/test/dir1/file.txt", []byte("content"))
|
||||
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// Create a read dir task
|
||||
task := NewReadDirTask("/test/dir1", fs)
|
||||
pool.Dispatch(task)
|
||||
|
||||
// Wait for result
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
if !result.IsSuccess() {
|
||||
t.Errorf("Task failed: %v", result.Error)
|
||||
}
|
||||
// DirPath should be in the result
|
||||
if result.DirPath != "/test/dir1" {
|
||||
t.Errorf("Result DirPath = %q, want %q", result.DirPath, "/test/dir1")
|
||||
}
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("Timed out waiting for result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ConcurrentCancellation(t *testing.T) {
|
||||
pool := NewWorkerPool(4)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// Create multiple tasks
|
||||
var tasks []*cancelTask
|
||||
for i := 0; i < 10; i++ {
|
||||
task := newCancelTask(fmt.Sprintf("concurrent-%d", i), 1*time.Second)
|
||||
tasks = append(tasks, task)
|
||||
pool.Dispatch(task)
|
||||
}
|
||||
|
||||
// Cancel half of them
|
||||
for i := 0; i < 5; i++ {
|
||||
tasks[i].Cancel()
|
||||
}
|
||||
|
||||
// Wait for all results
|
||||
for i := 0; i < 10; i++ {
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
// Results may be success or error depending on timing
|
||||
t.Logf("Result for %s: success=%v", result.TaskID, result.IsSuccess())
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("Timed out waiting for result %d", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_TimeoutWithRealTasks(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.SetDelay(100 * time.Millisecond)
|
||||
fs.CreateFile("/test/timeout.txt", []byte("content"))
|
||||
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// Create a task with short timeout
|
||||
task := NewReadFileTask("/test/timeout.txt", fs)
|
||||
|
||||
// Note: Real tasks don't have custom timeout yet
|
||||
// This test verifies that the timeout mechanism doesn't break existing functionality
|
||||
pool.Dispatch(task)
|
||||
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
if !result.IsSuccess() {
|
||||
t.Errorf("Task failed: %v", result.Error)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Timed out waiting for result")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
// Package mock provides a configurable mock filesystem for testing
|
||||
// the IO worker pool without touching the real disk.
|
||||
package mock
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// File represents a file or directory in the mock filesystem.
|
||||
type File struct {
|
||||
Path string
|
||||
Name string
|
||||
Content []byte
|
||||
ModTime time.Time
|
||||
Size int64
|
||||
IsDir bool
|
||||
}
|
||||
|
||||
// DirEntry mimics fs.DirEntry behavior for the mock.
|
||||
type DirEntry struct {
|
||||
name string
|
||||
isDir bool
|
||||
modTime time.Time
|
||||
size int64
|
||||
}
|
||||
|
||||
func (d DirEntry) Name() string { return d.name }
|
||||
func (d DirEntry) IsDir() bool { return d.isDir }
|
||||
func (d DirEntry) Info() (os.FileInfo, error) {
|
||||
return &mockFileInfo{name: d.name, isDir: d.isDir, modTime: d.modTime, size: d.size}, nil
|
||||
}
|
||||
|
||||
// mockFileInfo implements os.FileInfo for the mock.
|
||||
type mockFileInfo struct {
|
||||
name string
|
||||
isDir bool
|
||||
modTime time.Time
|
||||
size int64
|
||||
}
|
||||
|
||||
func (fi *mockFileInfo) Name() string { return fi.name }
|
||||
func (fi *mockFileInfo) Size() int64 { return fi.size }
|
||||
func (fi *mockFileInfo) Mode() os.FileMode { return 0644 }
|
||||
func (fi *mockFileInfo) ModTime() time.Time { return fi.modTime }
|
||||
func (fi *mockFileInfo) IsDir() bool { return fi.isDir }
|
||||
func (fi *mockFileInfo) Sys() any { return nil }
|
||||
|
||||
// FileChangeEvent represents an external filesystem change.
|
||||
type FileChangeEvent struct {
|
||||
Path string
|
||||
EventType string // "Created", "Modified", "Deleted"
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
// notifyEvent is a pending notification collected while holding the lock.
|
||||
type notifyEvent struct {
|
||||
path string
|
||||
eventType string
|
||||
}
|
||||
|
||||
// FileSystem is a thread-safe in-memory filesystem for testing.
|
||||
type FileSystem struct {
|
||||
mu sync.RWMutex
|
||||
files map[string]*File // path -> file
|
||||
delay time.Duration // uniform delay applied to all operations
|
||||
changes chan FileChangeEvent // async change notifications (nil = no notifications)
|
||||
}
|
||||
|
||||
// NewFileSystem creates an empty mock filesystem.
|
||||
func NewFileSystem() *FileSystem {
|
||||
return &FileSystem{
|
||||
files: make(map[string]*File),
|
||||
}
|
||||
}
|
||||
|
||||
// SetDelay sets a uniform delay applied to all IO operations.
|
||||
func (fs *FileSystem) SetDelay(d time.Duration) {
|
||||
fs.mu.Lock()
|
||||
defer fs.mu.Unlock()
|
||||
fs.delay = d
|
||||
}
|
||||
|
||||
// SetChangeEvents sets the channel for async change notifications.
|
||||
// Pass nil to disable notifications.
|
||||
func (fs *FileSystem) SetChangeEvents(ch chan FileChangeEvent) {
|
||||
fs.mu.Lock()
|
||||
defer fs.mu.Unlock()
|
||||
fs.changes = ch
|
||||
}
|
||||
|
||||
// sendNotifications sends any pending notification events.
|
||||
// Caller must NOT hold the mutex.
|
||||
func (fs *FileSystem) sendNotifications(events []notifyEvent) {
|
||||
fs.mu.RLock()
|
||||
ch := fs.changes
|
||||
fs.mu.RUnlock()
|
||||
|
||||
if ch == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for _, e := range events {
|
||||
select {
|
||||
case ch <- FileChangeEvent{
|
||||
Path: e.path,
|
||||
EventType: e.eventType,
|
||||
Time: time.Now(),
|
||||
}:
|
||||
default:
|
||||
// Drop event if channel is full (non-blocking)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CreateFile creates a file with the given content at the specified path.
|
||||
func (fs *FileSystem) CreateFile(path string, content []byte) error {
|
||||
fs.mu.Lock()
|
||||
|
||||
if fs.delay > 0 {
|
||||
fs.mu.Unlock()
|
||||
time.Sleep(fs.delay)
|
||||
fs.mu.Lock()
|
||||
}
|
||||
|
||||
name := filepath.Base(path)
|
||||
now := time.Now()
|
||||
f := &File{
|
||||
Path: path,
|
||||
Name: name,
|
||||
Content: content,
|
||||
ModTime: now,
|
||||
Size: int64(len(content)),
|
||||
IsDir: false,
|
||||
}
|
||||
fs.files[path] = f
|
||||
|
||||
// Collect notification while holding the lock
|
||||
var events []notifyEvent
|
||||
if fs.changes != nil {
|
||||
events = append(events, notifyEvent{path, "Created"})
|
||||
}
|
||||
|
||||
fs.mu.Unlock()
|
||||
|
||||
// Send notifications outside the lock (avoids deadlock)
|
||||
fs.sendNotifications(events)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadFile returns the content of a file at the given path.
|
||||
func (fs *FileSystem) ReadFile(path string) ([]byte, error) {
|
||||
fs.mu.Lock()
|
||||
|
||||
if fs.delay > 0 {
|
||||
fs.mu.Unlock()
|
||||
time.Sleep(fs.delay)
|
||||
fs.mu.Lock()
|
||||
}
|
||||
|
||||
f, ok := fs.files[path]
|
||||
if !ok {
|
||||
fs.mu.Unlock()
|
||||
return nil, fmt.Errorf("file not found: %s", path)
|
||||
}
|
||||
content := append([]byte(nil), f.Content...)
|
||||
fs.mu.Unlock()
|
||||
return content, nil
|
||||
}
|
||||
|
||||
// WriteFile replaces the content of a file at the given path.
|
||||
func (fs *FileSystem) WriteFile(path string, content []byte) error {
|
||||
fs.mu.Lock()
|
||||
|
||||
if fs.delay > 0 {
|
||||
fs.mu.Unlock()
|
||||
time.Sleep(fs.delay)
|
||||
fs.mu.Lock()
|
||||
}
|
||||
|
||||
f, ok := fs.files[path]
|
||||
if !ok {
|
||||
fs.mu.Unlock()
|
||||
return fmt.Errorf("file not found: %s", path)
|
||||
}
|
||||
|
||||
f.Content = content
|
||||
f.Size = int64(len(content))
|
||||
f.ModTime = time.Now()
|
||||
|
||||
var events []notifyEvent
|
||||
if fs.changes != nil {
|
||||
events = append(events, notifyEvent{path, "Modified"})
|
||||
}
|
||||
|
||||
fs.mu.Unlock()
|
||||
fs.sendNotifications(events)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteFile removes a file at the given path.
|
||||
func (fs *FileSystem) DeleteFile(path string) error {
|
||||
fs.mu.Lock()
|
||||
|
||||
if fs.delay > 0 {
|
||||
fs.mu.Unlock()
|
||||
time.Sleep(fs.delay)
|
||||
fs.mu.Lock()
|
||||
}
|
||||
|
||||
if _, ok := fs.files[path]; !ok {
|
||||
fs.mu.Unlock()
|
||||
return fmt.Errorf("file not found: %s", path)
|
||||
}
|
||||
|
||||
delete(fs.files, path)
|
||||
|
||||
var events []notifyEvent
|
||||
if fs.changes != nil {
|
||||
events = append(events, notifyEvent{path, "Deleted"})
|
||||
}
|
||||
|
||||
fs.mu.Unlock()
|
||||
fs.sendNotifications(events)
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateDir creates a directory at the given path.
|
||||
func (fs *FileSystem) CreateDir(path string) error {
|
||||
fs.mu.Lock()
|
||||
|
||||
if fs.delay > 0 {
|
||||
fs.mu.Unlock()
|
||||
time.Sleep(fs.delay)
|
||||
fs.mu.Lock()
|
||||
}
|
||||
|
||||
name := filepath.Base(path)
|
||||
f := &File{
|
||||
Path: path,
|
||||
Name: name,
|
||||
ModTime: time.Now(),
|
||||
IsDir: true,
|
||||
}
|
||||
fs.files[path] = f
|
||||
|
||||
var events []notifyEvent
|
||||
if fs.changes != nil {
|
||||
events = append(events, notifyEvent{path, "Created"})
|
||||
}
|
||||
|
||||
fs.mu.Unlock()
|
||||
fs.sendNotifications(events)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadDir returns a list of entries in the given directory.
|
||||
func (fs *FileSystem) ReadDir(path string) ([]DirEntry, error) {
|
||||
fs.mu.Lock()
|
||||
|
||||
if fs.delay > 0 {
|
||||
fs.mu.Unlock()
|
||||
time.Sleep(fs.delay)
|
||||
fs.mu.Lock()
|
||||
}
|
||||
|
||||
dirPath := filepath.Clean(path)
|
||||
if _, ok := fs.files[dirPath]; !ok {
|
||||
fs.mu.Unlock()
|
||||
return nil, fmt.Errorf("directory not found: %s", path)
|
||||
}
|
||||
|
||||
var entries []DirEntry
|
||||
|
||||
for _, f := range fs.files {
|
||||
if f.Path == dirPath {
|
||||
continue
|
||||
}
|
||||
parent := filepath.Dir(f.Path)
|
||||
if parent == dirPath {
|
||||
entries = append(entries, DirEntry{
|
||||
name: f.Name,
|
||||
isDir: f.IsDir,
|
||||
modTime: f.ModTime,
|
||||
size: f.Size,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by name
|
||||
for i := 0; i < len(entries); i++ {
|
||||
for j := i + 1; j < len(entries); j++ {
|
||||
if entries[i].name > entries[j].name {
|
||||
entries[i], entries[j] = entries[j], entries[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fs.mu.Unlock()
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// DirExists returns true if the path exists and is a directory.
|
||||
func (fs *FileSystem) DirExists(path string) bool {
|
||||
fs.mu.RLock()
|
||||
defer fs.mu.RUnlock()
|
||||
|
||||
f, ok := fs.files[path]
|
||||
return ok && f.IsDir
|
||||
}
|
||||
|
||||
// FileExists returns true if the path exists and is a file.
|
||||
func (fs *FileSystem) FileExists(path string) bool {
|
||||
fs.mu.RLock()
|
||||
defer fs.mu.RUnlock()
|
||||
|
||||
f, ok := fs.files[path]
|
||||
return ok && !f.IsDir
|
||||
}
|
||||
|
||||
// GetFile returns the file at the given path, or nil if not found.
|
||||
func (fs *FileSystem) GetFile(path string) *File {
|
||||
fs.mu.RLock()
|
||||
defer fs.mu.RUnlock()
|
||||
|
||||
return fs.files[path]
|
||||
}
|
||||
|
||||
// SetFileContent atomically replaces the content of an existing file.
|
||||
func (fs *FileSystem) SetFileContent(path string, content []byte) {
|
||||
fs.mu.Lock()
|
||||
|
||||
if fs.delay > 0 {
|
||||
fs.mu.Unlock()
|
||||
time.Sleep(fs.delay)
|
||||
fs.mu.Lock()
|
||||
}
|
||||
|
||||
f, ok := fs.files[path]
|
||||
if !ok {
|
||||
fs.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
f.Content = content
|
||||
f.Size = int64(len(content))
|
||||
f.ModTime = time.Now()
|
||||
|
||||
var events []notifyEvent
|
||||
if fs.changes != nil {
|
||||
events = append(events, notifyEvent{path, "Modified"})
|
||||
}
|
||||
|
||||
fs.mu.Unlock()
|
||||
fs.sendNotifications(events)
|
||||
}
|
||||
|
||||
// AddFile adds a file without triggering change notifications.
|
||||
// Useful for pre-populating the filesystem before tests.
|
||||
func (fs *FileSystem) AddFile(path string, content []byte, modTime time.Time) {
|
||||
fs.mu.Lock()
|
||||
defer fs.mu.Unlock()
|
||||
|
||||
name := filepath.Base(path)
|
||||
f := &File{
|
||||
Path: path,
|
||||
Name: name,
|
||||
Content: content,
|
||||
ModTime: modTime,
|
||||
Size: int64(len(content)),
|
||||
IsDir: false,
|
||||
}
|
||||
fs.files[path] = f
|
||||
}
|
||||
|
||||
// AddDir adds a directory without triggering change notifications.
|
||||
func (fs *FileSystem) AddDir(path string, modTime time.Time) {
|
||||
fs.mu.Lock()
|
||||
defer fs.mu.Unlock()
|
||||
|
||||
name := filepath.Base(path)
|
||||
f := &File{
|
||||
Path: path,
|
||||
Name: name,
|
||||
ModTime: modTime,
|
||||
IsDir: true,
|
||||
}
|
||||
fs.files[path] = f
|
||||
}
|
||||
|
||||
// RemoveFile removes a file without triggering change notifications.
|
||||
func (fs *FileSystem) RemoveFile(path string) {
|
||||
fs.mu.Lock()
|
||||
defer fs.mu.Unlock()
|
||||
|
||||
delete(fs.files, path)
|
||||
}
|
||||
|
||||
// ListPaths returns all file paths in the filesystem, optionally filtered by prefix.
|
||||
func (fs *FileSystem) ListPaths(prefix string) []string {
|
||||
fs.mu.RLock()
|
||||
defer fs.mu.RUnlock()
|
||||
|
||||
var paths []string
|
||||
for path := range fs.files {
|
||||
if prefix == "" || filepath.HasPrefix(path, prefix) {
|
||||
paths = append(paths, path)
|
||||
}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// Count returns the number of files and directories in the mock filesystem.
|
||||
func (fs *FileSystem) Count() (files int, dirs int) {
|
||||
fs.mu.RLock()
|
||||
defer fs.mu.RUnlock()
|
||||
|
||||
for _, f := range fs.files {
|
||||
if f.IsDir {
|
||||
dirs++
|
||||
} else {
|
||||
files++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package mock
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFileSystem_CreateFile(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
content := []byte("hello world")
|
||||
|
||||
err := fs.CreateFile("/test/hello.txt", content)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateFile failed: %v", err)
|
||||
}
|
||||
|
||||
f := fs.GetFile("/test/hello.txt")
|
||||
if f == nil {
|
||||
t.Fatal("File not found after creation")
|
||||
}
|
||||
if string(f.Content) != "hello world" {
|
||||
t.Errorf("Content = %q, want %q", string(f.Content), "hello world")
|
||||
}
|
||||
if f.Name != "hello.txt" {
|
||||
t.Errorf("Name = %q, want %q", f.Name, "hello.txt")
|
||||
}
|
||||
if f.Size != int64(len(content)) {
|
||||
t.Errorf("Size = %d, want %d", f.Size, len(content))
|
||||
}
|
||||
if f.IsDir {
|
||||
t.Error("IsDir should be false for a file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_ReadFile(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.CreateFile("/test/data.txt", []byte("data"))
|
||||
|
||||
content, err := fs.ReadFile("/test/data.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile failed: %v", err)
|
||||
}
|
||||
if string(content) != "data" {
|
||||
t.Errorf("ReadFile returned %q, want %q", string(content), "data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_ReadFile_NotFound(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
|
||||
_, err := fs.ReadFile("/nonexistent.txt")
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for nonexistent file, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_WriteFile(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.CreateFile("/test/update.txt", []byte("original"))
|
||||
|
||||
err := fs.WriteFile("/test/update.txt", []byte("updated"))
|
||||
if err != nil {
|
||||
t.Fatalf("WriteFile failed: %v", err)
|
||||
}
|
||||
|
||||
content, _ := fs.ReadFile("/test/update.txt")
|
||||
if string(content) != "updated" {
|
||||
t.Errorf("Content = %q, want %q", string(content), "updated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_WriteFile_NotFound(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
|
||||
err := fs.WriteFile("/nonexistent.txt", []byte("data"))
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for nonexistent file, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_DeleteFile(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.CreateFile("/test/delete.txt", []byte("to delete"))
|
||||
|
||||
err := fs.DeleteFile("/test/delete.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteFile failed: %v", err)
|
||||
}
|
||||
|
||||
if fs.FileExists("/test/delete.txt") {
|
||||
t.Error("File should not exist after deletion")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_DeleteFile_NotFound(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
|
||||
err := fs.DeleteFile("/nonexistent.txt")
|
||||
if err == nil {
|
||||
t.Fatal("Expected error for nonexistent file, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_CreateDir(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
|
||||
err := fs.CreateDir("/test/dir")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateDir failed: %v", err)
|
||||
}
|
||||
|
||||
if !fs.DirExists("/test/dir") {
|
||||
t.Error("Dir should exist after creation")
|
||||
}
|
||||
|
||||
f := fs.GetFile("/test/dir")
|
||||
if f == nil {
|
||||
t.Fatal("Directory file not found")
|
||||
}
|
||||
if !f.IsDir {
|
||||
t.Error("IsDir should be true for a directory")
|
||||
}
|
||||
if f.Name != "dir" {
|
||||
t.Errorf("Name = %q, want %q", f.Name, "dir")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_ReadDir(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.CreateDir("/test/dir")
|
||||
fs.CreateFile("/test/dir/a.txt", []byte("a"))
|
||||
fs.CreateFile("/test/dir/b.txt", []byte("b"))
|
||||
fs.CreateFile("/test/dir/c.txt", []byte("c"))
|
||||
|
||||
entries, err := fs.ReadDir("/test/dir")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadDir failed: %v", err)
|
||||
}
|
||||
|
||||
if len(entries) != 3 {
|
||||
t.Fatalf("Expected 3 entries, got %d", len(entries))
|
||||
}
|
||||
|
||||
// Check alphabetical order
|
||||
if entries[0].Name() != "a.txt" {
|
||||
t.Errorf("First entry = %q, want %q", entries[0].Name(), "a.txt")
|
||||
}
|
||||
if entries[1].Name() != "b.txt" {
|
||||
t.Errorf("Second entry = %q, want %q", entries[1].Name(), "b.txt")
|
||||
}
|
||||
if entries[2].Name() != "c.txt" {
|
||||
t.Errorf("Third entry = %q, want %q", entries[2].Name(), "c.txt")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_ReadDir_Empty(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.CreateDir("/test/empty")
|
||||
|
||||
entries, err := fs.ReadDir("/test/empty")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadDir failed: %v", err)
|
||||
}
|
||||
|
||||
if len(entries) != 0 {
|
||||
t.Errorf("Expected 0 entries, got %d", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_FileExists(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.CreateFile("/test/exist.txt", []byte("data"))
|
||||
|
||||
if !fs.FileExists("/test/exist.txt") {
|
||||
t.Error("File should exist")
|
||||
}
|
||||
if fs.FileExists("/test/noexist.txt") {
|
||||
t.Error("Nonexistent file should not exist")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_DirExists(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.CreateDir("/test/dir")
|
||||
|
||||
if !fs.DirExists("/test/dir") {
|
||||
t.Error("Directory should exist")
|
||||
}
|
||||
if fs.DirExists("/test/noexist") {
|
||||
t.Error("Nonexistent directory should not exist")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_Count(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.CreateFile("/test/a.txt", []byte("a"))
|
||||
fs.CreateFile("/test/b.txt", []byte("b"))
|
||||
fs.CreateDir("/test/dir")
|
||||
|
||||
files, dirs := fs.Count()
|
||||
if files != 2 {
|
||||
t.Errorf("Files = %d, want 2", files)
|
||||
}
|
||||
if dirs != 1 {
|
||||
t.Errorf("Dirs = %d, want 1", dirs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_SetDelay(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.SetDelay(50 * time.Millisecond)
|
||||
|
||||
start := time.Now()
|
||||
fs.ReadFile("/nonexistent.txt") // Will fail but delay should still apply
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if elapsed < 40*time.Millisecond {
|
||||
t.Errorf("Expected delay ~50ms, got %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_SetChangeEvents(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
ch := make(chan FileChangeEvent, 10)
|
||||
fs.SetChangeEvents(ch)
|
||||
|
||||
fs.CreateFile("/test/notify.txt", []byte("data"))
|
||||
|
||||
select {
|
||||
case event := <-ch:
|
||||
if event.Path != "/test/notify.txt" {
|
||||
t.Errorf("Event path = %q, want %q", event.Path, "/test/notify.txt")
|
||||
}
|
||||
if event.EventType != "Created" {
|
||||
t.Errorf("Event type = %q, want %q", event.EventType, "Created")
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Fatal("Expected change event, got none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_SetChangeEvents_NilChannel(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.SetChangeEvents(nil) // Disable notifications
|
||||
|
||||
// Should not panic
|
||||
fs.CreateFile("/test/silent.txt", []byte("data"))
|
||||
}
|
||||
|
||||
func TestFileSystem_AddFile(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
modTime := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
fs.AddFile("/test/pre.txt", []byte("pre"), modTime)
|
||||
|
||||
f := fs.GetFile("/test/pre.txt")
|
||||
if f == nil {
|
||||
t.Fatal("File not found after AddFile")
|
||||
}
|
||||
if !f.ModTime.Equal(modTime) {
|
||||
t.Errorf("ModTime = %v, want %v", f.ModTime, modTime)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_RemoveFile(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.AddFile("/test/remove.txt", []byte("data"), time.Now())
|
||||
|
||||
fs.RemoveFile("/test/remove.txt")
|
||||
|
||||
if fs.FileExists("/test/remove.txt") {
|
||||
t.Error("File should not exist after RemoveFile")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_ListPaths(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
fs.CreateFile("/test/a.txt", []byte("a"))
|
||||
fs.CreateFile("/test/b.txt", []byte("b"))
|
||||
fs.CreateFile("/other/c.txt", []byte("c"))
|
||||
|
||||
paths := fs.ListPaths("/test/")
|
||||
if len(paths) != 2 {
|
||||
t.Errorf("ListPaths returned %d paths, want 2", len(paths))
|
||||
}
|
||||
|
||||
pathsAll := fs.ListPaths("")
|
||||
if len(pathsAll) != 3 {
|
||||
t.Errorf("ListPaths with empty prefix returned %d paths, want 3", len(pathsAll))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_ConcurrentAccess(t *testing.T) {
|
||||
fs := NewFileSystem()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 100; i++ {
|
||||
wg.Add(1)
|
||||
go func(n int) {
|
||||
defer wg.Done()
|
||||
path := fmt.Sprintf("/test/concurrent_%d.txt", n)
|
||||
fs.CreateFile(path, []byte(fmt.Sprintf("content %d", n)))
|
||||
fs.ReadFile(path)
|
||||
fs.DeleteFile(path)
|
||||
}(i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package pool
|
||||
|
||||
import "time"
|
||||
|
||||
// Result is posted back to the logic goroutine when a task completes.
|
||||
// Results are immutable and contain all information needed to apply
|
||||
// the task outcome to state.
|
||||
type Result struct {
|
||||
TaskID string `json:"task_id"`
|
||||
TaskType TaskType `json:"task_type"`
|
||||
Success bool `json:"success"`
|
||||
Data any `json:"data,omitempty"`
|
||||
Error error `json:"error,omitempty"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
DirPath string `json:"dir_path,omitempty"`
|
||||
}
|
||||
|
||||
// IsSuccess returns true if the task completed successfully.
|
||||
func (r Result) IsSuccess() bool {
|
||||
return r.Success && r.Error == nil
|
||||
}
|
||||
|
||||
// IsError returns true if the task failed.
|
||||
func (r Result) IsError() bool {
|
||||
return !r.Success || r.Error != nil
|
||||
}
|
||||
|
||||
// IsBrowserResult returns true if this result is for a browser task.
|
||||
func (r Result) IsBrowserResult() bool {
|
||||
switch r.TaskType {
|
||||
case TypeReadDir, TypeBuildIndex, TypeLoadIndex, TypeLoadPages, TypeStatDir:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// IsFileResult returns true if this result is for a file operation.
|
||||
func (r Result) IsFileResult() bool {
|
||||
switch r.TaskType {
|
||||
case TypeReadFile, TypeWriteFile, TypeStatFile:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// IsCacheResult returns true if this result is for a cache operation.
|
||||
func (r Result) IsCacheResult() bool {
|
||||
switch r.TaskType {
|
||||
case TypeWriteCache, TypeReadCache, TypeInvalidate:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// IsStateResult returns true if this result is for state persistence.
|
||||
func (r Result) IsStateResult() bool {
|
||||
switch r.TaskType {
|
||||
case TypeSaveState, TypeSaveUndo:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Duration returns the time taken for this result (for benchmarking).
|
||||
func (r Result) Duration() time.Duration {
|
||||
// In production, this would be set by the worker.
|
||||
// For now, returns zero.
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
// Package pool provides the IO worker pool for the Pad editor.
|
||||
// It follows the architecture's single-owner pattern: the logic goroutine
|
||||
// owns all state, workers perform IO and post results, never touching state.
|
||||
package pool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"pad/internal/io/pool/mock"
|
||||
)
|
||||
|
||||
// taskCounter generates unique task IDs.
|
||||
var taskCounter atomic.Int64
|
||||
|
||||
// Priority determines which channel a task is dispatched to.
|
||||
type Priority int
|
||||
|
||||
const (
|
||||
HighPriority Priority = iota // UI-critical, blocks user progress
|
||||
LowPriority // Background work, can be delayed
|
||||
)
|
||||
|
||||
func (p Priority) String() string {
|
||||
switch p {
|
||||
case HighPriority:
|
||||
return "high"
|
||||
case LowPriority:
|
||||
return "low"
|
||||
default:
|
||||
return fmt.Sprintf("unknown(%d)", p)
|
||||
}
|
||||
}
|
||||
|
||||
// TaskType identifies the kind of work for result routing.
|
||||
type TaskType string
|
||||
|
||||
const (
|
||||
// Browser tasks
|
||||
TypeReadDir TaskType = "read_dir"
|
||||
TypeBuildIndex TaskType = "build_index"
|
||||
TypeLoadIndex TaskType = "load_index"
|
||||
TypeLoadPages TaskType = "load_pages"
|
||||
TypeStatDir TaskType = "stat_dir"
|
||||
|
||||
// File tasks
|
||||
TypeReadFile TaskType = "read_file"
|
||||
TypeWriteFile TaskType = "write_file"
|
||||
TypeStatFile TaskType = "stat_file"
|
||||
|
||||
// Cache tasks
|
||||
TypeWriteCache TaskType = "write_cache"
|
||||
TypeReadCache TaskType = "read_cache"
|
||||
TypeInvalidate TaskType = "invalidate_cache"
|
||||
|
||||
// State persistence
|
||||
TypeSaveState TaskType = "save_state"
|
||||
TypeSaveUndo TaskType = "save_undo"
|
||||
)
|
||||
|
||||
// Task represents a unit of work to be executed by a worker.
|
||||
// Tasks are immutable after creation.
|
||||
type Task interface {
|
||||
// Execute performs the task and returns a result.
|
||||
Execute() Result
|
||||
|
||||
// Priority returns the task priority level.
|
||||
Priority() Priority
|
||||
|
||||
// TaskID returns a unique identifier for this task.
|
||||
TaskID() string
|
||||
|
||||
// TaskType returns the type of task (for result routing).
|
||||
TaskType() TaskType
|
||||
|
||||
// DirPath returns the directory this task operates on, if any.
|
||||
DirPath() string
|
||||
|
||||
// Context returns the context for this task, used for cancellation.
|
||||
Context() context.Context
|
||||
|
||||
// Cancel cancels this task if it's still running.
|
||||
Cancel()
|
||||
|
||||
// Timeout returns the timeout for this task. Zero means no timeout.
|
||||
Timeout() time.Duration
|
||||
}
|
||||
|
||||
// --- Browser Tasks ---
|
||||
|
||||
// ReadDirTask reads directory entries from the filesystem.
|
||||
type ReadDirTask struct {
|
||||
taskID string
|
||||
Dir string
|
||||
FS *mock.FileSystem
|
||||
}
|
||||
|
||||
func NewReadDirTask(dir string, fs *mock.FileSystem) *ReadDirTask {
|
||||
return &ReadDirTask{
|
||||
taskID: fmt.Sprintf("read_dir_%s_%d", filepath.Base(dir), taskCounter.Add(1)),
|
||||
Dir: dir,
|
||||
FS: fs,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ReadDirTask) Execute() Result {
|
||||
entries, err := t.FS.ReadDir(t.Dir)
|
||||
if err != nil {
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeReadDir,
|
||||
Success: false,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeReadDir,
|
||||
Success: true,
|
||||
Data: entries,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ReadDirTask) Priority() Priority { return HighPriority }
|
||||
func (t *ReadDirTask) TaskID() string { return t.taskID }
|
||||
func (t *ReadDirTask) TaskType() TaskType { return TypeReadDir }
|
||||
func (t *ReadDirTask) DirPath() string { return t.Dir }
|
||||
func (t *ReadDirTask) Context() context.Context { return context.Background() }
|
||||
func (t *ReadDirTask) Cancel() {}
|
||||
func (t *ReadDirTask) Timeout() time.Duration { return 5 * time.Second }
|
||||
|
||||
// BuildIndexTask builds a directory index and writes it to cache.
|
||||
type BuildIndexTask struct {
|
||||
taskID string
|
||||
Dir string
|
||||
FS *mock.FileSystem
|
||||
}
|
||||
|
||||
func NewBuildIndexTask(dir string, fs *mock.FileSystem) *BuildIndexTask {
|
||||
return &BuildIndexTask{
|
||||
taskID: fmt.Sprintf("build_index_%s_%d", filepath.Base(dir), taskCounter.Add(1)),
|
||||
Dir: dir,
|
||||
FS: fs,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *BuildIndexTask) Execute() Result {
|
||||
// In production, this would read the directory, sort entries,
|
||||
// compute letter offsets, and write to cache.
|
||||
// For now, we just signal success with the directory info.
|
||||
entries, err := t.FS.ReadDir(t.Dir)
|
||||
if err != nil {
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeBuildIndex,
|
||||
Success: false,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeBuildIndex,
|
||||
Success: true,
|
||||
Data: entries,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *BuildIndexTask) Priority() Priority { return HighPriority }
|
||||
func (t *BuildIndexTask) TaskID() string { return t.taskID }
|
||||
func (t *BuildIndexTask) TaskType() TaskType { return TypeBuildIndex }
|
||||
func (t *BuildIndexTask) DirPath() string { return t.Dir }
|
||||
func (t *BuildIndexTask) Context() context.Context { return context.Background() }
|
||||
func (t *BuildIndexTask) Cancel() {}
|
||||
func (t *BuildIndexTask) Timeout() time.Duration { return 5 * time.Second }
|
||||
|
||||
// LoadIndexTask loads a cached directory index.
|
||||
type LoadIndexTask struct {
|
||||
taskID string
|
||||
Dir string
|
||||
FS *mock.FileSystem
|
||||
}
|
||||
|
||||
func NewLoadIndexTask(dir string, fs *mock.FileSystem) *LoadIndexTask {
|
||||
return &LoadIndexTask{
|
||||
taskID: fmt.Sprintf("load_index_%s_%d", filepath.Base(dir), taskCounter.Add(1)),
|
||||
Dir: dir,
|
||||
FS: fs,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *LoadIndexTask) Execute() Result {
|
||||
// In production, this would read the index from cache.
|
||||
// For now, we just signal success.
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeLoadIndex,
|
||||
Success: true,
|
||||
Data: nil,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *LoadIndexTask) Priority() Priority { return HighPriority }
|
||||
func (t *LoadIndexTask) TaskID() string { return t.taskID }
|
||||
func (t *LoadIndexTask) TaskType() TaskType { return TypeLoadIndex }
|
||||
func (t *LoadIndexTask) DirPath() string { return t.Dir }
|
||||
func (t *LoadIndexTask) Context() context.Context { return context.Background() }
|
||||
func (t *LoadIndexTask) Cancel() {}
|
||||
func (t *LoadIndexTask) Timeout() time.Duration { return 5 * time.Second }
|
||||
|
||||
// LoadPagesTask loads specific pages of directory entries from cache.
|
||||
type LoadPagesTask struct {
|
||||
taskID string
|
||||
Dir string
|
||||
PageIndices []int
|
||||
FS *mock.FileSystem
|
||||
}
|
||||
|
||||
func NewLoadPagesTask(dir string, pageIndices []int, fs *mock.FileSystem) *LoadPagesTask {
|
||||
return &LoadPagesTask{
|
||||
taskID: fmt.Sprintf("load_pages_%s_%d", filepath.Base(dir), taskCounter.Add(1)),
|
||||
Dir: dir,
|
||||
PageIndices: pageIndices,
|
||||
FS: fs,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *LoadPagesTask) Execute() Result {
|
||||
// In production, this would read pages from cache.
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeLoadPages,
|
||||
Success: true,
|
||||
Data: t.PageIndices,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *LoadPagesTask) Priority() Priority { return HighPriority }
|
||||
func (t *LoadPagesTask) TaskID() string { return t.taskID }
|
||||
func (t *LoadPagesTask) TaskType() TaskType { return TypeLoadPages }
|
||||
func (t *LoadPagesTask) DirPath() string { return t.Dir }
|
||||
func (t *LoadPagesTask) Context() context.Context { return context.Background() }
|
||||
func (t *LoadPagesTask) Cancel() {}
|
||||
func (t *LoadPagesTask) Timeout() time.Duration { return 5 * time.Second }
|
||||
|
||||
// StatDirTask gets directory metadata.
|
||||
type StatDirTask struct {
|
||||
taskID string
|
||||
Dir string
|
||||
FS *mock.FileSystem
|
||||
}
|
||||
|
||||
func NewStatDirTask(dir string, fs *mock.FileSystem) *StatDirTask {
|
||||
return &StatDirTask{
|
||||
taskID: fmt.Sprintf("stat_dir_%s_%d", filepath.Base(dir), taskCounter.Add(1)),
|
||||
Dir: dir,
|
||||
FS: fs,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *StatDirTask) Execute() Result {
|
||||
exists := t.FS.DirExists(t.Dir)
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeStatDir,
|
||||
Success: true,
|
||||
Data: map[string]bool{"exists": exists},
|
||||
}
|
||||
}
|
||||
|
||||
func (t *StatDirTask) Priority() Priority { return LowPriority }
|
||||
func (t *StatDirTask) TaskID() string { return t.taskID }
|
||||
func (t *StatDirTask) TaskType() TaskType { return TypeStatDir }
|
||||
func (t *StatDirTask) DirPath() string { return t.Dir }
|
||||
func (t *StatDirTask) Context() context.Context { return context.Background() }
|
||||
func (t *StatDirTask) Cancel() {}
|
||||
func (t *StatDirTask) Timeout() time.Duration { return 30 * time.Second }
|
||||
|
||||
// --- File Tasks ---
|
||||
|
||||
// ReadFileTask reads file content.
|
||||
type ReadFileTask struct {
|
||||
taskID string
|
||||
Path string
|
||||
FS *mock.FileSystem
|
||||
}
|
||||
|
||||
func NewReadFileTask(path string, fs *mock.FileSystem) *ReadFileTask {
|
||||
return &ReadFileTask{
|
||||
taskID: fmt.Sprintf("read_file_%s_%d", filepath.Base(path), taskCounter.Add(1)),
|
||||
Path: path,
|
||||
FS: fs,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ReadFileTask) Execute() Result {
|
||||
content, err := t.FS.ReadFile(t.Path)
|
||||
if err != nil {
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeReadFile,
|
||||
Success: false,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeReadFile,
|
||||
Success: true,
|
||||
Data: content,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *ReadFileTask) Priority() Priority { return HighPriority }
|
||||
func (t *ReadFileTask) TaskID() string { return t.taskID }
|
||||
func (t *ReadFileTask) TaskType() TaskType { return TypeReadFile }
|
||||
func (t *ReadFileTask) DirPath() string { return filepath.Dir(t.Path) }
|
||||
func (t *ReadFileTask) Context() context.Context { return context.Background() }
|
||||
func (t *ReadFileTask) Cancel() {}
|
||||
func (t *ReadFileTask) Timeout() time.Duration { return 5 * time.Second }
|
||||
|
||||
// WriteFileTask writes file content (auto-save).
|
||||
type WriteFileTask struct {
|
||||
taskID string
|
||||
Path string
|
||||
FS *mock.FileSystem
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func NewWriteFileTask(path string, data []byte, fs *mock.FileSystem) *WriteFileTask {
|
||||
return &WriteFileTask{
|
||||
taskID: fmt.Sprintf("write_file_%s_%d", filepath.Base(path), taskCounter.Add(1)),
|
||||
Path: path,
|
||||
FS: fs,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *WriteFileTask) Execute() Result {
|
||||
err := t.FS.WriteFile(t.Path, t.Data)
|
||||
if err != nil {
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeWriteFile,
|
||||
Success: false,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeWriteFile,
|
||||
Success: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *WriteFileTask) Priority() Priority { return LowPriority }
|
||||
func (t *WriteFileTask) TaskID() string { return t.taskID }
|
||||
func (t *WriteFileTask) TaskType() TaskType { return TypeWriteFile }
|
||||
func (t *WriteFileTask) DirPath() string { return filepath.Dir(t.Path) }
|
||||
func (t *WriteFileTask) Context() context.Context { return context.Background() }
|
||||
func (t *WriteFileTask) Cancel() {}
|
||||
func (t *WriteFileTask) Timeout() time.Duration { return 30 * time.Second }
|
||||
|
||||
// --- Cache Tasks ---
|
||||
|
||||
// WriteCacheTask writes cache data.
|
||||
type WriteCacheTask struct {
|
||||
taskID string
|
||||
Path string
|
||||
FS *mock.FileSystem
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func NewWriteCacheTask(path string, data []byte, fs *mock.FileSystem) *WriteCacheTask {
|
||||
return &WriteCacheTask{
|
||||
taskID: fmt.Sprintf("write_cache_%s_%d", filepath.Base(path), taskCounter.Add(1)),
|
||||
Path: path,
|
||||
FS: fs,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *WriteCacheTask) Execute() Result {
|
||||
err := t.FS.WriteFile(t.Path, t.Data)
|
||||
if err != nil {
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeWriteCache,
|
||||
Success: false,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeWriteCache,
|
||||
Success: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *WriteCacheTask) Priority() Priority { return LowPriority }
|
||||
func (t *WriteCacheTask) TaskID() string { return t.taskID }
|
||||
func (t *WriteCacheTask) TaskType() TaskType { return TypeWriteCache }
|
||||
func (t *WriteCacheTask) DirPath() string { return filepath.Dir(t.Path) }
|
||||
func (t *WriteCacheTask) Context() context.Context { return context.Background() }
|
||||
func (t *WriteCacheTask) Cancel() {}
|
||||
func (t *WriteCacheTask) Timeout() time.Duration { return 30 * time.Second }
|
||||
|
||||
// --- State Persistence Tasks ---
|
||||
|
||||
// SaveStateTask persists application state.
|
||||
type SaveStateTask struct {
|
||||
taskID string
|
||||
Path string
|
||||
FS *mock.FileSystem
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func NewSaveStateTask(path string, data []byte, fs *mock.FileSystem) *SaveStateTask {
|
||||
return &SaveStateTask{
|
||||
taskID: fmt.Sprintf("save_state_%s_%d", filepath.Base(path), taskCounter.Add(1)),
|
||||
Path: path,
|
||||
FS: fs,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *SaveStateTask) Execute() Result {
|
||||
err := t.FS.WriteFile(t.Path, t.Data)
|
||||
if err != nil {
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeSaveState,
|
||||
Success: false,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeSaveState,
|
||||
Success: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *SaveStateTask) Priority() Priority { return LowPriority }
|
||||
func (t *SaveStateTask) TaskID() string { return t.taskID }
|
||||
func (t *SaveStateTask) TaskType() TaskType { return TypeSaveState }
|
||||
func (t *SaveStateTask) DirPath() string { return filepath.Dir(t.Path) }
|
||||
func (t *SaveStateTask) Context() context.Context { return context.Background() }
|
||||
func (t *SaveStateTask) Cancel() {}
|
||||
func (t *SaveStateTask) Timeout() time.Duration { return 30 * time.Second }
|
||||
|
||||
// SaveUndoTask persists undo stack.
|
||||
type SaveUndoTask struct {
|
||||
taskID string
|
||||
Path string
|
||||
FS *mock.FileSystem
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func NewSaveUndoTask(path string, data []byte, fs *mock.FileSystem) *SaveUndoTask {
|
||||
return &SaveUndoTask{
|
||||
taskID: fmt.Sprintf("save_undo_%s_%d", filepath.Base(path), taskCounter.Add(1)),
|
||||
Path: path,
|
||||
FS: fs,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *SaveUndoTask) Execute() Result {
|
||||
err := t.FS.WriteFile(t.Path, t.Data)
|
||||
if err != nil {
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeSaveUndo,
|
||||
Success: false,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
return Result{
|
||||
TaskID: t.taskID,
|
||||
TaskType: TypeSaveUndo,
|
||||
Success: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *SaveUndoTask) Priority() Priority { return LowPriority }
|
||||
func (t *SaveUndoTask) TaskID() string { return t.taskID }
|
||||
func (t *SaveUndoTask) TaskType() TaskType { return TypeSaveUndo }
|
||||
func (t *SaveUndoTask) DirPath() string { return filepath.Dir(t.Path) }
|
||||
func (t *SaveUndoTask) Context() context.Context { return context.Background() }
|
||||
func (t *SaveUndoTask) Cancel() {}
|
||||
func (t *SaveUndoTask) Timeout() time.Duration { return 30 * time.Second }
|
||||
@@ -0,0 +1,406 @@
|
||||
package pool
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pad/internal/io/pool/mock"
|
||||
)
|
||||
|
||||
func TestReadDirTask_Execute_Success(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.CreateDir("/test/dir")
|
||||
fs.CreateFile("/test/dir/a.txt", []byte("a"))
|
||||
fs.CreateFile("/test/dir/b.txt", []byte("b"))
|
||||
|
||||
task := NewReadDirTask("/test/dir", fs)
|
||||
result := task.Execute()
|
||||
|
||||
if !result.IsSuccess() {
|
||||
t.Fatalf("Expected success, got error: %v", result.Error)
|
||||
}
|
||||
if result.TaskType != TypeReadDir {
|
||||
t.Errorf("TaskType = %v, want %v", result.TaskType, TypeReadDir)
|
||||
}
|
||||
if result.TaskID == "" {
|
||||
t.Error("TaskID should not be empty")
|
||||
}
|
||||
|
||||
entries, ok := result.Data.([]mock.DirEntry)
|
||||
if !ok {
|
||||
t.Fatalf("Data is not []mock.DirEntry, got %T", result.Data)
|
||||
}
|
||||
if len(entries) != 2 {
|
||||
t.Errorf("Expected 2 entries, got %d", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadDirTask_Execute_NotFound(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
|
||||
task := NewReadDirTask("/nonexistent", fs)
|
||||
result := task.Execute()
|
||||
|
||||
if result.IsSuccess() {
|
||||
t.Fatal("Expected failure for nonexistent directory")
|
||||
}
|
||||
if result.Error == nil {
|
||||
t.Error("Expected error, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildIndexTask_Execute(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.CreateDir("/test/dir")
|
||||
fs.CreateFile("/test/dir/file.txt", []byte("content"))
|
||||
|
||||
task := NewBuildIndexTask("/test/dir", fs)
|
||||
result := task.Execute()
|
||||
|
||||
if !result.IsSuccess() {
|
||||
t.Fatalf("Expected success, got error: %v", result.Error)
|
||||
}
|
||||
if result.TaskType != TypeBuildIndex {
|
||||
t.Errorf("TaskType = %v, want %v", result.TaskType, TypeBuildIndex)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadPagesTask_Execute(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
|
||||
task := NewLoadPagesTask("/test/dir", []int{0, 1, 2}, fs)
|
||||
result := task.Execute()
|
||||
|
||||
if !result.IsSuccess() {
|
||||
t.Fatalf("Expected success, got error: %v", result.Error)
|
||||
}
|
||||
if result.TaskType != TypeLoadPages {
|
||||
t.Errorf("TaskType = %v, want %v", result.TaskType, TypeLoadPages)
|
||||
}
|
||||
|
||||
pages, ok := result.Data.([]int)
|
||||
if !ok {
|
||||
t.Fatalf("Data is not []int, got %T", result.Data)
|
||||
}
|
||||
if len(pages) != 3 {
|
||||
t.Errorf("Expected 3 pages, got %d", len(pages))
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileTask_Execute_Success(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.CreateFile("/test/file.txt", []byte("hello world"))
|
||||
|
||||
task := NewReadFileTask("/test/file.txt", fs)
|
||||
result := task.Execute()
|
||||
|
||||
if !result.IsSuccess() {
|
||||
t.Fatalf("Expected success, got error: %v", result.Error)
|
||||
}
|
||||
if result.TaskType != TypeReadFile {
|
||||
t.Errorf("TaskType = %v, want %v", result.TaskType, TypeReadFile)
|
||||
}
|
||||
|
||||
content, ok := result.Data.([]byte)
|
||||
if !ok {
|
||||
t.Fatalf("Data is not []byte, got %T", result.Data)
|
||||
}
|
||||
if string(content) != "hello world" {
|
||||
t.Errorf("Content = %q, want %q", string(content), "hello world")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileTask_Execute_NotFound(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
|
||||
task := NewReadFileTask("/nonexistent.txt", fs)
|
||||
result := task.Execute()
|
||||
|
||||
if result.IsSuccess() {
|
||||
t.Fatal("Expected failure for nonexistent file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteFileTask_Execute(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.CreateFile("/test/file.txt", []byte("original"))
|
||||
|
||||
task := NewWriteFileTask("/test/file.txt", []byte("updated"), fs)
|
||||
result := task.Execute()
|
||||
|
||||
if !result.IsSuccess() {
|
||||
t.Fatalf("Expected success, got error: %v", result.Error)
|
||||
}
|
||||
if result.TaskType != TypeWriteFile {
|
||||
t.Errorf("TaskType = %v, want %v", result.TaskType, TypeWriteFile)
|
||||
}
|
||||
|
||||
// Verify file was actually written
|
||||
content, err := fs.ReadFile("/test/file.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile failed: %v", err)
|
||||
}
|
||||
if string(content) != "updated" {
|
||||
t.Errorf("File content = %q, want %q", string(content), "updated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteFileTask_Execute_NotFound(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
|
||||
task := NewWriteFileTask("/nonexistent.txt", []byte("data"), fs)
|
||||
result := task.Execute()
|
||||
|
||||
if result.IsSuccess() {
|
||||
t.Fatal("Expected failure for nonexistent file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveStateTask_Execute(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.CreateFile("/test/state.json", []byte("{}"))
|
||||
|
||||
task := NewSaveStateTask("/test/state.json", []byte(`{"key":"value"}`), fs)
|
||||
result := task.Execute()
|
||||
|
||||
if !result.IsSuccess() {
|
||||
t.Fatalf("Expected success, got error: %v", result.Error)
|
||||
}
|
||||
if result.TaskType != TypeSaveState {
|
||||
t.Errorf("TaskType = %v, want %v", result.TaskType, TypeSaveState)
|
||||
}
|
||||
|
||||
// Verify state was saved
|
||||
content, err := fs.ReadFile("/test/state.json")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile failed: %v", err)
|
||||
}
|
||||
if string(content) != `{"key":"value"}` {
|
||||
t.Errorf("State content = %q, want %q", string(content), `{"key":"value"}`)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveUndoTask_Execute(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.CreateFile("/test/undo.json", []byte("[]"))
|
||||
|
||||
task := NewSaveUndoTask("/test/undo.json", []byte(`[{"type":"insert"}]`), fs)
|
||||
result := task.Execute()
|
||||
|
||||
if !result.IsSuccess() {
|
||||
t.Fatalf("Expected success, got error: %v", result.Error)
|
||||
}
|
||||
if result.TaskType != TypeSaveUndo {
|
||||
t.Errorf("TaskType = %v, want %v", result.TaskType, TypeSaveUndo)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTask_Priority_ReadDir(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
task := NewReadDirTask("/test", fs)
|
||||
if task.Priority() != HighPriority {
|
||||
t.Errorf("Priority = %v, want %v", task.Priority(), HighPriority)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTask_Priority_BuildIndex(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
task := NewBuildIndexTask("/test", fs)
|
||||
if task.Priority() != HighPriority {
|
||||
t.Errorf("Priority = %v, want %v", task.Priority(), HighPriority)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTask_Priority_LoadPages(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
task := NewLoadPagesTask("/test", []int{0}, fs)
|
||||
if task.Priority() != HighPriority {
|
||||
t.Errorf("Priority = %v, want %v", task.Priority(), HighPriority)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTask_Priority_ReadFile(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
task := NewReadFileTask("/test/file.txt", fs)
|
||||
if task.Priority() != HighPriority {
|
||||
t.Errorf("Priority = %v, want %v", task.Priority(), HighPriority)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTask_Priority_WriteFile(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
task := NewWriteFileTask("/test/file.txt", []byte("data"), fs)
|
||||
if task.Priority() != LowPriority {
|
||||
t.Errorf("Priority = %v, want %v", task.Priority(), LowPriority)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTask_Priority_SaveState(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
task := NewSaveStateTask("/test/state.json", []byte("{}"), fs)
|
||||
if task.Priority() != LowPriority {
|
||||
t.Errorf("Priority = %v, want %v", task.Priority(), LowPriority)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTask_Priority_SaveUndo(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
task := NewSaveUndoTask("/test/undo.json", []byte("[]"), fs)
|
||||
if task.Priority() != LowPriority {
|
||||
t.Errorf("Priority = %v, want %v", task.Priority(), LowPriority)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTask_DirPath(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
|
||||
task := NewReadDirTask("/test/dir", fs)
|
||||
if task.DirPath() != "/test/dir" {
|
||||
t.Errorf("DirPath = %q, want %q", task.DirPath(), "/test/dir")
|
||||
}
|
||||
|
||||
task2 := NewReadFileTask("/test/dir/file.txt", fs)
|
||||
if task2.DirPath() != "/test/dir" {
|
||||
t.Errorf("DirPath = %q, want %q", task2.DirPath(), "/test/dir")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTask_TaskID_Unique(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
|
||||
task1 := NewReadDirTask("/test/dir", fs)
|
||||
task2 := NewReadDirTask("/test/dir", fs)
|
||||
|
||||
if task1.TaskID() == task2.TaskID() {
|
||||
t.Error("Task IDs should be unique")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTask_TaskType_String(t *testing.T) {
|
||||
tests := []struct {
|
||||
taskType TaskType
|
||||
want string
|
||||
}{
|
||||
{TypeReadDir, "read_dir"},
|
||||
{TypeBuildIndex, "build_index"},
|
||||
{TypeLoadIndex, "load_index"},
|
||||
{TypeLoadPages, "load_pages"},
|
||||
{TypeStatDir, "stat_dir"},
|
||||
{TypeReadFile, "read_file"},
|
||||
{TypeWriteFile, "write_file"},
|
||||
{TypeStatFile, "stat_file"},
|
||||
{TypeWriteCache, "write_cache"},
|
||||
{TypeReadCache, "read_cache"},
|
||||
{TypeInvalidate, "invalidate_cache"},
|
||||
{TypeSaveState, "save_state"},
|
||||
{TypeSaveUndo, "save_undo"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
if string(tt.taskType) != tt.want {
|
||||
t.Errorf("TaskType %v = %q, want %q", tt.taskType, string(tt.taskType), tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPriority_String(t *testing.T) {
|
||||
tests := []struct {
|
||||
priority Priority
|
||||
want string
|
||||
}{
|
||||
{HighPriority, "high"},
|
||||
{LowPriority, "low"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
if tt.priority.String() != tt.want {
|
||||
t.Errorf("Priority %v.String() = %q, want %q", tt.priority, tt.priority.String(), tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileTask_WithDelay(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.SetDelay(10 * time.Millisecond)
|
||||
fs.CreateFile("/test/delayed.txt", []byte("delayed"))
|
||||
|
||||
task := NewReadFileTask("/test/delayed.txt", fs)
|
||||
start := time.Now()
|
||||
result := task.Execute()
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if !result.IsSuccess() {
|
||||
t.Fatalf("Expected success, got error: %v", result.Error)
|
||||
}
|
||||
if elapsed < 5*time.Millisecond {
|
||||
t.Errorf("Expected delay ~10ms, got %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateFile_WithDelay(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.SetDelay(20 * time.Millisecond)
|
||||
|
||||
start := time.Now()
|
||||
err := fs.CreateFile("/test/delayed.txt", []byte("test"))
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("CreateFile failed: %v", err)
|
||||
}
|
||||
if elapsed < 15*time.Millisecond {
|
||||
t.Errorf("Expected delay ~20ms, got %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteFile_WithDelay(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.SetDelay(15 * time.Millisecond)
|
||||
fs.CreateFile("/test/delayed.txt", []byte("original"))
|
||||
|
||||
start := time.Now()
|
||||
err := fs.WriteFile("/test/delayed.txt", []byte("updated"))
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("WriteFile failed: %v", err)
|
||||
}
|
||||
if elapsed < 10*time.Millisecond {
|
||||
t.Errorf("Expected delay ~15ms, got %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteFile_WithDelay(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.SetDelay(10 * time.Millisecond)
|
||||
fs.CreateFile("/test/delayed.txt", []byte("test"))
|
||||
|
||||
start := time.Now()
|
||||
err := fs.DeleteFile("/test/delayed.txt")
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteFile failed: %v", err)
|
||||
}
|
||||
if elapsed < 5*time.Millisecond {
|
||||
t.Errorf("Expected delay ~10ms, got %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadDir_WithDelay(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.SetDelay(10 * time.Millisecond)
|
||||
fs.CreateDir("/test/dir")
|
||||
fs.CreateFile("/test/dir/a.txt", []byte("a"))
|
||||
|
||||
start := time.Now()
|
||||
_, err := fs.ReadDir("/test/dir")
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("ReadDir failed: %v", err)
|
||||
}
|
||||
if elapsed < 5*time.Millisecond {
|
||||
t.Errorf("Expected delay ~10ms, got %v", elapsed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
package pool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// WorkerPool manages a pool of worker goroutines that execute IO tasks.
|
||||
// It follows the architecture's single-owner pattern:
|
||||
// - Logic goroutine dispatches tasks on highWorkChan/lowWorkChan
|
||||
// - Workers execute tasks and post results on resultChan
|
||||
// - Workers never access state directly
|
||||
type WorkerPool struct {
|
||||
highWorkChan chan Task
|
||||
lowWorkChan chan Task
|
||||
resultChan chan Result
|
||||
workerCount int
|
||||
stopOnce sync.Once
|
||||
stopChan chan struct{}
|
||||
wg sync.WaitGroup
|
||||
taskCounter atomic.Int64
|
||||
running atomic.Bool
|
||||
|
||||
// pendingTasks tracks in-flight tasks for cancellation by directory.
|
||||
pendingTasks map[string][]Task
|
||||
pendingMu sync.Mutex
|
||||
}
|
||||
|
||||
// NewWorkerPool creates a new worker pool with the given number of workers.
|
||||
// Buffered channels prevent blocking when all workers are busy.
|
||||
func NewWorkerPool(workerCount int) *WorkerPool {
|
||||
if workerCount <= 0 {
|
||||
workerCount = 4
|
||||
}
|
||||
|
||||
return &WorkerPool{
|
||||
highWorkChan: make(chan Task, workerCount*2),
|
||||
lowWorkChan: make(chan Task, workerCount*2),
|
||||
resultChan: make(chan Result, workerCount*4),
|
||||
workerCount: workerCount,
|
||||
stopChan: make(chan struct{}),
|
||||
pendingTasks: make(map[string][]Task),
|
||||
}
|
||||
}
|
||||
|
||||
// Start begins processing tasks. Workers are started immediately.
|
||||
func (wp *WorkerPool) Start() {
|
||||
if wp.running.Swap(true) {
|
||||
return // Already started
|
||||
}
|
||||
|
||||
for i := 0; i < wp.workerCount; i++ {
|
||||
wp.wg.Add(1)
|
||||
go wp.worker(i)
|
||||
}
|
||||
}
|
||||
|
||||
// Stop gracefully shuts down the worker pool.
|
||||
// All in-flight tasks are completed before shutdown.
|
||||
func (wp *WorkerPool) Stop() {
|
||||
wp.stopOnce.Do(func() {
|
||||
wp.running.Store(false)
|
||||
close(wp.stopChan)
|
||||
// Close work channels so drain() can complete
|
||||
close(wp.highWorkChan)
|
||||
close(wp.lowWorkChan)
|
||||
// Wait for workers to finish draining
|
||||
wp.wg.Wait()
|
||||
close(wp.resultChan)
|
||||
})
|
||||
}
|
||||
|
||||
// Dispatch submits a task to the worker pool.
|
||||
// It blocks if the work channel is full (buffered to pool size).
|
||||
//
|
||||
// Use this for UI-critical tasks where the result is required for correctness.
|
||||
// The logic goroutine must expect exactly one result for every dispatched task.
|
||||
// Results are never dropped: the worker blocks until the logic goroutine
|
||||
// consumes the result from resultChan.
|
||||
func (wp *WorkerPool) Dispatch(task Task) {
|
||||
wp.taskCounter.Add(1)
|
||||
|
||||
// Track pending task for cancellation
|
||||
wp.trackPending(task)
|
||||
|
||||
if task.Priority() == HighPriority {
|
||||
wp.highWorkChan <- task
|
||||
} else {
|
||||
wp.lowWorkChan <- task
|
||||
}
|
||||
}
|
||||
|
||||
// DispatchNonBlocking attempts to submit a task without blocking.
|
||||
// Returns false if the channel is full, in which case the task is silently dropped.
|
||||
//
|
||||
// Use this ONLY for fire-and-forget background tasks that can be retried later
|
||||
// (e.g., auto-save, undo persistence, cache writes). The task is idempotent and
|
||||
// the application does not depend on receiving a result.
|
||||
//
|
||||
// CRITICAL: Do not use this for tasks where the logic goroutine waits for a
|
||||
// specific result. If the task is dropped, the logic goroutine will wait forever
|
||||
// for a result that will never arrive, causing a livelock.
|
||||
func (wp *WorkerPool) DispatchNonBlocking(task Task) bool {
|
||||
wp.taskCounter.Add(1)
|
||||
|
||||
if task.Priority() == HighPriority {
|
||||
select {
|
||||
case wp.highWorkChan <- task:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
select {
|
||||
case wp.lowWorkChan <- task:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WorkerID returns the number of workers in the pool.
|
||||
func (wp *WorkerPool) WorkerCount() int {
|
||||
return wp.workerCount
|
||||
}
|
||||
|
||||
// IsRunning returns true if the pool is currently running.
|
||||
func (wp *WorkerPool) IsRunning() bool {
|
||||
return wp.running.Load()
|
||||
}
|
||||
|
||||
// TaskCount returns the total number of tasks dispatched.
|
||||
func (wp *WorkerPool) TaskCount() int64 {
|
||||
return wp.taskCounter.Load()
|
||||
}
|
||||
|
||||
// ResultChan returns the result channel for the logic goroutine to consume
|
||||
// results from completed tasks.
|
||||
func (wp *WorkerPool) ResultChan() <-chan Result {
|
||||
return wp.resultChan
|
||||
}
|
||||
|
||||
// worker is the main loop for each worker goroutine.
|
||||
// It prioritizes high-priority tasks over low-priority tasks.
|
||||
func (wp *WorkerPool) worker(id int) {
|
||||
defer wp.wg.Done()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-wp.stopChan:
|
||||
// Drain remaining work before exiting
|
||||
wp.drain(wp.highWorkChan)
|
||||
wp.drain(wp.lowWorkChan)
|
||||
return
|
||||
|
||||
case task, ok := <-wp.highWorkChan:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
continue
|
||||
}
|
||||
result := wp.execute(task)
|
||||
wp.post(result)
|
||||
|
||||
default:
|
||||
// No high-priority work; check low-priority
|
||||
select {
|
||||
case <-wp.stopChan:
|
||||
// Drain remaining work before exiting
|
||||
wp.drain(wp.highWorkChan)
|
||||
wp.drain(wp.lowWorkChan)
|
||||
return
|
||||
|
||||
case task, ok := <-wp.highWorkChan:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
continue
|
||||
}
|
||||
result := wp.execute(task)
|
||||
wp.post(result)
|
||||
|
||||
case task, ok := <-wp.lowWorkChan:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
continue
|
||||
}
|
||||
result := wp.execute(task)
|
||||
wp.post(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// drain processes all remaining tasks in a channel before shutdown.
|
||||
func (wp *WorkerPool) drain(ch chan Task) {
|
||||
for task := range ch {
|
||||
result := wp.execute(task)
|
||||
wp.post(result)
|
||||
}
|
||||
}
|
||||
|
||||
// execute runs a task with timeout enforcement and captures timing information.
|
||||
func (wp *WorkerPool) execute(task Task) Result {
|
||||
start := time.Now()
|
||||
|
||||
// Apply timeout if specified
|
||||
ctx := task.Context()
|
||||
var cancel context.CancelFunc
|
||||
if timeout := task.Timeout(); timeout > 0 {
|
||||
ctx, cancel = context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
// Set the timeout context on the task if it supports it
|
||||
if setter, ok := task.(interface{ SetContext(context.Context) }); ok {
|
||||
setter.SetContext(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// Execute the task with timeout enforcement
|
||||
result := wp.executeWithTimeout(task, ctx)
|
||||
result.Timestamp = start.Add(time.Since(start))
|
||||
|
||||
// Set DirPath from the task
|
||||
result.DirPath = task.DirPath()
|
||||
|
||||
// Remove from pending tasks
|
||||
wp.untrackPending(task)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// executeWithTimeout runs a task with timeout enforcement.
|
||||
// If the task exceeds its timeout, it returns a timeout error.
|
||||
func (wp *WorkerPool) executeWithTimeout(task Task, ctx context.Context) Result {
|
||||
// Channel to receive the result
|
||||
resultChan := make(chan Result, 1)
|
||||
|
||||
// Run the task in a goroutine
|
||||
go func() {
|
||||
resultChan <- task.Execute()
|
||||
}()
|
||||
|
||||
// Wait for either the result or the context to be done
|
||||
select {
|
||||
case result := <-resultChan:
|
||||
return result
|
||||
case <-ctx.Done():
|
||||
// Task exceeded its timeout or was cancelled
|
||||
return Result{
|
||||
TaskID: task.TaskID(),
|
||||
TaskType: task.TaskType(),
|
||||
Success: false,
|
||||
Error: ctx.Err(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// post sends a result to the result channel.
|
||||
// Blocking: waits for the logic goroutine to drain the channel.
|
||||
// Results are never dropped to ensure every dispatched task produces exactly one result.
|
||||
func (wp *WorkerPool) post(result Result) {
|
||||
wp.resultChan <- result
|
||||
}
|
||||
|
||||
// CancelPendingTasks cancels all pending tasks for the given directory path.
|
||||
// This is useful when the user navigates away from a directory and pending
|
||||
// load operations should be cancelled.
|
||||
func (wp *WorkerPool) CancelPendingTasks(dirPath string) {
|
||||
wp.pendingMu.Lock()
|
||||
defer wp.pendingMu.Unlock()
|
||||
|
||||
tasks, ok := wp.pendingTasks[dirPath]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Cancel all pending tasks for this directory
|
||||
for _, task := range tasks {
|
||||
task.Cancel()
|
||||
}
|
||||
|
||||
// Remove the entry
|
||||
delete(wp.pendingTasks, dirPath)
|
||||
}
|
||||
|
||||
// trackPending adds a task to the pending tasks map for cancellation tracking.
|
||||
func (wp *WorkerPool) trackPending(task Task) {
|
||||
wp.pendingMu.Lock()
|
||||
defer wp.pendingMu.Unlock()
|
||||
|
||||
dirPath := task.DirPath()
|
||||
if dirPath == "" {
|
||||
return
|
||||
}
|
||||
|
||||
wp.pendingTasks[dirPath] = append(wp.pendingTasks[dirPath], task)
|
||||
}
|
||||
|
||||
// untrackPending removes a task from the pending tasks map.
|
||||
func (wp *WorkerPool) untrackPending(task Task) {
|
||||
wp.pendingMu.Lock()
|
||||
defer wp.pendingMu.Unlock()
|
||||
|
||||
dirPath := task.DirPath()
|
||||
tasks, ok := wp.pendingTasks[dirPath]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Remove the task from the list
|
||||
for i, t := range tasks {
|
||||
if t.TaskID() == task.TaskID() {
|
||||
wp.pendingTasks[dirPath] = append(tasks[:i], tasks[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// taskWrapper adds an ID to a task for tracking results.
|
||||
type taskWrapper struct {
|
||||
id int64
|
||||
original Task
|
||||
}
|
||||
|
||||
func (tw *taskWrapper) Execute() Result {
|
||||
return tw.original.Execute()
|
||||
}
|
||||
|
||||
func (tw *taskWrapper) Priority() Priority {
|
||||
return tw.original.Priority()
|
||||
}
|
||||
|
||||
func (tw *taskWrapper) TaskID() string {
|
||||
return tw.original.TaskID()
|
||||
}
|
||||
|
||||
func (tw *taskWrapper) TaskType() TaskType {
|
||||
return tw.original.TaskType()
|
||||
}
|
||||
|
||||
func (tw *taskWrapper) DirPath() string {
|
||||
return tw.original.DirPath()
|
||||
}
|
||||
@@ -0,0 +1,772 @@
|
||||
package pool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pad/internal/io/pool/mock"
|
||||
)
|
||||
|
||||
// stubTask is a minimal task implementation for testing the worker pool.
|
||||
type stubTask struct {
|
||||
id string
|
||||
taskType TaskType
|
||||
priority Priority
|
||||
data any
|
||||
err error
|
||||
execute func() (any, error)
|
||||
}
|
||||
|
||||
func (t *stubTask) Execute() Result {
|
||||
if t.execute != nil {
|
||||
data, err := t.execute()
|
||||
return Result{
|
||||
TaskID: t.id,
|
||||
TaskType: t.taskType,
|
||||
Success: err == nil,
|
||||
Data: data,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
return Result{
|
||||
TaskID: t.id,
|
||||
TaskType: t.taskType,
|
||||
Success: t.err == nil,
|
||||
Data: t.data,
|
||||
Error: t.err,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *stubTask) Priority() Priority { return t.priority }
|
||||
func (t *stubTask) TaskID() string { return t.id }
|
||||
func (t *stubTask) TaskType() TaskType { return t.taskType }
|
||||
func (t *stubTask) DirPath() string { return "" }
|
||||
func (t *stubTask) Context() context.Context { return context.Background() }
|
||||
func (t *stubTask) Cancel() {}
|
||||
func (t *stubTask) Timeout() time.Duration { return 5 * time.Second }
|
||||
|
||||
func TestWorkerPool_StartStop(t *testing.T) {
|
||||
pool := NewWorkerPool(4)
|
||||
pool.Start()
|
||||
|
||||
if !pool.IsRunning() {
|
||||
t.Error("Pool should be running after Start()")
|
||||
}
|
||||
|
||||
pool.Stop()
|
||||
|
||||
if pool.IsRunning() {
|
||||
t.Error("Pool should not be running after Stop()")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_StartMultiple(t *testing.T) {
|
||||
pool := NewWorkerPool(4)
|
||||
pool.Start()
|
||||
pool.Start() // Should be a no-op
|
||||
pool.Start() // Should be a no-op
|
||||
|
||||
if pool.WorkerCount() != 4 {
|
||||
t.Errorf("WorkerCount = %d, want 4", pool.WorkerCount())
|
||||
}
|
||||
|
||||
pool.Stop()
|
||||
}
|
||||
|
||||
func TestWorkerPool_StopMultiple(t *testing.T) {
|
||||
pool := NewWorkerPool(4)
|
||||
pool.Start()
|
||||
pool.Stop()
|
||||
pool.Stop() // Should be a no-op (stopOnce)
|
||||
pool.Stop() // Should be a no-op
|
||||
|
||||
if pool.IsRunning() {
|
||||
t.Error("Pool should not be running after Stop()")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_DispatchHighPriority(t *testing.T) {
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
task := &stubTask{
|
||||
id: "test-high",
|
||||
taskType: TypeReadFile,
|
||||
priority: HighPriority,
|
||||
data: "result",
|
||||
}
|
||||
|
||||
pool.Dispatch(task)
|
||||
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
if result.TaskID != "test-high" {
|
||||
t.Errorf("Result TaskID = %q, want %q", result.TaskID, "test-high")
|
||||
}
|
||||
if !result.IsSuccess() {
|
||||
t.Errorf("Result should be successful, got error: %v", result.Error)
|
||||
}
|
||||
if result.Data != "result" {
|
||||
t.Errorf("Result.Data = %v, want %v", result.Data, "result")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Timed out waiting for result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_DispatchLowPriority(t *testing.T) {
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
task := &stubTask{
|
||||
id: "test-low",
|
||||
taskType: TypeSaveState,
|
||||
priority: LowPriority,
|
||||
data: "saved",
|
||||
}
|
||||
|
||||
pool.Dispatch(task)
|
||||
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
if result.TaskID != "test-low" {
|
||||
t.Errorf("Result TaskID = %q, want %q", result.TaskID, "test-low")
|
||||
}
|
||||
if !result.IsSuccess() {
|
||||
t.Errorf("Result should be successful, got error: %v", result.Error)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Timed out waiting for result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_PriorityPreemption(t *testing.T) {
|
||||
// Use 1 worker to force serialization
|
||||
pool := NewWorkerPool(1)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
var lowExecuted atomic.Bool
|
||||
var highExecuted atomic.Bool
|
||||
|
||||
// Low priority task that takes time
|
||||
lowTask := &stubTask{
|
||||
id: "low",
|
||||
taskType: TypeSaveState,
|
||||
priority: LowPriority,
|
||||
execute: func() (any, error) {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
lowExecuted.Store(true)
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
|
||||
// High priority task that completes quickly
|
||||
highTask := &stubTask{
|
||||
id: "high",
|
||||
taskType: TypeReadFile,
|
||||
priority: HighPriority,
|
||||
execute: func() (any, error) {
|
||||
highExecuted.Store(true)
|
||||
return "fast", nil
|
||||
},
|
||||
}
|
||||
|
||||
// Dispatch low priority first
|
||||
pool.Dispatch(lowTask)
|
||||
|
||||
// Immediately dispatch high priority
|
||||
pool.Dispatch(highTask)
|
||||
|
||||
// Wait for high priority result (should complete before low)
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
if result.TaskID != "high" {
|
||||
t.Errorf("First result TaskID = %q, want %q", result.TaskID, "high")
|
||||
}
|
||||
if !highExecuted.Load() {
|
||||
t.Error("High priority task should have executed first")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Timed out waiting for high priority result")
|
||||
}
|
||||
|
||||
// Wait for low priority result
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
if result.TaskID != "low" {
|
||||
t.Errorf("Second result TaskID = %q, want %q", result.TaskID, "low")
|
||||
}
|
||||
if !lowExecuted.Load() {
|
||||
t.Error("Low priority task should have executed second")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Timed out waiting for low priority result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ResultOrderHighPriority(t *testing.T) {
|
||||
// Use 1 worker to force serialization
|
||||
pool := NewWorkerPool(1)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
taskCount := 5
|
||||
var results []string
|
||||
var mu sync.Mutex
|
||||
|
||||
for i := 0; i < taskCount; i++ {
|
||||
task := &stubTask{
|
||||
id: fmt.Sprintf("high-%d", i),
|
||||
taskType: TypeReadFile,
|
||||
priority: HighPriority,
|
||||
}
|
||||
pool.Dispatch(task)
|
||||
}
|
||||
|
||||
for i := 0; i < taskCount; i++ {
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
mu.Lock()
|
||||
results = append(results, result.TaskID)
|
||||
mu.Unlock()
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("Timed out waiting for result %d", i)
|
||||
}
|
||||
}
|
||||
|
||||
if len(results) != taskCount {
|
||||
t.Errorf("Got %d results, want %d", len(results), taskCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ResultOrderMixedPriority(t *testing.T) {
|
||||
// Use 1 worker to force serialization
|
||||
pool := NewWorkerPool(1)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// Dispatch 3 low priority tasks first
|
||||
for i := 0; i < 3; i++ {
|
||||
task := &stubTask{
|
||||
id: fmt.Sprintf("low-%d", i),
|
||||
taskType: TypeSaveState,
|
||||
priority: LowPriority,
|
||||
}
|
||||
pool.Dispatch(task)
|
||||
}
|
||||
|
||||
// Dispatch 2 high priority tasks
|
||||
for i := 0; i < 2; i++ {
|
||||
task := &stubTask{
|
||||
id: fmt.Sprintf("high-%d", i),
|
||||
taskType: TypeReadFile,
|
||||
priority: HighPriority,
|
||||
}
|
||||
pool.Dispatch(task)
|
||||
}
|
||||
|
||||
// Collect results in order
|
||||
var results []string
|
||||
var mu sync.Mutex
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
mu.Lock()
|
||||
results = append(results, result.TaskID)
|
||||
mu.Unlock()
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("Timed out waiting for result %d", i)
|
||||
}
|
||||
}
|
||||
|
||||
// High priority tasks should complete before low priority ones
|
||||
// (they are dispatched to highWorkChan which is checked first)
|
||||
if len(results) != 5 {
|
||||
t.Errorf("Got %d results, want 5", len(results))
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_DispatchNonBlocking(t *testing.T) {
|
||||
pool := NewWorkerPool(1)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// First dispatch should succeed
|
||||
task1 := &stubTask{
|
||||
id: "test-1",
|
||||
taskType: TypeReadFile,
|
||||
priority: HighPriority,
|
||||
}
|
||||
if !pool.DispatchNonBlocking(task1) {
|
||||
t.Error("First DispatchNonBlocking should succeed")
|
||||
}
|
||||
|
||||
// Collect the result
|
||||
select {
|
||||
case <-pool.resultChan:
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("Timed out waiting for first result")
|
||||
}
|
||||
|
||||
// Second dispatch should also succeed
|
||||
task2 := &stubTask{
|
||||
id: "test-2",
|
||||
taskType: TypeReadFile,
|
||||
priority: HighPriority,
|
||||
}
|
||||
if !pool.DispatchNonBlocking(task2) {
|
||||
t.Error("Second DispatchNonBlocking should succeed")
|
||||
}
|
||||
|
||||
// Collect the result
|
||||
select {
|
||||
case <-pool.resultChan:
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("Timed out waiting for second result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_TaskCounter(t *testing.T) {
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
task := &stubTask{
|
||||
id: fmt.Sprintf("test-%d", i),
|
||||
taskType: TypeReadFile,
|
||||
priority: HighPriority,
|
||||
}
|
||||
pool.Dispatch(task)
|
||||
}
|
||||
|
||||
if pool.TaskCount() != 10 {
|
||||
t.Errorf("TaskCount = %d, want 10", pool.TaskCount())
|
||||
}
|
||||
|
||||
// Collect all results
|
||||
for i := 0; i < 10; i++ {
|
||||
select {
|
||||
case <-pool.resultChan:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("Timed out waiting for result %d", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ConcurrentDispatch(t *testing.T) {
|
||||
pool := NewWorkerPool(4)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
// Result channel buffer = workerCount * 4 = 16
|
||||
// Use fewer tasks to avoid dropped results
|
||||
taskCount := 16
|
||||
|
||||
for i := 0; i < taskCount; i++ {
|
||||
wg.Add(1)
|
||||
go func(n int) {
|
||||
defer wg.Done()
|
||||
task := &stubTask{
|
||||
id: fmt.Sprintf("concurrent-%d", n),
|
||||
taskType: TypeReadFile,
|
||||
priority: HighPriority,
|
||||
}
|
||||
pool.Dispatch(task)
|
||||
}(i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
if pool.TaskCount() != int64(taskCount) {
|
||||
t.Errorf("TaskCount = %d, want %d", pool.TaskCount(), taskCount)
|
||||
}
|
||||
|
||||
// Collect all results
|
||||
for i := 0; i < taskCount; i++ {
|
||||
select {
|
||||
case <-pool.resultChan:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("Timed out waiting for result %d", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_GracefulShutdown(t *testing.T) {
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
|
||||
var completed atomic.Int64
|
||||
|
||||
// Dispatch tasks that take time
|
||||
for i := 0; i < 5; i++ {
|
||||
task := &stubTask{
|
||||
id: fmt.Sprintf("shutdown-%d", i),
|
||||
taskType: TypeReadFile,
|
||||
priority: HighPriority,
|
||||
execute: func() (any, error) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
completed.Add(1)
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
pool.Dispatch(task)
|
||||
}
|
||||
|
||||
// Stop the pool (should wait for in-flight tasks)
|
||||
pool.Stop()
|
||||
|
||||
// All tasks should have completed
|
||||
if completed.Load() != 5 {
|
||||
t.Errorf("Completed = %d, want 5", completed.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ResultWithRealTasks(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.CreateFile("/test/file.txt", []byte("content"))
|
||||
fs.CreateDir("/test/dir")
|
||||
fs.CreateFile("/test/dir/a.txt", []byte("a"))
|
||||
fs.CreateFile("/test/dir/b.txt", []byte("b"))
|
||||
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// Read file task
|
||||
readTask := NewReadFileTask("/test/file.txt", fs)
|
||||
pool.Dispatch(readTask)
|
||||
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
if !result.IsSuccess() {
|
||||
t.Errorf("ReadFile task failed: %v", result.Error)
|
||||
}
|
||||
content, ok := result.Data.([]byte)
|
||||
if !ok {
|
||||
t.Fatalf("Result data is not []byte, got %T", result.Data)
|
||||
}
|
||||
if string(content) != "content" {
|
||||
t.Errorf("Content = %q, want %q", string(content), "content")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Timed out waiting for read file result")
|
||||
}
|
||||
|
||||
// Read dir task
|
||||
readDirTask := NewReadDirTask("/test/dir", fs)
|
||||
pool.Dispatch(readDirTask)
|
||||
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
if !result.IsSuccess() {
|
||||
t.Errorf("ReadDir task failed: %v", result.Error)
|
||||
}
|
||||
entries, ok := result.Data.([]mock.DirEntry)
|
||||
if !ok {
|
||||
t.Fatalf("Result data is not []mock.DirEntry, got %T", result.Data)
|
||||
}
|
||||
if len(entries) != 2 {
|
||||
t.Errorf("Entries count = %d, want 2", len(entries))
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Timed out waiting for read dir result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ResultWithRealTasksAndDelay(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
fs.SetDelay(20 * time.Millisecond)
|
||||
fs.CreateFile("/test/delayed.txt", []byte("delayed"))
|
||||
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
task := NewReadFileTask("/test/delayed.txt", fs)
|
||||
start := time.Now()
|
||||
pool.Dispatch(task)
|
||||
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
elapsed := time.Since(start)
|
||||
if !result.IsSuccess() {
|
||||
t.Errorf("ReadFile task failed: %v", result.Error)
|
||||
}
|
||||
if elapsed < 15*time.Millisecond {
|
||||
t.Errorf("Expected delay ~20ms, got %v", elapsed)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Timed out waiting for delayed result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_OnlyHighPriority(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
// Create all files upfront
|
||||
for i := 0; i < 5; i++ {
|
||||
fs.CreateFile(fmt.Sprintf("/test/file%d.txt", i), []byte(fmt.Sprintf("file%d", i)))
|
||||
}
|
||||
fs.CreateFile("/test/state.json", []byte("{}"))
|
||||
|
||||
pool := NewWorkerPool(2)
|
||||
pool.Start()
|
||||
defer pool.Stop()
|
||||
|
||||
// Only dispatch high priority tasks
|
||||
for i := 0; i < 5; i++ {
|
||||
task := NewReadFileTask(fmt.Sprintf("/test/file%d.txt", i), fs)
|
||||
pool.Dispatch(task)
|
||||
}
|
||||
|
||||
// Dispatch a low priority task
|
||||
saveTask := NewSaveStateTask("/test/state.json", []byte("{}"), fs)
|
||||
pool.Dispatch(saveTask)
|
||||
|
||||
// Collect results - high priority should complete first
|
||||
for i := 0; i < 6; i++ {
|
||||
select {
|
||||
case result := <-pool.resultChan:
|
||||
// Just verify we got results
|
||||
if !result.IsSuccess() {
|
||||
t.Errorf("Result %d failed: %v", i, result.Error)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("Timed out waiting for result %d", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ChangeEvents(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
ch := make(chan mock.FileChangeEvent, 10)
|
||||
fs.SetChangeEvents(ch)
|
||||
|
||||
fs.CreateFile("/test/notify.txt", []byte("data"))
|
||||
|
||||
select {
|
||||
case event := <-ch:
|
||||
if event.Path != "/test/notify.txt" {
|
||||
t.Errorf("Event path = %q, want %q", event.Path, "/test/notify.txt")
|
||||
}
|
||||
if event.EventType != "Created" {
|
||||
t.Errorf("Event type = %q, want %q", event.EventType, "Created")
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Fatal("Expected change event, got none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ChangeEventsOnModify(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
ch := make(chan mock.FileChangeEvent, 10)
|
||||
fs.SetChangeEvents(ch)
|
||||
|
||||
fs.CreateFile("/test/modify.txt", []byte("original"))
|
||||
|
||||
// Consume the "Created" event
|
||||
<-ch
|
||||
|
||||
// Modify the file
|
||||
fs.WriteFile("/test/modify.txt", []byte("modified"))
|
||||
|
||||
select {
|
||||
case event := <-ch:
|
||||
if event.EventType != "Modified" {
|
||||
t.Errorf("Event type = %q, want %q", event.EventType, "Modified")
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Fatal("Expected modified event, got none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ChangeEventsOnDelete(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
ch := make(chan mock.FileChangeEvent, 10)
|
||||
fs.SetChangeEvents(ch)
|
||||
|
||||
fs.CreateFile("/test/delete.txt", []byte("data"))
|
||||
|
||||
// Consume the "Created" event
|
||||
<-ch
|
||||
|
||||
// Delete the file
|
||||
fs.DeleteFile("/test/delete.txt")
|
||||
|
||||
select {
|
||||
case event := <-ch:
|
||||
if event.EventType != "Deleted" {
|
||||
t.Errorf("Event type = %q, want %q", event.EventType, "Deleted")
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Fatal("Expected deleted event, got none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ChangeEventsOnDirCreate(t *testing.T) {
|
||||
fs := mock.NewFileSystem()
|
||||
ch := make(chan mock.FileChangeEvent, 10)
|
||||
fs.SetChangeEvents(ch)
|
||||
|
||||
fs.CreateDir("/test/newdir")
|
||||
|
||||
select {
|
||||
case event := <-ch:
|
||||
if event.EventType != "Created" {
|
||||
t.Errorf("Event type = %q, want %q", event.EventType, "Created")
|
||||
}
|
||||
if !fs.DirExists("/test/newdir") {
|
||||
t.Error("Directory should exist after create")
|
||||
}
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
t.Fatal("Expected created event, got none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ResultIsSuccess(t *testing.T) {
|
||||
result := Result{
|
||||
TaskID: "test",
|
||||
Success: true,
|
||||
}
|
||||
if !result.IsSuccess() {
|
||||
t.Error("Result should be successful")
|
||||
}
|
||||
|
||||
result2 := Result{
|
||||
TaskID: "test",
|
||||
Success: false,
|
||||
Error: fmt.Errorf("error"),
|
||||
}
|
||||
if result2.IsSuccess() {
|
||||
t.Error("Result should not be successful")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ResultIsError(t *testing.T) {
|
||||
result := Result{
|
||||
TaskID: "test",
|
||||
Success: false,
|
||||
Error: fmt.Errorf("error"),
|
||||
}
|
||||
if !result.IsError() {
|
||||
t.Error("Result should have error")
|
||||
}
|
||||
|
||||
result2 := Result{
|
||||
TaskID: "test",
|
||||
Success: true,
|
||||
}
|
||||
if result2.IsError() {
|
||||
t.Error("Result should not have error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ResultIsBrowserResult(t *testing.T) {
|
||||
tests := []struct {
|
||||
taskType TaskType
|
||||
want bool
|
||||
}{
|
||||
{TypeReadDir, true},
|
||||
{TypeBuildIndex, true},
|
||||
{TypeLoadIndex, true},
|
||||
{TypeLoadPages, true},
|
||||
{TypeStatDir, true},
|
||||
{TypeReadFile, false},
|
||||
{TypeWriteFile, false},
|
||||
{TypeSaveState, false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
result := Result{TaskType: tt.taskType}
|
||||
if result.IsBrowserResult() != tt.want {
|
||||
t.Errorf("Result.TaskType=%v IsBrowserResult()=%v, want %v",
|
||||
tt.taskType, result.IsBrowserResult(), tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ResultIsFileResult(t *testing.T) {
|
||||
tests := []struct {
|
||||
taskType TaskType
|
||||
want bool
|
||||
}{
|
||||
{TypeReadFile, true},
|
||||
{TypeWriteFile, true},
|
||||
{TypeStatFile, true},
|
||||
{TypeReadDir, false},
|
||||
{TypeBuildIndex, false},
|
||||
{TypeSaveState, false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
result := Result{TaskType: tt.taskType}
|
||||
if result.IsFileResult() != tt.want {
|
||||
t.Errorf("Result.TaskType=%v IsFileResult()=%v, want %v",
|
||||
tt.taskType, result.IsFileResult(), tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ResultIsCacheResult(t *testing.T) {
|
||||
tests := []struct {
|
||||
taskType TaskType
|
||||
want bool
|
||||
}{
|
||||
{TypeWriteCache, true},
|
||||
{TypeReadCache, true},
|
||||
{TypeInvalidate, true},
|
||||
{TypeReadFile, false},
|
||||
{TypeSaveState, false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
result := Result{TaskType: tt.taskType}
|
||||
if result.IsCacheResult() != tt.want {
|
||||
t.Errorf("Result.TaskType=%v IsCacheResult()=%v, want %v",
|
||||
tt.taskType, result.IsCacheResult(), tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_ResultIsStateResult(t *testing.T) {
|
||||
tests := []struct {
|
||||
taskType TaskType
|
||||
want bool
|
||||
}{
|
||||
{TypeSaveState, true},
|
||||
{TypeSaveUndo, true},
|
||||
{TypeReadFile, false},
|
||||
{TypeBuildIndex, false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
result := Result{TaskType: tt.taskType}
|
||||
if result.IsStateResult() != tt.want {
|
||||
t.Errorf("Result.TaskType=%v IsStateResult()=%v, want %v",
|
||||
tt.taskType, result.IsStateResult(), tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_DefaultWorkerCount(t *testing.T) {
|
||||
pool := NewWorkerPool(0)
|
||||
if pool.WorkerCount() != 4 {
|
||||
t.Errorf("WorkerCount = %d, want 4 (default)", pool.WorkerCount())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool_NegativeWorkerCount(t *testing.T) {
|
||||
pool := NewWorkerPool(-1)
|
||||
if pool.WorkerCount() != 4 {
|
||||
t.Errorf("WorkerCount = %d, want 4 (default)", pool.WorkerCount())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user