gunk-dev/the-valley

tail.go

source672eff5ffaecmain's published tip history
2.9 KiB
1package event
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "io"
8 "os"
9 "path/filepath"
10 "time"
11
12 "github.com/fsnotify/fsnotify"
13)
14
15// Tail follows the events file at path, sending each newly appended Event to
16// out. It blocks until ctx is cancelled. New events are emitted starting from
17// the end of the file at the time Tail is called (it does NOT replay existing
18// history). If the file does not yet exist, Tail waits for it to appear.
19//
20// Tail is used by the dashboard to subscribe to klaus-internal invalidation
21// signals (e.g. PRApprovalChanged) written by other klaus processes such as
22// `klaus approve`. Compared with watching the run state directory, tailing
23// the event log gives a precise, intent-bearing signal rather than relying on
24// fsnotify of a JSON state file as a proxy.
25func Tail(ctx context.Context, path string, out chan<- Event) error {
26 if err := waitForFile(ctx, path); err != nil {
27 return err
28 }
29 if ctx.Err() != nil {
30 return nil
31 }
32
33 watcher, err := fsnotify.NewWatcher()
34 if err != nil {
35 return err
36 }
37 defer watcher.Close()
38
39 if err := watcher.Add(filepath.Dir(path)); err != nil {
40 return err
41 }
42
43 f, err := os.Open(path)
44 if err != nil {
45 return err
46 }
47 defer func() {
48 if f != nil {
49 f.Close()
50 }
51 }()
52
53 if _, err := f.Seek(0, io.SeekEnd); err != nil {
54 return err
55 }
56
57 var pending []byte
58
59 drain := func() error {
60 buf := make([]byte, 32*1024)
61 for {
62 n, err := f.Read(buf)
63 if n > 0 {
64 pending = append(pending, buf[:n]...)
65 for {
66 idx := bytes.IndexByte(pending, '\n')
67 if idx < 0 {
68 break
69 }
70 line := pending[:idx]
71 pending = pending[idx+1:]
72 if len(line) == 0 {
73 continue
74 }
75 var evt Event
76 if err := json.Unmarshal(line, &evt); err != nil {
77 continue
78 }
79 select {
80 case out <- evt:
81 case <-ctx.Done():
82 return ctx.Err()
83 }
84 }
85 }
86 if err == io.EOF {
87 return nil
88 }
89 if err != nil {
90 return err
91 }
92 }
93 }
94
95 if err := drain(); err != nil {
96 return err
97 }
98
99 // fsnotify is reliable on modern OSes; this fallback only exists to catch
100 // rare missed notifications, so a long interval is fine.
101 const poll = 10 * time.Second
102 ticker := time.NewTicker(poll)
103 defer ticker.Stop()
104
105 for {
106 select {
107 case <-ctx.Done():
108 return nil
109 case ev, ok := <-watcher.Events:
110 if !ok {
111 return nil
112 }
113 if filepath.Clean(ev.Name) != filepath.Clean(path) {
114 continue
115 }
116 if ev.Op&(fsnotify.Write|fsnotify.Chmod|fsnotify.Create) != 0 {
117 if err := drain(); err != nil {
118 return err
119 }
120 }
121 case <-watcher.Errors:
122 // Non-fatal — keep going.
123 case <-ticker.C:
124 // Defensive: catch missed write notifications.
125 if err := drain(); err != nil {
126 return err
127 }
128 }
129 }
130}
131
132func waitForFile(ctx context.Context, path string) error {
133 for {
134 if _, err := os.Stat(path); err == nil {
135 return nil
136 }
137 select {
138 case <-ctx.Done():
139 return nil
140 case <-time.After(200 * time.Millisecond):
141 }
142 }
143}