-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjaws.go
More file actions
981 lines (900 loc) · 26.4 KB
/
jaws.go
File metadata and controls
981 lines (900 loc) · 26.4 KB
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
// package jaws provides a mechanism to create dynamic
// webpages using Javascript and WebSockets.
//
// It integrates well with Go's html/template package,
// but can be used without it. It can be used with any
// router that supports the standard ServeHTTP interface.
package jaws
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"maps"
"net"
"net/http"
"net/netip"
"net/textproto"
"net/url"
"slices"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/linkdata/deadlock"
"github.com/linkdata/jaws/lib/assets"
"github.com/linkdata/jaws/lib/jid"
"github.com/linkdata/jaws/lib/tag"
"github.com/linkdata/jaws/lib/what"
"github.com/linkdata/jaws/lib/wire"
"github.com/linkdata/secureheaders"
"github.com/linkdata/staticserve"
)
const (
DefaultUpdateInterval = time.Millisecond * 100 // Default browser update interval
DefaultWebSocketPingInterval = time.Minute // Default WebSocket keepalive ping interval
DefaultWebSocketTimeout = time.Second * 10 // WebSocket must connect and respond within this interval
)
type subscription struct {
msgCh chan wire.Message
rq *Request
}
// Jid is the identifier type used for HTML elements managed by JaWS.
//
// It is provided as a convenience alias to the value defined in the jid
// subpackage so applications do not have to import that package directly
// when working with element IDs.
type Jid = jid.Jid // convenience alias
// Jaws holds the server-side state and configuration for a JaWS instance.
//
// A single Jaws value coordinates template lookup, session handling and the
// request lifecycle that keeps the browser and backend synchronized via
// WebSockets. The zero value is not ready for use; construct instances with
// New to ensure the helper goroutines and static assets are prepared.
type Jaws struct {
CookieName string // Name for session cookies, defaults to "jaws"
Logger Logger // Optional logger to use
Debug bool // Set to true to enable debug info in generated HTML code
MakeAuth MakeAuthFn // Optional function to create With.Auth for Templates
BaseContext context.Context // Non-nil base context for Requests, set to context.Background() in New()
WebSocketPingInterval time.Duration // Interval between keepalive pings on active WebSocket connections. Defaults to DefaultWebSocketPingInterval. Set <=0 to disable keepalive pings.
webSocketTimeout time.Duration // timeout duration passed to ServeWith
bcastCh chan wire.Message
subCh chan subscription
unsubCh chan chan wire.Message
updateTicker *time.Ticker
reqPool sync.Pool
serveJS *staticserve.StaticServe
serveCSS *staticserve.StaticServe
mu deadlock.RWMutex // protects following
headPrefix string
faviconURL string
cspHeader string
tmplookers []TemplateLookuper
kg *bufio.Reader
closeCh chan struct{} // closed when Close() has been called
requests map[uint64]*Request
sessions map[uint64]*Session
dirty map[any]int
dirtOrder int
}
// New allocates a JaWS instance with the default configuration.
//
// The returned Jaws value is ready for use: static assets are embedded,
// internal goroutines are configured and the request pool is primed. Call
// Close when the instance is no longer needed to free associated resources.
func New() (jw *Jaws, err error) {
var serveJS, serveCSS *staticserve.StaticServe
if serveJS, err = staticserve.New("/jaws/.jaws.js", assets.JavascriptText); err == nil {
if serveCSS, err = staticserve.New("/jaws/.jaws.css", assets.JawsCSS); err == nil {
tmp := &Jaws{
CookieName: assets.DefaultCookieName,
BaseContext: context.Background(),
WebSocketPingInterval: DefaultWebSocketPingInterval,
webSocketTimeout: DefaultWebSocketTimeout,
serveJS: serveJS,
serveCSS: serveCSS,
bcastCh: make(chan wire.Message, 1),
subCh: make(chan subscription, 1),
unsubCh: make(chan chan wire.Message, 1),
updateTicker: time.NewTicker(DefaultUpdateInterval),
kg: bufio.NewReader(rand.Reader),
requests: make(map[uint64]*Request),
sessions: make(map[uint64]*Session),
dirty: make(map[any]int),
closeCh: make(chan struct{}),
}
if err = tmp.GenerateHeadHTML(); err == nil {
jw = tmp
jw.reqPool.New = func() any {
return (&Request{
Jaws: jw,
tagMap: make(map[any][]*Element),
}).clearLocked()
}
}
}
}
return
}
// Close frees resources associated with the JaWS object, and
// closes the completion channel if the JaWS was created with New().
// Once the completion channel is closed, broadcasts and sends may be discarded.
// Subsequent calls to Close() have no effect.
func (jw *Jaws) Close() {
jw.mu.Lock()
select {
case <-jw.closeCh:
// already closed
default:
close(jw.closeCh)
}
jw.updateTicker.Stop()
jw.mu.Unlock()
}
// Done returns the channel that is closed when Close has been called.
func (jw *Jaws) Done() <-chan struct{} {
return jw.closeCh
}
// AddTemplateLookuper adds an object that can resolve
// strings to *template.Template.
func (jw *Jaws) AddTemplateLookuper(tl TemplateLookuper) (err error) {
if tl != nil {
if err = tag.NewErrNotComparable(tl); err == nil {
jw.mu.Lock()
if !slices.Contains(jw.tmplookers, tl) {
jw.tmplookers = append(jw.tmplookers, tl)
}
jw.mu.Unlock()
}
}
return
}
// RemoveTemplateLookuper removes the given object from
// the list of TemplateLookupers.
func (jw *Jaws) RemoveTemplateLookuper(tl TemplateLookuper) (err error) {
if tl != nil {
if err = tag.NewErrNotComparable(tl); err == nil {
jw.mu.Lock()
jw.tmplookers = slices.DeleteFunc(jw.tmplookers, func(x TemplateLookuper) bool { return x == tl })
jw.mu.Unlock()
}
}
return
}
// LookupTemplate queries the known TemplateLookupers in the order
// they were added and returns the first found.
func (jw *Jaws) LookupTemplate(name string) *template.Template {
jw.mu.RLock()
defer jw.mu.RUnlock()
for _, tl := range jw.tmplookers {
if t := tl.Lookup(name); t != nil {
return t
}
}
return nil
}
// RequestCount returns the number of Requests.
//
// The count includes all Requests, including those being rendered,
// those waiting for the WebSocket callback and those active.
func (jw *Jaws) RequestCount() (n int) {
jw.mu.RLock()
n = len(jw.requests)
jw.mu.RUnlock()
return
}
// Log sends an error to the Logger set in the Jaws.
// Has no effect if the err is nil or the Logger is nil.
// Returns err.
func (jw *Jaws) Log(err error) error {
if err != nil && jw != nil && jw.Logger != nil {
jw.Logger.Error("jaws", "err", err)
}
return err
}
// MustLog sends an error to the Logger set in the Jaws or
// panics with the given error if no Logger is set.
// Has no effect if the err is nil.
func (jw *Jaws) MustLog(err error) {
if err != nil {
if jw != nil && jw.Logger != nil {
jw.Logger.Error("jaws", "err", err)
} else {
panic(err)
}
}
}
// NextID returns an int64 unique within lifetime of the program.
func NextID() int64 {
return atomic.AddInt64((*int64)(&NextJid), 1)
}
// AppendID appends the result of NextID() in text form to the given slice.
func AppendID(b []byte) []byte {
return strconv.AppendInt(b, NextID(), 32)
}
// MakeID returns a string in the form 'jaws.X' where X is a unique string within lifetime of the program.
func MakeID() string {
return string(AppendID([]byte("jaws.")))
}
// NewRequest returns a new pending JaWS request.
//
// Call this as soon as you start processing a HTML request, and store the
// returned Request pointer so it can be used while constructing the HTML
// response in order to register the JaWS id's you use in the response, and
// use it's Key attribute when sending the Javascript portion of the reply.
//
// Automatic timeout handling is performed by ServeWithTimeout. The default
// Serve() helper uses a 10-second timeout.
func (jw *Jaws) NewRequest(hr *http.Request) (rq *Request) {
jw.mu.Lock()
defer jw.mu.Unlock()
for rq == nil {
jawsKey := jw.nonZeroRandomLocked()
if _, ok := jw.requests[jawsKey]; !ok {
rq = jw.getRequestLocked(jawsKey, hr)
jw.requests[jawsKey] = rq
}
}
return
}
func (jw *Jaws) nonZeroRandomLocked() (val uint64) {
random := make([]byte, 8)
for val == 0 {
if _, err := io.ReadFull(jw.kg, random); err != nil {
panic(err)
}
val = binary.LittleEndian.Uint64(random)
}
return
}
// UseRequest extracts the JaWS request with the given key from the request
// map if it exists and the HTTP request remote IP matches.
//
// Call it when receiving the WebSocket connection on '/jaws/:key' to get the
// associated Request, and then call it's ServeHTTP method to process the
// WebSocket messages.
//
// Returns nil if the key was not found or the IP doesn't match, in which
// case you should return a HTTP "404 Not Found" status.
func (jw *Jaws) UseRequest(jawsKey uint64, hr *http.Request) (rq *Request) {
if jawsKey != 0 {
var err error
jw.mu.Lock()
if waitingRq, ok := jw.requests[jawsKey]; ok {
if err = waitingRq.claim(hr); err == nil {
rq = waitingRq
}
}
jw.mu.Unlock()
_ = jw.Log(err)
}
return
}
// SessionCount returns the number of active sessions.
func (jw *Jaws) SessionCount() (n int) {
jw.mu.RLock()
n = len(jw.sessions)
jw.mu.RUnlock()
return
}
// Sessions returns a list of all active sessions, which may be nil.
func (jw *Jaws) Sessions() (sl []*Session) {
jw.mu.RLock()
if n := len(jw.sessions); n > 0 {
sl = make([]*Session, 0, n)
for _, sess := range jw.sessions {
sl = append(sl, sess)
}
}
jw.mu.RUnlock()
return
}
func (jw *Jaws) getSessionLocked(sessIds []uint64, remoteIP netip.Addr) *Session {
for _, sessId := range sessIds {
if sess, ok := jw.sessions[sessId]; ok && equalIP(remoteIP, sess.remoteIP) {
if !sess.isDead() {
return sess
}
}
}
return nil
}
func cutString(s string, sep byte) (before, after string) {
if i := strings.IndexByte(s, sep); i >= 0 {
return s[:i], s[i+1:]
}
return s, ""
}
func getCookieSessionsIds(h http.Header, wanted string) (cookies []uint64) {
for _, line := range h["Cookie"] {
if strings.Contains(line, wanted) {
var part string
line = textproto.TrimString(line)
for len(line) > 0 {
part, line = cutString(line, ';')
if part = textproto.TrimString(part); part != "" {
name, val := cutString(part, '=')
name = textproto.TrimString(name)
if name == wanted {
if len(val) > 1 && val[0] == '"' && val[len(val)-1] == '"' {
val = val[1 : len(val)-1]
}
if sessId := assets.JawsKeyValue(val); sessId != 0 {
cookies = append(cookies, sessId)
}
}
}
}
}
}
return
}
// GetSession returns the Session associated with the given *http.Request, or nil.
func (jw *Jaws) GetSession(hr *http.Request) (sess *Session) {
if hr != nil {
if sessIds := getCookieSessionsIds(hr.Header, jw.CookieName); len(sessIds) > 0 {
remoteIP := parseIP(hr.RemoteAddr)
jw.mu.RLock()
sess = jw.getSessionLocked(sessIds, remoteIP)
jw.mu.RUnlock()
}
}
return
}
// NewSession creates a new Session.
//
// Any pre-existing Session will be cleared and closed.
// This may call Session.Close() on an existing session and therefore requires
// the JaWS processing loop (`Serve()` or `ServeWithTimeout()`) to be running.
//
// Subsequent Requests created with `NewRequest()` that have the cookie set and
// originates from the same IP will be able to access the Session.
func (jw *Jaws) NewSession(w http.ResponseWriter, hr *http.Request) (sess *Session) {
if hr != nil {
if oldSess := jw.GetSession(hr); oldSess != nil {
oldSess.Clear()
oldSess.Close()
}
sess = jw.newSession(w, hr)
}
return
}
func (jw *Jaws) newSession(w http.ResponseWriter, hr *http.Request) (sess *Session) {
secure := requestIsSecure(hr)
jw.mu.Lock()
defer jw.mu.Unlock()
for sess == nil {
sessionID := jw.nonZeroRandomLocked()
if _, ok := jw.sessions[sessionID]; !ok {
sess = newSession(jw, sessionID, parseIP(hr.RemoteAddr), secure)
jw.sessions[sessionID] = sess
if w != nil {
http.SetCookie(w, &sess.cookie)
}
hr.AddCookie(&sess.cookie)
}
}
return
}
func (jw *Jaws) deleteSession(sessionID uint64) {
jw.mu.Lock()
delete(jw.sessions, sessionID)
jw.mu.Unlock()
}
func (jw *Jaws) FaviconURL() (s string) {
jw.mu.RLock()
s = jw.faviconURL
jw.mu.RUnlock()
return
}
// ContentSecurityPolicy returns the generated Content-Security-Policy header value.
func (jw *Jaws) ContentSecurityPolicy() (s string) {
jw.mu.RLock()
s = jw.cspHeader
jw.mu.RUnlock()
return
}
// SecureHeadersMiddleware wraps next with security headers that match the
// current JaWS configuration.
//
// It snapshots secureheaders.DefaultHeaders, replacing the
// Content-Security-Policy value with ContentSecurityPolicy so responses allow
// the resources configured by GenerateHeadHTML.
//
// The returned middleware does not trust forwarded HTTPS headers.
// The next handler must be non-nil.
func (jw *Jaws) SecureHeadersMiddleware(next http.Handler) http.Handler {
hdrs := maps.Clone(secureheaders.DefaultHeaders)
hdrs["Content-Security-Policy"] = []string{jw.ContentSecurityPolicy()}
return secureheaders.Middleware{
Handler: next,
Header: hdrs,
}
}
// GenerateHeadHTML (re-)generates the HTML code that goes in the HEAD section, ensuring
// that the provided URL resources in `extra` are loaded, along with the JaWS javascript.
// If one of the resources is named "favicon", it's URL will be stored and can
// be retrieved using FaviconURL().
//
// You only need to call this if you add your own images, scripts and stylesheets.
func (jw *Jaws) GenerateHeadHTML(extra ...string) (err error) {
var jawsurl *url.URL
if jawsurl, err = url.Parse(jw.serveJS.Name); err == nil {
var cssurl *url.URL
if cssurl, err = url.Parse(jw.serveCSS.Name); err == nil {
var urls []*url.URL
urls = append(urls, cssurl)
urls = append(urls, jawsurl)
for _, urlstr := range extra {
if u, e := url.Parse(urlstr); e == nil {
if !strings.HasSuffix(u.Path, jawsurl.Path) {
urls = append(urls, u)
}
} else {
err = errors.Join(err, e)
}
}
headPrefix, faviconURL := assets.PreloadHTML(urls...)
if jw.Debug {
headPrefix += `<meta name="jawsDebug" content="true">`
}
headPrefix += `<meta name="jawsKey" content="`
cspHeader, csperr := secureheaders.BuildContentSecurityPolicy(urls)
err = errors.Join(err, csperr)
jw.mu.Lock()
jw.headPrefix = headPrefix
jw.faviconURL = faviconURL
jw.cspHeader = cspHeader
jw.mu.Unlock()
}
}
return
}
// Broadcast sends a message to all Requests.
//
// It must not be called before the JaWS processing loop (`Serve()` or
// `ServeWithTimeout()`) is running. Otherwise this call may block once the
// internal broadcast channel fills.
//
// All convenience helpers on Jaws that call Broadcast inherit this requirement.
func (jw *Jaws) Broadcast(msg wire.Message) {
switch msg.Dest.(type) {
case nil: // send to all requests
case *Request: // send to that request
case string: // HTML id (accepted by all requests)
default:
expanded, err := tag.TagExpand(nil, msg.Dest)
jw.MustLog(err)
switch len(expanded) {
case 0:
// no tags, so no requests will match
return
case 1:
msg.Dest = expanded[0]
default:
msg.Dest = expanded
}
}
select {
case <-jw.Done():
case jw.bcastCh <- msg:
}
}
// setDirty marks all Elements that have one or more of the given tags as dirty.
func (jw *Jaws) setDirty(tags []any) {
jw.mu.Lock()
for _, tagValue := range tags {
jw.dirtOrder++
jw.dirty[tagValue] = jw.dirtOrder
}
jw.mu.Unlock()
}
// Dirty marks all Elements that have one or more of the given tags as dirty.
//
// Note that if any of the tags are a TagGetter, it will be called with a nil Request.
// Prefer using Request.Dirty() which avoids this.
func (jw *Jaws) Dirty(dirtyTags ...any) {
jw.setDirty(tag.MustTagExpand(nil, dirtyTags))
}
func (jw *Jaws) distributeDirt() int {
var reqs []*Request
var dirt []any
jw.mu.Lock()
if len(jw.dirty) > 0 {
dirt = make([]any, 0, len(jw.dirty))
for k := range jw.dirty {
dirt = append(dirt, k)
}
sort.Slice(dirt, func(i, j int) bool { return jw.dirty[dirt[i]] < jw.dirty[dirt[j]] })
clear(jw.dirty)
jw.dirtOrder = 0
reqs = make([]*Request, 0, len(jw.requests))
for _, rq := range jw.requests {
reqs = append(reqs, rq)
}
}
jw.mu.Unlock()
for _, rq := range reqs {
rq.appendDirtyTags(dirt)
}
return len(dirt)
}
// Reload requests all Requests to reload their current page.
func (jw *Jaws) Reload() {
jw.Broadcast(wire.Message{
What: what.Reload,
})
}
// Redirect requests all Requests to navigate to the given URL.
func (jw *Jaws) Redirect(url string) {
jw.Broadcast(wire.Message{
What: what.Redirect,
Data: url,
})
}
// Alert sends an alert to all Requests. The lvl argument should be one of Bootstraps alert levels:
// primary, secondary, success, danger, warning, info, light or dark.
func (jw *Jaws) Alert(lvl, msg string) {
jw.Broadcast(wire.Message{
What: what.Alert,
Data: lvl + "\n" + msg,
})
}
// Pending returns the number of requests waiting for their WebSocket callbacks.
func (jw *Jaws) Pending() (n int) {
jw.mu.RLock()
defer jw.mu.RUnlock()
for _, rq := range jw.requests {
if !rq.claimed.Load() {
n++
}
}
return
}
func (jw *Jaws) getWebSocketTimeout() (t time.Duration) {
jw.mu.RLock()
t = jw.webSocketTimeout
jw.mu.RUnlock()
return
}
// ServeWithTimeout begins processing requests with the given timeout.
// It is intended to run on it's own goroutine.
// It returns when Close is called.
func (jw *Jaws) ServeWithTimeout(requestTimeout time.Duration) {
const minInterval = time.Millisecond * 10
const maxInterval = time.Second
maintenanceInterval := requestTimeout / 2
if maintenanceInterval > maxInterval {
maintenanceInterval = maxInterval
}
if maintenanceInterval < minInterval {
maintenanceInterval = minInterval
}
subs := map[chan wire.Message]*Request{}
t := time.NewTicker(maintenanceInterval)
jw.mu.Lock()
jw.webSocketTimeout = requestTimeout
jw.mu.Unlock()
defer func() {
t.Stop()
for ch, rq := range subs {
rq.cancel(nil)
close(ch)
}
}()
killSub := func(msgCh chan wire.Message) {
if _, ok := subs[msgCh]; ok {
delete(subs, msgCh)
close(msgCh)
}
}
// it's critical that we keep the broadcast
// distribution loop running, so any Request
// that fails to process it's messages quickly
// enough must be terminated. the alternative
// would be to drop some messages, but that
// could mean nonreproducible and seemingly
// random failures in processing logic.
mustBroadcast := func(msg wire.Message) {
for msgCh, rq := range subs {
if msg.Dest == nil || rq.wantMessage(&msg) {
select {
case msgCh <- msg:
default:
// the exception is Update messages, more will follow eventually
if msg.What != what.Update {
killSub(msgCh)
rq.cancel(fmt.Errorf("%v: broadcast channel full sending %s", rq, msg.String()))
}
}
}
}
}
for {
select {
case <-jw.Done():
return
case <-jw.updateTicker.C:
if jw.distributeDirt() > 0 {
mustBroadcast(wire.Message{What: what.Update})
}
case <-t.C:
jw.maintenance(requestTimeout)
case sub := <-jw.subCh:
if sub.msgCh != nil {
subs[sub.msgCh] = sub.rq
}
case msgCh := <-jw.unsubCh:
killSub(msgCh)
case msg, ok := <-jw.bcastCh:
if ok {
mustBroadcast(msg)
}
}
}
}
// Serve calls ServeWithTimeout(DefaultWebSocketTimeout).
// It is intended to run on it's own goroutine.
// It returns when Close is called.
func (jw *Jaws) Serve() {
jw.ServeWithTimeout(DefaultWebSocketTimeout)
}
func (jw *Jaws) subscribe(rq *Request, size int) chan wire.Message {
msgCh := make(chan wire.Message, size)
select {
case <-jw.Done():
close(msgCh)
return nil
case jw.subCh <- subscription{msgCh: msgCh, rq: rq}:
}
return msgCh
}
func (jw *Jaws) unsubscribe(msgCh chan wire.Message) {
select {
case <-jw.Done():
case jw.unsubCh <- msgCh:
}
}
func (jw *Jaws) maintenance(requestTimeout time.Duration) {
jw.mu.Lock()
defer jw.mu.Unlock()
now := time.Now()
for _, rq := range jw.requests {
if rq.maintenance(now, requestTimeout) {
jw.recycleLocked(rq)
}
}
for k, sess := range jw.sessions {
if sess.isDead() {
delete(jw.sessions, k)
}
}
}
func equalIP(a, b netip.Addr) bool {
return a.Compare(b) == 0 || (a.IsLoopback() && b.IsLoopback())
}
func parseIP(remoteAddr string) (ip netip.Addr) {
if remoteAddr != "" {
if host, _, err := net.SplitHostPort(remoteAddr); err == nil {
ip, _ = netip.ParseAddr(host)
} else {
ip, _ = netip.ParseAddr(remoteAddr)
}
}
return
}
func requestIsSecure(hr *http.Request) (yes bool) {
yes = secureheaders.RequestIsSecure(hr, true)
return
}
func maybePanic(err error) {
if err != nil {
panic(err)
}
}
// SetInner sends a request to replace the inner HTML of
// all HTML elements matching target.
func (jw *Jaws) SetInner(target any, innerHTML template.HTML) {
jw.Broadcast(wire.Message{
Dest: target,
What: what.Inner,
Data: string(innerHTML),
})
}
// SetAttr sends a request to replace the given attribute value in
// all HTML elements matching target.
func (jw *Jaws) SetAttr(target any, attr, val string) {
jw.Broadcast(wire.Message{
Dest: target,
What: what.SAttr,
Data: attr + "\n" + val,
})
}
// RemoveAttr sends a request to remove the given attribute from
// all HTML elements matching target.
func (jw *Jaws) RemoveAttr(target any, attr string) {
jw.Broadcast(wire.Message{
Dest: target,
What: what.RAttr,
Data: attr,
})
}
// SetClass sends a request to set the given class in
// all HTML elements matching target.
func (jw *Jaws) SetClass(target any, cls string) {
jw.Broadcast(wire.Message{
Dest: target,
What: what.SClass,
Data: cls,
})
}
// RemoveClass sends a request to remove the given class from
// all HTML elements matching target.
func (jw *Jaws) RemoveClass(target any, cls string) {
jw.Broadcast(wire.Message{
Dest: target,
What: what.RClass,
Data: cls,
})
}
// SetValue sends a request to set the HTML "value" attribute of
// all HTML elements matching target.
func (jw *Jaws) SetValue(target any, val string) {
jw.Broadcast(wire.Message{
Dest: target,
What: what.Value,
Data: val,
})
}
// Insert calls the Javascript 'insertBefore()' method on
// all HTML elements matching target.
//
// The position parameter 'where' may be either a HTML ID, an child index or the text 'null'.
func (jw *Jaws) Insert(target any, where, html string) {
jw.Broadcast(wire.Message{
Dest: target,
What: what.Insert,
Data: where + "\n" + html,
})
}
// Replace replaces HTML on all HTML elements matching target.
func (jw *Jaws) Replace(target any, html string) {
jw.Broadcast(wire.Message{
Dest: target,
What: what.Replace,
Data: html,
})
}
// Delete removes the HTML element(s) matching target.
func (jw *Jaws) Delete(target any) {
jw.Broadcast(wire.Message{
Dest: target,
What: what.Delete,
})
}
// Append calls the Javascript 'appendChild()' method on all HTML elements matching target.
func (jw *Jaws) Append(target any, html template.HTML) {
jw.Broadcast(wire.Message{
Dest: target,
What: what.Append,
Data: string(html),
})
}
func maybeCompactJSON(in string) (out string) {
out = in
if strings.ContainsAny(in, "\n\t") {
var b bytes.Buffer
if err := json.Compact(&b, []byte(in)); err == nil {
out = b.String()
}
}
return
}
var whitespaceRemover = strings.NewReplacer(" ", "", "\n", "", "\t", "")
// JsCall calls the Javascript function 'jsfunc' with the argument 'jsonstr'
// on all Requests that have the target UI tag.
func (jw *Jaws) JsCall(tagValue any, jsfunc, jsonstr string) {
jw.Broadcast(wire.Message{
Dest: tagValue,
What: what.Call,
Data: whitespaceRemover.Replace(jsfunc) + "=" + maybeCompactJSON(jsonstr),
})
}
func (jw *Jaws) getRequestLocked(jawsKey uint64, hr *http.Request) (rq *Request) {
rq = jw.reqPool.Get().(*Request)
rq.JawsKey = jawsKey
rq.lastWrite = time.Now()
rq.initial = hr
rq.ctx, rq.cancelFn = context.WithCancelCause(jw.BaseContext)
if hr != nil {
rq.remoteIP = parseIP(hr.RemoteAddr)
if sess := jw.getSessionLocked(getCookieSessionsIds(hr.Header, jw.CookieName), rq.remoteIP); sess != nil {
sess.addRequest(rq)
rq.session = sess
}
}
return rq
}
func (jw *Jaws) recycleLocked(rq *Request) {
rq.mu.Lock()
defer rq.mu.Unlock()
if rq.JawsKey != 0 {
delete(jw.requests, rq.JawsKey)
rq.clearLocked()
jw.reqPool.Put(rq)
}
}
func (jw *Jaws) recycle(rq *Request) {
jw.mu.Lock()
defer jw.mu.Unlock()
jw.recycleLocked(rq)
}
var headerCacheControlNoStore = []string{"no-store"}
// ServeHTTP can handle the required JaWS endpoints, which all start with "/jaws/".
func (jw *Jaws) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if len(r.URL.Path) > 6 && strings.HasPrefix(r.URL.Path, "/jaws/") {
if r.URL.Path[6] == '.' {
switch r.URL.Path {
case jw.serveCSS.Name:
jw.serveCSS.ServeHTTP(w, r)
return
case jw.serveJS.Name:
jw.serveJS.ServeHTTP(w, r)
return
case "/jaws/.ping":
w.Header()["Cache-Control"] = headerCacheControlNoStore
select {
case <-jw.Done():
w.WriteHeader(http.StatusServiceUnavailable)
default:
w.WriteHeader(http.StatusNoContent)
}
return
default:
if jawsKeyString, ok := strings.CutPrefix(r.URL.Path, "/jaws/.tail/"); ok {
jawsKey := assets.JawsKeyValue(jawsKeyString)
jw.mu.RLock()
rq := jw.requests[jawsKey]
jw.mu.RUnlock()
if rq != nil {
if err := rq.writeTailScriptResponse(w); err != nil {
rq.cancel(err)
}
return
}
}
}
} else if rq := jw.UseRequest(assets.JawsKeyValue(r.URL.Path[6:]), r); rq != nil {
rq.ServeHTTP(w, r)
return
}
}
w.WriteHeader(http.StatusNotFound)
}
type sessioner struct {
jw *Jaws
h http.Handler
}
func (sess sessioner) ServeHTTP(wr http.ResponseWriter, r *http.Request) {
if sess.jw.GetSession(r) == nil {
sess.jw.newSession(wr, r)
}
sess.h.ServeHTTP(wr, r)
}
// Session returns a http.Handler that ensures a JaWS Session exists before invoking h.
func (jw *Jaws) Session(h http.Handler) http.Handler {
return sessioner{jw: jw, h: h}
}