-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrequest_test.go
More file actions
4601 lines (4151 loc) · 125 KB
/
Copy pathrequest_test.go
File metadata and controls
4601 lines (4151 loc) · 125 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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package jaws
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"html/template"
"io"
"log"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
"time"
"github.com/coder/websocket"
"github.com/linkdata/deadlock"
"github.com/linkdata/jaws/lib/jid"
"github.com/linkdata/jaws/lib/key"
"github.com/linkdata/jaws/lib/tag"
"github.com/linkdata/jaws/lib/what"
"github.com/linkdata/jaws/lib/wire"
)
const testTimeout = time.Second * 3
type eventErrorLogger struct {
mu sync.Mutex
errs []error
}
func (*eventErrorLogger) Info(string, ...any) {}
func (*eventErrorLogger) Warn(string, ...any) {}
func (l *eventErrorLogger) Error(_ string, args ...any) {
l.mu.Lock()
defer l.mu.Unlock()
for i := 0; i+1 < len(args); i += 2 {
if args[i] == "err" {
if err, ok := args[i+1].(error); ok {
l.errs = append(l.errs, err)
}
}
}
}
func (l *eventErrorLogger) loggedErrors() (errs []error) {
l.mu.Lock()
errs = append(errs, l.errs...)
l.mu.Unlock()
return
}
func fillWsCh(ch chan wire.WsMsg) {
for {
select {
case ch <- wire.WsMsg{}:
default:
return
}
}
}
func TestRequest_MiscBranches(t *testing.T) {
rq := newTestRequest(t)
defer rq.Close()
reg := testRegisterUI{Updater: &testUi{}}
elem := rq.NewElement(reg)
if err := elem.JawsRender(nil, nil); err != nil {
t.Fatal(err)
}
if rq.Request.Initial() == nil {
t.Fatal("expected initial request")
}
if rq.Initial() == nil {
t.Fatal("expected initial request from writer")
}
e2 := rq.NewElement(&testUi{})
id2 := e2.Jid()
rq.DeleteElement(e2)
if rq.GetElementByJid(id2) != nil {
t.Fatal("expected deleted element")
}
}
func TestRequest_DeleteElementNil(t *testing.T) {
rq := newTestRequest(t)
defer rq.Close()
// GetElementByJid returns nil for an unknown Jid, so forwarding that result to
// DeleteElement must be a no-op rather than a nil dereference, matching the rest of
// the nil-tolerant *Element-accepting Request methods (Tag, TagExpanded, TagsOf).
rq.DeleteElement(rq.GetElementByJid(Jid(999)))
rq.DeleteElement(nil)
}
func TestRequest_TagExpandedDoesNotRetagConcurrentDeletion(t *testing.T) {
rq := &Request{tagMap: make(map[any][]*Element)}
elem := rq.NewElement(&testUi{})
tagValue := tag.Tag("deleted")
done := make(chan struct{})
// A mutex wait is not durably blocked for testing/synctest, so use the
// RWMutex's writer preference to observe that TagExpanded is waiting for its
// write lock. Since this bare Request has no other goroutines, TryRLock
// failing proves TagExpanded passed its pre-lock checks and queued as a writer.
rq.mu.RLock()
go func() {
rq.TagExpanded(elem, []any{tagValue})
close(done)
}()
for rq.mu.TryRLock() {
rq.mu.RUnlock()
runtime.Gosched()
}
// Deletion stores this flag while holding rq.mu. Store it directly here to
// model that state transition between TagExpanded's check and registration;
// the empty tag map means deletion's other cleanup has no bearing on the test.
elem.deleted.Store(true)
rq.mu.RUnlock()
<-done
if tags := rq.TagsOf(elem); len(tags) != 0 {
t.Fatalf("deleted Element retained tags: %v", tags)
}
}
func TestRequest_DeleteElements(t *testing.T) {
rq := newTestRequest(t)
defer rq.Close()
other := newTestRequest(t)
defer other.Close()
shared := tag.Tag("shared")
newTagged := func(rq *testRequest) *Element {
elem := rq.NewElement(&testUi{})
elem.Tag(shared)
return elem
}
// Empty and all-unusable input must not disturb the registry, and must not panic
// on the nil element.
rq.DeleteElements(nil)
rq.DeleteElements([]*Element{})
foreign := newTagged(other)
rq.DeleteElements([]*Element{nil, foreign})
if foreign.Deleted() {
t.Error("DeleteElements deleted an element belonging to another Request")
}
// Single element: the fast path still unregisters and marks it deleted.
single := newTagged(rq)
rq.DeleteElements([]*Element{single})
if !single.Deleted() || rq.GetElementByJid(single.Jid()) != nil {
t.Error("DeleteElements did not unregister a single element")
}
// Several elements at once, with a repeat and a foreign element mixed in. The
// shared tag entry must be dropped once its last element is gone.
keep := newTagged(rq)
a, b, c := newTagged(rq), newTagged(rq), newTagged(rq)
rq.DeleteElements([]*Element{a, b, c, b, nil, foreign})
for i, elem := range []*Element{a, b, c} {
if !elem.Deleted() {
t.Errorf("element %d not marked deleted", i)
}
if rq.GetElementByJid(elem.Jid()) != nil {
t.Errorf("element %d still registered", i)
}
}
if foreign.Deleted() {
t.Error("DeleteElements deleted a foreign element in a batch")
}
if got := rq.GetElements(shared); len(got) != 1 || got[0] != keep {
t.Errorf("tag entry after batch = %v, want only the kept element", got)
}
rq.DeleteElements([]*Element{keep})
if got := rq.GetElements(shared); len(got) != 0 {
t.Errorf("tag entry not dropped once empty: %v", got)
}
}
func TestRequest_Registrations(t *testing.T) {
is := newTestHelper(t)
rq := newTestRequest(t)
defer rq.Close()
x := &testUi{}
is.Equal(rq.wantMessage(&wire.Message{Dest: x}), false)
jid := rq.Register(x)
is.True(jid.IsValid())
is.Equal(rq.wantMessage(&wire.Message{Dest: x}), true)
is.Equal(rq.wantMessage(&wire.Message{Dest: "Jid.1"}), false)
}
func TestRequest_wantMessage_KeyDest(t *testing.T) {
is := newTestHelper(t)
rq := newTestRequest(t)
defer rq.Close()
liveKey := rq.JawsKey
is.True(liveKey != 0)
tests := []struct {
name string
dest key.Key
want bool
}{
{"matching key", liveKey, true},
{"other key", liveKey + 1, false},
{"zero key", 0, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
newTestHelper(t).Equal(rq.wantMessage(&wire.Message{Dest: tt.dest}), tt.want)
})
}
}
// TestRequest_wantMessage_RejectsFinishedRequest is the core broadcast regression:
// wantMessage gates the identity-key match on the registered() lifecycle state, so
// a finished Request stops matching its own key. The *Request pointer is never
// reused, and while the finished Request stays reachable its key value is held
// reserved by a tombstone, so a message aimed at that key reaches no one and a later
// Request matches only its own distinct key. (Once the finished Request is collected
// the tombstone is removed and the key value may eventually be reissued to a new
// Request.)
func TestRequest_wantMessage_RejectsFinishedRequest(t *testing.T) {
is := newTestHelper(t)
jw, _ := New()
go jw.Serve()
defer jw.Close()
rq := jw.NewRequest(httptest.NewRequest(http.MethodGet, "/", nil))
staleKey := rq.JawsKey
is.True(rq.wantMessage(&wire.Message{Dest: staleKey}))
// Finishing unregisters rq; it keeps its key but no longer matches it.
jw.recycle(rq)
is.Equal(rq.wantMessage(&wire.Message{Dest: staleKey}), false)
// A later client gets a distinct Request with a distinct key. It matches only its
// own key, and the finished Request's key is not reassigned to it (rq is still
// reachable here, so its key stays reserved).
replacement := jw.NewRequest(httptest.NewRequest(http.MethodGet, "/next", nil))
defer jw.recycle(replacement)
is.True(replacement != rq)
is.True(replacement.wantMessage(&wire.Message{Dest: replacement.JawsKey}))
is.Equal(replacement.wantMessage(&wire.Message{Dest: staleKey}), false)
}
func TestRequest_HeadHTML(t *testing.T) {
is := newTestHelper(t)
jw, _ := New()
defer jw.Close()
rq := jw.NewRequest(nil)
defer jw.recycle(rq)
var sb strings.Builder
is.NoErr(rq.Writer(&sb).HeadHTML())
txt := sb.String()
is.Equal(strings.Contains(txt, rq.JawsKeyString()), true)
is.Equal(strings.Contains(txt, jw.serveJS.Name), true)
is.Equal(strings.Contains(txt, `meta name="jawsDebug"`), false)
is.Equal(strings.Count(txt, "<script"), strings.Count(txt, "</script>"))
is.Equal(strings.Count(txt, "<style>"), strings.Count(txt, "</style>"))
}
func TestRequest_HeadHTML_DebugMeta(t *testing.T) {
jw, err := New()
if err != nil {
t.Fatal(err)
}
defer jw.Close()
jw.Debug = true
if err = jw.GenerateHeadHTML(); err != nil {
t.Fatal(err)
}
rq := jw.NewRequest(nil)
defer jw.recycle(rq)
var sb strings.Builder
if err = rq.Writer(&sb).HeadHTML(); err != nil {
t.Fatal(err)
}
txt := sb.String()
if !strings.Contains(txt, `meta name="jawsDebug"`) {
t.Fatalf("expected debug meta in head html, got %q", txt)
}
}
func TestRequestWriter_TailHTML(t *testing.T) {
th := newTestHelper(t)
jw, _ := New()
defer jw.Close()
rq := jw.NewRequest(nil)
defer jw.recycle(rq)
item := &testUi{}
e := rq.NewElement(item)
e.SetAttr("hidden", "yes")
e.RemoveAttr("hidden")
e.SetClass("cls")
e.RemoveClass("cls")
rq.muQueue.Lock()
num := len(rq.wsQueue)
rq.muQueue.Unlock()
th.Equal(num, 4)
var buf bytes.Buffer
th.NoErr(rq.Writer(&buf).TailHTML())
want := fmt.Sprintf(`
<noscript><div class="jaws-alert">This site requires Javascript for full functionality.</div><img src="/jaws/%s/noscript" alt="noscript"></noscript>
<script src="/jaws/.tail/%s"></script>
`, rq.JawsKeyString(), rq.JawsKeyString())
th.Equal(buf.String(), want)
// TailHTML should not consume wsQueue messages.
rq.muQueue.Lock()
num = len(rq.wsQueue)
rq.muQueue.Unlock()
th.Equal(num, 4)
}
func TestRequest_writeTailScript_EscapesScriptClose(t *testing.T) {
th := newTestHelper(t)
jw, _ := New()
defer jw.Close()
rq := jw.NewRequest(nil)
defer jw.recycle(rq)
item := &testUi{}
e := rq.NewElement(item)
e.SetAttr("title", "</script><img onerror=alert(1) src=x>")
w := httptest.NewRecorder()
b, sent := rq.drainTailScript()
if err := rq.writeTailResponse(w, b, sent); err != nil {
t.Fatal(err)
}
s := w.Body.String()
if strings.Contains(s, "</script><img") {
t.Fatalf("writeTailScript did not escape </script> in attribute value: %s", s)
}
th.True(strings.Contains(s, `\x3c/script>`))
}
func TestRequest_writeTailScript_QuotesAstralAndLineSeparators(t *testing.T) {
th := newTestHelper(t)
jw, _ := New()
defer jw.Close()
rq := jw.NewRequest(nil)
defer jw.recycle(rq)
item := &testUi{}
e := rq.NewElement(item)
// U+1FFFE is a non-printable astral code point: strconv.Quote would emit it as the
// Go-only escape \U0001fffe, which JavaScript silently mis-decodes to the literal
// text "U0001fffe", so the value must instead survive as literal UTF-8. U+2028 is a
// JavaScript line separator that must be escaped so it cannot break the inline
// <script> string literal.
e.SetAttr("data-x", "a\U0001FFFEb\u2028c")
w := httptest.NewRecorder()
b, sent := rq.drainTailScript()
if err := rq.writeTailResponse(w, b, sent); err != nil {
t.Fatal(err)
}
s := w.Body.String()
// No Go-only \U escape: JavaScript drops the backslash and keeps the letters.
if strings.Contains(s, `\U`) {
t.Fatalf("tail script contains a Go-only \\U escape JavaScript cannot decode: %s", s)
}
// The astral rune survives verbatim as literal UTF-8.
th.True(strings.Contains(s, "\U0001FFFE"))
// The line separator is escaped, not emitted literally.
th.True(strings.Contains(s, `\u2028`))
if strings.ContainsRune(s, '\u2028') {
t.Fatalf("tail script contains a literal U+2028 line separator: %q", s)
}
}
func TestRequest_writeTailScript_PreservesNonAttrMessages(t *testing.T) {
th := newTestHelper(t)
jw, _ := New()
defer jw.Close()
rq := jw.NewRequest(nil)
defer jw.recycle(rq)
item := &testUi{}
e := rq.NewElement(item)
// queue a mix of attribute and non-attribute messages
e.SetAttr("hidden", "")
e.SetValue("hello")
e.SetClass("cls")
e.SetInner("content")
rq.muQueue.Lock()
th.Equal(len(rq.wsQueue), 4)
rq.muQueue.Unlock()
w := httptest.NewRecorder()
b, sent := rq.drainTailScript()
if err := rq.writeTailResponse(w, b, sent); err != nil {
t.Fatal(err)
}
// SAttr and SClass consumed, Value and Inner preserved
rq.muQueue.Lock()
th.Equal(len(rq.wsQueue), 2)
th.Equal(rq.wsQueue[0].What, what.Value)
th.Equal(rq.wsQueue[1].What, what.Inner)
rq.muQueue.Unlock()
}
func TestRequest_writeTailScript_RemoveAttrAndClass(t *testing.T) {
th := newTestHelper(t)
jw, _ := New()
defer jw.Close()
rq := jw.NewRequest(nil)
defer jw.recycle(rq)
item := &testUi{}
e := rq.NewElement(item)
e.RemoveAttr("hidden")
e.RemoveClass("cls")
w := httptest.NewRecorder()
b, sent := rq.drainTailScript()
if err := rq.writeTailResponse(w, b, sent); err != nil {
t.Fatal(err)
}
s := w.Body.String()
th.True(strings.Contains(s, `removeAttribute("hidden");`))
th.True(strings.Contains(s, `classList?.remove("cls");`))
rq.muQueue.Lock()
th.Equal(len(rq.wsQueue), 0)
rq.muQueue.Unlock()
}
// TestRequest_writeTailScript_IsolatesEachFixup verifies each attribute/class fixup
// is wrapped in its own try/catch, so a fixup that throws at runtime (e.g. a class
// token containing whitespace, which the ?. element guard does not catch) cannot
// abandon the fixups that follow it. The drain removes these messages from wsQueue,
// making the tail script their sole applier, so the isolation mirrors the per-order
// isolation the WebSocket client applies in jawsMessage.
func TestRequest_writeTailScript_IsolatesEachFixup(t *testing.T) {
th := newTestHelper(t)
jw, _ := New()
defer jw.Close()
rq := jw.NewRequest(nil)
defer jw.recycle(rq)
e1 := rq.NewElement(&testUi{})
e2 := rq.NewElement(&testUi{})
e3 := rq.NewElement(&testUi{})
// A valid fixup, then one whose class token throws in the browser (whitespace is
// not a valid classList token), then another valid fixup.
e1.SetClass("ok-first")
e2.SetClass("btn primary")
e3.SetClass("ok-last")
w := httptest.NewRecorder()
b, sent := rq.drainTailScript()
if err := rq.writeTailResponse(w, b, sent); err != nil {
t.Fatal(err)
}
s := w.Body.String()
// One try and one catch per fixup.
th.Equal(strings.Count(s, "try{document.getElementById("), 3)
th.Equal(strings.Count(s, "}catch(e){console.error(e);}"), 3)
// The fixup after the throwing one lives in its own isolated statement, so the
// throwing one cannot prevent it from running.
th.True(strings.Contains(s, `classList?.add("ok-last");}catch(e){console.error(e);}`))
}
// TestRequest_TailScriptConcurrentWithRecycle exercises a /jaws/.tail fetch
// racing recycle of the same still-pending request. The handler holds jw.mu (read)
// across the drainTailScript call and recycle needs the jw.mu write lock, so the
// drain and recycle are serialized: the fetch can never drain a finished request.
// releaseBuffersLocked also takes muQueue to reset wsQueue/tailsent, the lock
// drainTailScript holds, so that reset cannot race the drain either. Run with -race.
func TestRequest_TailScriptConcurrentWithRecycle(t *testing.T) {
jw, _ := New()
defer jw.Close()
// Fetch the tail script via the public endpoint while recycling the same
// request, repeated enough to overlap under the race detector.
const n = 300
var wg sync.WaitGroup
for i := 0; i < n; i++ {
rq := jw.NewRequest(nil)
e := rq.NewElement(&testUi{})
e.SetAttr("hidden", "yes")
e.SetClass("cls")
tailURL := "/jaws/.tail/" + rq.JawsKeyString()
wg.Add(2)
go func() {
defer wg.Done()
jw.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, tailURL, nil))
}()
go func() {
defer wg.Done()
jw.recycle(rq)
}()
}
wg.Wait()
}
// TestRequest_wantMessageConcurrentWithRecycle stresses the broadcast identity
// check: wantMessage reads the lifecycle state and rq.JawsKey under rq.mu while
// completion transitions the state to reqFinished under the same lock. The read and
// write must be serialized so there is no data race. Run with -race.
func TestRequest_wantMessageConcurrentWithRecycle(t *testing.T) {
jw, _ := New()
defer jw.Close()
const n = 300
var wg sync.WaitGroup
for i := 0; i < n; i++ {
rq := jw.NewRequest(nil)
staleKey := rq.JawsKey
wg.Add(2)
go func() {
defer wg.Done()
rq.wantMessage(&wire.Message{Dest: staleKey})
}()
go func() {
defer wg.Done()
jw.recycle(rq)
}()
}
wg.Wait()
}
func TestRequest_SendArrivesOk(t *testing.T) {
is := newTestHelper(t)
rq := newTestRequest(t)
defer rq.Close()
x := &testUi{}
jid := rq.Register(x)
elem := rq.GetElementByJid(jid)
is.True(elem != nil)
rq.Jaws.Broadcast(wire.Message{Dest: x, What: what.Inner, Data: "bar"})
select {
case <-time.NewTimer(time.Hour).C:
is.Error("timeout")
case msg := <-rq.OutCh:
elem := rq.GetElementByJid(jid)
is.True(elem != nil)
if elem != nil {
is.Equal(msg, wire.WsMsg{Jid: elem.jid, Data: "bar", What: what.Inner})
}
}
}
func TestRequest_SetContext(t *testing.T) {
rq := newTestRequest(t)
defer rq.Close()
type testKey string
rq.SetContext(func(oldCtx context.Context) (newCtx context.Context) {
return context.WithValue(oldCtx, testKey("key"), "val")
})
if rq.Context().Value(testKey("key")) != "val" {
t.Fatal("val not set")
}
}
func TestRequest_SetContext_NilPanics(t *testing.T) {
jw, err := New()
if err != nil {
t.Fatal(err)
}
defer jw.Close()
rq := jw.NewRequest(nil)
defer jw.recycle(rq)
// No Logger is configured, so reportMisuse panics in both debug and production.
defer func() {
x := recover()
if x == nil {
t.Fatal("expected panic")
}
if got := fmt.Sprint(x); !strings.Contains(got, "SetContext function returned a nil context") {
t.Fatalf("unexpected panic %q", got)
}
}()
rq.SetContext(func(context.Context) context.Context { return nil })
}
func TestRequest_SetContextCancellationStopsQueuedEvents(t *testing.T) {
th := newTestHelper(t)
rq := newTestRequest(t)
defer rq.Close()
block := make(chan struct{})
started := make(chan struct{}, 1)
var calls int32
item := &testUi{}
rq.Register(item, func(elem *Element, value string) error {
if atomic.AddInt32(&calls, 1) == 1 {
started <- struct{}{}
<-block
}
return nil
})
jid := jidForTag(rq.Request, item)
if jid == 0 {
t.Fatal("missing jid")
}
select {
case <-th.C:
th.Timeout()
case rq.InCh <- wire.WsMsg{Jid: jid, What: what.Input, Data: "1"}:
}
select {
case <-th.C:
th.Timeout()
case rq.InCh <- wire.WsMsg{Jid: jid, What: what.Input, Data: "2"}:
}
select {
case <-th.C:
th.Timeout()
case <-started:
}
rq.SetContext(func(oldCtx context.Context) context.Context {
ctx, cancel := context.WithCancel(oldCtx)
cancel()
return ctx
})
close(block)
// Negative assertion: confirm the queued second event never fires after the
// context is replaced and cancelled. This proves absence over elapsed time, so
// it intentionally waits on the real clock rather than running in a synctest
// bubble.
deadline := time.Now().Add(200 * time.Millisecond)
for time.Now().Before(deadline) {
if atomic.LoadInt32(&calls) > 1 {
break
}
time.Sleep(time.Millisecond)
}
if got := atomic.LoadInt32(&calls); got != 1 {
t.Fatalf("expected queued events to stop after context replacement cancellation, got %d calls", got)
}
}
type deferredAfterContext struct {
context.Context
mu sync.Mutex
done chan struct{}
err error
callback func()
onAfter func()
}
func (ctx *deferredAfterContext) Done() <-chan struct{} { return ctx.done }
func (ctx *deferredAfterContext) Err() error {
ctx.mu.Lock()
defer ctx.mu.Unlock()
return ctx.err
}
func (ctx *deferredAfterContext) AfterFunc(fn func()) func() bool {
if ctx.onAfter != nil {
ctx.onAfter()
}
ctx.mu.Lock()
ctx.callback = fn
ctx.mu.Unlock()
return func() bool { return false }
}
func TestRequest_SetContextRegistersAfterFuncOutsideLock(t *testing.T) {
jw, err := New()
if err != nil {
t.Fatal(err)
}
rq := jw.NewRequest(nil)
observed := make(chan context.Context, 1)
custom := &deferredAfterContext{
Context: rq.Context(),
done: make(chan struct{}),
onAfter: func() {
observed <- rq.Context()
},
}
setDone := make(chan struct{})
go func() {
rq.SetContext(func(context.Context) context.Context { return custom })
close(setDone)
}()
select {
case <-setDone:
case <-time.After(2 * time.Second):
t.Fatal("SetContext deadlocked while a custom AfterFunc hook re-entered Request.Context")
}
select {
case got := <-observed:
if got != custom {
t.Fatalf("AfterFunc hook observed context %T, want replacement context", got)
}
default:
t.Fatal("replacement context's AfterFunc hook was not registered")
}
jw.Close()
}
func (ctx *deferredAfterContext) cancel() {
ctx.mu.Lock()
ctx.err = context.Canceled
close(ctx.done)
ctx.mu.Unlock()
}
func (ctx *deferredAfterContext) fire() {
ctx.mu.Lock()
fn := ctx.callback
ctx.mu.Unlock()
if fn != nil {
fn()
}
}
func TestRequest_SetContextDelayedCallbackDoesNotCancelNextRequest(t *testing.T) {
jw, err := New()
if err != nil {
t.Fatal(err)
}
defer jw.Close()
first := jw.NewRequest(nil)
callbackCalled := make(chan struct{}, 1)
var callbackArmed atomic.Bool
first.mu.Lock()
firstCancel := first.cancelFn
first.cancelFn = func(cause error) {
firstCancel(cause)
if callbackArmed.Load() {
callbackCalled <- struct{}{}
}
}
first.mu.Unlock()
deferred := &deferredAfterContext{done: make(chan struct{})}
first.SetContext(func(old context.Context) context.Context {
deferred.Context = old
return deferred
})
deferred.cancel()
jw.recycle(first)
// Requests keep a stable identity and are never reused, so NewRequest returns a
// distinct Request. A delayed SetContext callback still bound to first must not
// reach this next Request's context.
second := jw.NewRequest(nil)
if second == first {
t.Fatal("NewRequest reused a finished Request identity")
}
defer jw.recycle(second)
secondCtx := second.Context()
callbackArmed.Store(true)
deferred.fire()
select {
case <-callbackCalled:
case <-time.After(testTimeout):
t.Fatal("delayed SetContext callback did not run")
}
select {
case <-secondCtx.Done():
t.Fatal("delayed SetContext callback canceled the next Request")
default:
}
}
func TestRequest_OutboundRespectsContextDone(t *testing.T) {
th := newTestHelper(t)
rq := newTestRequest(t)
defer rq.Close()
var callCount int32
x := &testUi{}
rq.Register(x, func(elem *Element, value string) error {
atomic.AddInt32(&callCount, 1)
rq.cancel(nil)
return errors.New(value)
})
fillWsCh(rq.OutCh)
rq.Jaws.Broadcast(wire.Message{Dest: x, What: what.Hook, Data: "bar"})
select {
case <-th.C:
th.Equal(int(atomic.LoadInt32(&callCount)), 0)
th.Timeout()
case <-rq.Jaws.Done():
th.Fatal("jaws done too soon")
case <-rq.ctx.Done():
}
th.Equal(int(atomic.LoadInt32(&callCount)), 1)
select {
case <-rq.Jaws.Done():
th.Fatal("jaws done too soon")
default:
}
}
func TestRequest_Trigger(t *testing.T) {
th := newTestHelper(t)
rq := newTestRequest(t)
defer rq.Close()
gotFooCall := make(chan struct{})
gotEndCall := make(chan struct{})
fooItem := &testUi{}
rq.Register(fooItem, func(elem *Element, value string) error {
defer close(gotFooCall)
return nil
})
errItem := &testUi{}
rq.Register(errItem, func(elem *Element, value string) error {
return errors.New(value)
})
endItem := &testUi{}
rq.Register(endItem, func(elem *Element, value string) error {
defer close(gotEndCall)
return nil
})
// broadcasts from ourselves should not invoke fn
rq.Jaws.Broadcast(wire.Message{Dest: endItem, What: what.Input, Data: ""}) // to know when to stop
select {
case <-th.C:
th.Timeout()
case s := <-rq.OutCh:
th.Fatal(s)
case <-gotFooCall:
th.Fatal("gotFooCall")
case <-gotEndCall:
}
// global broadcast should invoke fn
rq.Jaws.Broadcast(wire.Message{Dest: fooItem, What: what.Input, Data: "bar"})
select {
case <-th.C:
th.Timeout()
case s := <-rq.OutCh:
th.Fatal(s)
case <-gotFooCall:
}
// fn returning error should send an danger alert message
rq.Jaws.Broadcast(wire.Message{Dest: errItem, What: what.Input, Data: "omg"})
select {
case <-th.C:
th.Timeout()
case msg := <-rq.OutCh:
th.Equal(msg.Format(), (&wire.WsMsg{
Data: "danger\nomg",
Jid: jid.Jid(0),
What: what.Alert,
}).Format())
}
}
// TestRequest_EventFnQueue uses an event handler that deliberately blocks
// (busy-waiting on sleepDone) to fill the event queue. That busy-wait is the
// device under test and keeps re-arming the clock, so this test is not suited to
// a synctest bubble; it stays on the real clock with deadline-bounded waits.
func TestRequest_EventFnQueue(t *testing.T) {
th := newTestHelper(t)
rq := newTestRequest(t)
defer rq.Close()
// calls to slow event functions queue up and are executed in order
firstDoneCh := make(chan struct{})
var sleepDone int32
var callCount int32
sleepItem := &testUi{}
rq.Register(sleepItem, func(elem *Element, value string) error {
count := int(atomic.AddInt32(&callCount, 1))
if value != strconv.Itoa(count) {
t.Logf("val=%s, count=%d, cap=%d", value, count, cap(rq.OutCh))
th.Fail()
}
if count == 1 {
close(firstDoneCh)
}
for atomic.LoadInt32(&sleepDone) == 0 {
select {
case <-t.Context().Done():
return nil
default:
time.Sleep(time.Millisecond)
}
}
return nil
})
for i := 0; i < cap(rq.OutCh); i++ {
rq.Jaws.Broadcast(wire.Message{Dest: sleepItem, What: what.Input, Data: strconv.Itoa(i + 1)})
}
select {
case <-th.C:
th.Timeout()
case <-rq.DoneCh:
th.Fatal("doneCh")
case <-firstDoneCh:
}
th.Equal(atomic.LoadInt32(&callCount), int32(1))
atomic.StoreInt32(&sleepDone, 1)
th.Equal(rq.PanicVal, nil)
for int(atomic.LoadInt32(&callCount)) < cap(rq.OutCh) {
select {
case <-th.C:
t.Logf("callCount=%d, cap=%d", atomic.LoadInt32(&callCount), cap(rq.OutCh))
th.Equal(rq.PanicVal, nil)
th.Timeout()
default:
time.Sleep(time.Millisecond)
}
}
th.Equal(atomic.LoadInt32(&callCount), int32(cap(rq.OutCh)))
}
// TestRequest_EventFnQueueOverflowCancelsRequest verifies that when a client floods
// events faster than a slow handler can drain them, the request is cancelled rather
// than silently dropping events and limping on with inconsistent state, and that it
// does not panic even with no Logger configured (the default).
func TestRequest_EventFnQueueOverflowCancelsRequest(t *testing.T) {
th := newTestHelper(t)
rq := newTestRequest(t)
defer rq.Close()
var wait int32
bombItem := &testUi{}
rq.Register(bombItem, func(elem *Element, value string) error {
delay := 1 << atomic.AddInt32(&wait, 1)
select {
case <-t.Context().Done():
case <-time.NewTimer(time.Millisecond * time.Duration(min(1000, delay))).C:
}
return nil
})
// No Logger configured (the default): the overflow back-pressure must cancel
// the request without panicking. ExpectPanic stays false, so any panic that
// does escape is re-raised by the harness and fails the test.
rq.Jaws.Logger = nil
jid := jidForTag(rq.Request, bombItem)
for {
select {
case <-rq.DoneCh:
if t.Context().Err() != nil {
t.Error("test timed out before event channel full")
}
th.True(!rq.Panicked)
return
case <-th.C:
th.Timeout()
case rq.InCh <- wire.WsMsg{Jid: jid, What: what.Input}:
}
}
}
// TestRequest_ClaimRefreshesLastWriteAndStartServeGuards verifies that claim()
// refreshes lastWrite so a request claimed long after its initial render is not
// treated as idle and retired before ServeHTTP sets running, and that startServe()
// refuses a request that has finished (recycle unregisters it and resets claimed)
// rather than driving a finished, unregistered *Request.
func TestRequest_ClaimRefreshesLastWriteAndStartServeGuards(t *testing.T) {
jw, err := New()
if err != nil {
t.Fatal(err)
}
defer jw.Close()