Make state single-owner and stabilize race detector
Frame now carries view state (scale/focus/query) to the main goroutine, which reads only the frame-receiver-stored snapshot. Renderer owns Gio widget editors (registered by ID) and the draw scale. Autosave timer sends a token to the logic goroutine instead of touching state; Shutdown waits for the owner to exit before FlushAll. Tests access state only through owner-side Inspect/WithState helpers (harness + in-package). Fixed double-Harness.Run race in two e2e tests, made TestWorkerPool_PriorityPreemption deterministic, and raised the lazy-loading test timeout that was too short under -race. go test -race ./... is now green.
This commit is contained in:
+74
-37
@@ -9,6 +9,20 @@ import (
|
||||
"pad/internal/io/pool/mock"
|
||||
)
|
||||
|
||||
// withState runs fn on the logic goroutine (the sole state owner) and fails
|
||||
// the test on timeout. Test-only helper (architecture.md §1): tests must
|
||||
// never touch l.state directly while Run() is active.
|
||||
func withState(t *testing.T, l *Logic, fn func(*State)) {
|
||||
t.Helper()
|
||||
_, ok := l.Inspect(func(st *State) any {
|
||||
fn(st)
|
||||
return nil
|
||||
})
|
||||
if !ok {
|
||||
t.Fatalf("withState: inspect timed out")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoSaveE2E(t *testing.T) {
|
||||
// 1. Setup
|
||||
mockFS := mock.NewFileSystem()
|
||||
@@ -18,7 +32,7 @@ func TestAutoSaveE2E(t *testing.T) {
|
||||
|
||||
l := NewLogic(mockFS, "/", func(string) {})
|
||||
go l.Run()
|
||||
defer l.Done()
|
||||
defer l.Shutdown()
|
||||
|
||||
// Drain frameChan to prevent deadlocks
|
||||
go func() {
|
||||
@@ -26,16 +40,21 @@ func TestAutoSaveE2E(t *testing.T) {
|
||||
}
|
||||
}()
|
||||
|
||||
l.state.Editor.Filename = filename
|
||||
TheState = l.state
|
||||
withState(t, l, func(st *State) {
|
||||
TheState = st
|
||||
})
|
||||
|
||||
// 2. Open File
|
||||
// 2. Open File (OpenFile also sets Editor.Filename on the owner)
|
||||
OpenFile(filename)
|
||||
|
||||
|
||||
// Wait for the file to be loaded by checking if ChunkedBuffer is populated
|
||||
success := false
|
||||
for i := 0; i < 20; i++ {
|
||||
if l.state.Editor.ChunkedBuffer != nil && l.state.Editor.ChunkedBuffer.FileLen() > 0 {
|
||||
v, ok := l.Inspect(func(st *State) any {
|
||||
cb := st.Editor.ChunkedBuffer
|
||||
return cb != nil && cb.FileLen() > 0
|
||||
})
|
||||
if ok && v.(bool) {
|
||||
success = true
|
||||
break
|
||||
}
|
||||
@@ -45,12 +64,16 @@ func TestAutoSaveE2E(t *testing.T) {
|
||||
t.Fatal("Timed out waiting for file to load")
|
||||
}
|
||||
|
||||
// 3. Edit
|
||||
l.state.Editor.CursorPosition = len(initialContent)
|
||||
HandleInsert(" World")
|
||||
// 3. Edit (owner-side)
|
||||
withState(t, l, func(st *State) {
|
||||
st.Editor.CursorPosition = len(initialContent)
|
||||
HandleInsert(" World")
|
||||
})
|
||||
|
||||
// 4. Trigger auto-save
|
||||
l.markDirty()
|
||||
// 4. Trigger auto-save (owner-side)
|
||||
withState(t, l, func(st *State) {
|
||||
l.markDirty()
|
||||
})
|
||||
|
||||
// 5. Wait for the write to complete
|
||||
success = false
|
||||
@@ -95,7 +118,7 @@ func TestLargeFileChunkBoundary(t *testing.T) {
|
||||
|
||||
l := NewLogic(mockFS, "/", func(string) {})
|
||||
go l.Run()
|
||||
defer l.Done()
|
||||
defer l.Shutdown()
|
||||
|
||||
// Drain frameChan to prevent deadlocks
|
||||
go func() {
|
||||
@@ -103,15 +126,20 @@ func TestLargeFileChunkBoundary(t *testing.T) {
|
||||
}
|
||||
}()
|
||||
|
||||
l.state.Editor.Filename = filename
|
||||
TheState = l.state
|
||||
withState(t, l, func(st *State) {
|
||||
TheState = st
|
||||
})
|
||||
|
||||
// --- 2. Open File ---
|
||||
OpenFile(filename)
|
||||
|
||||
success := false
|
||||
for i := 0; i < 20; i++ {
|
||||
if l.state.Editor.ChunkedBuffer != nil && l.state.Editor.ChunkedBuffer.FileLen() > 0 {
|
||||
v, ok := l.Inspect(func(st *State) any {
|
||||
cb := st.Editor.ChunkedBuffer
|
||||
return cb != nil && cb.FileLen() > 0
|
||||
})
|
||||
if ok && v.(bool) {
|
||||
success = true
|
||||
break
|
||||
}
|
||||
@@ -121,25 +149,28 @@ func TestLargeFileChunkBoundary(t *testing.T) {
|
||||
t.Fatal("Timed out waiting for large file to load")
|
||||
}
|
||||
|
||||
cb := l.state.Editor.ChunkedBuffer
|
||||
if cb == nil {
|
||||
t.Fatal("ChunkedBuffer is nil after opening large file")
|
||||
}
|
||||
|
||||
// --- 3. Edit near the end of chunk 1 (position 65000, inside chunk 1) ---
|
||||
l.state.Editor.CursorPosition = 65000
|
||||
HandleInsert("CHUNK1")
|
||||
withState(t, l, func(st *State) {
|
||||
st.Editor.CursorPosition = 65000
|
||||
HandleInsert("CHUNK1")
|
||||
})
|
||||
|
||||
// --- 4. Edit right at the chunk 0 / chunk 1 boundary (position 65535) ---
|
||||
l.state.Editor.CursorPosition = 65535
|
||||
HandleInsert("BOUNDARY")
|
||||
withState(t, l, func(st *State) {
|
||||
st.Editor.CursorPosition = 65535
|
||||
HandleInsert("BOUNDARY")
|
||||
})
|
||||
|
||||
// --- 5. Edit near the end of chunk 3 (position 262000) ---
|
||||
l.state.Editor.CursorPosition = 262000
|
||||
HandleInsert("CHUNK3")
|
||||
withState(t, l, func(st *State) {
|
||||
st.Editor.CursorPosition = 262000
|
||||
HandleInsert("CHUNK3")
|
||||
})
|
||||
|
||||
// --- 6. Trigger save ---
|
||||
l.FlushAll()
|
||||
// --- 6. Trigger save (owner-side) ---
|
||||
withState(t, l, func(st *State) {
|
||||
l.FlushAll()
|
||||
})
|
||||
|
||||
// --- 7. Read back from mockFS and verify byte-for-byte ---
|
||||
savedContent, err := mockFS.ReadFile(filename)
|
||||
@@ -234,7 +265,7 @@ func TestFlushOnExitE2E(t *testing.T) {
|
||||
|
||||
l := NewLogic(mockFS, "/", func(string) {})
|
||||
go l.Run()
|
||||
defer l.Done()
|
||||
defer l.Shutdown()
|
||||
|
||||
// Drain frameChan to prevent deadlocks
|
||||
go func() {
|
||||
@@ -242,16 +273,22 @@ func TestFlushOnExitE2E(t *testing.T) {
|
||||
}
|
||||
}()
|
||||
|
||||
l.state.Editor.Filename = filename
|
||||
l.state.Editor.Buffer = initialContent
|
||||
TheState = l.state
|
||||
withState(t, l, func(st *State) {
|
||||
st.Editor.Filename = filename
|
||||
st.Editor.Buffer = initialContent
|
||||
TheState = st
|
||||
})
|
||||
|
||||
// 2. Edit
|
||||
l.state.Editor.CursorPosition = len(initialContent)
|
||||
HandleInsert(" World")
|
||||
// 2. Edit (owner-side)
|
||||
withState(t, l, func(st *State) {
|
||||
st.Editor.CursorPosition = len(initialContent)
|
||||
HandleInsert(" World")
|
||||
})
|
||||
|
||||
// 3. Trigger Flush
|
||||
l.FlushAll()
|
||||
// 3. Trigger Flush (owner-side)
|
||||
withState(t, l, func(st *State) {
|
||||
l.FlushAll()
|
||||
})
|
||||
|
||||
// 4. Assert
|
||||
content, _ := mockFS.ReadFile(filename)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package editor
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"pad/internal/ui"
|
||||
)
|
||||
|
||||
// Frame is the unit of handoff from the logic goroutine to the frame
|
||||
// receiver. Per architecture.md §9, the frame is the ONLY cross-goroutine
|
||||
// state carrier: the main goroutine must never read *State directly, it
|
||||
// reads the snapshot stored here by the frame receiver (under the frame
|
||||
// mutex).
|
||||
//
|
||||
// Elems is the computed element tree for the next draw.
|
||||
// The remaining fields are the view-state snapshot that the main goroutine
|
||||
// needs to route events and forward input:
|
||||
//
|
||||
// - Scale: current px-per-Dp, so the main goroutine can detect scale
|
||||
// changes and pass the scale to the renderer's Draw call.
|
||||
// - FocusedElementID: which registered element receives key/edit events.
|
||||
// - Query: the search query the logic goroutine is currently filtering
|
||||
// with; the main goroutine compares it against the (main-owned) search
|
||||
// widget's text and forwards changes via SearchQueryChan.
|
||||
type Frame struct {
|
||||
Elems []ui.Element
|
||||
Scale float32
|
||||
FocusedElementID string
|
||||
Query string
|
||||
}
|
||||
|
||||
// frameOf wraps a computed element tree with the current view-state
|
||||
// snapshot. Must be called on the logic goroutine.
|
||||
func (l *Logic) frameOf(elems []ui.Element) Frame {
|
||||
return Frame{
|
||||
Elems: elems,
|
||||
Scale: l.state.scale,
|
||||
FocusedElementID: l.state.FocusedElementID,
|
||||
Query: l.state.Browser.Query,
|
||||
}
|
||||
}
|
||||
|
||||
// inspectReq is a test-only request to run fn on the logic goroutine.
|
||||
// It preserves the single-owner invariant (architecture.md §1): the fn
|
||||
// executes on the owner, not on the caller. fn must not block on sends to
|
||||
// logic channels.
|
||||
type inspectReq struct {
|
||||
fn func(st *State) any
|
||||
resp chan any
|
||||
}
|
||||
|
||||
// Inspect runs fn on the logic goroutine and returns its result. It is
|
||||
// intended for tests; production code must use the regular channels.
|
||||
func (l *Logic) Inspect(fn func(st *State) any) (any, bool) {
|
||||
req := &inspectReq{fn: fn, resp: make(chan any, 1)}
|
||||
select {
|
||||
case l.inspectChan <- req:
|
||||
case <-time.After(5 * time.Second):
|
||||
return nil, false
|
||||
}
|
||||
select {
|
||||
case v := <-req.resp:
|
||||
return v, true
|
||||
case <-time.After(5 * time.Second):
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
@@ -16,25 +16,29 @@ func TestOpenFileIntegration(t *testing.T) {
|
||||
|
||||
l := NewLogic(mockFS, "/", func(string) {})
|
||||
go l.Run()
|
||||
defer l.Done()
|
||||
defer l.Shutdown()
|
||||
|
||||
// Drain frameChan to prevent deadlocks
|
||||
go func() {
|
||||
for range l.FrameChan() {
|
||||
}
|
||||
}()
|
||||
|
||||
TheState = l.state // Initialize global state
|
||||
|
||||
// Initialize global state on the owner
|
||||
withState(t, l, func(st *State) {
|
||||
TheState = st
|
||||
})
|
||||
|
||||
// 2. Open File
|
||||
// OpenFile dispatches the task to openFileChan, which Run() will consume
|
||||
OpenFile(filename)
|
||||
|
||||
|
||||
// 3. Process the Result
|
||||
// We wait for the state to update, which happens when ReadChunkTask completes
|
||||
success := false
|
||||
for i := 0; i < 20; i++ {
|
||||
if l.state.Editor.GetBuffer() == content {
|
||||
v, ok := l.Inspect(func(st *State) any { return st.Editor.GetBuffer() })
|
||||
if ok && v.(string) == content {
|
||||
success = true
|
||||
break
|
||||
}
|
||||
@@ -43,6 +47,7 @@ func TestOpenFileIntegration(t *testing.T) {
|
||||
|
||||
// 4. Assert
|
||||
if !success {
|
||||
t.Errorf("Expected content %q, got %q", content, l.state.Editor.Buffer)
|
||||
got, _ := l.Inspect(func(st *State) any { return st.Editor.Buffer })
|
||||
t.Errorf("Expected content %q, got %q", content, got)
|
||||
}
|
||||
}
|
||||
|
||||
+87
-68
@@ -45,23 +45,29 @@ type ResultEvent struct {
|
||||
}
|
||||
|
||||
// Logic runs the logic goroutine and provides channels for communication.
|
||||
//
|
||||
// Single-owner invariant (architecture.md §1): the logic goroutine is the
|
||||
// sole reader/writer of l.state. Every other goroutine talks to it through
|
||||
// the channels below. The only exception is Inspect, a test-only request
|
||||
// channel whose fn still executes on the owner.
|
||||
type Logic struct {
|
||||
state *State
|
||||
browserManager *browser.BrowserManager
|
||||
configChan chan ConfigUpdate
|
||||
frameChan chan []ui.Element
|
||||
frameChan chan Frame // frames carry the view-state snapshot
|
||||
inputChan chan []ui.InputEvent
|
||||
layoutChan chan ui.GlyphLayout
|
||||
resultChan chan ResultEvent
|
||||
searchQueryChan chan string
|
||||
openFileChan chan string
|
||||
retryChan chan string // Added for auto-save retries
|
||||
retryChan chan string // auto-save retries
|
||||
autosaveChan chan struct{} // auto-save debounce ticks (timer -> owner)
|
||||
inspectChan chan *inspectReq
|
||||
workerPool *pool.WorkerPool
|
||||
mockFS pool.FileSystem
|
||||
mu sync.Mutex
|
||||
done chan struct{}
|
||||
saveTimer *time.Timer // Added for auto-save debounce
|
||||
saveGeneration int // Added for stale timer filtering
|
||||
exitWg sync.WaitGroup
|
||||
saveTimer *time.Timer // auto-save debounce timer; non-nil while pending
|
||||
}
|
||||
|
||||
// NewLogic creates a new Logic instance, accepting an optional mockFS.
|
||||
@@ -89,13 +95,15 @@ func NewLogic(mfs pool.FileSystem, path string, openfunc func(string)) *Logic {
|
||||
state: state,
|
||||
browserManager: bm,
|
||||
configChan: make(chan ConfigUpdate),
|
||||
frameChan: make(chan []ui.Element, 1),
|
||||
frameChan: make(chan Frame, 1),
|
||||
inputChan: make(chan []ui.InputEvent),
|
||||
layoutChan: make(chan ui.GlyphLayout),
|
||||
resultChan: make(chan ResultEvent),
|
||||
searchQueryChan: make(chan string),
|
||||
openFileChan: make(chan string),
|
||||
retryChan: make(chan string, 1), // Buffered channel
|
||||
autosaveChan: make(chan struct{}),
|
||||
inspectChan: make(chan *inspectReq),
|
||||
workerPool: wp,
|
||||
mockFS: mockFS,
|
||||
done: make(chan struct{}),
|
||||
@@ -110,7 +118,7 @@ func (l *Logic) ConfigChan() chan<- ConfigUpdate {
|
||||
}
|
||||
|
||||
// FrameChan returns the frame channel for the logic goroutine.
|
||||
func (l *Logic) FrameChan() <-chan []ui.Element {
|
||||
func (l *Logic) FrameChan() <-chan Frame {
|
||||
return l.frameChan
|
||||
}
|
||||
|
||||
@@ -140,13 +148,11 @@ func (l *Logic) SearchQueryChan() chan<- string {
|
||||
var TheState *State
|
||||
var TheLogic *Logic
|
||||
|
||||
// Scale returns the current scale factor (pixels per DP).
|
||||
func (l *Logic) Scale() float32 {
|
||||
return l.state.Scale()
|
||||
}
|
||||
|
||||
// Run runs the logic goroutine loop.
|
||||
func (l *Logic) Run() {
|
||||
l.exitWg.Add(1)
|
||||
defer l.exitWg.Done()
|
||||
|
||||
// Dispatch initial directory index build on startup
|
||||
log.Printf("Logic: Dispatching BuildIndexTask")
|
||||
l.workerPool.Dispatch(pool.NewBuildIndexTask(l.state.Browser.CurrentPath, l.mockFS))
|
||||
@@ -158,26 +164,26 @@ func (l *Logic) Run() {
|
||||
case update := <-l.configChan:
|
||||
log.Printf("Logic: ConfigEvent")
|
||||
update.apply(l.state)
|
||||
l.frameChan <- l.state.layout(l.browserManager)
|
||||
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
|
||||
case layout := <-l.layoutChan:
|
||||
// Store the full GlyphLayout on editor state.
|
||||
// Derive LastLineY from it for scroll clamping.
|
||||
l.state.Editor.GlyphLayout = layout
|
||||
log.Printf("LOGIC received GlyphLayout: ByteOffsets=%d, VisualLineStarts=%d", len(layout.ByteOffsets), len(layout.VisualLineStarts))
|
||||
log.Printf("LOGIC received GlyphLayout: ByteOffsets=%d, VisualLineStarts=%d", len(layout.ByteOffsets), len(layout.VisualLineStarts))
|
||||
var derivedLastLineY ui.Dp
|
||||
if len(layout.Y) > 0 {
|
||||
derivedLastLineY = layout.Y[len(layout.Y)-1]
|
||||
}
|
||||
if derivedLastLineY != l.state.LastLineY {
|
||||
l.state.LastLineY = derivedLastLineY
|
||||
l.frameChan <- l.state.layout(l.browserManager)
|
||||
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
|
||||
}
|
||||
case events := <-l.inputChan:
|
||||
log.Printf("Logic: InputEvents")
|
||||
for _, evt := range events {
|
||||
evt.Handler(evt.Data)
|
||||
}
|
||||
l.frameChan <- l.state.layout(l.browserManager)
|
||||
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
|
||||
case query := <-l.searchQueryChan:
|
||||
log.Printf("Logic: SearchQuery")
|
||||
if query != l.state.Browser.Query {
|
||||
@@ -186,7 +192,7 @@ func (l *Logic) Run() {
|
||||
browser.HandleSearch(&l.state.Browser, query)
|
||||
}
|
||||
}
|
||||
l.frameChan <- l.state.layout(l.browserManager)
|
||||
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
|
||||
case path := <-l.openFileChan:
|
||||
log.Printf("Logic: OpenFileChan %s", path)
|
||||
// Create chunked buffer for virtual scrolling
|
||||
@@ -201,30 +207,61 @@ func (l *Logic) Run() {
|
||||
log.Printf("Logic: Retrying save for %s", filename)
|
||||
if filename == l.state.Editor.Filename {
|
||||
// Reconstruct full content from chunked buffer for saving
|
||||
var content []byte
|
||||
if l.state.Editor.ChunkedBuffer != nil {
|
||||
fullContent, err := l.state.Editor.ChunkedBuffer.FullContent()
|
||||
if err != nil {
|
||||
log.Printf("Error reconstructing full content for saving %s: %v", filename, err)
|
||||
return
|
||||
}
|
||||
content = []byte(fullContent)
|
||||
} else {
|
||||
content = []byte(l.state.Editor.Buffer)
|
||||
content, ok := l.fullContentBytes()
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
l.workerPool.DispatchNonBlocking(
|
||||
pool.NewWriteFileTask(filename, content, l.mockFS),
|
||||
)
|
||||
}
|
||||
case <-l.autosaveChan:
|
||||
// Auto-save debounce tick. The timer goroutine only sent a token;
|
||||
// the owner reconstructs content and dispatches the write.
|
||||
l.saveTimer = nil
|
||||
if l.state.Editor.Filename == "" {
|
||||
break
|
||||
}
|
||||
content, ok := l.fullContentBytes()
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
log.Printf("Logic: Dispatching WriteFileTask for %s, content len=%d", l.state.Editor.Filename, len(content))
|
||||
l.workerPool.DispatchNonBlocking(
|
||||
pool.NewWriteFileTask(l.state.Editor.Filename, content, l.mockFS),
|
||||
)
|
||||
case req := <-l.inspectChan:
|
||||
// Test-only: fn runs on the owner, preserving single ownership.
|
||||
req.resp <- req.fn(l.state)
|
||||
case res := <-l.workerPool.ResultChan():
|
||||
l.handleWorkerResult(res)
|
||||
case <-l.resultChan:
|
||||
l.frameChan <- l.state.layout(l.browserManager)
|
||||
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fullContentBytes reconstructs the full file content from the chunked
|
||||
// buffer (or the deprecated full Buffer). Returns ok=false on error.
|
||||
// Must be called on the logic goroutine.
|
||||
func (l *Logic) fullContentBytes() ([]byte, bool) {
|
||||
if l.state.Editor.ChunkedBuffer != nil {
|
||||
fullContent, err := l.state.Editor.ChunkedBuffer.FullContent()
|
||||
if err != nil {
|
||||
log.Printf("Error reconstructing full content: %v", err)
|
||||
return nil, false
|
||||
}
|
||||
return []byte(fullContent), true
|
||||
}
|
||||
return []byte(l.state.Editor.Buffer), true
|
||||
}
|
||||
|
||||
// markDirty triggers the auto-save debounce timer.
|
||||
// Must be called on the logic goroutine.
|
||||
//
|
||||
// The timer callback runs on a timer goroutine and only sends a token on
|
||||
// autosaveChan; the owner (Run loop) does all state reads and the worker
|
||||
// dispatch. This keeps the timer goroutine out of state (architecture.md §1).
|
||||
func (l *Logic) markDirty() {
|
||||
if l.state.Editor.Filename == "" {
|
||||
return
|
||||
@@ -235,30 +272,8 @@ func (l *Logic) markDirty() {
|
||||
if l.saveTimer != nil {
|
||||
l.saveTimer.Stop()
|
||||
}
|
||||
gen := l.saveGeneration
|
||||
l.saveGeneration++
|
||||
filename := l.state.Editor.Filename
|
||||
|
||||
l.saveTimer = time.AfterFunc(1*time.Second, func() {
|
||||
log.Printf("Logic: Auto-save timer fired for %s, gen=%d, current=%d", filename, gen+1, l.saveGeneration)
|
||||
if l.saveGeneration == gen+1 {
|
||||
// Reconstruct full content from chunked buffer for saving
|
||||
var content []byte
|
||||
if l.state.Editor.ChunkedBuffer != nil {
|
||||
fullContent, err := l.state.Editor.ChunkedBuffer.FullContent()
|
||||
if err != nil {
|
||||
log.Printf("Error reconstructing full content for auto-save: %v", err)
|
||||
return
|
||||
}
|
||||
content = []byte(fullContent)
|
||||
} else {
|
||||
content = []byte(l.state.Editor.Buffer)
|
||||
}
|
||||
log.Printf("Logic: Dispatching WriteFileTask for %s, content len=%d", filename, len(content))
|
||||
l.workerPool.DispatchNonBlocking(
|
||||
pool.NewWriteFileTask(filename, content, l.mockFS),
|
||||
)
|
||||
}
|
||||
l.autosaveChan <- struct{}{}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -344,7 +359,7 @@ func (l *Logic) handleWorkerResult(res pool.Result) {
|
||||
})
|
||||
}
|
||||
}
|
||||
l.frameChan <- l.state.layout(l.browserManager)
|
||||
l.frameChan <- l.frameOf(l.state.layout(l.browserManager))
|
||||
}
|
||||
|
||||
// applyBuildIndexResult applies a completed BuildIndexTask result to browser state.
|
||||
@@ -387,24 +402,24 @@ 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()
|
||||
// WaitForExit blocks until the logic goroutine has fully stopped. After
|
||||
// this returns, the caller (e.g. Shutdown) may touch state single-threaded.
|
||||
func (l *Logic) WaitForExit() {
|
||||
l.exitWg.Wait()
|
||||
}
|
||||
|
||||
// FlushAll triggers synchronous writes for all dirty files.
|
||||
//
|
||||
// Must be called either from the logic goroutine (e.g. via GoToBrowser) or
|
||||
// after the logic goroutine has fully stopped (Shutdown). It touches state
|
||||
// directly, so it must never run concurrently with Run (single-owner
|
||||
// invariant, architecture.md §1).
|
||||
func (l *Logic) FlushAll() {
|
||||
for filename := range l.state.Editor.fileVersion {
|
||||
if l.state.Editor.IsDirty() && l.state.Editor.Filename == filename {
|
||||
// Reconstruct full content from chunked buffer for saving
|
||||
var content []byte
|
||||
if l.state.Editor.ChunkedBuffer != nil {
|
||||
fullContent, err := l.state.Editor.ChunkedBuffer.FullContent()
|
||||
if err != nil {
|
||||
log.Printf("Error reconstructing full content for flush: %v", err)
|
||||
return
|
||||
}
|
||||
content = []byte(fullContent)
|
||||
} else {
|
||||
content = []byte(l.state.Editor.Buffer)
|
||||
content, ok := l.fullContentBytes()
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// In a real app, this would be a blocking call to the FS
|
||||
l.mockFS.WriteFileAtomic(filename, content)
|
||||
@@ -414,8 +429,12 @@ func (l *Logic) FlushAll() {
|
||||
}
|
||||
|
||||
// Shutdown gracefully shuts down the logic goroutine and worker pool.
|
||||
// The logic goroutine is stopped FIRST so that FlushAll can touch state
|
||||
// single-threaded; the worker pool is stopped last so in-flight results
|
||||
// still have a reader until then.
|
||||
func (l *Logic) Shutdown() {
|
||||
l.FlushAll()
|
||||
l.Done()
|
||||
l.WaitForExit()
|
||||
l.FlushAll()
|
||||
l.workerPool.Stop()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user