Fix deadlock when opening files and update E2E tests

This commit is contained in:
gmp
2026-06-04 13:06:30 -04:00
parent d06f8af0f7
commit ca828569f7
13 changed files with 617 additions and 97 deletions
+76
View File
@@ -0,0 +1,76 @@
package editor
import (
"log"
"testing"
"time"
"pad/internal/io/pool"
)
// TestWriteFailureTracking verifies that a write failure updates WriteFailed status
func TestWriteFailureTracking(t *testing.T) {
state := NewState()
filename := "test.txt"
state.Editor.Filename = filename
// Simulate a write failure
state.Editor.SetWriteFailed(filename, true)
if !state.Editor.WriteFailed() {
t.Errorf("Expected WriteFailed() to be true")
}
// Reset
state.Editor.SetWriteFailed(filename, false)
if state.Editor.WriteFailed() {
t.Errorf("Expected WriteFailed() to be false")
}
}
// TestAutoSave_RetryFails verifies that failed writes trigger retry mechanism.
// TestAutoSave_RetryFails verifies that failed writes trigger retry mechanism.
func TestAutoSave_RetryFails(t *testing.T) {
// Setup: New Logic, set mock FS to fail
l := NewLogic(nil)
// Start a goroutine to drain frameChan to prevent deadlocks
go func() {
for range l.frameChan {
}
}()
filename := "test.txt"
l.state.Editor.Filename = filename
l.state.Editor.Buffer = "hello"
// Mock FS to fail on Write
l.mockFS.SetWriteError(true)
// 1. Manually dispatch a write task
task := pool.NewWriteFileTask(filename, []byte("hello"), l.mockFS)
l.workerPool.Dispatch(task)
// 2. Manually process the result to trigger the failure state
res := <-l.workerPool.ResultChan()
l.handleWorkerResult(res)
// 3. Assert failure
if !l.state.Editor.WriteFailed() {
t.Errorf("Expected WriteFailed() to be true")
}
// 4. Assert retry scheduled
retryTriggered := false
select {
case filename := <-l.retryChan:
log.Printf("Test: Received retry for %s", filename)
retryTriggered = true
case <-time.After(5 * time.Second):
t.Log("Test: Timed out waiting for retry trigger in retryChan")
}
if !retryTriggered {
t.Errorf("Retry was not triggered")
}
}
+91
View File
@@ -0,0 +1,91 @@
package editor
import (
"testing"
"time"
"pad/internal/io/pool/mock"
)
func TestAutoSaveE2E(t *testing.T) {
// 1. Setup
mockFS := mock.NewFileSystem()
filename := "/test.txt"
initialContent := "Hello"
mockFS.AddFile(filename, []byte(initialContent), time.Now())
l := NewLogic(mockFS)
go l.Run()
defer l.Done()
// Drain frameChan to prevent deadlocks
go func() {
for range l.FrameChan() {
}
}()
l.state.Editor.Filename = filename
TheState = l.state
// 2. Open File
OpenFile(filename)
l.state.Editor.Buffer = initialContent
l.state.Editor.CursorPosition = len(initialContent)
// 3. Edit
HandleInsert(" World")
// 4. Trigger auto-save
l.markDirty()
// 5. Wait for the write to complete
success := false
for i := 0; i < 20; i++ {
content, _ := mockFS.ReadFile(filename)
if string(content) == "Hello World" {
success = true
break
}
time.Sleep(200 * time.Millisecond)
}
// 6. Assert
if !success {
t.Errorf("Timed out waiting for file to save")
}
}
func TestFlushOnExitE2E(t *testing.T) {
// 1. Setup
mockFS := mock.NewFileSystem()
filename := "/test.txt"
initialContent := "Hello"
mockFS.AddFile(filename, []byte(initialContent), time.Now())
l := NewLogic(mockFS)
go l.Run()
defer l.Done()
// Drain frameChan to prevent deadlocks
go func() {
for range l.FrameChan() {
}
}()
l.state.Editor.Filename = filename
l.state.Editor.Buffer = initialContent
TheState = l.state
// 2. Edit
l.state.Editor.CursorPosition = len(initialContent)
HandleInsert(" World")
// 3. Trigger Flush
l.FlushAll()
// 4. Assert
content, _ := mockFS.ReadFile(filename)
if string(content) != "Hello World" {
t.Errorf("Expected 'Hello World', got %q", string(content))
}
}
+21 -29
View File
@@ -4,53 +4,45 @@ import (
"testing"
"time"
"pad/internal/browser"
"pad/internal/io/pool"
"pad/internal/io/pool/mock"
)
func TestOpenFileIntegration(t *testing.T) {
// 1. Setup Logic
// We need to re-create the setup logic to control the environment
mockFS := mock.NewFileSystem()
// Add a file
filename := "/README.md"
content := "Hello World"
mockFS.AddFile(filename, []byte(content), time.Now())
wp := pool.NewWorkerPool(4)
wp.Start()
l := NewLogic(mockFS)
go l.Run()
defer l.Done()
// Initialize state manually
state := NewState()
TheState = state // Initialize global state
state.Browser.CurrentPath = "/"
_, _ = browser.NewBrowserManager(&state.Browser, wp, mockFS)
// 2. Simulate File Tap
// We need to trigger the file tap, which dispatches a ReadFileTask
// and calls OpenFile(filename).
// Drain frameChan to prevent deadlocks
go func() {
for range l.FrameChan() {
}
}()
// OpenFile sets filename and changes page
TheState = l.state // Initialize global state
// 2. Open File
// OpenFile dispatches the task to openFileChan, which Run() will consume
OpenFile(filename)
// Dispatch ReadFileTask
task := pool.NewReadFileTask(filename, mockFS)
wp.Dispatch(task)
// 3. Process the Result
// The logic loop would normally do this, we do it manually for the test
res := <-wp.ResultChan()
// Apply result
if res.Success {
if content, ok := res.Data.([]byte); ok {
state.Editor.Buffer = string(content)
// We wait for the state to update, which happens when ReadFileTask completes
success := false
for i := 0; i < 20; i++ {
if l.state.Editor.Buffer == content {
success = true
break
}
time.Sleep(100 * time.Millisecond)
}
// 4. Assert
if state.Editor.Buffer != content {
t.Errorf("Expected content %q, got %q", content, state.Editor.Buffer)
if !success {
t.Errorf("Expected content %q, got %q", content, l.state.Editor.Buffer)
}
}
+110 -16
View File
@@ -3,6 +3,7 @@ package editor
import (
"log"
"sync"
"time"
"pad/internal/browser"
"pad/internal/io/pool"
@@ -45,28 +46,34 @@ type ResultEvent struct {
// Logic runs the logic goroutine and provides channels for communication.
type Logic struct {
state *State
browserManager *browser.BrowserManager // Add this field
browserManager *browser.BrowserManager
configChan chan ConfigUpdate
frameChan chan []ui.Element
inputChan chan []ui.InputEvent
layoutChan chan ui.GlyphLayout // per-glyph layout feedback from renderer (replaces lastLineYChan)
layoutChan chan ui.GlyphLayout
resultChan chan ResultEvent
searchQueryChan chan string // search text updates from main goroutine
openFileChan chan string // Added for asynchronous file loading
searchQueryChan chan string
openFileChan chan string
retryChan chan string // Added for auto-save retries
workerPool *pool.WorkerPool
mockFS *mock.FileSystem
mu sync.Mutex
done chan struct{}
saveTimer *time.Timer // Added for auto-save debounce
saveGeneration int // Added for stale timer filtering
}
// NewLogic creates a new Logic instance.
func NewLogic() *Logic {
// NewLogic creates a new Logic instance, accepting an optional mockFS.
func NewLogic(mfs *mock.FileSystem) *Logic {
state := NewState()
TheState = state
// Initialize mock filesystem with sample data
mockFS := mock.NewFileSystem()
populateMockFileSystem(mockFS)
// Initialize mock filesystem if nil
mockFS := mfs
if mockFS == nil {
mockFS = mock.NewFileSystem()
populateMockFileSystem(mockFS)
}
// Initialize worker pool
wp := pool.NewWorkerPool(4)
@@ -76,20 +83,22 @@ func NewLogic() *Logic {
state.Browser.CurrentPath = "/"
bm, _ := browser.NewBrowserManager(&state.Browser, wp, mockFS)
return &Logic{
TheLogic = &Logic{
state: state,
browserManager: bm, // Add to struct
browserManager: bm,
configChan: make(chan ConfigUpdate),
frameChan: make(chan []ui.Element),
frameChan: make(chan []ui.Element, 1),
inputChan: make(chan []ui.InputEvent),
layoutChan: make(chan ui.GlyphLayout),
resultChan: make(chan ResultEvent),
resultChan: make(chan ResultEvent),
searchQueryChan: make(chan string),
openFileChan: make(chan string), // Initialized
openFileChan: make(chan string),
retryChan: make(chan string, 1), // Buffered channel
workerPool: wp,
mockFS: mockFS,
done: make(chan struct{}),
}
return TheLogic
}
// ConfigChan returns the unified config channel for the logic goroutine.
@@ -126,8 +135,8 @@ func (l *Logic) SearchQueryChan() chan<- string {
return l.searchQueryChan
}
// TheState is the global editor state, set once at startup.
var TheState *State
var TheLogic *Logic
// Scale returns the current scale factor (pixels per DP).
func (l *Logic) Scale() float32 {
@@ -179,8 +188,14 @@ func (l *Logic) Run() {
log.Printf("Logic: OpenFileChan %s", path)
// Dispatch ReadFileTask to worker pool
l.workerPool.Dispatch(pool.NewReadFileTask(path, l.mockFS))
case filename := <-l.retryChan:
log.Printf("Logic: Retrying save for %s", filename)
if filename == l.state.Editor.Filename {
l.workerPool.DispatchNonBlocking(
pool.NewWriteFileTask(filename, []byte(l.state.Editor.Buffer), l.mockFS),
)
}
case res := <-l.workerPool.ResultChan():
log.Printf("Logic: WorkerResult %s", res.TaskType)
l.handleWorkerResult(res)
case <-l.resultChan:
l.frameChan <- l.state.layout(l.browserManager)
@@ -188,6 +203,31 @@ func (l *Logic) Run() {
}
}
// markDirty triggers the auto-save debounce timer.
func (l *Logic) markDirty() {
if l.state.Editor.Filename == "" {
return
}
l.state.Editor.fileVersion[l.state.Editor.Filename]++
// 1s debounce
if l.saveTimer != nil {
l.saveTimer.Stop()
}
gen := l.saveGeneration
l.saveGeneration++
buffer := l.state.Editor.Buffer
filename := l.state.Editor.Filename
l.saveTimer = time.AfterFunc(1*time.Second, func() {
if l.saveGeneration == gen+1 { // Corrected generation check
l.workerPool.DispatchNonBlocking(
pool.NewWriteFileTask(filename, []byte(buffer), l.mockFS),
)
}
})
}
// handleWorkerResult processes results from the worker pool.
func (l *Logic) handleWorkerResult(res pool.Result) {
if res.IsBrowserResult() {
@@ -199,6 +239,29 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
l.state.Editor.Buffer = string(content)
}
}
} else if res.TaskType == pool.TypeWriteFile {
if res.Success {
l.state.Editor.lastWriteVersion[res.FilePath] = l.state.Editor.fileVersion[res.FilePath]
l.state.Editor.SetWriteFailed(res.FilePath, false)
} else {
log.Printf("Auto-save failed for %s: %v", res.FilePath, res.Error)
l.state.Editor.SetWriteFailed(res.FilePath, true)
// Trigger retry logic: exponential backoff
attempts := l.state.Editor.IncrementRetryAttempts(res.FilePath)
// Simple backoff: 1s, 2s, 4s, 8s... max 30s
delay := time.Duration(1<<(attempts-1)) * time.Second
if delay > 30*time.Second {
delay = 30 * time.Second
}
filename := res.FilePath
log.Printf("Scheduling retry for %s in %v (attempt %d)", filename, delay, attempts)
time.AfterFunc(delay, func() {
log.Printf("Firing retry for %s", filename)
l.retryChan <- filename
})
}
}
l.frameChan <- l.state.layout(l.browserManager)
}
@@ -223,7 +286,38 @@ func (l *Logic) State() *State {
return l.state
}
// PruneMaps removes old entries to keep memory usage bounded.
// Keeps entries for the last 1000 files.
func (l *Logic) PruneMaps() {
if len(l.state.Editor.fileVersion) <= 1000 {
return
}
// Simply clear the maps for now. A true LRU would require
// tracking access times.
l.state.Editor.fileVersion = make(map[string]int)
l.state.Editor.lastWriteVersion = make(map[string]int)
l.state.Editor.writeFailed = make(map[string]bool)
l.state.Editor.retryAttempts = make(map[string]int)
}
// Done signals the logic goroutine to stop.
func (l *Logic) Done() {
close(l.done)
}
// FlushAll triggers synchronous writes for all dirty files.
func (l *Logic) FlushAll() {
l.mu.Lock()
defer l.mu.Unlock()
for filename := range l.state.Editor.fileVersion {
if l.state.Editor.IsDirty() && l.state.Editor.Filename == filename {
// Trigger a synchronous write for the active dirty file
content := l.state.Editor.Buffer
// In a real app, this would be a blocking call to the FS
l.mockFS.WriteFile(filename, []byte(content))
l.state.Editor.lastWriteVersion[filename] = l.state.Editor.fileVersion[filename]
}
}
}
+68 -15
View File
@@ -3,6 +3,7 @@ package editor
import (
"log"
"sort"
"time"
"unicode/utf8"
"pad/internal/browser"
@@ -45,14 +46,44 @@ const (
// EditorState holds all editor-specific state.
type EditorState struct {
Buffer string // Document content
CursorPosition int // Byte offset
GlyphLayout ui.GlyphLayout // Per-glyph layout from renderer
SelectionStart int // -1 if no selection
SelectionEnd int // -1 if no selection
Dirty bool // Needs save
CursorVisible bool // Blink state
// UndoStack []EditCommand // Planned for later
Buffer string
CursorPosition int
GlyphLayout ui.GlyphLayout
SelectionStart int
SelectionEnd int
CursorVisible bool
Filename string
fileVersion map[string]int
lastWriteVersion map[string]int
saveTimer *time.Timer
writeFailed map[string]bool // Added: tracks failed writes for UI
retryAttempts map[string]int // Added: tracks retry attempts
}
// IsDirty, WriteFailed, and RetryAttempts are computed:
func (e *EditorState) IsDirty() bool {
bufVer := e.fileVersion[e.Filename]
writeVer := e.lastWriteVersion[e.Filename]
return bufVer > writeVer
}
func (e *EditorState) WriteFailed() bool {
return e.writeFailed[e.Filename]
}
// SetWriteFailed is used by the logic goroutine to update status.
func (e *EditorState) SetWriteFailed(filename string, failed bool) {
e.writeFailed[filename] = failed
if !failed {
e.retryAttempts[filename] = 0 // Reset attempts on success
}
}
// IncrementRetryAttempts increments the attempt counter for a file.
func (e *EditorState) IncrementRetryAttempts(filename string) int {
e.retryAttempts[filename]++
return e.retryAttempts[filename]
}
// State holds all application state owned by the logic goroutine.
@@ -79,9 +110,13 @@ func NewState() *State {
page: BrowserPage, // Reverted to BrowserPage
Browser: *browser.NewBrowserState(),
Editor: EditorState{
CursorPosition: 0,
SelectionStart: -1,
SelectionEnd: -1,
CursorPosition: 0,
SelectionStart: -1,
SelectionEnd: -1,
fileVersion: make(map[string]int),
lastWriteVersion: make(map[string]int),
writeFailed: make(map[string]bool),
retryAttempts: make(map[string]int),
},
}
}
@@ -167,7 +202,21 @@ func GoToEditor(data any) {
// OpenFile sets the active filename and switches to the editor page.
// data is the filename string from the browser list.
func OpenFile(data any) {
TheState.Editor.Buffer = "Select a file to edit..." // Placeholder, should be loaded from file
filename := data.(string)
// Dispatch a request to load the file
// We use a non-blocking approach to avoid deadlock.
// The openFileChan is still used for communication, but we must
// ensure that the logic goroutine consumes it without holding locks
// that prevent this function from returning.
// Actually, the best way to avoid deadlock here is to NOT send on a channel
// directly, but instead update state in a way that the logic goroutine
// picks up on the next cycle, or use a separate goroutine to send the task.
go func() {
TheLogic.openFileChan <- filename
}()
TheState.Editor.Filename = filename
TheState.Editor.CursorPosition = 0 // Reset cursor to top
TheState.ScrollOffset = 0 // Reset editor scroll to top when opening a new file
TheState.page = EditorPage
@@ -323,7 +372,7 @@ func HandleDelete() {
return
}
TheState.Editor.Buffer = buf[:pos] + buf[pos+1:]
TheState.Editor.Dirty = true
markDirty()
}
// HandleInsert inserts a string at the current cursor position.
@@ -333,7 +382,7 @@ func HandleInsert(s string) {
// Simple string concatenation for now
TheState.Editor.Buffer = buf[:pos] + s + buf[pos:]
TheState.Editor.CursorPosition += len(s)
TheState.Editor.Dirty = true
markDirty()
}
// HandleBackspace removes the character before the cursor.
@@ -346,7 +395,11 @@ func HandleBackspace() {
// Simple string slice
TheState.Editor.Buffer = buf[:pos-1] + buf[pos:]
TheState.Editor.CursorPosition--
TheState.Editor.Dirty = true
markDirty()
}
func markDirty() {
TheLogic.markDirty()
}
// EditorLayout computes the element tree for the editor page.