From 1b760393bcb8d1e8caff9378a862e5386a9a8f37 Mon Sep 17 00:00:00 2001 From: Raja Subramanian Date: Tue, 3 Jun 2025 08:23:37 -0700 Subject: [PATCH] WHIP support. (#3692) * WHIP support. WHIP like signalling with added support for data channels. * clean up * Paul feedback * deps --- go.mod | 23 +- go.sum | 46 +-- pkg/rtc/room.go | 52 +-- pkg/rtc/transport.go | 1 - pkg/service/roommanager.go | 50 ++- pkg/service/roommanager_service.go | 189 +++++++++++ pkg/service/rtcrestservice.go | 527 +++++++++++++++++++++++++++++ pkg/service/rtcservice.go | 6 - pkg/service/server.go | 48 +-- pkg/service/wire.go | 2 + pkg/service/wire_gen.go | 12 +- 11 files changed, 856 insertions(+), 100 deletions(-) create mode 100644 pkg/service/roommanager_service.go create mode 100644 pkg/service/rtcrestservice.go diff --git a/go.mod b/go.mod index b60c6e1a..538e783b 100644 --- a/go.mod +++ b/go.mod @@ -23,7 +23,7 @@ require ( github.com/jxskiss/base62 v1.1.0 github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 github.com/livekit/mediatransportutil v0.0.0-20250519131108-fb90f5acfded - github.com/livekit/protocol v1.38.1-0.20250519021605-53d1afe260e9 + github.com/livekit/protocol v1.39.1-0.20250603151335-3ea1acd38bb3 github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c github.com/mackerelio/go-osstat v0.2.5 github.com/magefile/mage v1.15.0 @@ -34,20 +34,21 @@ require ( github.com/pion/datachannel v1.5.10 github.com/pion/dtls/v3 v3.0.6 github.com/pion/ice/v4 v4.0.10 - github.com/pion/interceptor v0.1.37 + github.com/pion/interceptor v0.1.38 github.com/pion/rtcp v1.2.15 - github.com/pion/rtp v1.8.15 + github.com/pion/rtp v1.8.16 github.com/pion/sctp v1.8.39 - github.com/pion/sdp/v3 v3.0.11 + github.com/pion/sdp/v3 v3.0.13 github.com/pion/transport/v3 v3.0.7 github.com/pion/turn/v4 v4.0.2 github.com/pion/webrtc/v4 v4.1.1 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.22.0 - github.com/redis/go-redis/v9 v9.8.0 + github.com/redis/go-redis/v9 v9.9.0 github.com/rs/cors v1.11.1 github.com/stretchr/testify v1.10.0 github.com/thoas/go-funk v0.9.3 + github.com/tomnomnom/linkheader v0.0.0-20180905144013-02ca5825eb80 github.com/twitchtv/twirp v8.1.3+incompatible github.com/ua-parser/uap-go v0.0.0-20250126222208-a52596c19dff github.com/urfave/cli/v2 v2.27.5 @@ -55,7 +56,7 @@ require ( go.uber.org/atomic v1.11.0 go.uber.org/multierr v1.11.0 go.uber.org/zap v1.27.0 - golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 + golang.org/x/exp v0.0.0-20250531010427-b6e5de432a8b golang.org/x/mod v0.24.0 golang.org/x/sync v0.14.0 google.golang.org/protobuf v1.36.6 @@ -86,7 +87,7 @@ require ( github.com/docker/go-units v0.5.0 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/go-jose/go-jose/v3 v3.0.4 // indirect - github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/logr v1.4.3 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/google/cel-go v0.25.0 // indirect github.com/google/go-cmp v0.7.0 // indirect @@ -106,7 +107,7 @@ require ( github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/term v0.5.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/nats-io/nats.go v1.42.0 // indirect + github.com/nats-io/nats.go v1.43.0 // indirect github.com/nats-io/nkeys v0.4.11 // indirect github.com/nats-io/nuid v1.0.1 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect @@ -137,8 +138,8 @@ require ( golang.org/x/sys v0.33.0 // indirect golang.org/x/text v0.25.0 // indirect golang.org/x/tools v0.33.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20250512202823-5a2f75b736a9 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250512202823-5a2f75b736a9 // indirect - google.golang.org/grpc v1.72.1 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20250528174236-200df99c418a // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250528174236-200df99c418a // indirect + google.golang.org/grpc v1.72.2 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index 558a87d8..f6ffe082 100644 --- a/go.sum +++ b/go.sum @@ -80,8 +80,8 @@ github.com/gammazero/workerpool v1.1.3 h1:WixN4xzukFoN0XSeXF6puqEqFTl2mECI9S6W44 github.com/gammazero/workerpool v1.1.3/go.mod h1:wPjyBLDbyKnUn2XwwyD3EEwo9dHutia9/fwNmSHWACc= github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= -github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= -github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= @@ -169,8 +169,8 @@ github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 h1:9x+U2HGLrSw5AT github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ= github.com/livekit/mediatransportutil v0.0.0-20250519131108-fb90f5acfded h1:ylZPdnlX1RW9Z15SD4mp87vT2D2shsk0hpLJwSPcq3g= github.com/livekit/mediatransportutil v0.0.0-20250519131108-fb90f5acfded/go.mod h1:mSNtYzSf6iY9xM3UX42VEI+STHvMgHmrYzEHPcdhB8A= -github.com/livekit/protocol v1.38.1-0.20250519021605-53d1afe260e9 h1:EGfadmT1Ps8/Z1RugvQz9v2DO6psCOK/BBuXbtGA7tQ= -github.com/livekit/protocol v1.38.1-0.20250519021605-53d1afe260e9/go.mod h1:6HPISM0bkTXTk9RIaQTCe0IDbomBPz7Jwp+N3w5sqL0= +github.com/livekit/protocol v1.39.1-0.20250603151335-3ea1acd38bb3 h1:CyhrGOhY8BbH72BhAL+xu7FNTRUhRjk46lYoLCcd2ys= +github.com/livekit/protocol v1.39.1-0.20250603151335-3ea1acd38bb3/go.mod h1:6HPISM0bkTXTk9RIaQTCe0IDbomBPz7Jwp+N3w5sqL0= github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c h1:WwEr0YBejYbKzk8LSaO9h8h0G9MnE7shyDu8yXQWmEc= github.com/livekit/psrpc v0.6.1-0.20250511053145-465289d72c3c/go.mod h1:kmD+AZPkWu0MaXIMv57jhNlbiSZZ/Jx4bzlxBDVmJes= github.com/mackerelio/go-osstat v0.2.5 h1:+MqTbZUhoIt4m8qzkVoXUJg1EuifwlAJSk4Yl2GXh+o= @@ -214,8 +214,8 @@ github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/nats-io/nats.go v1.42.0 h1:ynIMupIOvf/ZWH/b2qda6WGKGNSjwOUutTpWRvAmhaM= -github.com/nats-io/nats.go v1.42.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g= +github.com/nats-io/nats.go v1.43.0 h1:uRFZ2FEoRvP64+UUhaTokyS18XBCR/xM2vQZKO4i8ug= +github.com/nats-io/nats.go v1.43.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g= github.com/nats-io/nkeys v0.4.11 h1:q44qGV008kYd9W1b1nEBkNzvnWxtRSQ7A8BoqRrcfa0= github.com/nats-io/nkeys v0.4.11/go.mod h1:szDimtgmfOi9n25JpfIdGw12tZFYXqhGxjhVxsatHVE= github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= @@ -238,8 +238,8 @@ github.com/pion/dtls/v3 v3.0.6 h1:7Hkd8WhAJNbRgq9RgdNh1aaWlZlGpYTzdqjy9x9sK2E= github.com/pion/dtls/v3 v3.0.6/go.mod h1:iJxNQ3Uhn1NZWOMWlLxEEHAN5yX7GyPvvKw04v9bzYU= github.com/pion/ice/v4 v4.0.10 h1:P59w1iauC/wPk9PdY8Vjl4fOFL5B+USq1+xbDcN6gT4= github.com/pion/ice/v4 v4.0.10/go.mod h1:y3M18aPhIxLlcO/4dn9X8LzLLSma84cx6emMSu14FGw= -github.com/pion/interceptor v0.1.37 h1:aRA8Zpab/wE7/c0O3fh1PqY0AJI3fCSEM5lRWJVorwI= -github.com/pion/interceptor v0.1.37/go.mod h1:JzxbJ4umVTlZAf+/utHzNesY8tmRkM2lVmkS82TTj8Y= +github.com/pion/interceptor v0.1.38 h1:Mgt3XIIq47uR5vcLLahfRucE6tFPjxHak+z5ZZFEzLU= +github.com/pion/interceptor v0.1.38/go.mod h1:HS9X+Ue5LDE6q2C2tuvOuO83XkBdJFgn6MBDtfoJX4Q= github.com/pion/logging v0.2.3 h1:gHuf0zpoh1GW67Nr6Gj4cv5Z9ZscU7g/EaoC/Ke/igI= github.com/pion/logging v0.2.3/go.mod h1:z8YfknkquMe1csOrxK5kc+5/ZPAzMxbKLX5aXpbpC90= github.com/pion/mdns/v2 v2.0.7 h1:c9kM8ewCgjslaAmicYMFQIde2H9/lrZpjBkN8VwoVtM= @@ -248,12 +248,12 @@ github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8= github.com/pion/rtcp v1.2.15 h1:LZQi2JbdipLOj4eBjK4wlVoQWfrZbh3Q6eHtWtJBZBo= github.com/pion/rtcp v1.2.15/go.mod h1:jlGuAjHMEXwMUHK78RgX0UmEJFV4zUKOFHR7OP+D3D0= -github.com/pion/rtp v1.8.15 h1:MuhuGn1cxpVCPLNY1lI7F1tQ8Spntpgf12ob+pOYT8s= -github.com/pion/rtp v1.8.15/go.mod h1:bAu2UFKScgzyFqvUKmbvzSdPr+NGbZtv6UB2hesqXBk= +github.com/pion/rtp v1.8.16 h1:0mpfguLyN9HCpPIXcoOho4BkMsz5eB1Yjvf+obI5cEQ= +github.com/pion/rtp v1.8.16/go.mod h1:bAu2UFKScgzyFqvUKmbvzSdPr+NGbZtv6UB2hesqXBk= github.com/pion/sctp v1.8.39 h1:PJma40vRHa3UTO3C4MyeJDQ+KIobVYRZQZ0Nt7SjQnE= github.com/pion/sctp v1.8.39/go.mod h1:cNiLdchXra8fHQwmIoqw0MbLLMs+f7uQ+dGMG2gWebE= -github.com/pion/sdp/v3 v3.0.11 h1:VhgVSopdsBKwhCFoyyPmT1fKMeV9nLMrEKxNOdy3IVI= -github.com/pion/sdp/v3 v3.0.11/go.mod h1:88GMahN5xnScv1hIMTqLdu/cOcUkj6a9ytbncwMCq2E= +github.com/pion/sdp/v3 v3.0.13 h1:uN3SS2b+QDZnWXgdr69SM8KB4EbcnPnPf2Laxhty/l4= +github.com/pion/sdp/v3 v3.0.13/go.mod h1:88GMahN5xnScv1hIMTqLdu/cOcUkj6a9ytbncwMCq2E= github.com/pion/srtp/v3 v3.0.4 h1:2Z6vDVxzrX3UHEgrUyIGM4rRouoC7v+NiF1IHtp9B5M= github.com/pion/srtp/v3 v3.0.4/go.mod h1:1Jx3FwDoxpRaTh1oRV8A/6G1BnFL+QI82eK4ms8EEJQ= github.com/pion/stun/v3 v3.0.0 h1:4h1gwhWLWuZWOJIJR9s2ferRO+W3zA/b6ijOI6mKzUw= @@ -278,8 +278,8 @@ github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzM github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= github.com/puzpuzpuz/xsync/v3 v3.5.1 h1:GJYJZwO6IdxN/IKbneznS6yPkVC+c3zyY/j19c++5Fg= github.com/puzpuzpuz/xsync/v3 v3.5.1/go.mod h1:VjzYrABPabuM4KyBh1Ftq6u8nhwY5tBPKP9jpmh0nnA= -github.com/redis/go-redis/v9 v9.8.0 h1:q3nRvjrlge/6UD7eTu/DSg2uYiU2mCL0G/uzBWqhicI= -github.com/redis/go-redis/v9 v9.8.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= +github.com/redis/go-redis/v9 v9.9.0 h1:URbPQ4xVQSQhZ27WMQVmZSo3uT3pL+4IdHVcYq2nVfM= +github.com/redis/go-redis/v9 v9.9.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= @@ -308,6 +308,8 @@ github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOf github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/thoas/go-funk v0.9.3 h1:7+nAEx3kn5ZJcnDm2Bh23N2yOtweO14bi//dvRtgLpw= github.com/thoas/go-funk v0.9.3/go.mod h1:+IWnUfUmFO1+WVYQWQtIJHeRRdaIyyYglZN7xzUPe4Q= +github.com/tomnomnom/linkheader v0.0.0-20180905144013-02ca5825eb80 h1:nrZ3ySNYwJbSpD6ce9duiP+QkD3JuLCcWkdaehUS/3Y= +github.com/tomnomnom/linkheader v0.0.0-20180905144013-02ca5825eb80/go.mod h1:iFyPdL66DjUD96XmzVL3ZntbzcflLnznH0fr99w5VqE= github.com/twitchtv/twirp v8.1.3+incompatible h1:+F4TdErPgSUbMZMwp13Q/KgDVuI7HJXP61mNV3/7iuU= github.com/twitchtv/twirp v8.1.3+incompatible/go.mod h1:RRJoFSAmTEh2weEqWtpPE3vFK5YBhA6bqp2l1kfCC5A= github.com/ua-parser/uap-go v0.0.0-20250126222208-a52596c19dff h1:NwMEGwb7JJ8wPjT8OPKP5hO1Xz6AQ7Z00+GLSJfW21s= @@ -365,8 +367,8 @@ golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1m golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8= golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= -golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 h1:y5zboxd6LQAqYIhHnB48p0ByQ/GnQx2BE33L8BOHQkI= -golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6/go.mod h1:U6Lno4MTRCDY+Ba7aCcauB9T60gsv5s4ralQzP72ZoQ= +golang.org/x/exp v0.0.0-20250531010427-b6e5de432a8b h1:QoALfVG9rhQ/M7vYDScfPdWjGL9dlsVVM5VGh7aKoAA= +golang.org/x/exp v0.0.0-20250531010427-b6e5de432a8b/go.mod h1:U6Lno4MTRCDY+Ba7aCcauB9T60gsv5s4ralQzP72ZoQ= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= @@ -475,12 +477,12 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/genproto/googleapis/api v0.0.0-20250512202823-5a2f75b736a9 h1:WvBuA5rjZx9SNIzgcU53OohgZy6lKSus++uY4xLaWKc= -google.golang.org/genproto/googleapis/api v0.0.0-20250512202823-5a2f75b736a9/go.mod h1:W3S/3np0/dPWsWLi1h/UymYctGXaGBM2StwzD0y140U= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250512202823-5a2f75b736a9 h1:IkAfh6J/yllPtpYFU0zZN1hUPYdT0ogkBT/9hMxHjvg= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250512202823-5a2f75b736a9/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= -google.golang.org/grpc v1.72.1 h1:HR03wO6eyZ7lknl75XlxABNVLLFc2PAb6mHlYh756mA= -google.golang.org/grpc v1.72.1/go.mod h1:wH5Aktxcg25y1I3w7H69nHfXdOG3UiadoBtjh3izSDM= +google.golang.org/genproto/googleapis/api v0.0.0-20250528174236-200df99c418a h1:SGktgSolFCo75dnHJF2yMvnns6jCmHFJ0vE4Vn2JKvQ= +google.golang.org/genproto/googleapis/api v0.0.0-20250528174236-200df99c418a/go.mod h1:a77HrdMjoeKbnd2jmgcWdaS++ZLZAEq3orIOAEIKiVw= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250528174236-200df99c418a h1:v2PbRU4K3llS09c7zodFpNePeamkAwG3mPrAery9VeE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250528174236-200df99c418a/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/grpc v1.72.2 h1:TdbGzwb82ty4OusHWepvFWGLgIbNo1/SUynEN0ssqv8= +google.golang.org/grpc v1.72.2/go.mod h1:wH5Aktxcg25y1I3w7H69nHfXdOG3UiadoBtjh3izSDM= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/pkg/rtc/room.go b/pkg/rtc/room.go index ba4b4e5f..fbfede4b 100644 --- a/pkg/rtc/room.go +++ b/pkg/rtc/room.go @@ -99,7 +99,7 @@ type Room struct { protoRoom *livekit.Room internal *livekit.RoomInternal protoProxy *utils.ProtoProxy[*livekit.Room] - Logger logger.Logger + logger logger.Logger config WebRTCConfig audioConfig *sfu.AudioConfig @@ -241,7 +241,7 @@ func NewRoom( r := &Room{ protoRoom: utils.CloneProto(room), internal: internal, - Logger: LoggerWithRoom( + logger: LoggerWithRoom( logger.GetLogger().WithComponent(sutils.ComponentRoom), livekit.RoomName(room.Name), livekit.RoomID(room.Sid), @@ -294,6 +294,10 @@ func NewRoom( return r } +func (r *Room) Logger() logger.Logger { + return r.logger +} + func (r *Room) ToProto() *livekit.Room { return r.protoProxy.Get() } @@ -527,7 +531,7 @@ func (r *Room) Join(participant types.LocalParticipant, requestSource routing.Me r.launchTargetAgents(maps.Values(r.agentDispatches), participant, livekit.JobType_JT_PARTICIPANT) - r.Logger.Debugw("new participant joined", + r.logger.Debugw("new participant joined", "pID", participant.ID(), "participant", participant.Identity(), "clientInfo", logger.Proto(participant.GetClientInfo()), @@ -728,7 +732,7 @@ func (r *Room) RemoveParticipant(identity livekit.ParticipantIdentity, pID livek go func() { _, err := r.agentClient.TerminateJob(context.Background(), agentJob.Id, rpc.JobTerminateReason_AGENT_LEFT_ROOM) if err != nil { - r.Logger.Infow("failed sending TerminateJob RPC", "error", err, "jobID", agentJob.Id, "participant", identity) + r.logger.Infow("failed sending TerminateJob RPC", "error", err, "jobID", agentJob.Id, "participant", identity) } }() } @@ -914,7 +918,7 @@ func (r *Room) CloseIfEmpty() { if elapsed >= int64(timeout) { r.Close(types.ParticipantCloseReasonRoomClosed) - r.Logger.Infow("closing idle room", "reason", reason) + r.logger.Infow("closing idle room", "reason", reason) } } @@ -930,7 +934,7 @@ func (r *Room) Close(reason types.ParticipantCloseReason) { close(r.closed) r.lock.Unlock() - r.Logger.Infow("closing room") + r.logger.Infow("closing room") for _, p := range r.GetParticipants() { _ = p.Close(true, reason, false) } @@ -971,7 +975,7 @@ func (r *Room) sendRoomUpdate() { err := p.SendRoomUpdate(roomInfo) if err != nil { - r.Logger.Warnw("failed to send room update", err, "participant", p.Identity()) + r.logger.Warnw("failed to send room update", err, "participant", p.Identity()) } } } @@ -1049,7 +1053,7 @@ func (r *Room) DeleteAgentDispatch(dispatchID string) (*livekit.AgentDispatch, e if agentJob != nil { err := agentJob.waitForParticipantLeaving() if err == ErrJobShutdownTimeout { - r.Logger.Infow("Agent Worker did not disconnect after 3s") + r.logger.Infow("Agent Worker did not disconnect after 3s") } } r.RemoveParticipant(p.Identity(), p.ID(), types.ParticipantCloseReasonServiceRequestRemoveParticipant) @@ -1071,7 +1075,7 @@ func (r *Room) OnRoomUpdated(f func()) { func (r *Room) SimulateScenario(participant types.LocalParticipant, simulateScenario *livekit.SimulateScenario) error { switch scenario := simulateScenario.Scenario.(type) { case *livekit.SimulateScenario_SpeakerUpdate: - r.Logger.Infow("simulating speaker update", "participant", participant.Identity(), "duration", scenario.SpeakerUpdate) + r.logger.Infow("simulating speaker update", "participant", participant.Identity(), "duration", scenario.SpeakerUpdate) go func() { <-time.After(time.Duration(scenario.SpeakerUpdate) * time.Second) r.sendSpeakerChanges([]*livekit.SpeakerInfo{{ @@ -1086,33 +1090,33 @@ func (r *Room) SimulateScenario(participant types.LocalParticipant, simulateScen Level: 0.9, }}) case *livekit.SimulateScenario_Migration: - r.Logger.Infow("simulating migration", "participant", participant.Identity()) + r.logger.Infow("simulating migration", "participant", participant.Identity()) // drop participant without necessarily cleaning up if err := participant.Close(false, types.ParticipantCloseReasonSimulateMigration, true); err != nil { return err } case *livekit.SimulateScenario_NodeFailure: - r.Logger.Infow("simulating node failure", "participant", participant.Identity()) + r.logger.Infow("simulating node failure", "participant", participant.Identity()) // drop participant without necessarily cleaning up if err := participant.Close(false, types.ParticipantCloseReasonSimulateNodeFailure, true); err != nil { return err } case *livekit.SimulateScenario_ServerLeave: - r.Logger.Infow("simulating server leave", "participant", participant.Identity()) + r.logger.Infow("simulating server leave", "participant", participant.Identity()) if err := participant.Close(true, types.ParticipantCloseReasonSimulateServerLeave, false); err != nil { return err } case *livekit.SimulateScenario_SwitchCandidateProtocol: - r.Logger.Infow("simulating switch candidate protocol", "participant", participant.Identity()) + r.logger.Infow("simulating switch candidate protocol", "participant", participant.Identity()) participant.ICERestart(&livekit.ICEConfig{ PreferenceSubscriber: livekit.ICECandidateType(scenario.SwitchCandidateProtocol), PreferencePublisher: livekit.ICECandidateType(scenario.SwitchCandidateProtocol), }) case *livekit.SimulateScenario_SubscriberBandwidth: if scenario.SubscriberBandwidth > 0 { - r.Logger.Infow("simulating subscriber bandwidth start", "participant", participant.Identity(), "bandwidth", scenario.SubscriberBandwidth) + r.logger.Infow("simulating subscriber bandwidth start", "participant", participant.Identity(), "bandwidth", scenario.SubscriberBandwidth) } else { - r.Logger.Infow("simulating subscriber bandwidth end", "participant", participant.Identity()) + r.logger.Infow("simulating subscriber bandwidth end", "participant", participant.Identity()) } participant.SetSubscriberChannelCapacity(scenario.SubscriberBandwidth) case *livekit.SimulateScenario_DisconnectSignalOnResume: @@ -1189,7 +1193,7 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types. continue } - r.Logger.Debugw("subscribing to new track", + r.logger.Debugw("subscribing to new track", "participant", existingParticipant.Identity(), "pID", existingParticipant.ID(), "publisher", participant.Identity(), @@ -1227,7 +1231,7 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types. r.Name(), r.ID(), ); err != nil { - r.Logger.Errorw("failed to launch participant egress", err) + r.logger.Errorw("failed to launch participant egress", err) } }() } @@ -1243,7 +1247,7 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types. r.Name(), r.ID(), ); err != nil { - r.Logger.Errorw("failed to launch track egress", err) + r.logger.Errorw("failed to launch track egress", err) } }() } @@ -1277,15 +1281,15 @@ func (r *Room) onParticipantUpdate(p types.LocalParticipant) { } func (r *Room) onDataPacket(source types.LocalParticipant, kind livekit.DataPacket_Kind, dp *livekit.DataPacket) { - BroadcastDataPacketForRoom(r, source, kind, dp, r.Logger) + BroadcastDataPacketForRoom(r, source, kind, dp, r.logger) } func (r *Room) onDataMessage(source types.LocalParticipant, data []byte) { - BroadcastDataMessageForRoom(r, source, data, r.Logger) + BroadcastDataMessageForRoom(r, source, data, r.logger) } func (r *Room) onMetrics(source types.Participant, dp *livekit.DataPacket) { - BroadcastMetricsForRoom(r, source, dp, r.Logger) + BroadcastMetricsForRoom(r, source, dp, r.logger) } func (r *Room) subscribeToExistingTracks(p types.LocalParticipant) { @@ -1310,7 +1314,7 @@ func (r *Room) subscribeToExistingTracks(p types.LocalParticipant) { } } if len(trackIDs) > 0 { - r.Logger.Debugw("subscribed participant to existing tracks", "trackID", trackIDs) + r.logger.Debugw("subscribed participant to existing tracks", "trackID", trackIDs) } } @@ -1520,7 +1524,7 @@ func (r *Room) connectionQualityWorker() { continue } if err := op.SendConnectionQualityUpdate(update); err != nil { - r.Logger.Warnw("could not send connection quality update", err, + r.logger.Warnw("could not send connection quality update", err, "participant", op.Identity()) } } @@ -1670,7 +1674,7 @@ func (r *Room) createAgentDispatchesFromRoomAgent() { for _, ag := range roomDisp { _, err := r.createAgentDispatchFromParams(ag.AgentName, ag.Metadata) if err != nil { - r.Logger.Warnw("failed storing room dispatch", err) + r.logger.Warnw("failed storing room dispatch", err) } } } diff --git a/pkg/rtc/transport.go b/pkg/rtc/transport.go index 4744a2da..8b9afd4a 100644 --- a/pkg/rtc/transport.go +++ b/pkg/rtc/transport.go @@ -1064,7 +1064,6 @@ func (t *PCTransport) CreateReadableDataChannel(label string, dci *webrtc.DataCh buffer := make([]byte, dataChannelBufferSize) for { n, _, err := rawDC.ReadDataChannel(buffer) - t.params.Logger.Infow("RAJA read data", "data", string(buffer[:n])) // REMVOE if err != nil { if !errors.Is(err, io.EOF) && !strings.Contains(err.Error(), "state=Closed") { t.params.Logger.Warnw("error reading data channel", err, "label", dc.Label()) diff --git a/pkg/service/roommanager.go b/pkg/service/roommanager.go index 9fc441e0..761f486a 100644 --- a/pkg/service/roommanager.go +++ b/pkg/service/roommanager.go @@ -70,6 +70,7 @@ type RoomManager struct { router routing.Router roomAllocator RoomAllocator roomManagerServer rpc.TypedRoomManagerServer + rtcRestServer rpc.RTCRestServer[livekit.NodeID] roomStore ObjectStore telemetry telemetry.TelemetryService clientConfManager clientconfiguration.ClientConfigurationManager @@ -82,9 +83,10 @@ type RoomManager struct { rooms map[livekit.RoomName]*rtc.Room - roomServers utils.MultitonService[rpc.RoomTopic] - agentDispatchServers utils.MultitonService[rpc.RoomTopic] - participantServers utils.MultitonService[rpc.ParticipantTopic] + roomServers utils.MultitonService[rpc.RoomTopic] + agentDispatchServers utils.MultitonService[rpc.RoomTopic] + participantServers utils.MultitonService[rpc.ParticipantTopic] + rtcRestParticipantServers utils.MultitonService[rpc.ParticipantTopic] iceConfigCache *sutils.IceConfigCache[iceConfigCacheKey] @@ -151,6 +153,14 @@ func NewLocalRoomManager( return nil, err } + r.rtcRestServer, err = rpc.NewRTCRestServer[livekit.NodeID](rtcRestService{r}, bus, rpc.WithDefaultServerOptions(conf.PSRPC, logger.GetLogger())) + if err != nil { + return nil, err + } + if err := r.rtcRestServer.RegisterAllCommonTopics(currentNode.NodeID()); err != nil { + return nil, err + } + return r, nil } @@ -222,9 +232,11 @@ func (r *RoomManager) Stop() { } r.roomManagerServer.Kill() + r.rtcRestServer.Kill() r.roomServers.Kill() r.agentDispatchServers.Kill() r.participantServers.Kill() + r.rtcRestParticipantServers.Kill() if r.rtcConfig != nil { if r.rtcConfig.UDPMux != nil { @@ -480,16 +492,28 @@ func (r *RoomManager) StartSession( return err } + var participantServerClosers utils.Closers participantTopic := rpc.FormatParticipantTopic(room.Name(), participant.Identity()) participantServer := must.Get(rpc.NewTypedParticipantServer(r, r.bus)) - killParticipantServer := r.participantServers.Replace(participantTopic, participantServer) + participantServerClosers = append(participantServerClosers, utils.CloseFunc(r.participantServers.Replace(participantTopic, participantServer))) if err := participantServer.RegisterAllParticipantTopics(participantTopic); err != nil { - killParticipantServer() + participantServerClosers.Close() pLogger.Errorw("could not join register participant topic", err) _ = participant.Close(true, types.ParticipantCloseReasonMessageBusFailed, false) return err } + if useOneShotSignallingMode { + rtcRestParticipantServer := must.Get(rpc.NewTypedRTCRestParticipantServer(rtcRestParticipantService{r}, r.bus)) + participantServerClosers = append(participantServerClosers, utils.CloseFunc(r.rtcRestParticipantServers.Replace(participantTopic, rtcRestParticipantServer))) + if err := rtcRestParticipantServer.RegisterAllCommonTopics(participantTopic); err != nil { + participantServerClosers.Close() + pLogger.Errorw("could not join register participant topic for rtc rest participant server", err) + _ = participant.Close(true, types.ParticipantCloseReasonMessageBusFailed, false) + return err + } + } + if err = r.roomStore.StoreParticipant(ctx, room.Name(), participant.ToProto()); err != nil { pLogger.Errorw("could not store participant", err) } @@ -509,7 +533,7 @@ func (r *RoomManager) StartSession( clientMeta := &livekit.AnalyticsClientMeta{Region: r.currentNode.Region(), Node: string(r.currentNode.NodeID())} r.telemetry.ParticipantJoined(ctx, protoRoom, participant.ToProto(), pi.Client, clientMeta, true) participant.OnClose(func(p types.LocalParticipant) { - killParticipantServer() + participantServerClosers.Close() if err := r.roomStore.DeleteParticipant(ctx, room.Name(), p.Identity()); err != nil { pLogger.Errorw("could not delete participant", err) @@ -594,22 +618,22 @@ func (r *RoomManager) getOrCreateRoom(ctx context.Context, createRoom *livekit.C r.telemetry.RoomEnded(ctx, roomInfo) prometheus.RoomEnded(time.Unix(roomInfo.CreationTime, 0)) if err := r.deleteRoom(ctx, roomName); err != nil { - newRoom.Logger.Errorw("could not delete room", err) + newRoom.Logger().Errorw("could not delete room", err) } - newRoom.Logger.Infow("room closed") + newRoom.Logger().Infow("room closed") }) newRoom.OnRoomUpdated(func() { if err := r.roomStore.StoreRoom(ctx, newRoom.ToProto(), newRoom.Internal()); err != nil { - newRoom.Logger.Errorw("could not handle metadata update", err) + newRoom.Logger().Errorw("could not handle metadata update", err) } }) newRoom.OnParticipantChanged(func(p types.LocalParticipant) { if !p.IsDisconnected() { if err := r.roomStore.StoreParticipant(ctx, roomName, p.ToProto()); err != nil { - newRoom.Logger.Errorw("could not handle participant change", err) + newRoom.Logger().Errorw("could not handle participant change", err) } } }) @@ -787,7 +811,7 @@ func (r *RoomManager) DeleteRoom(ctx context.Context, req *livekit.DeleteRoomReq return nil, err } } else { - room.Logger.Infow("deleting room") + room.Logger().Infow("deleting room") room.Close(types.ParticipantCloseReasonServiceRequestDeleteRoom) } return &livekit.DeleteRoomResponse{}, nil @@ -815,7 +839,7 @@ func (r *RoomManager) SendData(ctx context.Context, req *livekit.SendDataRequest return nil, ErrRoomNotFound } - room.Logger.Debugw("api send data", "size", len(req.Data)) + room.Logger().Debugw("api send data", "size", len(req.Data)) room.SendDataPacket(&livekit.DataPacket{ Kind: req.Kind, DestinationIdentities: req.DestinationIdentities, @@ -838,7 +862,7 @@ func (r *RoomManager) UpdateRoomMetadata(ctx context.Context, req *livekit.Updat return nil, ErrRoomNotFound } - room.Logger.Debugw("updating room") + room.Logger().Debugw("updating room") done := room.SetMetadata(req.Metadata) // wait till the update is applied <-done diff --git a/pkg/service/roommanager_service.go b/pkg/service/roommanager_service.go new file mode 100644 index 00000000..b95b7e22 --- /dev/null +++ b/pkg/service/roommanager_service.go @@ -0,0 +1,189 @@ +package service + +import ( + "context" + "fmt" + "time" + + "github.com/livekit/livekit-server/pkg/routing" + "github.com/livekit/livekit-server/pkg/rtc/types" + "github.com/livekit/livekit-server/pkg/telemetry/prometheus" + "github.com/livekit/protocol/livekit" + "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/rpc" + "github.com/livekit/psrpc" + "github.com/pion/webrtc/v4" + "golang.org/x/sync/errgroup" + "google.golang.org/protobuf/types/known/emptypb" +) + +type rtcRestService struct { + *RoomManager +} + +func (s rtcRestService) Create(ctx context.Context, req *rpc.RTCRestCreateRequest) (*rpc.RTCRestCreateResponse, error) { + pi, err := routing.ParticipantInitFromStartSession(req.StartSession, s.RoomManager.currentNode.Region()) + if err != nil { + logger.Errorw("rtcRest service: could not create participant init", err) + return nil, err + } + + prometheus.IncrementParticipantRtcInit(1) + + if err = s.RoomManager.StartSession( + ctx, + *pi, + routing.NewNullMessageSource(livekit.ConnectionID(req.StartSession.ConnectionId)), // no requestSource + routing.NewNullMessageSink(livekit.ConnectionID(req.StartSession.ConnectionId)), // no responseSink + true, // useOneShotSignallingMode + ); err != nil { + logger.Errorw("rtcRest service: could not start session", err) + return nil, err + } + + room := s.RoomManager.GetRoom(ctx, livekit.RoomName(req.StartSession.RoomName)) + if room == nil { + logger.Errorw("rtcRest service: could not find room", nil, "room", req.StartSession.RoomName) + return nil, ErrRoomNotFound + } + + lp := room.GetParticipant(pi.Identity) + if lp == nil { + room.Logger().Errorw("rtcRest service: could not find local participant", nil, "participant", pi.Identity) + return nil, ErrParticipantNotFound + } + + if err := lp.HandleOffer(webrtc.SessionDescription{Type: webrtc.SDPTypeOffer, SDP: req.OfferSdp}); err != nil { + lp.GetLogger().Errorw("rtcRest service: could not handle offer", err) + return nil, err + } + + // wait for subscriptions to resolve + eg, _ := errgroup.WithContext(ctx) + for publisherIdentity, trackList := range req.SubscribedParticipantTracks { + for _, trackName := range trackList.TrackNames { + eg.Go(func() error { + for { + if lp.IsTrackNameSubscribed(livekit.ParticipantIdentity(publisherIdentity), trackName) { + return nil + } + time.Sleep(50 * time.Millisecond) + } + }) + } + } + err = eg.Wait() + if err != nil { + lp.GetLogger().Errorw("rtcRest service: could not subscribe to tracks", err) + return nil, err + } + + answer, err := lp.GetAnswer() + if err != nil { + lp.GetLogger().Errorw("rtcRest service: could not get answer", err) + return nil, err + } + + iceSessionID, err := lp.GetPublisherICESessionUfrag() + if err != nil { + lp.GetLogger().Errorw("rtcRest service: could not get ICE session ID", err) + return nil, err + } + + var iceServers []*livekit.ICEServer + apiKey, _, err := s.RoomManager.getFirstKeyPair() + if err != nil { + iceServers = s.RoomManager.iceServersForParticipant( + apiKey, + lp, + false, + ) + } + return &rpc.RTCRestCreateResponse{ + AnswerSdp: answer.SDP, + ParticipantId: string(lp.ID()), + IceServers: iceServers, + IceSessionId: iceSessionID, + }, nil +} + +type rtcRestParticipantService struct { + *RoomManager +} + +func (r rtcRestParticipantService) ICETrickle(ctx context.Context, req *rpc.RTCRestParticipantICETrickleRequest) (*emptypb.Empty, error) { + room := r.RoomManager.GetRoom(ctx, livekit.RoomName(req.Room)) + if room == nil { + return nil, ErrRoomNotFound + } + + lp := room.GetParticipantByID(livekit.ParticipantID(req.ParticipantId)) + if lp == nil { + return nil, ErrParticipantNotFound + } + + iceSessionID, err := lp.GetPublisherICESessionUfrag() + if err != nil { + lp.GetLogger().Warnw("rtcRestParticipant service ice-trickle: could not get ICE session ufrag", err) + return nil, psrpc.NewError(psrpc.Internal, err) + } + + if req.IceSessionId != iceSessionID { + return nil, psrpc.NewError( + psrpc.FailedPrecondition, + fmt.Errorf("ice session mismatch, expected: %s, got: %s", iceSessionID, req.IceSessionId), + ) + } + + if err := lp.HandleICETrickleSDPFragment(req.SdpFragment); err != nil { + return nil, psrpc.NewError(psrpc.InvalidArgument, err) + } + + return &emptypb.Empty{}, nil +} + +func (r rtcRestParticipantService) ICERestart(ctx context.Context, req *rpc.RTCRestParticipantICERestartRequest) (*rpc.RTCRestParticipantICERestartResponse, error) { + room := r.RoomManager.GetRoom(ctx, livekit.RoomName(req.Room)) + if room == nil { + return nil, ErrRoomNotFound + } + + lp := room.GetParticipantByID(livekit.ParticipantID(req.ParticipantId)) + if lp == nil { + return nil, ErrParticipantNotFound + } + + sdpFragment, err := lp.HandleICERestartSDPFragment(req.SdpFragment) + if err != nil { + return nil, psrpc.NewError(psrpc.InvalidArgument, err) + } + + iceSessionID, err := lp.GetPublisherICESessionUfrag() + if err != nil { + lp.GetLogger().Warnw("rtcRestParticipant service ice-restart: could not get ICE session ufrag", err) + return nil, psrpc.NewError(psrpc.Internal, err) + } + + return &rpc.RTCRestParticipantICERestartResponse{ + IceSessionId: iceSessionID, + SdpFragment: sdpFragment, + }, nil +} + +func (r rtcRestParticipantService) DeleteSession(ctx context.Context, req *rpc.RTCRestParticipantDeleteSessionRequest) (*emptypb.Empty, error) { + room := r.RoomManager.GetRoom(ctx, livekit.RoomName(req.Room)) + if room == nil { + return nil, ErrRoomNotFound + } + + lp := room.GetParticipantByID(livekit.ParticipantID(req.ParticipantId)) + if lp != nil { + room.RemoveParticipant( + lp.Identity(), + lp.ID(), + types.ParticipantCloseReasonClientRequestLeave, + ) + } + + return &emptypb.Empty{}, nil +} diff --git a/pkg/service/rtcrestservice.go b/pkg/service/rtcrestservice.go new file mode 100644 index 00000000..364759af --- /dev/null +++ b/pkg/service/rtcrestservice.go @@ -0,0 +1,527 @@ +// Copyright 2023 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package service + +import ( + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "strings" + + "github.com/livekit/livekit-server/pkg/config" + "github.com/livekit/livekit-server/pkg/routing" + "github.com/livekit/livekit-server/pkg/rtc" + "github.com/livekit/livekit-server/pkg/rtc/types" + sutils "github.com/livekit/livekit-server/pkg/utils" + "github.com/livekit/protocol/livekit" + "github.com/livekit/protocol/logger" + "github.com/livekit/protocol/rpc" + "github.com/livekit/protocol/utils/guid" + "github.com/livekit/psrpc" + "github.com/pion/webrtc/v4" + "github.com/tomnomnom/linkheader" +) + +const ( + cParticipantPath = "/whip/v1" + cParticipantIDPath = "/whip/v1/{participant_id}" +) + +type RTCRestService struct { + http.Handler + + config *config.Config + router routing.Router + roomAllocator RoomAllocator + client rpc.RTCRestClient[livekit.NodeID] + topicFormatter rpc.TopicFormatter + participantClient rpc.TypedRTCRestParticipantClient +} + +func NewRTCRestService( + config *config.Config, + router routing.Router, + roomAllocator RoomAllocator, + clientParams rpc.ClientParams, + topicFormatter rpc.TopicFormatter, + participantClient rpc.TypedRTCRestParticipantClient, +) (*RTCRestService, error) { + client, err := rpc.NewRTCRestClient[livekit.NodeID](clientParams.Args()) + if err != nil { + return nil, err + } + + return &RTCRestService{ + config: config, + router: router, + roomAllocator: roomAllocator, + client: client, + topicFormatter: topicFormatter, + participantClient: participantClient, + }, nil +} + +func (s *RTCRestService) SetupRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET "+cParticipantPath, s.handleGet) + mux.HandleFunc("OPTIONS "+cParticipantPath, s.handleOptions) + mux.HandleFunc("POST "+cParticipantPath, s.handleCreate) + mux.HandleFunc("GET "+cParticipantIDPath, s.handleParticipantGet) + mux.HandleFunc("PATCH "+cParticipantIDPath, s.handleParticipantPatch) + mux.HandleFunc("DELETE "+cParticipantIDPath, s.handleParticipantDelete) +} + +func (s *RTCRestService) handleGet(w http.ResponseWriter, r *http.Request) { + // https:/www.rfc-editor.org/rfc/rfc9725.html#name-http-usage + w.WriteHeader(http.StatusNoContent) +} + +func (s *RTCRestService) handleOptions(w http.ResponseWriter, r *http.Request) { + logger.Infow("RAJA got here to options", "req", r) // REMOVE + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Headers", "*") + w.Header().Set("Access-Control-Allow-Methods", "PATCH, OPTIONS, GET, POST, DELETE") + w.Header().Set("Access-Control-Expose-Headers", "*") + + w.WriteHeader(http.StatusOK) + + // According to https://www.rfc-editor.org/rfc/rfc9725.html#name-stun-turn-server-configurat, + // ICE servers can be returned in OPTIONS response, but not recommended. + // + // Supporting that here is tricky. This would have to get region settings like the + // session CREATE POST request and send a request to get ICE servers from a + // region + media node that is selected. The issue is that a subsequent POST, + // although unlikely, may end up in a different region. Media node in one region and + // TURN in another region, although shuttling media across regions, should still work. + // But, as this is not a recommended way, not supporting it. +} + +type createRequest struct { + RoomName livekit.RoomName + ParticipantInit routing.ParticipantInit + ClientIP string + OfferSDP string + SubscribedParticipantTrackNames map[string][]string +} + +func (s *RTCRestService) validateCreate(r *http.Request) (*createRequest, int, error) { + claims := GetGrants(r.Context()) + if claims == nil || claims.Video == nil { + return nil, http.StatusUnauthorized, rtc.ErrPermissionDenied + } + + if err := EnsureCreatePermission(r.Context()); err != nil { + return nil, http.StatusUnauthorized, err + } + + roomName, err := EnsureJoinPermission(r.Context()) + if err != nil { + return nil, http.StatusUnauthorized, err + } + if roomName == "" { + return nil, http.StatusUnauthorized, errors.New("room name cannot be empty") + } + if limit := s.config.Limit.MaxRoomNameLength; limit > 0 && len(roomName) > limit { + return nil, http.StatusBadRequest, fmt.Errorf("%w: max length %d", ErrRoomNameExceedsLimits, limit) + } + + if claims.Identity == "" { + return nil, http.StatusBadRequest, ErrIdentityEmpty + } + if limit := s.config.Limit.MaxParticipantIdentityLength; limit > 0 && len(claims.Identity) > limit { + return nil, http.StatusBadRequest, fmt.Errorf("%w: max length %d", ErrParticipantIdentityExceedsLimits, limit) + } + + var clientInfo struct { + ClientIP string `json:"clientIp"` + SubscribedParticipantTrackNames map[string][]string `json:"subscribedParticipantTrackNames"` + } + clientInfoHeader := r.Header.Get("X-LiveKit-ClientInfo") + if clientInfoHeader != "" { + if err := json.NewDecoder(strings.NewReader(clientInfoHeader)).Decode(&clientInfo); err != nil { + return nil, http.StatusBadRequest, fmt.Errorf("malformed json in client info header: %s", err) + } + } + + offerSDPBytes, err := ioutil.ReadAll(r.Body) + if err != nil { + return nil, http.StatusBadRequest, fmt.Errorf("body does not have SDP offer: %s", err) + } + offerSDP := string(offerSDPBytes) + sd := &webrtc.SessionDescription{ + Type: webrtc.SDPTypeOffer, + SDP: offerSDP, + } + _, err = sd.Unmarshal() + if err != nil { + return nil, http.StatusBadRequest, fmt.Errorf("malformed SDP offer: %s", err) + } + + pi := routing.ParticipantInit{ + Identity: livekit.ParticipantIdentity(claims.Identity), + Name: livekit.ParticipantName(claims.Name), + AutoSubscribe: true, + Client: &livekit.ClientInfo{ + Protocol: types.CurrentProtocol, + }, + Grants: claims, + CreateRoom: &livekit.CreateRoomRequest{ + Name: string(roomName), + RoomPreset: claims.RoomPreset, + }, + AdaptiveStream: false, + DisableICELite: true, + } + SetRoomConfiguration(pi.CreateRoom, claims.GetRoomConfiguration()) + + return &createRequest{ + roomName, + pi, + clientInfo.ClientIP, + offerSDP, + clientInfo.SubscribedParticipantTrackNames, + }, http.StatusOK, nil +} + +func (s *RTCRestService) handleCreate(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Content-type") != "application/sdp" { + handleError("Create", w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type"))) + return + } + + w.Header().Add("Content-type", "application/sdp") + + req, status, err := s.validateCreate(r) + if err != nil { + handleError("Create", w, r, status, err) + return + } + + if err := s.roomAllocator.SelectRoomNode(r.Context(), req.RoomName, ""); err != nil { + handleError("Create", w, r, http.StatusInternalServerError, err) + return + } + + rtcNode, err := s.router.GetNodeForRoom(r.Context(), req.RoomName) + if err != nil { + handleError("Create", w, r, http.StatusInternalServerError, err) + return + } + + connID := livekit.ConnectionID(guid.New("CO_")) + starSession, err := req.ParticipantInit.ToStartSession(req.RoomName, connID) + if err != nil { + handleError("Create", w, r, http.StatusInternalServerError, err) + return + } + + subscribedParticipantTracks := map[string]*rpc.RTCRestCreateRequest_TrackList{} + for identity, trackNames := range req.SubscribedParticipantTrackNames { + subscribedParticipantTracks[identity] = &rpc.RTCRestCreateRequest_TrackList{ + TrackNames: trackNames, + } + } + + res, err := s.client.Create(r.Context(), livekit.NodeID(rtcNode.Id), &rpc.RTCRestCreateRequest{ + OfferSdp: req.OfferSDP, + StartSession: starSession, + SubscribedParticipantTracks: subscribedParticipantTracks, + }) + if err != nil { + handleError("Create", w, r, http.StatusServiceUnavailable, err) + return + } + + // created resource sent in Location header: + // https://www.rfc-editor.org/rfc/rfc9725.html#name-ingest-session-setup + // using relative location + w.Header().Add("Location", fmt.Sprintf("%s/%s", cParticipantPath, res.ParticipantId)) + + // ICE servers as Link header(s): + // https://www.rfc-editor.org/rfc/rfc9725.html#name-stun-turn-server-configurat + var iceServerLinks []*linkheader.Link + for _, iceServer := range res.IceServers { + for _, iceURL := range iceServer.Urls { + iceServerLink := &linkheader.Link{ + URL: url.PathEscape(iceURL), + Rel: "ice-server", + Params: map[string]string{}, + } + if iceServer.Username != "" { + iceServerLink.Params["username"] = iceServer.Username + } + if iceServer.Credential != "" { + iceServerLink.Params["credential"] = iceServer.Credential + } + + iceServerLinks = append(iceServerLinks, iceServerLink) + } + } + for _, iceServerLink := range iceServerLinks { + w.Header().Add("Link", iceServerLink.String()) + } + + // To support ICE Trickle/Restart, HTTP PATCH should have an ETag + // send ICE session ID (ICE ufrag is used as ID) in ETag header + // https://www.rfc-editor.org/rfc/rfc9725.html#name-http-patch-request-usage + if res.IceSessionId != "" { + w.Header().Add("ETag", res.IceSessionId) + } + + // 201 Status Created + w.WriteHeader(http.StatusCreated) + + // SDP answer in the response body + w.Write([]byte(res.AnswerSdp)) + + sutils.GetLogger(r.Context()).Infow( + "API RTCRest.Create", + "connID", connID, + "participant", req.ParticipantInit.Identity, + "room", req.RoomName, + "status", http.StatusCreated, + "response", logger.Proto(res), + ) + return +} + +func (s *RTCRestService) handleParticipantGet(w http.ResponseWriter, r *http.Request) { + // https:/www.rfc-editor.org/rfc/rfc9725.html#name-http-usage + w.WriteHeader(http.StatusNoContent) +} + +func (s *RTCRestService) iceTrickle( + w http.ResponseWriter, + r *http.Request, + roomName livekit.RoomName, + participantIdentity livekit.ParticipantIdentity, + pID livekit.ParticipantID, + iceSessionID string, + sdpFragment string, +) { + _, err := s.participantClient.ICETrickle( + r.Context(), + s.topicFormatter.ParticipantTopic(r.Context(), roomName, participantIdentity), + &rpc.RTCRestParticipantICETrickleRequest{ + Room: string(roomName), + ParticipantIdentity: string(participantIdentity), + ParticipantId: string(pID), + IceSessionId: iceSessionID, + SdpFragment: sdpFragment, + }, + ) + if err != nil { + var pe psrpc.Error + if errors.As(err, &pe) { + switch pe.Code() { + case psrpc.NotFound: + handleError("Patch", w, r, http.StatusNotFound, errors.New(pe.Error())) + + case psrpc.InvalidArgument: + switch pe.Error() { + case rtc.ErrInvalidSDPFragment.Error(), rtc.ErrMidMismatch.Error(), rtc.ErrICECredentialMismatch.Error(): + handleError("Patch", w, r, http.StatusBadRequest, errors.New(pe.Error())) + default: + handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error())) + } + default: + handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error())) + } + } else { + handleError("Patch", w, r, http.StatusInternalServerError, nil) + } + return + } + sutils.GetLogger(r.Context()).Infow( + "API RTCRest.Patch", + "method", "ice-trickle", + "room", roomName, + "participant", participantIdentity, + "pID", pID, + "sdpFragment", sdpFragment, + "status", http.StatusNoContent, + ) + w.WriteHeader(http.StatusNoContent) +} + +func (s *RTCRestService) iceRestart( + w http.ResponseWriter, + r *http.Request, + roomName livekit.RoomName, + participantIdentity livekit.ParticipantIdentity, + pID livekit.ParticipantID, + sdpFragment string, +) { + res, err := s.participantClient.ICERestart( + r.Context(), + s.topicFormatter.ParticipantTopic(r.Context(), roomName, participantIdentity), + &rpc.RTCRestParticipantICERestartRequest{ + Room: string(roomName), + ParticipantIdentity: string(participantIdentity), + ParticipantId: string(pID), + SdpFragment: sdpFragment, + }, + ) + if err != nil { + var pe psrpc.Error + if errors.As(err, &pe) { + switch pe.Code() { + case psrpc.NotFound: + handleError("Patch", w, r, http.StatusNotFound, errors.New(pe.Error())) + + case psrpc.InvalidArgument: + switch pe.Error() { + case rtc.ErrInvalidSDPFragment.Error(): + handleError("Patch", w, r, http.StatusBadRequest, errors.New(pe.Error())) + default: + handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error())) + } + default: + handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error())) + } + } else { + handleError("Patch", w, r, http.StatusInternalServerError, nil) + } + return + } + sutils.GetLogger(r.Context()).Infow( + "API RTCRest.Patch", + "method", "ice-restart", + "room", roomName, + "participant", participantIdentity, + "pID", pID, + "sdpFragment", sdpFragment, + "status", http.StatusNoContent, + "res", logger.Proto(res), + ) + if res.IceSessionId != "" { + w.Header().Add("ETag", res.IceSessionId) + } + w.WriteHeader(http.StatusOK) + w.Write([]byte(res.SdpFragment)) +} + +func (s *RTCRestService) handleParticipantPatch(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Content-type") != "application/trickle-ice-sdpfrag" { + handleError("Patch", w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type"))) + return + } + + w.Header().Add("Content-type", "application/trickle-ice-sdpfrag") + + // https://www.rfc-editor.org/rfc/rfc9725.html#name-http-patch-request-usage + ifMatch := r.Header.Get("If-Match") + if ifMatch == "" { + handleError("Patch", w, r, http.StatusPreconditionRequired, errors.New("missing entity tag")) + return + } + + claims := GetGrants(r.Context()) + if claims == nil || claims.Video == nil { + handleError("Patch", w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied) + return + } + + roomName, err := EnsureJoinPermission(r.Context()) + if err != nil { + handleError("Patch", w, r, http.StatusUnauthorized, err) + return + } + if roomName == "" { + handleError("Patch", w, r, http.StatusUnauthorized, errors.New("room name cannot be empty")) + return + } + if claims.Identity == "" { + handleError("Patch", w, r, http.StatusUnauthorized, errors.New("participant identity cannot be empty")) + return + } + pID := livekit.ParticipantID(r.PathValue("participant_id")) + if pID == "" { + handleError("Patch", w, r, http.StatusUnauthorized, errors.New("participant ID cannot be empty")) + return + } + + sdpFragmentBytes, err := ioutil.ReadAll(r.Body) + if err != nil { + handleError("Patch", w, r, http.StatusBadRequest, fmt.Errorf("body does not have SDP fragment: %s", err)) + } + sdpFragment := string(sdpFragmentBytes) + + if ifMatch == "*" { + s.iceRestart(w, r, roomName, livekit.ParticipantIdentity(claims.Identity), pID, sdpFragment) + } else { + s.iceTrickle(w, r, roomName, livekit.ParticipantIdentity(claims.Identity), pID, ifMatch, sdpFragment) + } +} + +func (s *RTCRestService) handleParticipantDelete(w http.ResponseWriter, r *http.Request) { + claims := GetGrants(r.Context()) + if claims == nil || claims.Video == nil { + handleError("Delete", w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied) + return + } + + roomName, err := EnsureJoinPermission(r.Context()) + if err != nil { + handleError("Delete", w, r, http.StatusUnauthorized, err) + return + } + if roomName == "" { + handleError("Delete", w, r, http.StatusUnauthorized, errors.New("room name cannot be empty")) + return + } + if claims.Identity == "" { + handleError("Delete", w, r, http.StatusUnauthorized, errors.New("participant identity cannot be empty")) + return + } + + _, err = s.participantClient.DeleteSession( + r.Context(), + s.topicFormatter.ParticipantTopic(r.Context(), roomName, livekit.ParticipantIdentity(claims.Identity)), + &rpc.RTCRestParticipantDeleteSessionRequest{ + Room: string(roomName), + ParticipantIdentity: claims.Identity, + ParticipantId: r.PathValue("participant_id"), + }, + ) + if err != nil { + handleError("Delete", w, r, http.StatusNotFound, err) + return + } + + sutils.GetLogger(r.Context()).Infow( + "API RTCRest.Delete", + "participant", claims.Identity, + "pID", r.PathValue("participant_id"), + "room", roomName, + "status", http.StatusOK, + ) + w.WriteHeader(http.StatusOK) +} + +func handleError(method string, w http.ResponseWriter, r *http.Request, status int, err error) { + sutils.GetLogger(r.Context()).Warnw( + fmt.Sprintf("API RTCRest.%s", method), err, + "status", status, + ) + w.WriteHeader(status) + json.NewEncoder(w).Encode(struct { + Error string `json:"error"` + }{ + Error: err.Error(), + }) +} diff --git a/pkg/service/rtcservice.go b/pkg/service/rtcservice.go index 030fcd4a..f1c23d23 100644 --- a/pkg/service/rtcservice.go +++ b/pkg/service/rtcservice.go @@ -45,9 +45,7 @@ import ( type RTCService struct { router routing.MessageRouter roomAllocator RoomAllocator - store ServiceStore upgrader websocket.Upgrader - currentNode routing.LocalNode config *config.Config isDev bool limits config.LimitConfig @@ -61,16 +59,12 @@ type RTCService struct { func NewRTCService( conf *config.Config, ra RoomAllocator, - store ServiceStore, router routing.MessageRouter, - currentNode routing.LocalNode, telemetry telemetry.TelemetryService, ) *RTCService { s := &RTCService{ router: router, roomAllocator: ra, - store: store, - currentNode: currentNode, config: conf, isDev: conf.Development, limits: conf.Limit, diff --git a/pkg/service/server.go b/pkg/service/server.go index d3f92d48..7aa22072 100644 --- a/pkg/service/server.go +++ b/pkg/service/server.go @@ -46,20 +46,21 @@ import ( ) type LivekitServer struct { - config *config.Config - ioService *IOInfoService - rtcService *RTCService - agentService *AgentService - httpServer *http.Server - promServer *http.Server - router routing.Router - roomManager *RoomManager - signalServer *SignalServer - turnServer *turn.Server - currentNode routing.LocalNode - running atomic.Bool - doneChan chan struct{} - closedChan chan struct{} + config *config.Config + ioService *IOInfoService + rtcService *RTCService + rtcRestService *RTCRestService + agentService *AgentService + httpServer *http.Server + promServer *http.Server + router routing.Router + roomManager *RoomManager + signalServer *SignalServer + turnServer *turn.Server + currentNode routing.LocalNode + running atomic.Bool + doneChan chan struct{} + closedChan chan struct{} } func NewLivekitServer(conf *config.Config, @@ -70,6 +71,7 @@ func NewLivekitServer(conf *config.Config, sipService *SIPService, ioService *IOInfoService, rtcService *RTCService, + rtcRestService *RTCRestService, agentService *AgentService, keyProvider auth.KeyProvider, router routing.Router, @@ -79,13 +81,14 @@ func NewLivekitServer(conf *config.Config, currentNode routing.LocalNode, ) (s *LivekitServer, err error) { s = &LivekitServer{ - config: conf, - ioService: ioService, - rtcService: rtcService, - agentService: agentService, - router: router, - roomManager: roomManager, - signalServer: signalServer, + config: conf, + ioService: ioService, + rtcService: rtcService, + rtcRestService: rtcRestService, + agentService: agentService, + router: router, + roomManager: roomManager, + signalServer: signalServer, // turn server starts automatically turnServer: turnServer, currentNode: currentNode, @@ -100,7 +103,9 @@ func NewLivekitServer(conf *config.Config, AllowOriginFunc: func(origin string) bool { return true }, + AllowedMethods: []string{"OPTIONS", "HEAD", "GET", "POST", "PATCH", "DELETE"}, AllowedHeaders: []string{"*"}, + ExposedHeaders: []string{"*"}, // allow preflight to be cached for a day MaxAge: 86400, }), @@ -140,6 +145,7 @@ func NewLivekitServer(conf *config.Config, xtwirp.RegisterServer(mux, sipServer) mux.Handle("/rtc", rtcService) rtcService.SetupRoutes(mux) + rtcRestService.SetupRoutes(mux) mux.Handle("/agent", agentService) mux.HandleFunc("/", s.defaultHandler) diff --git a/pkg/service/wire.go b/pkg/service/wire.go index 7e1f78d1..37a77527 100644 --- a/pkg/service/wire.go +++ b/pkg/service/wire.go @@ -79,6 +79,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live NewRoomAllocator, NewRoomService, NewRTCService, + NewRTCRestService, NewAgentService, NewAgentDispatchService, agent.NewAgentClient, @@ -94,6 +95,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live rpc.NewTopicFormatter, rpc.NewTypedRoomClient, rpc.NewTypedParticipantClient, + rpc.NewTypedRTCRestParticipantClient, rpc.NewTypedAgentDispatchInternalClient, NewLocalRoomManager, NewTURNAuthHandler, diff --git a/pkg/service/wire_gen.go b/pkg/service/wire_gen.go index 9558733a..c2ef8d55 100644 --- a/pkg/service/wire_gen.go +++ b/pkg/service/wire_gen.go @@ -120,7 +120,15 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live return nil, err } sipService := NewSIPService(sipConfig, nodeID, messageBus, sipClient, sipStore, roomService, telemetryService) - rtcService := NewRTCService(conf, roomAllocator, objectStore, router, currentNode, telemetryService) + rtcService := NewRTCService(conf, roomAllocator, router, telemetryService) + rtcRestParticipantClient, err := rpc.NewTypedRTCRestParticipantClient(clientParams) + if err != nil { + return nil, err + } + serviceRTCRestService, err := NewRTCRestService(conf, router, roomAllocator, clientParams, topicFormatter, rtcRestParticipantClient) + if err != nil { + return nil, err + } agentService, err := NewAgentService(conf, currentNode, messageBus, keyProvider) if err != nil { return nil, err @@ -147,7 +155,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live if err != nil { return nil, err } - livekitServer, err := NewLivekitServer(conf, roomService, agentDispatchService, egressService, ingressService, sipService, ioInfoService, rtcService, agentService, keyProvider, router, roomManager, signalServer, server, currentNode) + livekitServer, err := NewLivekitServer(conf, roomService, agentDispatchService, egressService, ingressService, sipService, ioInfoService, rtcService, serviceRTCRestService, agentService, keyProvider, router, roomManager, signalServer, server, currentNode) if err != nil { return nil, err }