-
Notifications
You must be signed in to change notification settings - Fork 111
/
watcher.go
229 lines (191 loc) · 4.32 KB
/
watcher.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package file
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/fsnotify/fsnotify"
runtimev1 "github.com/rilldata/rill/proto/gen/rill/runtime/v1"
"github.com/rilldata/rill/runtime/drivers"
)
const batchInterval = 250 * time.Millisecond
const maxBufferSize = 1000
// watcher implements a recursive, batching file watcher on top of fsnotify.
type watcher struct {
root string
watcher *fsnotify.Watcher
done chan struct{}
err error
mu sync.Mutex
subscribers map[string]drivers.WatchCallback
buffer []drivers.WatchEvent
}
func newWatcher(root string) (*watcher, error) {
fsw, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
w := &watcher{
root: root,
watcher: fsw,
done: make(chan struct{}),
subscribers: make(map[string]drivers.WatchCallback),
}
err = w.addDir(root, false)
if err != nil {
w.watcher.Close()
return nil, err
}
go w.run()
return w, nil
}
func (w *watcher) close() {
w.closeWithErr(nil)
}
func (w *watcher) closeWithErr(err error) {
w.mu.Lock()
defer w.mu.Unlock()
select {
case <-w.done:
// Already closed
return
default:
}
closeErr := w.watcher.Close()
w.err = errors.Join(err, closeErr)
if w.err == nil {
w.err = fmt.Errorf("file watcher closed")
}
close(w.done)
}
func (w *watcher) subscribe(ctx context.Context, fn drivers.WatchCallback) error {
w.mu.Lock()
if w.err != nil {
w.mu.Unlock()
return w.err
}
id := fmt.Sprintf("%v", fn)
w.subscribers[id] = fn
w.mu.Unlock()
defer func() {
w.mu.Lock()
delete(w.subscribers, id)
w.mu.Unlock()
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-w.done:
return w.err
}
}
// flush emits buffered events to all subscribers.
// Note it is called in the event loop in runInner, so new events will not be appended to w.buffer while a flush is running.
// Calls to flush block until all subscribers have processed the events. This is an acceptable trade-off for now, but we may want to revisit it in the future.
func (w *watcher) flush() {
if len(w.buffer) == 0 {
return
}
w.mu.Lock()
defer w.mu.Unlock()
for _, fn := range w.subscribers {
fn(w.buffer)
}
w.buffer = nil
}
func (w *watcher) run() {
err := w.runInner()
w.closeWithErr(err)
}
func (w *watcher) runInner() error {
ticker := time.NewTicker(batchInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
ticker.Stop()
w.flush()
case err, ok := <-w.watcher.Errors:
if !ok {
return nil
}
return err
case e, ok := <-w.watcher.Events:
if !ok {
return nil
}
we := drivers.WatchEvent{}
if e.Has(fsnotify.Create) || e.Has(fsnotify.Write) {
we.Type = runtimev1.FileEvent_FILE_EVENT_WRITE
} else if e.Has(fsnotify.Remove) || e.Has(fsnotify.Rename) {
we.Type = runtimev1.FileEvent_FILE_EVENT_DELETE
} else {
continue
}
path, err := filepath.Rel(w.root, e.Name)
if err != nil {
return err
}
path = filepath.Join("/", path)
we.Path = path
if e.Has(fsnotify.Create) {
info, err := os.Stat(e.Name)
we.Dir = err == nil && info.IsDir()
}
w.buffer = append(w.buffer, we)
// Calling addDir after appending to w.buffer, to sequence events correctly
if we.Dir && e.Has(fsnotify.Create) {
err = w.addDir(e.Name, true)
if err != nil {
return err
}
}
// Reset the timer so we only flush when no events have been observed for batchInterval.
// (But to avoid the buffer growing infinitely in edge cases, we enforce a max buffer size.)
if len(w.buffer) < maxBufferSize {
ticker.Reset(batchInterval)
} else {
ticker.Stop()
w.flush()
}
}
}
}
func (w *watcher) addDir(path string, replay bool) error {
err := w.watcher.Add(path)
if err != nil {
return err
}
entries, err := os.ReadDir(path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
for _, e := range entries {
fullPath := filepath.Join(path, e.Name())
if replay {
ep, err := filepath.Rel(w.root, fullPath)
if err != nil {
return err
}
ep = filepath.Join("/", ep)
w.buffer = append(w.buffer, drivers.WatchEvent{
Path: ep,
Type: runtimev1.FileEvent_FILE_EVENT_WRITE,
Dir: e.IsDir(),
})
}
if e.IsDir() {
err := w.addDir(fullPath, replay)
if err != nil {
return err
}
}
}
return nil
}