-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathreloader.go
322 lines (286 loc) · 7.45 KB
/
reloader.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/fs"
"log"
"math"
"mime"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
func watchForReload(ctx context.Context, root string, reload chan struct{}) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(fmt.Errorf("creating new fsnotify watcher: %v", err))
}
go debounceEvents(ctx, 125*time.Millisecond, watcher, func(event fsnotify.Event) {
if !reloadableFilename(event.Name) {
return
}
if isDir(event.Name) {
if err := watchDirRecursively(watcher, event.Name); err != nil {
panic(err)
}
return
}
reload <- struct{}{}
watcher.Close()
})
if err := watchDirRecursively(watcher, root); err != nil {
panic(fmt.Errorf("adding dir to watch: %w", err))
}
}
// reloadableFilename tests whether the file is one we want to trigger a reload
// from if it is modified. it tries not to cause a lot of unnecessary reloads
// by ignoring temporary files from editors like vim and Emacs.
func reloadableFilename(path string) bool {
ext := filepath.Ext(path)
// ignore vim swap files: .swp, .swo, .swn, etc
if len(ext) == 4 && strings.HasPrefix(ext, ".sw") {
return false
}
// ignore vim and Emacs backup files
if strings.HasSuffix(ext, "~") {
return false
}
// ignore Emacs autosave files
if strings.HasPrefix(ext, "#") && strings.HasSuffix(ext, "#") {
return false
}
return true
}
func isDir(path string) bool {
fi, err := os.Stat(path)
if err != nil {
log.Printf("error stat'ing path %s, skipping", path)
return false
}
return fi.IsDir()
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return !errors.Is(err, fs.ErrNotExist)
}
func watchDirRecursively(watcher *fsnotify.Watcher, root string) error {
err := fs.WalkDir(os.DirFS(root), ".", func(path string, d fs.DirEntry, _ error) error {
if d.IsDir() {
path = filepath.Join(root, path)
if err := watcher.Add(path); err != nil {
return fmt.Errorf("adding path %s to watch: %w", path, err)
}
log.Printf("adding %s to watch", path)
}
return nil
})
return err
}
func startReloadRevProxy(socketPath string, buildComplete *sync.Cond, port string) error {
// FIXME(paulsmith): addr should be a command line flag or env var, here
// and elsewhere
addr := "0.0.0.0:" + port
ln, err := net.Listen("tcp4", addr)
if err != nil {
return fmt.Errorf("listening to port: %w", err)
}
target, err := url.Parse("http://" + addr)
if err != nil {
return fmt.Errorf("parsing URL: %w", err)
}
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.Transport = &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", socketPath)
},
}
proxy.ModifyResponse = modifyResponseAddDevReload
reloadHandler := new(devReloader)
reloadHandler.complete = buildComplete
reloadHandler.verboseLogging = os.Getenv("VERBOSE") != ""
mux := http.NewServeMux()
mux.Handle("/", proxy)
mux.Handle("/--dev-reload", reloadHandler)
srv := http.Server{Handler: mux}
// FIXME(paulsmith): shutdown
//nolint:errcheck
go srv.Serve(ln)
fmt.Fprintf(os.Stdout, "\x1b[1;36m↑↑ PUSHUP DEV RELOADER ON http://%s ↑↑\x1b[0m\n", addr)
return nil
}
func modifyResponseAddDevReload(res *http.Response) error {
mediatype, _, err := mime.ParseMediaType(res.Header.Get("Content-Type"))
if err != nil {
return fmt.Errorf("parsing MIME type: %w", err)
}
// FIXME(paulsmith): we might not want to skip injecting in the case of a
// hx-boost link
if mediatype == "text/html" {
if res.Header.Get("Pushup-Partial") == "true" || res.Header.Get("HX-Response") == "true" {
return nil
}
doc, err := appendDevReloaderScript(res.Body)
if err != nil {
return fmt.Errorf("appending dev reloading script: %w", err)
}
if err := res.Body.Close(); err != nil {
return fmt.Errorf("closing proxied response body: %w", err)
}
var buf bytes.Buffer
if err := html.Render(&buf, doc); err != nil {
return fmt.Errorf("rendering modified HTML doc: %w", err)
}
res.Body = io.NopCloser(&buf)
res.ContentLength = int64(buf.Len())
res.Header.Set("Content-Length", strconv.Itoa(buf.Len()))
}
return nil
}
type devReloader struct {
complete *sync.Cond
verboseLogging bool
}
func (d *devReloader) ServeHTTP(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
panic("can't flush response so SSE not supported")
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
built := make(chan struct{})
done := make(chan struct{})
// FIXME(paulsmith): this probably leaks goroutines
go func() {
d.complete.L.Lock()
d.complete.Wait()
d.complete.L.Unlock()
select {
case built <- struct{}{}:
case <-done:
return
}
}()
loop:
for {
select {
case <-built:
//nolint:errcheck
w.Write([]byte("event: reload\ndata: \n\n"))
case <-r.Context().Done():
if d.verboseLogging {
log.Printf("client disconnected")
}
close(done)
break loop
case <-time.After(1 * time.Second):
//nolint:errcheck
w.Write([]byte(":keepalive\n\n"))
flusher.Flush()
}
}
}
var devReloaderScript = `
if (!window.EventSource) {
throw "Server-sent events not supported by this browser, live reloading disabled";
}
var source = new EventSource("/--dev-reload");
source.onmessage = e => {
console.log("message:", e.data);
}
source.addEventListener("reload", () => {
console.log("%c↑↑ Pushup server changed, reloading page ↑↑", "color: green");
location.reload(true);
}, false);
source.addEventListener("open", e => {
console.log("%c↑↑ Connection to Pushup server for dev mode reloading established ↑↑", "color: green");
}, false);
source.onerror = err => {
console.error("SSE error:", err);
};
`
func appendDevReloaderScript(r io.Reader) (*html.Node, error) {
doc, err := html.Parse(r)
if err != nil {
return nil, fmt.Errorf("parsing HTML: %w", err)
}
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "body" {
text := &html.Node{
Type: html.TextNode,
Data: devReloaderScript,
}
script := &html.Node{
Type: html.ElementNode,
Data: "script",
DataAtom: atom.Script,
Attr: []html.Attribute{
{Key: "type", Val: "text/javascript"},
},
}
script.AppendChild(text)
n.AppendChild(script)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(doc)
return doc, nil
}
func debounceEvents(ctx context.Context, interval time.Duration, watcher *fsnotify.Watcher, fn func(event fsnotify.Event)) {
var mu sync.Mutex
timers := make(map[string]*time.Timer)
has := func(ev fsnotify.Event, op fsnotify.Op) bool {
return ev.Op&op == op
}
for {
select {
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Printf("file watch error: %v", err)
case ev, ok := <-watcher.Events:
if !ok {
return
}
if !has(ev, fsnotify.Create) && !has(ev, fsnotify.Write) {
continue
}
mu.Lock()
t, ok := timers[ev.Name]
mu.Unlock()
if !ok {
t = time.AfterFunc(math.MaxInt64, func() {
fn(ev)
mu.Lock()
defer mu.Unlock()
delete(timers, ev.Name)
})
t.Stop()
mu.Lock()
timers[ev.Name] = t
mu.Unlock()
}
t.Reset(interval)
case <-ctx.Done():
return
}
}
}