-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprotocol_e2e_test.go
More file actions
1769 lines (1657 loc) · 55.1 KB
/
Copy pathprotocol_e2e_test.go
File metadata and controls
1769 lines (1657 loc) · 55.1 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
//go:build e2e
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// Controller commands (all output is content-free):
//
// QODER2API_E2E=1 go test -tags=e2e . -run '^TestProtocolE2E(Native|DefaultNative)$' -count=1 -v
// QODER2API_E2E=1 QODER2API_E2E_REFRESH=1 go test -tags=e2e . -run '^TestProtocolE2ERefresh$' -count=1 -v
//
// The harness uses the production local auth directory and endpoints by default.
// Content-silent overrides are available through QODER2API_E2E_AUTH_DIR,
// QODER2API_E2E_INFER_ENDPOINT, QODER2API_E2E_OPENAPI_ENDPOINT, and
// QODER2API_E2E_WEB_ENDPOINT. QODER2API_DUMP_DIR is deliberately ignored.
const (
protocolE2ESetupTimeout = 90 * time.Second
protocolE2ERouteTimeout = 2 * time.Minute
protocolE2ERefreshTimeout = 90 * time.Second
protocolE2EPrompt = "Synthetic protocol validation. Reply only OK."
)
type protocolE2EResult struct {
Route string
Stream bool
HTTPStatus int
HTTPSuccess bool
SchemaSuccess bool
Duration time.Duration
UpstreamShapes []string
}
type protocolE2EConfig struct {
authDir string
inferEndpoint string
openapiEndpoint string
webEndpoint string
}
type protocolE2ECapabilityCounts struct {
credentialEncrypt atomic.Int64
credentialDecrypt atomic.Int64
runtimeGenerate atomic.Int64
modelCacheDecrypt atomic.Int64
contextNew atomic.Int64
contextPrepare atomic.Int64
}
type protocolE2ECountingCredentialCodec struct {
inner credentialCodec
counts *protocolE2ECapabilityCounts
}
func (c *protocolE2ECountingCredentialCodec) Encrypt(ctx context.Context, plain, machineKey string) (string, error) {
c.counts.credentialEncrypt.Add(1)
return c.inner.Encrypt(ctx, plain, machineKey)
}
func (c *protocolE2ECountingCredentialCodec) Decrypt(ctx context.Context, blob, machineKey string) (string, error) {
c.counts.credentialDecrypt.Add(1)
return c.inner.Decrypt(ctx, blob, machineKey)
}
type protocolE2ECountingRuntimeFieldGenerator struct {
inner runtimeFieldGenerator
counts *protocolE2ECapabilityCounts
}
func (g *protocolE2ECountingRuntimeFieldGenerator) Generate(ctx context.Context, input runtimeFieldInput) (runtimeFieldOutput, error) {
g.counts.runtimeGenerate.Add(1)
return g.inner.Generate(ctx, input)
}
type protocolE2ECountingModelCacheDecryptor struct {
inner modelCacheDecryptor
counts *protocolE2ECapabilityCounts
}
func (d *protocolE2ECountingModelCacheDecryptor) Decrypt(ctx context.Context, blob, uid string) ([]byte, error) {
d.counts.modelCacheDecrypt.Add(1)
return d.inner.Decrypt(ctx, blob, uid)
}
type protocolE2ECountingContextFactory struct {
inner protocolContextFactory
counts *protocolE2ECapabilityCounts
}
func (f *protocolE2ECountingContextFactory) New(ctx context.Context, config protocolContextConfig) (protocolContext, error) {
f.counts.contextNew.Add(1)
created, err := f.inner.New(ctx, config)
if created == nil {
return nil, err
}
return &protocolE2ECountingContext{inner: created, counts: f.counts}, err
}
type protocolE2ECountingContext struct {
inner protocolContext
counts *protocolE2ECapabilityCounts
}
func (c *protocolE2ECountingContext) PrepareInferRequest(ctx context.Context, input inferRequestInput) (*preparedRequest, error) {
c.counts.contextPrepare.Add(1)
return c.inner.PrepareInferRequest(ctx, input)
}
func (c *protocolE2ECountingContext) Close() error {
if c == nil || c.inner == nil {
return nil
}
return c.inner.Close()
}
const (
protocolE2EUpstreamLineLimit = 64 << 10
protocolE2EUpstreamFrameLimit = 512 << 10
)
type protocolE2EUpstreamObserver struct {
fragment []byte
discardLine bool
frameEvent []byte
frameData []byte
frameHasEvent bool
frameHasData bool
frameDataBeforeEvent bool
shapes map[protocolHarnessUpstreamShape]struct{}
sawFinish bool
finishWithoutData bool
postFinish bool
incompleteFrame bool
frameFailure protocolHarnessUpstreamReason
finalized bool
success bool
reason protocolHarnessUpstreamReason
onShape func(protocolHarnessUpstreamShape)
onFinalize func(protocolHarnessUpstreamReason)
}
func newProtocolE2EUpstreamObserver() *protocolE2EUpstreamObserver {
return &protocolE2EUpstreamObserver{}
}
func (o *protocolE2EUpstreamObserver) Write(payload []byte) (int, error) {
written := len(payload)
for len(payload) > 0 {
newline := bytes.IndexByte(payload, '\n')
if newline < 0 {
o.appendFragment(payload)
break
}
o.appendFragment(payload[:newline])
o.processFragment()
payload = payload[newline+1:]
}
return written, nil
}
func (o *protocolE2EUpstreamObserver) appendFragment(fragment []byte) {
if o.discardLine {
return
}
if len(o.fragment)+len(fragment) > protocolE2EUpstreamLineLimit {
o.zeroBytes(&o.fragment)
o.discardLine = true
o.incompleteFrame = true
return
}
o.fragment = append(o.fragment, fragment...)
}
func (o *protocolE2EUpstreamObserver) processFragment() {
if o.discardLine {
o.discardLine = false
o.zeroBytes(&o.fragment)
return
}
line := bytes.TrimSuffix(o.fragment, []byte{'\r'})
if len(line) == 0 {
o.zeroBytes(&o.fragment)
o.finishFrame()
return
}
if line[0] == ':' {
o.zeroBytes(&o.fragment)
return
}
field, value, found := bytes.Cut(line, []byte{':'})
if !found {
o.addShape(protocolHarnessUpstreamUnknownField)
o.zeroBytes(&o.fragment)
return
}
switch string(field) {
case "event":
if o.sawFinish {
o.postFinish = true
o.zeroBytes(&o.fragment)
return
}
if o.frameHasEvent {
o.addShape(protocolHarnessUpstreamMultilineEvent)
}
value = bytes.TrimSpace(value)
o.appendFrameValue(&o.frameEvent, value, ' ')
o.frameHasEvent = true
case "data":
if o.sawFinish {
o.postFinish = true
o.zeroBytes(&o.fragment)
return
}
if o.frameHasData {
o.addShape(protocolHarnessUpstreamMultilineData)
}
if !o.frameHasEvent {
o.frameDataBeforeEvent = true
}
value = bytes.TrimPrefix(value, []byte{' '})
o.appendFrameValue(&o.frameData, value, '\n')
o.frameHasData = true
default:
o.addShape(protocolHarnessUpstreamUnknownField)
}
o.zeroBytes(&o.fragment)
}
func (o *protocolE2EUpstreamObserver) appendFrameValue(target *[]byte, value []byte, separator byte) {
extra := len(value)
if len(*target) > 0 {
extra++
}
if len(o.frameEvent)+len(o.frameData)+extra > protocolE2EUpstreamFrameLimit {
o.incompleteFrame = true
return
}
if len(*target) > 0 {
*target = append(*target, separator)
}
*target = append(*target, value...)
}
func (o *protocolE2EUpstreamObserver) finishFrame() {
if !o.frameHasEvent && !o.frameHasData {
o.resetFrame()
return
}
if o.sawFinish {
o.postFinish = true
o.resetFrame()
return
}
event := string(o.frameEvent)
if event == "finish" {
if o.frameDataBeforeEvent {
o.addShape(protocolHarnessUpstreamDataBeforeTerminalEvent)
}
if !o.frameHasData || len(o.frameData) == 0 {
o.finishWithoutData = true
o.resetFrame()
return
}
var terminal map[string]json.RawMessage
if json.Unmarshal(o.frameData, &terminal) != nil {
o.markFrameFailure(protocolHarnessUpstreamFinishInvalidJSON)
} else if terminal == nil {
o.markFrameFailure(protocolHarnessUpstreamMalformed)
} else {
o.sawFinish = true
}
o.resetFrame()
return
}
if o.frameHasData {
o.validateEnvelope(o.frameData, event != "")
}
o.resetFrame()
}
func (o *protocolE2EUpstreamObserver) validateEnvelope(data []byte, namedEvent bool) {
var envelope struct {
StatusCodeValue *int `json:"statusCodeValue"`
Body string `json:"body"`
Error json.RawMessage `json:"error"`
}
if json.Unmarshal(data, &envelope) != nil {
if namedEvent {
o.markFrameFailure(protocolHarnessUpstreamNamedEventInvalidJSON)
} else {
o.markFrameFailure(protocolHarnessClassifyUnnamedNonJSON(data))
}
return
}
if envelope.StatusCodeValue == nil {
o.markFrameFailure(protocolHarnessUpstreamEnvelopeMissingStatus)
return
}
if *envelope.StatusCodeValue != http.StatusOK {
o.markFrameFailure(protocolHarnessUpstreamNonOKStatus)
return
}
if len(envelope.Error) != 0 && string(bytes.TrimSpace(envelope.Error)) != "null" {
o.markFrameFailure(protocolHarnessUpstreamOuterError)
return
}
if envelope.Body == "" {
return
}
var inner struct {
Error json.RawMessage `json:"error"`
}
innerData := bytes.TrimSpace([]byte(envelope.Body))
if bytes.Equal(innerData, []byte("[DONE]")) {
o.addShape(protocolHarnessUpstreamInnerDoneMarkerShape)
return
}
if len(innerData) == 0 || innerData[0] != '{' {
o.markFrameFailure(protocolHarnessUpstreamInnerJSONNonObject)
return
}
if json.Unmarshal(innerData, &inner) != nil {
o.markFrameFailure(protocolHarnessUpstreamInnerNonJSONObj)
return
}
if len(inner.Error) != 0 && string(bytes.TrimSpace(inner.Error)) != "null" {
o.markFrameFailure(protocolHarnessUpstreamInnerError)
}
}
func (o *protocolE2EUpstreamObserver) markFrameFailure(reason protocolHarnessUpstreamReason) {
if o.frameFailure == "" {
o.frameFailure = reason
}
}
func (o *protocolE2EUpstreamObserver) addShape(shape protocolHarnessUpstreamShape) {
if o.shapes == nil {
o.shapes = make(map[protocolHarnessUpstreamShape]struct{})
}
if _, exists := o.shapes[shape]; exists {
return
}
o.shapes[shape] = struct{}{}
if o.onShape != nil {
o.onShape(shape)
}
}
func (o *protocolE2EUpstreamObserver) resetFrame() {
o.zeroBytes(&o.frameEvent)
o.zeroBytes(&o.frameData)
o.frameHasEvent = false
o.frameHasData = false
o.frameDataBeforeEvent = false
}
func (*protocolE2EUpstreamObserver) zeroBytes(value *[]byte) {
for index := range *value {
(*value)[index] = 0
}
*value = nil
}
func (o *protocolE2EUpstreamObserver) Finalize(err error) {
if o == nil || o.finalized {
return
}
o.finalized = true
if len(o.fragment) != 0 || o.discardLine || o.frameHasEvent || o.frameHasData {
o.processFragment()
o.finishFrame()
}
o.reason = o.failureReason(err)
o.success = o.reason == ""
if o.onFinalize != nil {
o.onFinalize(o.reason)
}
}
func (o *protocolE2EUpstreamObserver) failureReason(err error) protocolHarnessUpstreamReason {
switch {
case err != nil && !errors.Is(err, io.EOF):
return protocolHarnessUpstreamReadFailure
case o.postFinish:
return protocolHarnessUpstreamPostFinish
case o.incompleteFrame:
return protocolHarnessUpstreamIncompleteFrame
case o.frameFailure != "":
return o.frameFailure
case o.finishWithoutData:
return protocolHarnessUpstreamFinishWithoutData
case !o.sawFinish:
return protocolHarnessUpstreamMissingFinish
default:
return ""
}
}
func (o *protocolE2EUpstreamObserver) Success() bool {
return o != nil && o.finalized && o.success
}
func (o *protocolE2EUpstreamObserver) Reason() protocolHarnessUpstreamReason {
if o == nil || !o.finalized {
return ""
}
return o.reason
}
func (o *protocolE2EUpstreamObserver) HasShape(shape protocolHarnessUpstreamShape) bool {
if o == nil {
return false
}
_, ok := o.shapes[shape]
return ok
}
type protocolE2ECountingTransport struct {
base http.RoundTripper
calls atomic.Int64
readFailures atomic.Int64
upstreamObserved atomic.Int64
upstreamSuccess atomic.Int64
upstreamMissingFinish atomic.Int64
upstreamFinishWithoutData atomic.Int64
upstreamFinishInvalidJSON atomic.Int64
upstreamNamedEventInvalidJSON atomic.Int64
upstreamEnvelopeDoneMarker atomic.Int64
upstreamEnvelopeNonJSONObj atomic.Int64
upstreamEnvelopeNonJSONArr atomic.Int64
upstreamEnvelopeNonJSONQuoted atomic.Int64
upstreamEnvelopeNonJSONNumber atomic.Int64
upstreamEnvelopeNonJSONLiteral atomic.Int64
upstreamEnvelopeNonJSONOther atomic.Int64
upstreamEnvelopeInvalidJSON atomic.Int64
upstreamEnvelopeMissingStatus atomic.Int64
upstreamNonOKStatus atomic.Int64
upstreamOuterError atomic.Int64
upstreamInnerError atomic.Int64
upstreamInnerJSONNonObject atomic.Int64
upstreamInnerNonJSONObj atomic.Int64
upstreamIncompleteFrame atomic.Int64
upstreamMalformed atomic.Int64
upstreamReadFailure atomic.Int64
upstreamPostFinish atomic.Int64
upstreamUnknownField atomic.Int64
upstreamMultilineEvent atomic.Int64
upstreamMultilineData atomic.Int64
upstreamDataBeforeTerminalEvent atomic.Int64
upstreamInnerDoneMarkerShape atomic.Int64
}
func (t *protocolE2ECountingTransport) upstreamSnapshot() protocolHarnessUpstreamSnapshot {
if t == nil {
return protocolHarnessUpstreamSnapshot{}
}
return protocolHarnessUpstreamSnapshot{
Observed: t.upstreamObserved.Load(),
Success: t.upstreamSuccess.Load(),
MissingFinish: t.upstreamMissingFinish.Load(),
FinishWithoutData: t.upstreamFinishWithoutData.Load(),
FinishInvalidJSON: t.upstreamFinishInvalidJSON.Load(),
NamedEventInvalidJSON: t.upstreamNamedEventInvalidJSON.Load(),
EnvelopeDoneMarker: t.upstreamEnvelopeDoneMarker.Load(),
EnvelopeNonJSONObj: t.upstreamEnvelopeNonJSONObj.Load(),
EnvelopeNonJSONArr: t.upstreamEnvelopeNonJSONArr.Load(),
EnvelopeNonJSONQuoted: t.upstreamEnvelopeNonJSONQuoted.Load(),
EnvelopeNonJSONNumber: t.upstreamEnvelopeNonJSONNumber.Load(),
EnvelopeNonJSONLiteral: t.upstreamEnvelopeNonJSONLiteral.Load(),
EnvelopeNonJSONOther: t.upstreamEnvelopeNonJSONOther.Load(),
EnvelopeInvalidJSON: t.upstreamEnvelopeInvalidJSON.Load(),
EnvelopeMissingStatus: t.upstreamEnvelopeMissingStatus.Load(),
NonOKStatus: t.upstreamNonOKStatus.Load(),
OuterError: t.upstreamOuterError.Load(),
InnerError: t.upstreamInnerError.Load(),
InnerJSONNonObject: t.upstreamInnerJSONNonObject.Load(),
InnerNonJSONObj: t.upstreamInnerNonJSONObj.Load(),
IncompleteFrame: t.upstreamIncompleteFrame.Load(),
Malformed: t.upstreamMalformed.Load(),
ReadFailure: t.upstreamReadFailure.Load(),
PostFinish: t.upstreamPostFinish.Load(),
UnknownField: t.upstreamUnknownField.Load(),
MultilineEvent: t.upstreamMultilineEvent.Load(),
MultilineData: t.upstreamMultilineData.Load(),
DataBeforeTerminalEvent: t.upstreamDataBeforeTerminalEvent.Load(),
InnerDoneMarkerShape: t.upstreamInnerDoneMarkerShape.Load(),
}
}
func (t *protocolE2ECountingTransport) recordUpstreamShape(shape protocolHarnessUpstreamShape) {
switch shape {
case protocolHarnessUpstreamUnknownField:
t.upstreamUnknownField.Add(1)
case protocolHarnessUpstreamMultilineEvent:
t.upstreamMultilineEvent.Add(1)
case protocolHarnessUpstreamMultilineData:
t.upstreamMultilineData.Add(1)
case protocolHarnessUpstreamDataBeforeTerminalEvent:
t.upstreamDataBeforeTerminalEvent.Add(1)
case protocolHarnessUpstreamInnerDoneMarkerShape:
t.upstreamInnerDoneMarkerShape.Add(1)
}
}
func (t *protocolE2ECountingTransport) recordUpstreamResult(reason protocolHarnessUpstreamReason) {
switch reason {
case "":
t.upstreamSuccess.Add(1)
case protocolHarnessUpstreamMissingFinish:
t.upstreamMissingFinish.Add(1)
case protocolHarnessUpstreamFinishWithoutData:
t.upstreamFinishWithoutData.Add(1)
case protocolHarnessUpstreamFinishInvalidJSON:
t.upstreamFinishInvalidJSON.Add(1)
case protocolHarnessUpstreamNamedEventInvalidJSON:
t.upstreamNamedEventInvalidJSON.Add(1)
case protocolHarnessUpstreamEnvelopeDoneMarker:
t.upstreamEnvelopeDoneMarker.Add(1)
case protocolHarnessUpstreamEnvelopeNonJSONObj:
t.upstreamEnvelopeNonJSONObj.Add(1)
case protocolHarnessUpstreamEnvelopeNonJSONArr:
t.upstreamEnvelopeNonJSONArr.Add(1)
case protocolHarnessUpstreamEnvelopeNonJSONQuoted:
t.upstreamEnvelopeNonJSONQuoted.Add(1)
case protocolHarnessUpstreamEnvelopeNonJSONNumber:
t.upstreamEnvelopeNonJSONNumber.Add(1)
case protocolHarnessUpstreamEnvelopeNonJSONLiteral:
t.upstreamEnvelopeNonJSONLiteral.Add(1)
case protocolHarnessUpstreamEnvelopeNonJSONOther:
t.upstreamEnvelopeNonJSONOther.Add(1)
case protocolHarnessUpstreamEnvelopeInvalidJSON:
t.upstreamEnvelopeInvalidJSON.Add(1)
case protocolHarnessUpstreamEnvelopeMissingStatus:
t.upstreamEnvelopeMissingStatus.Add(1)
case protocolHarnessUpstreamNonOKStatus:
t.upstreamNonOKStatus.Add(1)
case protocolHarnessUpstreamOuterError:
t.upstreamOuterError.Add(1)
case protocolHarnessUpstreamInnerError:
t.upstreamInnerError.Add(1)
case protocolHarnessUpstreamInnerJSONNonObject:
t.upstreamInnerJSONNonObject.Add(1)
case protocolHarnessUpstreamInnerNonJSONObj:
t.upstreamInnerNonJSONObj.Add(1)
case protocolHarnessUpstreamIncompleteFrame:
t.upstreamIncompleteFrame.Add(1)
case protocolHarnessUpstreamMalformed:
t.upstreamMalformed.Add(1)
case protocolHarnessUpstreamReadFailure:
t.upstreamReadFailure.Add(1)
case protocolHarnessUpstreamPostFinish:
t.upstreamPostFinish.Add(1)
default:
t.upstreamMalformed.Add(1)
}
}
type protocolE2EObservedBody struct {
inner io.ReadCloser
counter *atomic.Int64
failed atomic.Bool
observer *protocolE2EUpstreamObserver
}
func (b *protocolE2EObservedBody) Read(payload []byte) (int, error) {
count, err := b.inner.Read(payload)
if b.observer != nil && count > 0 {
_, _ = b.observer.Write(payload[:count])
}
if err != nil {
if b.observer != nil {
b.observer.Finalize(err)
}
if !errors.Is(err, io.EOF) && b.failed.CompareAndSwap(false, true) {
b.counter.Add(1)
}
}
return count, err
}
func (b *protocolE2EObservedBody) Close() error {
if b.observer != nil {
b.observer.Finalize(nil)
}
return b.inner.Close()
}
func protocolE2EIsEventStream(response *http.Response) bool {
if response == nil || response.StatusCode != http.StatusOK {
return false
}
mediaType := strings.ToLower(strings.TrimSpace(strings.Split(response.Header.Get("Content-Type"), ";")[0]))
return mediaType == "text/event-stream"
}
func (t *protocolE2ECountingTransport) RoundTrip(request *http.Request) (*http.Response, error) {
t.calls.Add(1)
response, err := t.base.RoundTrip(request)
if response != nil && response.Body != nil {
observed := &protocolE2EObservedBody{inner: response.Body, counter: &t.readFailures}
if protocolE2EIsEventStream(response) {
t.upstreamObserved.Add(1)
observer := newProtocolE2EUpstreamObserver()
observer.onShape = t.recordUpstreamShape
observer.onFinalize = t.recordUpstreamResult
observed.observer = observer
}
response.Body = observed
}
return response, err
}
type protocolE2EHarness struct {
services *protocolServices
auth *authManager
handler http.Handler
capabilities *protocolE2ECapabilityCounts
transport *protocolE2ECountingTransport
refreshTransport *protocolE2ECountingTransport
denyRefresh *protocolHarnessDenyTransport
readOnlyAuth bool
closeIdle []func()
closeOnce sync.Once
closeFailed bool
}
type protocolE2EJSONField struct {
key string
allowed []string
}
type protocolE2EJSONExpectation struct {
strings []protocolE2EJSONField
arrays []string
}
type protocolE2ESSEExpectation struct {
events []string
requireDone bool
validateData func([]byte) bool
validateEventData func(string, []byte) bool
}
type protocolE2ERouteSpec struct {
name string
path string
json protocolE2EJSONExpectation
sse protocolE2ESSEExpectation
}
type protocolE2EValidation struct {
ok bool
category string
}
type protocolE2EResponseProbe struct {
header http.Header
status int
length int64
pipe *io.PipeWriter
validation <-chan protocolE2EValidation
}
func TestProtocolE2ENative(t *testing.T) {
runProtocolE2ENative(t)
}
func TestProtocolE2ERefresh(t *testing.T) {
runProtocolE2ERefresh(t)
}
func TestProtocolE2EDefaultNative(t *testing.T) {
requireProtocolE2E(t)
if _, err := parseAppConfig(nil, envLookup(nil), io.Discard); err != nil {
protocolE2EFatal(t, "default-config")
}
harness := newProtocolE2EHarness(t, false)
harness.runRoute(t, protocolE2ERouteSpecs()[0], false)
if harness.Close() {
t.Errorf("protocol E2E cleanup failed: status=0 category=cleanup length=0")
}
}
type protocolE2ERoundTripperFunc func(*http.Request) (*http.Response, error)
func (f protocolE2ERoundTripperFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return f(request)
}
type protocolE2ESingleReadBody struct {
payload []byte
read bool
}
func (b *protocolE2ESingleReadBody) Read(payload []byte) (int, error) {
if b.read {
return 0, io.EOF
}
b.read = true
return copy(payload, b.payload), nil
}
func (*protocolE2ESingleReadBody) Close() error { return nil }
type protocolE2ESyntheticReadFailureBody struct{}
func (*protocolE2ESyntheticReadFailureBody) Read(payload []byte) (int, error) {
return copy(payload, "synthetic"), errors.New("synthetic body read failure")
}
func (*protocolE2ESyntheticReadFailureBody) Close() error { return nil }
func TestProtocolE2EUpstreamObserverAcceptsSplitAuthoritativeFinish(t *testing.T) {
payload := []byte("data:{\"statusCodeValue\":200,\"body\":\"{}\"}\n\nevent:finish\ndata:{\"totalDuration\":1}\n\n")
for split := 0; split <= len(payload); split++ {
observer := newProtocolE2EUpstreamObserver()
_, _ = observer.Write(payload[:split])
_, _ = observer.Write(payload[split:])
observer.Finalize(io.EOF)
if !observer.Success() {
t.Fatalf("authoritative finish rejected at synthetic split %d", split)
}
}
}
func TestProtocolE2EUpstreamObserverAcceptsProductionCompatibleFramesAcrossSplits(t *testing.T) {
for _, test := range []struct {
name string
payload string
shapes []protocolHarnessUpstreamShape
}{
{
name: "data before terminal event",
payload: "data:{\"totalDuration\":1}\nevent:finish\n\n",
shapes: []protocolHarnessUpstreamShape{protocolHarnessUpstreamDataBeforeTerminalEvent},
},
{
name: "multiline data",
payload: "event:finish\ndata:{\"totalDuration\":\ndata:1}\n\n",
shapes: []protocolHarnessUpstreamShape{protocolHarnessUpstreamMultilineData},
},
{
name: "repeated event lines",
payload: "event:synthetic\nevent:frame\ndata:{\"statusCodeValue\":200,\"body\":\"{}\"}\n\nevent:finish\ndata:{}\n\n",
shapes: []protocolHarnessUpstreamShape{protocolHarnessUpstreamMultilineEvent},
},
{
name: "ignored standard and unknown fields",
payload: "id:synthetic\nretry:1\nsynthetic:ignored\ndata:{\"statusCodeValue\":200,\"body\":\"{}\"}\n\nevent:finish\ndata:{}\n\n",
shapes: []protocolHarnessUpstreamShape{protocolHarnessUpstreamUnknownField},
},
{
name: "inner done marker before authoritative finish",
payload: "data:{\"statusCodeValue\":200,\"body\":\" [DONE] \"}\n\nevent:finish\ndata:{}\n\n",
shapes: []protocolHarnessUpstreamShape{protocolHarnessUpstreamInnerDoneMarkerShape},
},
} {
t.Run(test.name, func(t *testing.T) {
payload := []byte(test.payload)
for split := 0; split <= len(payload); split++ {
observer := newProtocolE2EUpstreamObserver()
_, _ = observer.Write(payload[:split])
_, _ = observer.Write(payload[split:])
observer.Finalize(io.EOF)
if !observer.Success() {
t.Fatalf("production-compatible upstream shape rejected as %q at synthetic split %d", observer.Reason(), split)
}
for _, shape := range test.shapes {
if !observer.HasShape(shape) {
t.Fatalf("safe upstream shape %q absent at synthetic split %d", shape, split)
}
}
}
})
}
}
func TestProtocolE2EUpstreamObserverClassifiesUnsafeTerminalShapesAcrossSplits(t *testing.T) {
for _, test := range []struct {
name string
payload string
endErr error
want protocolHarnessUpstreamReason
}{
{name: "empty", want: protocolHarnessUpstreamMissingFinish},
{name: "partial frame", payload: "data:{\"statusCodeValue\":200,\"body\":\"{}\"}\n\n", want: protocolHarnessUpstreamMissingFinish},
{name: "finish without data", payload: "event:finish\n\n", want: protocolHarnessUpstreamFinishWithoutData},
{name: "finish data invalid JSON", payload: "event:finish\ndata:{\n\n", want: protocolHarnessUpstreamFinishInvalidJSON},
{name: "named non-finish event data invalid JSON", payload: "event:heartbeat\ndata:{\n\n", want: protocolHarnessUpstreamNamedEventInvalidJSON},
{name: "unnamed exact done marker", payload: "data: [DONE] \n\n", want: protocolHarnessUpstreamEnvelopeDoneMarker},
{name: "unnamed nonjson object-like", payload: "data: {\n\n", want: protocolHarnessUpstreamEnvelopeNonJSONObj},
{name: "unnamed nonjson array-like", payload: "data: [synthetic\n\n", want: protocolHarnessUpstreamEnvelopeNonJSONArr},
{name: "unnamed nonjson quoted-like", payload: "data: \"synthetic\n\n", want: protocolHarnessUpstreamEnvelopeNonJSONQuoted},
{name: "unnamed nonjson number-like", payload: "data: -synthetic\n\n", want: protocolHarnessUpstreamEnvelopeNonJSONNumber},
{name: "unnamed nonjson literal-like", payload: "data: true-synthetic\n\n", want: protocolHarnessUpstreamEnvelopeNonJSONLiteral},
{name: "unnamed nonjson text token", payload: "data: synthetic\n\n", want: protocolHarnessUpstreamEnvelopeNonJSONOther},
{name: "normal envelope missing status", payload: "data:{\"body\":\"{}\"}\n\n", want: protocolHarnessUpstreamEnvelopeMissingStatus},
{name: "non-200 status", payload: "data:{\"statusCodeValue\":503,\"body\":\"synthetic\"}\n\n", want: protocolHarnessUpstreamNonOKStatus},
{name: "outer error", payload: "data:{\"statusCodeValue\":200,\"error\":{}}\n\n", want: protocolHarnessUpstreamOuterError},
{name: "inner error", payload: "data:{\"statusCodeValue\":200,\"body\":\"{\\\"error\\\":{}}\"}\n\n", want: protocolHarnessUpstreamInnerError},
{name: "inner JSON null", payload: "data:{\"statusCodeValue\":200,\"body\":\"null\"}\n\nevent:finish\ndata:{}\n\n", want: protocolHarnessUpstreamInnerJSONNonObject},
{name: "inner JSON array", payload: "data:{\"statusCodeValue\":200,\"body\":\"[]\"}\n\nevent:finish\ndata:{}\n\n", want: protocolHarnessUpstreamInnerJSONNonObject},
{name: "inner JSON string", payload: "data:{\"statusCodeValue\":200,\"body\":\"\\\"synthetic\\\"\"}\n\nevent:finish\ndata:{}\n\n", want: protocolHarnessUpstreamInnerJSONNonObject},
{name: "inner JSON number", payload: "data:{\"statusCodeValue\":200,\"body\":\"1\"}\n\nevent:finish\ndata:{}\n\n", want: protocolHarnessUpstreamInnerJSONNonObject},
{name: "inner JSON literal", payload: "data:{\"statusCodeValue\":200,\"body\":\"true\"}\n\nevent:finish\ndata:{}\n\n", want: protocolHarnessUpstreamInnerJSONNonObject},
{name: "inner done marker without finish", payload: "data:{\"statusCodeValue\":200,\"body\":\" [DONE] \"}\n\n", want: protocolHarnessUpstreamMissingFinish},
{name: "inner nonjson object-like", payload: "data:{\"statusCodeValue\":200,\"body\":\"{\"}\n\n", want: protocolHarnessUpstreamInnerNonJSONObj},
{name: "inner nonjson array-like", payload: "data:{\"statusCodeValue\":200,\"body\":\"[synthetic\"}\n\n", want: protocolHarnessUpstreamInnerJSONNonObject},
{name: "inner nonjson quoted-like", payload: "data:{\"statusCodeValue\":200,\"body\":\"\\\"synthetic\"}\n\n", want: protocolHarnessUpstreamInnerJSONNonObject},
{name: "inner nonjson number-like", payload: "data:{\"statusCodeValue\":200,\"body\":\"-synthetic\"}\n\n", want: protocolHarnessUpstreamInnerJSONNonObject},
{name: "inner nonjson literal-like", payload: "data:{\"statusCodeValue\":200,\"body\":\"true-synthetic\"}\n\n", want: protocolHarnessUpstreamInnerJSONNonObject},
{name: "inner nonjson text token", payload: "data:{\"statusCodeValue\":200,\"body\":\"synthetic\"}\n\n", want: protocolHarnessUpstreamInnerJSONNonObject},
{name: "read failure after finish", payload: "event:finish\ndata:{}\n\n", endErr: errors.New("synthetic read failure"), want: protocolHarnessUpstreamReadFailure},
{name: "data after finish", payload: "event:finish\ndata:{}\n\ndata:{\"statusCodeValue\":200,\"body\":\"{}\"}\n\n", want: protocolHarnessUpstreamPostFinish},
{name: "frame after finish", payload: "event:finish\ndata:{}\n\nevent:synthetic\n\n", want: protocolHarnessUpstreamPostFinish},
} {
t.Run(test.name, func(t *testing.T) {
payload := []byte(test.payload)
for split := 0; split <= len(payload); split++ {
observer := newProtocolE2EUpstreamObserver()
_, _ = observer.Write(payload[:split])
_, _ = observer.Write(payload[split:])
observer.Finalize(test.endErr)
if observer.Success() {
t.Fatalf("unsafe upstream terminal shape was accepted at synthetic split %d", split)
}
if got := observer.Reason(); got != test.want {
t.Fatalf("upstream reason = %q, want %q at synthetic split %d", got, test.want, split)
}
}
})
}
}
func TestProtocolE2EUpstreamObserverClassifiesBoundedIncompleteFrame(t *testing.T) {
observer := newProtocolE2EUpstreamObserver()
_, _ = observer.Write(append([]byte("data:"), bytes.Repeat([]byte{'x'}, protocolE2EUpstreamLineLimit+1)...))
observer.Finalize(io.EOF)
if got := observer.Reason(); got != protocolHarnessUpstreamIncompleteFrame {
t.Fatalf("bounded incomplete frame reason = %q, want %q", got, protocolHarnessUpstreamIncompleteFrame)
}
}
func TestProtocolE2EUpstreamObservedBodyCloseFinalizesCompleteFinish(t *testing.T) {
observer := newProtocolE2EUpstreamObserver()
body := &protocolE2EObservedBody{
inner: &protocolE2ESingleReadBody{payload: []byte("event:finish\ndata:{}\n\n")},
counter: &atomic.Int64{},
observer: observer,
}
buffer := make([]byte, 128)
if count, err := body.Read(buffer); count == 0 || err != nil {
t.Fatal("synthetic finish body read failed")
}
if err := body.Close(); err != nil {
t.Fatal("synthetic finish body close failed")
}
if !observer.Success() {
t.Fatal("complete authoritative finish did not finalize on close")
}
}
func TestProtocolE2ETransportIgnoresNonEventStreamSuccess(t *testing.T) {
transport := &protocolE2ECountingTransport{base: protocolE2ERoundTripperFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"queue":{"isQueued":true}}`)),
}, nil
})}
response, err := transport.RoundTrip(httptest.NewRequest(http.MethodGet, "https://example.invalid/synthetic-queue", nil))
if err != nil || response == nil {
t.Fatal("synthetic non-event-stream response setup failed")
}
_, _ = io.Copy(io.Discard, response.Body)
_ = response.Body.Close()
if transport.upstreamSnapshot() != (protocolHarnessUpstreamSnapshot{}) {
t.Fatal("non-event-stream response was classified as authoritative upstream SSE")
}
}
func TestProtocolE2ETransportReadFailureAccounting(t *testing.T) {
transport := &protocolE2ECountingTransport{base: protocolE2ERoundTripperFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: &protocolE2ESyntheticReadFailureBody{},
}, nil
})}
request := httptest.NewRequest(http.MethodGet, "https://example.invalid/synthetic-read-failure", nil)
response, err := transport.RoundTrip(request)
if err != nil || response == nil || response.Body == nil {
t.Fatal("synthetic transport response setup failed")
}
_, _ = io.ReadAll(response.Body)
_ = response.Body.Close()
if transport.calls.Load() != 1 || transport.readFailures.Load() != 1 {
t.Fatalf("transport calls/read failures = %d/%d, want 1/1", transport.calls.Load(), transport.readFailures.Load())
}
}
func requireProtocolE2E(t *testing.T) {
t.Helper()
if os.Getenv("QODER2API_E2E") != "1" {
t.Skip("authorized protocol E2E disabled; set QODER2API_E2E=1")
}
}
func protocolE2EEnvironmentConfig() protocolE2EConfig {
authDir := strings.TrimSpace(os.Getenv("QODER2API_E2E_AUTH_DIR"))
if authDir == "" {
authDir = filepath.Join(homeDir(), ".qoder", ".auth")
}
return protocolE2EConfig{
authDir: authDir,
inferEndpoint: strings.TrimSpace(os.Getenv("QODER2API_E2E_INFER_ENDPOINT")),
openapiEndpoint: strings.TrimSpace(os.Getenv("QODER2API_E2E_OPENAPI_ENDPOINT")),
webEndpoint: strings.TrimSpace(os.Getenv("QODER2API_E2E_WEB_ENDPOINT")),
}
}
func protocolE2ECloneDefaultTransport() (http.RoundTripper, func()) {
if standard, ok := http.DefaultTransport.(*http.Transport); ok {
cloned := standard.Clone()
return cloned, cloned.CloseIdleConnections
}
return http.DefaultTransport, func() {}
}
func protocolE2ERequireLocalAuth(t *testing.T, authDir string) {
t.Helper()
for _, name := range []string{"machine_id", "user"} {
info, err := os.Stat(filepath.Join(authDir, name))
if err != nil || !info.Mode().IsRegular() || info.Size() == 0 {
t.Skip("authorized encrypted local credential prerequisite unavailable")
}
}
}
func protocolE2EFatal(t *testing.T, category string) {
t.Helper()
t.Fatalf("protocol E2E setup failed: status=0 category=%s length=0", category)
}
func newProtocolE2EHarness(t *testing.T, allowRefresh bool) *protocolE2EHarness {
t.Helper()
requireProtocolE2E(t)
config := protocolE2EEnvironmentConfig()
protocolE2ERequireLocalAuth(t, config.authDir)
setupCtx, cancel := context.WithTimeout(context.Background(), protocolE2ESetupTimeout)
defer cancel()
capabilities := &protocolE2ECapabilityCounts{}
services, err := newProtocolServices(productionProtocolHostDeps())
if err != nil || services == nil {
protocolE2EFatal(t, "protocol-services")
}
harness := &protocolE2EHarness{
services: services,
capabilities: capabilities,
readOnlyAuth: !allowRefresh,
}
t.Cleanup(func() {
harness.Close()
})
harness.installCapabilityCounters()
auth, err := newAuthManager(
services,
config.authDir,
config.openapiEndpoint,
config.inferEndpoint,
config.webEndpoint,
func(string, ...any) {},
)
if err != nil || auth == nil {
protocolE2EFatal(t, "auth-construction")
}
harness.auth = auth
if err := auth.load(setupCtx); err != nil {