forked from livepeer/go-livepeer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream_test.go
More file actions
2118 lines (1803 loc) · 70.4 KB
/
Copy pathstream_test.go
File metadata and controls
2118 lines (1803 loc) · 70.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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package byoc
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"math/rand/v2"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"testing/synctest"
"time"
ethcommon "github.com/ethereum/go-ethereum/common"
"github.com/livepeer/go-livepeer/core"
"github.com/livepeer/go-livepeer/media"
"github.com/livepeer/go-livepeer/net"
"github.com/livepeer/go-livepeer/pm"
"github.com/livepeer/go-livepeer/trickle"
"github.com/livepeer/go-tools/drivers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func newTestBYOCGatewayServer(node *core.LivepeerNode) *BYOCGatewayServer {
if node == nil {
node = mockJobLivepeerNode()
}
statusStore := NewMockStreamStatusStore()
return NewBYOCGatewayServer(node, statusStore, nil, nil, http.NewServeMux())
}
// mockStreamStatusStore is a mock implementation of streamStatusStore for testing
type mockStreamStatusStore struct {
mock.Mock
store map[string]map[string]interface{}
mu sync.RWMutex
}
func NewMockStreamStatusStore() *mockStreamStatusStore {
return &mockStreamStatusStore{
store: make(map[string]map[string]interface{}),
}
}
// Helper: check if any test added an expectation for a method name.
func (m *mockStreamStatusStore) hasExpectation(method string) bool {
for _, c := range m.ExpectedCalls {
if c.Method == method {
return true
}
}
return false
}
func (m *mockStreamStatusStore) Store(streamID string, status map[string]interface{}) {
m.mu.Lock()
defer m.mu.Unlock()
// Use mock override if one exists
if m.hasExpectation("Store") {
m.Called(streamID, status)
return
}
// Default real logic
if m.store == nil {
m.store = make(map[string]map[string]interface{})
}
m.store[streamID] = status
}
func (m *mockStreamStatusStore) Clear(streamID string) {
m.mu.Lock()
defer m.mu.Unlock()
if m.hasExpectation("Clear") {
m.Called(streamID)
return
}
delete(m.store, streamID)
}
func (m *mockStreamStatusStore) Get(streamID string) (map[string]interface{}, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
if m.hasExpectation("Get") {
args := m.Called(streamID)
if args.Get(0) == nil {
return nil, args.Bool(1)
}
return args.Get(0).(map[string]interface{}), args.Bool(1)
}
value, ok := m.store[streamID]
return value, ok
}
func (m *mockStreamStatusStore) StoreIfNotExists(streamID string, key string, status interface{}) {
m.mu.Lock()
defer m.mu.Unlock()
if m.hasExpectation("StoreIfNotExists") {
m.Called(streamID, key, status)
return
}
if m.store == nil {
m.store = make(map[string]map[string]interface{})
}
if _, ok := m.store[streamID]; !ok {
m.store[streamID] = make(map[string]interface{})
}
if _, exists := m.store[streamID][key]; !exists {
m.store[streamID][key] = status
}
}
func (m *mockStreamStatusStore) StoreKey(streamID, key string, status interface{}) {
m.mu.Lock()
defer m.mu.Unlock()
if m.hasExpectation("StoreKey") {
m.Called(streamID, key, status)
return
}
if m.store == nil {
m.store = make(map[string]map[string]interface{})
}
if _, ok := m.store[streamID]; !ok {
m.store[streamID] = make(map[string]interface{})
}
m.store[streamID][key] = status
}
var stubOrchServerUrl string
// testOrch wraps mockOrchestrator to override a few methods needed by lphttp in tests
type testStreamOrch struct {
*mockJobOrchestrator
svc *url.URL
capURL string
}
func (o *testStreamOrch) ServiceURI() *url.URL { return o.svc }
func (o *testStreamOrch) GetUrlForCapability(capability string) string { return o.capURL }
// streamingResponseWriter implements http.ResponseWriter for streaming responses
type streamingResponseWriter struct {
pipe *io.PipeWriter
headers http.Header
status int
}
func (w *streamingResponseWriter) Header() http.Header {
return w.headers
}
func (w *streamingResponseWriter) Write(data []byte) (int, error) {
return w.pipe.Write(data)
}
func (w *streamingResponseWriter) WriteHeader(statusCode int) {
w.status = statusCode
}
// Helper: base64-encoded JobRequest with JobParameters (Enable all true, test-capability name)
func base64TestJobRequest(timeout int, enableVideoIngress, enableVideoEgress, enableDataOutput bool) string {
params := JobParameters{
EnableVideoIngress: enableVideoIngress,
EnableVideoEgress: enableVideoEgress,
EnableDataOutput: enableDataOutput,
}
paramsStr, _ := json.Marshal(params)
jr := JobRequest{
Capability: "test-capability",
Parameters: string(paramsStr),
Request: "{}",
Timeout: timeout,
}
b, _ := json.Marshal(jr)
return base64.StdEncoding.EncodeToString(b)
}
func orchAIStreamStartNoUrlsHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/ai/stream/start" {
http.NotFound(w, r)
return
}
//Headers for trickle urls intentionally left out to prevent starting trickle streams for optional streams
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Control-Url", fmt.Sprintf("%s%s%s", stubOrchServerUrl, "/ai/trickle/", "test-stream-control"))
w.Header().Set("X-Events-Url", fmt.Sprintf("%s%s%s", stubOrchServerUrl, "/ai/trickle/", "test-stream-events"))
w.WriteHeader(http.StatusOK)
}
func orchAIStreamStopHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/ai/stream/stop" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
}
func orchCapabilityUrlHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func TestStartStream_MaxBodyLimit(t *testing.T) {
// Setup server with minimal dependencies
synctest.Test(t, func(t *testing.T) {
node := mockJobLivepeerNode()
server := httptest.NewServer(http.HandlerFunc(orchTokenHandler))
defer server.Close()
node.OrchestratorPool = newStubOrchestratorPool(node, []string{server.URL})
// Set up mock sender to prevent nil pointer dereference
mockSender := pm.MockSender{}
mockSender.On("StartSession", mock.Anything).Return("foo")
mockSender.On("CreateTicketBatch", mock.Anything, mock.Anything).Return(mockTicketBatch(10), nil)
node.Sender = &mockSender
node.Balances = core.NewAddressBalances(10 * time.Second)
defer node.Balances.StopCleanup()
bsg := newTestBYOCGatewayServer(node)
// Prepare a valid job request header
jobDetails := JobRequestDetails{StreamId: "test-stream"}
jobParams := JobParameters{EnableVideoIngress: true, EnableVideoEgress: true, EnableDataOutput: true}
jobReq := JobRequest{
ID: "job-1",
Request: marshalToString(t, jobDetails),
Parameters: marshalToString(t, jobParams),
Capability: "test-capability",
Timeout: 10,
}
jobReqB, err := json.Marshal(jobReq)
assert.NoError(t, err)
jobReqB64 := base64.StdEncoding.EncodeToString(jobReqB)
// Create a body over 10MB
bigBody := bytes.Repeat([]byte("a"), 10<<20+1) // 10MB + 1 byte
req := httptest.NewRequest(http.MethodPost, "/ai/stream/start", bytes.NewReader(bigBody))
req.Header.Set(jobRequestHdr, jobReqB64)
w := httptest.NewRecorder()
handler := bsg.StartStream()
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusRequestEntityTooLarge, w.Code)
})
}
func TestStreamStart_SetupStream(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
node := mockJobLivepeerNode()
server := httptest.NewServer(http.HandlerFunc(orchTokenHandler))
defer server.Close()
node.OrchestratorPool = newStubOrchestratorPool(node, []string{server.URL})
// Set up mock sender to prevent nil pointer dereference
mockSender := pm.MockSender{}
mockSender.On("StartSession", mock.Anything).Return("foo")
mockSender.On("CreateTicketBatch", mock.Anything, mock.Anything).Return(mockTicketBatch(10), nil)
node.Sender = &mockSender
node.Balances = core.NewAddressBalances(10 * time.Second)
defer node.Balances.StopCleanup()
bsg := newTestBYOCGatewayServer(node)
drivers.NodeStorage = drivers.NewMemoryDriver(nil)
// Prepare a valid gatewayJob
jobParams := JobParameters{EnableVideoIngress: true, EnableVideoEgress: true, EnableDataOutput: true}
paramsStr := marshalToString(t, jobParams)
jobReq := &JobRequest{
Capability: "test-capability",
Parameters: paramsStr,
Timeout: 10,
}
orchJob := &orchJob{Req: jobReq, Params: &jobParams}
gatewayJob := &gatewayJob{Job: orchJob}
// Prepare a valid StartRequest body
startReq := StartRequest{
Stream: "teststream",
RtmpOutput: "rtmp://output",
StreamId: "streamid",
Params: "{}",
}
body, _ := json.Marshal(startReq)
req := httptest.NewRequest(http.MethodPost, "/ai/stream/start", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
urls, code, err := bsg.setupStream(context.Background(), req, gatewayJob)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, code)
assert.NotNil(t, urls)
assert.Equal(t, "teststream-streamid", urls.StreamId)
//confirm all urls populated
assert.NotEmpty(t, urls.WhipUrl)
assert.NotEmpty(t, urls.RtmpUrl)
assert.NotEmpty(t, urls.WhepUrl)
assert.NotEmpty(t, urls.RtmpOutputUrl)
assert.Contains(t, urls.RtmpOutputUrl, "rtmp://output")
assert.NotEmpty(t, urls.DataUrl)
assert.NotEmpty(t, urls.StatusUrl)
assert.NotEmpty(t, urls.UpdateUrl)
//confirm StreamPipeline created
stream, err := bsg.streamPipeline(urls.StreamId)
assert.NoError(t, err)
assert.NotNil(t, stream)
assert.Equal(t, urls.StreamId, stream.StreamID)
assert.Equal(t, bsg.streamPipelineRequest(urls.StreamId), []byte("{\"params\":{}}"))
bsg.removeStreamPipeline(urls.StreamId)
//test with no data output
jobParams = JobParameters{EnableVideoIngress: true, EnableVideoEgress: true, EnableDataOutput: false}
paramsStr = marshalToString(t, jobParams)
jobReq.Parameters = paramsStr
gatewayJob.Job.Params = &jobParams
req.Body = io.NopCloser(bytes.NewReader(body))
urls, code, err = bsg.setupStream(context.Background(), req, gatewayJob)
assert.NotNil(t, urls)
assert.Empty(t, urls.DataUrl)
bsg.removeStreamPipeline(urls.StreamId)
//test with no video ingress
jobParams = JobParameters{EnableVideoIngress: false, EnableVideoEgress: true, EnableDataOutput: true}
paramsStr = marshalToString(t, jobParams)
jobReq.Parameters = paramsStr
gatewayJob.Job.Params = &jobParams
req.Body = io.NopCloser(bytes.NewReader(body))
urls, code, err = bsg.setupStream(context.Background(), req, gatewayJob)
assert.NotNil(t, urls)
assert.Empty(t, urls.WhipUrl)
assert.Empty(t, urls.RtmpUrl)
bsg.removeStreamPipeline(urls.StreamId)
//test with no video egress
jobParams = JobParameters{EnableVideoIngress: true, EnableVideoEgress: false, EnableDataOutput: true}
paramsStr = marshalToString(t, jobParams)
jobReq.Parameters = paramsStr
gatewayJob.Job.Params = &jobParams
req.Body = io.NopCloser(bytes.NewReader(body))
urls, code, err = bsg.setupStream(context.Background(), req, gatewayJob)
assert.NotNil(t, urls)
assert.Empty(t, urls.WhepUrl)
assert.Empty(t, urls.RtmpOutputUrl)
bsg.removeStreamPipeline(urls.StreamId)
// Test with nil job
urls, code, err = bsg.setupStream(context.Background(), req, nil)
assert.Error(t, err)
assert.Equal(t, http.StatusBadRequest, code)
assert.Nil(t, urls)
assert.Zero(t, len(bsg.StreamPipelines))
// Test with invalid JSON body
badReq := httptest.NewRequest(http.MethodPost, "/ai/stream/start", bytes.NewReader([]byte("notjson")))
badReq.Header.Set("Content-Type", "application/json")
urls, code, err = bsg.setupStream(context.Background(), badReq, gatewayJob)
assert.Error(t, err)
assert.Equal(t, http.StatusBadRequest, code)
assert.Nil(t, urls)
assert.Zero(t, len(bsg.StreamPipelines))
// Test with stream name ending in -out (should return nil, 0, nil)
outReq := StartRequest{
Stream: "teststream-out",
RtmpOutput: "rtmp://output",
StreamId: "streamid",
Params: "{}",
}
outBody, _ := json.Marshal(outReq)
outReqHTTP := httptest.NewRequest(http.MethodPost, "/ai/stream/start", bytes.NewReader(outBody))
outReqHTTP.Header.Set("Content-Type", "application/json")
urls, code, err = bsg.setupStream(context.Background(), outReqHTTP, gatewayJob)
assert.NoError(t, err)
assert.Equal(t, 0, code)
assert.Nil(t, urls)
assert.Zero(t, len(bsg.StreamPipelines))
})
}
func TestRunStream_RunAndCancelStream(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
node := mockJobLivepeerNode()
// Set up an lphttp-based orchestrator test server with trickle endpoints
mux := http.NewServeMux()
mockOrch := &mockJobOrchestrator{}
mockOrch.On("VerifySig", mock.Anything, mock.Anything, mock.Anything).Return(true)
mockOrch.On("DebitFees", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return()
bso := &BYOCOrchestratorServer{orch: nil, httpMux: mux, node: node}
// Configure trickle server on the mux (imitate production trickle endpoints)
bso.trickleSrv = trickle.ConfigureServer(trickle.TrickleServerConfig{
Mux: mux,
BasePath: "/ai/trickle/",
Autocreate: true,
})
// Register orchestrator endpoints used by runStream path
mux.HandleFunc("/ai/stream/start", orchAIStreamStartNoUrlsHandler)
mux.HandleFunc("/ai/stream/stop", orchAIStreamStopHandler)
mux.HandleFunc("/process/token", orchTokenHandler)
server := httptest.NewServer(bso.httpMux)
defer server.Close()
stubOrchServerUrl = server.URL
// Configure mock orchestrator behavior expected by lphttp handlers
parsedURL, _ := url.Parse(server.URL)
capabilitySrv := httptest.NewServer(http.HandlerFunc(orchCapabilityUrlHandler))
defer capabilitySrv.Close()
// attach our orchestrator implementation to lphttp
bso.orch = &testStreamOrch{mockJobOrchestrator: mockOrch, svc: parsedURL, capURL: capabilitySrv.URL}
// Prepare a gatewayJob with a dummy orchestrator token
jobReq := &JobRequest{
ID: "test-stream",
Capability: "test-capability",
Timeout: 10,
Request: "{}",
}
jobParams := JobParameters{EnableVideoIngress: true, EnableVideoEgress: true, EnableDataOutput: true}
paramsStr := marshalToString(t, jobParams)
jobReq.Parameters = paramsStr
orchToken := createMockJobToken(server.URL)
orchJob := &orchJob{Req: jobReq, Params: &jobParams}
gatewayJob := &gatewayJob{Job: orchJob, Orchs: []JobToken{*orchToken}, node: node}
// Setup a LivepeerServer and a mock pipeline
bsg := newTestBYOCGatewayServer(node)
bsg.node.OrchestratorPool = newStubOrchestratorPool(bsg.node, []string{server.URL})
drivers.NodeStorage = drivers.NewMemoryDriver(nil)
mockSender := pm.MockSender{}
mockSender.On("StartSession", mock.Anything).Return("foo").Times(4)
mockSender.On("CreateTicketBatch", "foo", 10).Return(mockTicketBatch(10), nil).Twice() //payment sent on start and stop (only once on stop)
node.Sender = &mockSender
node.Balances = core.NewAddressBalances(10 * time.Second)
defer node.Balances.StopCleanup()
//now sign job and create a sig for the sender to include
gatewayJob.sign()
sender, err := getJobSender(context.TODO(), node)
assert.NoError(t, err)
orchJob.Req.Sender = sender.Addr
orchJob.Req.Sig = sender.Sig
// Minimal aiRequestParams and liveRequestParams
params := byocAIRequestParams{
liveParams: &byocLiveRequestParams{
requestID: "req-1",
stream: "test-stream",
streamID: "test-stream",
sendErrorEvent: func(err error) {},
segmentReader: nil,
},
node: node,
}
bsg.newStreamPipeline("req-1", "test-stream", "test-capability", params, nil)
// Should not panic and should clean up
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); bsg.runStream(gatewayJob) }()
go func() { defer wg.Done(); bsg.monitorStream(gatewayJob.Job.Req.ID) }()
// Cancel the stream after a short delay to simulate shutdown
done := make(chan struct{})
go func() {
stream, _ := bsg.streamPipeline(gatewayJob.Job.Req.ID)
if stream != nil {
// Wait for kickOrch to be set and call it to cancel the stream
timeout := time.After(1 * time.Second)
var kickOrch context.CancelCauseFunc
waitLoop:
for {
select {
case <-timeout:
// Timeout waiting for kickOrch, proceed anyway
break waitLoop
default:
params, err := bsg.streamPipelineParams(gatewayJob.Job.Req.ID)
if err == nil {
params.liveParams.mu.Lock()
kickOrch = params.liveParams.kickOrch
params.liveParams.mu.Unlock()
}
if err == nil && kickOrch != nil {
kickOrch(errors.New("test cancellation"))
break waitLoop
}
}
}
}
close(done)
}()
<-done
// Wait for both goroutines to finish before asserting
wg.Wait()
_, err = bsg.streamPipeline(params.liveParams.streamID)
assert.Error(t, err)
// Clean up external capabilities streams
if node.ExternalCapabilities != nil {
for streamID := range node.ExternalCapabilities.Streams {
node.ExternalCapabilities.RemoveStream(streamID)
}
}
//confirm external capability stream removed
_, ok := node.ExternalCapabilities.GetStream("test-stream")
assert.False(t, ok)
})
}
// TestRunStream_OrchestratorFailover tests that runStream fails over to a second orchestrator
// when the first one fails, and stops when the second orchestrator also fails
func TestRunStream_OrchestratorFailover(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
node := mockJobLivepeerNode()
// Channels to signal when each orchestrator is contacted
orch1Started := make(chan struct{}, 1)
orch2Started := make(chan struct{}, 1)
// Set up an lphttp-based orchestrator test server with trickle endpoints
mux := http.NewServeMux()
mockOrch := &mockJobOrchestrator{}
mockOrch.On("VerifySig", mock.Anything, mock.Anything, mock.Anything).Return(true)
mockOrch.On("DebitFees", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return()
mockOrch2 := *mockOrch
bso := &BYOCOrchestratorServer{orch: nil, httpMux: mux, node: node}
// Configure trickle server on the mux (imitate production trickle endpoints)
bso.trickleSrv = trickle.ConfigureServer(trickle.TrickleServerConfig{
Mux: mux,
BasePath: "/ai/trickle/",
Autocreate: true,
})
// Register orchestrator endpoints used by runStream path - wrap to signal when called
mux.HandleFunc("/ai/stream/start", func(w http.ResponseWriter, r *http.Request) {
select {
case orch1Started <- struct{}{}:
default:
}
orchAIStreamStartNoUrlsHandler(w, r)
})
mux.HandleFunc("/ai/stream/stop", orchAIStreamStopHandler)
mux.HandleFunc("/process/token", orchTokenHandler)
server := httptest.NewServer(bso.httpMux)
defer server.Close()
mux2 := http.NewServeMux()
bso2 := &BYOCOrchestratorServer{orch: nil, httpMux: mux2, node: mockJobLivepeerNode()}
// Configure trickle server on the mux (imitate production trickle endpoints)
bso2.trickleSrv = trickle.ConfigureServer(trickle.TrickleServerConfig{
Mux: mux2,
BasePath: "/ai/trickle/",
Autocreate: true,
})
// Register orchestrator endpoints used by runStream path - wrap to signal when called
mux2.HandleFunc("/ai/stream/start", func(w http.ResponseWriter, r *http.Request) {
select {
case orch2Started <- struct{}{}:
default:
}
orchAIStreamStartNoUrlsHandler(w, r)
})
mux2.HandleFunc("/ai/stream/stop", orchAIStreamStopHandler)
mux2.HandleFunc("/process/token", orchTokenHandler)
server2 := httptest.NewServer(bso2.httpMux)
defer server2.Close()
// Configure mock orchestrator behavior expected by lphttp handlers
parsedURL, _ := url.Parse(server.URL)
capabilitySrv := httptest.NewServer(http.HandlerFunc(orchCapabilityUrlHandler))
defer capabilitySrv.Close()
parsedURL2, _ := url.Parse(server2.URL)
capabilitySrv2 := httptest.NewServer(http.HandlerFunc(orchCapabilityUrlHandler))
defer capabilitySrv2.Close()
// attach our orchestrator implementation to lphttp
bso.orch = &testStreamOrch{mockJobOrchestrator: mockOrch, svc: parsedURL, capURL: capabilitySrv.URL}
bso2.orch = &testStreamOrch{mockJobOrchestrator: &mockOrch2, svc: parsedURL2, capURL: capabilitySrv2.URL}
// Prepare a gatewayJob with a dummy orchestrator token
jobReq := &JobRequest{
ID: "test-stream",
Capability: "test-capability",
Timeout: 10,
Request: "{}",
}
jobParams := JobParameters{EnableVideoIngress: true, EnableVideoEgress: true, EnableDataOutput: true}
paramsStr := marshalToString(t, jobParams)
jobReq.Parameters = paramsStr
orchToken := createMockJobToken(server.URL)
orchToken2 := createMockJobToken(server2.URL)
orchToken2.TicketParams.Recipient = ethcommon.HexToAddress("0x1111111111111111111111111111111111111112").Bytes()
orchJob := &orchJob{Req: jobReq, Params: &jobParams}
gatewayJob := &gatewayJob{Job: orchJob, Orchs: []JobToken{*orchToken, *orchToken2}, node: node}
// Setup a LivepeerServer and a mock pipeline
bsg := newTestBYOCGatewayServer(node)
bsg.node.OrchestratorPool = newStubOrchestratorPool(bsg.node, []string{server.URL, server2.URL})
drivers.NodeStorage = drivers.NewMemoryDriver(nil)
mockSender := pm.MockSender{}
mockSender.On("StartSession", mock.Anything).Return("foo").Times(4)
mockSender.On("CreateTicketBatch", "foo", orchJob.Req.Timeout).Return(mockTicketBatch(orchJob.Req.Timeout), nil).Times(4) //payment sent on start and stop of each Orch (only once on stop)
node.Sender = &mockSender
node.Balances = core.NewAddressBalances(10 * time.Second)
defer node.Balances.StopCleanup()
//now sign job and create a sig for the sender to include
gatewayJob.sign()
sender, err := getJobSender(context.TODO(), node)
assert.NoError(t, err)
orchJob.Req.Sender = sender.Addr
orchJob.Req.Sig = sender.Sig
// Minimal aiRequestParams and liveRequestParams
params := byocAIRequestParams{
liveParams: &byocLiveRequestParams{
requestID: "req-1",
stream: "test-stream",
streamID: "test-stream",
sendErrorEvent: func(err error) {},
segmentReader: media.NewSwitchableSegmentReader(),
},
node: node,
}
bsg.newStreamPipeline("req-1", "test-stream", "test-capability", params, nil)
streamID := gatewayJob.Job.Req.ID
// Should not panic and should clean up
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); bsg.runStream(gatewayJob) }()
go func() { defer wg.Done(); bsg.monitorStream(streamID) }()
// Wait for first orchestrator to be contacted
select {
case <-orch1Started:
t.Log("Orchestrator 1 started")
case <-time.After(1 * time.Second):
t.Fatal("Timeout waiting for orchestrator 1 to start")
}
// Kick the first orchestrator to trigger failover
params2, err := bsg.streamPipelineParams(streamID)
if err != nil {
t.Fatalf("Failed to get stream params: %v", err)
}
params2.liveParams.mu.Lock()
kickOrch := params2.liveParams.kickOrch
params2.liveParams.mu.Unlock()
if kickOrch == nil {
t.Fatal("kickOrch should be set after orchestrator starts")
}
kickOrch(errors.New("test cancellation orch1"))
t.Log("Orchestrator 1 kicked")
// Wait for failover to second orchestrator
select {
case <-orch2Started:
t.Log("Orchestrator 2 started (failover successful)")
case <-time.After(1 * time.Second):
t.Fatal("Timeout waiting for orchestrator 2 to start after failover")
}
//kick the second Orchestrator
params3, err := bsg.streamPipelineParams(streamID)
if err != nil {
t.Fatalf("Failed to get stream params: %v", err)
}
params3.liveParams.mu.Lock()
kickOrch2 := params3.liveParams.kickOrch
params3.liveParams.mu.Unlock()
if kickOrch2 == nil {
t.Fatal("kickOrch should be set after orchestrator 2 starts")
}
kickOrch2(errors.New("test cancellation orch2"))
t.Log("Orchestrator 2 kicked")
// Wait for both goroutines to finish before asserting
wg.Wait()
// After cancel, the stream should be removed from byoc StreamPipelines
_, err = bsg.streamPipeline(streamID)
assert.Error(t, err)
// Clean up external capabilities streams
if node.ExternalCapabilities != nil {
for streamID := range node.ExternalCapabilities.Streams {
node.ExternalCapabilities.RemoveStream(streamID)
}
}
})
}
func TestStartStreamHandler(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
node := mockJobLivepeerNode()
orch1Started := make(chan struct{}, 1)
// Set up an lphttp-based orchestrator test server with trickle endpoints
mux := http.NewServeMux()
bsg := newTestBYOCGatewayServer(node)
mockSender := pm.MockSender{}
mockSender.On("StartSession", mock.Anything).Return("foo")
mockSender.On("CreateTicketBatch", mock.Anything, mock.Anything).Return(mockTicketBatch(10), nil)
node.Sender = &mockSender
node.Balances = core.NewAddressBalances(1 * time.Second)
//setup Orch server stub
mux.HandleFunc("/process/token", orchTokenHandler)
mux.HandleFunc("/ai/stream/start", func(w http.ResponseWriter, r *http.Request) {
select {
case orch1Started <- struct{}{}:
default:
}
orchAIStreamStartNoUrlsHandler(w, r)
})
server := httptest.NewServer(mux)
defer server.Close()
bsg.node.OrchestratorPool = newStubOrchestratorPool(bsg.node, []string{server.URL})
drivers.NodeStorage = drivers.NewMemoryDriver(nil)
// Prepare a valid StartRequest body
startReq := StartRequest{
Stream: "teststream",
RtmpOutput: "rtmp://output",
StreamId: "streamid",
Params: "{}",
}
body, _ := json.Marshal(startReq)
req := httptest.NewRequest(http.MethodPost, "/process/stream/start", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Livepeer", base64TestJobRequest(10, true, true, true))
w := httptest.NewRecorder()
handler := bsg.StartStream()
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
body = w.Body.Bytes()
var streamUrls StreamUrls
err := json.Unmarshal(body, &streamUrls)
assert.NoError(t, err)
stream, err := bsg.streamPipeline(streamUrls.StreamId)
assert.NoError(t, err)
assert.NotNil(t, stream)
assert.Equal(t, streamUrls.StreamId, stream.StreamID)
//kick the orch to stop the stream and cleanup
<-orch1Started
streamParams, _ := bsg.streamPipelineParams(streamUrls.StreamId)
if streamParams.liveParams.kickOrch != nil {
streamParams.liveParams.kickOrch(errors.New("test cleanup"))
}
bsg.node.Balances.StopCleanup()
})
}
func TestStopStreamHandler(t *testing.T) {
t.Run("StreamNotFound", func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
// Test case 1: Stream doesn't exist - should return 404
bsg := newTestBYOCGatewayServer(nil)
req := httptest.NewRequest(http.MethodPost, "/process/stream/{streamId}/stop", nil)
req.SetPathValue("streamId", "non-existent-stream")
w := httptest.NewRecorder()
handler := bsg.StopStream()
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusNotFound, w.Code)
assert.Contains(t, w.Body.String(), "Stream not found")
})
})
t.Run("StreamExistsAndStopsSuccessfully", func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
// Test case 2: Stream exists - should stop stream and attempt to send request to orchestrator
node := mockJobLivepeerNode()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Mock orchestrator response handlers
switch r.URL.Path {
case "/process/token":
orchTokenHandler(w, r)
case "/ai/stream/stop":
// Mock successful stop response from orchestrator
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status": "stopped"}`))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
node.OrchestratorPool = newStubOrchestratorPool(node, []string{server.URL})
bsg := newTestBYOCGatewayServer(node)
drivers.NodeStorage = drivers.NewMemoryDriver(nil)
mockSender := pm.MockSender{}
mockSender.On("StartSession", mock.Anything).Return("foo").Times(4)
mockSender.On("CreateTicketBatch", "foo", 10).Return(mockTicketBatch(10), nil).Once()
node.Sender = &mockSender
node.Balances = core.NewAddressBalances(10 * time.Second)
defer node.Balances.StopCleanup()
// Create a stream to stop
streamID := "test-stream-to-stop"
// Create minimal AI session with properly formatted URL
token := createMockJobToken(server.URL)
// Create stream parameters
params := byocAIRequestParams{
liveParams: &byocLiveRequestParams{
requestID: "req-1",
orchToken: *token,
stream: streamID,
streamID: streamID,
sendErrorEvent: func(err error) {},
segmentReader: nil,
},
node: node,
}
// Add the stream to StreamPipelines
stream := bsg.newStreamPipeline("req-1", streamID, "test-capability", params, nil)
assert.NotNil(t, stream)
// Verify stream exists before stopping
_, err := bsg.streamPipeline(streamID)
assert.NoError(t, err, "Stream should exist before stopping")
// Create stop request with proper job header
jobParams := JobParameters{EnableVideoIngress: true, EnableVideoEgress: true, EnableDataOutput: true}
jobDetails := JobRequestDetails{StreamId: streamID}
jobReq := JobRequest{
ID: streamID,
Request: marshalToString(t, jobDetails),
Capability: "test-capability",
Parameters: marshalToString(t, jobParams),
Timeout: 10,
}
jobReqB, err := json.Marshal(jobReq)
assert.NoError(t, err)
jobReqB64 := base64.StdEncoding.EncodeToString(jobReqB)
req := httptest.NewRequest(http.MethodPost, "/process/stream/{streamId}/stop", strings.NewReader(`{"reason": "test stop"}`))
req.SetPathValue("streamId", streamID)
req.Header.Set("Content-Type", "application/json")
req.Header.Set(jobRequestHdr, jobReqB64)
w := httptest.NewRecorder()
handler := bsg.StopStream()
handler.ServeHTTP(w, req)
// The response might vary depending on orchestrator communication success
// The important thing is that the stream is removed regardless
assert.Contains(t, []int{http.StatusOK, http.StatusInternalServerError, http.StatusBadRequest}, w.Code,
"Should return valid HTTP status")
// Verify stream was removed from StreamPipelines (this should always happen)
_, err = bsg.streamPipeline(streamID)
assert.Error(t, err, "Stream should be removed after stopping")
})
})
t.Run("StreamExistsButOrchestratorError", func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
// Test case 3: Stream exists but orchestrator returns error
node := mockJobLivepeerNode()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/process/token":
orchTokenHandler(w, r)
case "/ai/stream/stop":
// Mock orchestrator error
http.Error(w, "Orchestrator error", http.StatusInternalServerError)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
node.OrchestratorPool = newStubOrchestratorPool(node, []string{server.URL})
bsg := newTestBYOCGatewayServer(node)
drivers.NodeStorage = drivers.NewMemoryDriver(nil)
mockSender := pm.MockSender{}
mockSender.On("StartSession", mock.Anything).Return("foo").Times(4)
mockSender.On("CreateTicketBatch", "foo", 10).Return(mockTicketBatch(10), nil).Once()
node.Sender = &mockSender
node.Balances = core.NewAddressBalances(10 * time.Second)
defer node.Balances.StopCleanup()
streamID := "test-stream-orch-error"
// Create minimal AI session
token := createMockJobToken(server.URL)
params := byocAIRequestParams{
liveParams: &byocLiveRequestParams{
requestID: "req-1",
orchToken: *token,
stream: streamID,
streamID: streamID,
sendErrorEvent: func(err error) {},
segmentReader: nil,
},
node: node,
}
// Add the stream
stream := bsg.newStreamPipeline("req-1", streamID, "test-capability", params, nil)
assert.NotNil(t, stream)
// Create stop request
jobParams := JobParameters{EnableVideoIngress: true, EnableVideoEgress: true, EnableDataOutput: true}
jobDetails := JobRequestDetails{StreamId: streamID}
jobReq := JobRequest{
ID: streamID,
Request: marshalToString(t, jobDetails),
Capability: "test-capability",
Parameters: marshalToString(t, jobParams),
Timeout: 10,
}
jobReqB, err := json.Marshal(jobReq)
assert.NoError(t, err)
jobReqB64 := base64.StdEncoding.EncodeToString(jobReqB)
req := httptest.NewRequest(http.MethodPost, "/process/stream/{streamId}/stop", nil)
req.SetPathValue("streamId", streamID)
req.Header.Set(jobRequestHdr, jobReqB64)
w := httptest.NewRecorder()
handler := bsg.StopStream()
handler.ServeHTTP(w, req)
// Returns 200 OK because Gateway removed the stream. If the Orchestrator errors, it will return
// the error in the response body
assert.Equal(t, http.StatusOK, w.Code)
// Stream should still be removed even if orchestrator returns error
_, err = bsg.streamPipeline(streamID)
assert.Error(t, err, "Stream should be removed even on orchestrator error")
})
})
}
func TestStartStreamWhipIngestHandler(t *testing.T) {
min := 10000
max := 65535
// rand.Intn returns a non-negative pseudo-random integer in the range [0, n).
// Adding min to the result shifts the range to [min, max].
randomNumber := rand.IntN(max-min+1) + min
t.Setenv("LIVE_AI_WHIP_ADDR", fmt.Sprintf(":%d", randomNumber))
whipServer := media.NewWHIPServer()
synctest.Test(t, func(t *testing.T) {
node := mockJobLivepeerNode()
node.WorkDir = t.TempDir()
server := httptest.NewServer(http.HandlerFunc(orchTokenHandler))
defer server.Close()
node.OrchestratorPool = newStubOrchestratorPool(node, []string{server.URL})
bsg := newTestBYOCGatewayServer(node)