< Summary

Information
Class: Livekit.Server.Sdk.Dotnet.BaseService
Assembly: LivekitApi
File(s): /home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitApi/BaseService.cs
Line coverage
95%
Covered lines: 107
Uncovered lines: 5
Coverable lines: 112
Total lines: 227
Line coverage: 95.5%
Branch coverage
75%
Covered branches: 27
Total branches: 36
Branch coverage: 75%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)100%1212100%
SendAsync()100%44100%
SdkVersion()30%111078.57%
ToHttpScheme(...)83.33%6683.33%
WithTrailingSlash(...)75%44100%
AuthHeader(...)100%11100%
AuthHeader(...)100%11100%

File(s)

/home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitApi/BaseService.cs

#LineLine coverage
 1using System;
 2using System.Linq;
 3using System.Net.Http;
 4using System.Net.Http.Headers;
 5using System.Reflection;
 6using System.Text;
 7using System.Threading;
 8using System.Threading.Tasks;
 9using Google.Protobuf;
 10
 11namespace Livekit.Server.Sdk.Dotnet
 12{
 13    /// <summary>
 14    /// Base class of the service clients: holds the credentials and the <see cref="HttpClient"/>, signs every
 15    /// call with a short-lived token and sends it as a Twirp request.
 16    /// </summary>
 17    public class BaseService
 18    {
 119        private static readonly HttpClientHandler SharedHandler = new HttpClientHandler();
 20
 121        private static readonly MediaTypeHeaderValue ProtobufContentType = new MediaTypeHeaderValue(
 122            "application/protobuf"
 123        );
 24
 25        // Product token sent as User-Agent: livekit-server-sdk-dotnet/<version>
 126        private static readonly ProductInfoHeaderValue UserAgent = new ProductInfoHeaderValue(
 127            "livekit-server-sdk-dotnet",
 128            SdkVersion()
 129        );
 30
 31        private readonly string apiKey;
 32        private readonly string apiSecret;
 33        private readonly Uri baseUri;
 34
 35        /// <summary>
 36        /// The <see cref="HttpClient"/> the requests are sent with: the one supplied to the constructor, or one
 37        /// owned by the SDK (which shares a connection pool with the other SDK-owned clients).
 38        /// </summary>
 39        protected readonly HttpClient httpClient;
 40
 41        /// <summary>
 42        /// Stores the credentials and the <see cref="HttpClient"/> the requests are sent with.
 43        /// </summary>
 44        /// <param name="host">URL of the LiveKit server, <c>http(s)://</c> or <c>ws(s)://</c>; a subpath such as <c>htt
 45        /// <param name="apiKey">API key; the <c>LIVEKIT_API_KEY</c> environment variable when omitted.</param>
 46        /// <param name="apiSecret">API secret; the <c>LIVEKIT_API_SECRET</c> environment variable when omitted.</param>
 47        /// <param name="client">Optional <see cref="HttpClient"/> to send the requests with. The SDK never modifies it,
 12048        public BaseService(
 12049            string host,
 12050            string apiKey = null,
 12051            string apiSecret = null,
 12052            HttpClient client = null
 12053        )
 12054        {
 12055            this.apiKey = apiKey ?? Environment.GetEnvironmentVariable("LIVEKIT_API_KEY");
 12056            this.apiSecret = apiSecret ?? Environment.GetEnvironmentVariable("LIVEKIT_API_SECRET");
 57
 12058            if (string.IsNullOrEmpty(this.apiKey) || string.IsNullOrEmpty(this.apiSecret))
 259            {
 260                throw new ArgumentException("apiKey and apiSecret must be set");
 61            }
 11862            if (Encoding.UTF8.GetBytes(this.apiSecret).Length < 32)
 163            {
 164                throw new ArgumentException(
 165                    "apiSecret must be at least 256 bits long. Currently it is "
 166                        + Encoding.UTF8.GetBytes(this.apiSecret).Length * 8
 167                        + " bits long"
 168                );
 69            }
 70
 11771            baseUri = new Uri(WithTrailingSlash(ToHttpScheme(host)));
 11772            if (client == null)
 7773            {
 74                // SDK-owned clients share one handler (and its connection pool): service clients
 75                // are often created per request and never disposed
 7776                httpClient = new HttpClient(SharedHandler, false) { BaseAddress = baseUri };
 7777            }
 78            else
 4079            {
 80                // A caller-supplied client may be shared with other code (or other service
 81                // clients) and may already have sent requests, so it is never modified: the base
 82                // address, the bearer token and the user agent travel with each request instead.
 4083                httpClient = client;
 4084            }
 11785        }
 86
 87        /// <summary>
 88        /// Sends one Twirp call: a protobuf-encoded POST to <paramref name="route"/> (relative
 89        /// to the host, e.g. <c>twirp/livekit.RoomService/CreateRoom</c>) signed with
 90        /// <paramref name="bearerToken"/>, parsed with <paramref name="parser"/>. Every call builds
 91        /// its own request, so concurrent calls never share headers and the shared
 92        /// <see cref="HttpClient"/> is left untouched. A non-2xx answer is raised as
 93        /// <see cref="TwirpException"/>.
 94        /// </summary>
 95        internal async Task<TResponse> SendAsync<TRequest, TResponse>(
 96            string route,
 97            TRequest request,
 98            MessageParser<TResponse> parser,
 99            string bearerToken,
 100            CancellationToken cancellationToken = default
 101        )
 102            where TRequest : IMessage
 103            where TResponse : IMessage<TResponse>
 301104        {
 301105            using (var content = new ByteArrayContent(request.ToByteArray()))
 301106            {
 301107                content.Headers.ContentType = ProtobufContentType;
 108                using (
 301109                    var message = new HttpRequestMessage(HttpMethod.Post, new Uri(baseUri, route))
 110                )
 301111                {
 301112                    message.Content = content;
 301113                    message.Headers.Authorization = new AuthenticationHeaderValue(
 301114                        "Bearer",
 301115                        bearerToken
 301116                    );
 117                    // A request header replaces the client's default one, so keep the caller's own
 118                    // User-Agent products and add the SDK's after them
 907119                    foreach (var product in httpClient.DefaultRequestHeaders.UserAgent)
 2120                    {
 2121                        message.Headers.UserAgent.Add(product);
 2122                    }
 301123                    message.Headers.UserAgent.Add(UserAgent);
 124
 125                    using (
 301126                        var response = await httpClient
 301127                            .SendAsync(message, cancellationToken)
 301128                            .ConfigureAwait(false)
 129                    )
 300130                    {
 300131                        var body = await response
 300132                            .Content.ReadAsByteArrayAsync()
 300133                            .ConfigureAwait(false);
 300134                        if (!response.IsSuccessStatusCode)
 16135                        {
 16136                            throw TwirpException.FromResponse(
 16137                                Encoding.UTF8.GetString(body),
 16138                                (int)response.StatusCode
 16139                            );
 140                        }
 284141                        return parser.ParseFrom(body);
 142                    }
 143                }
 144            }
 284145        }
 146
 147        private static string SdkVersion()
 1148        {
 1149            var assembly = typeof(BaseService).Assembly;
 1150            var informational = assembly
 1151                .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)
 1152                .OfType<AssemblyInformationalVersionAttribute>()
 1153                .FirstOrDefault();
 1154            var version = informational != null ? informational.InformationalVersion : null;
 1155            if (string.IsNullOrEmpty(version))
 0156            {
 0157                version = assembly.GetName().Version?.ToString(3) ?? "0.0.0";
 0158            }
 1159            var plus = version.IndexOf('+');
 1160            return plus >= 0 ? version.Substring(0, plus) : version;
 1161        }
 162
 163        // LIVEKIT_URL is usually the WebSocket URL of the server; the service APIs speak HTTP on
 164        // the same host (the Node and Python SDKs do the same conversion)
 165        private static string ToHttpScheme(string host)
 117166        {
 117167            if (host == null)
 0168            {
 0169                return null;
 170            }
 117171            if (host.StartsWith("wss://", StringComparison.OrdinalIgnoreCase))
 1172            {
 1173                return "https://" + host.Substring("wss://".Length);
 174            }
 116175            if (host.StartsWith("ws://", StringComparison.OrdinalIgnoreCase))
 1176            {
 1177                return "http://" + host.Substring("ws://".Length);
 178            }
 115179            return host;
 117180        }
 181
 182        // Twirp routes are relative ("twirp/livekit.X/Y") and System.Uri drops the last path
 183        // segment of a base address without a trailing "/" when resolving a relative reference,
 184        // so "https://my.server.com/livekit" would send requests to "https://my.server.com/twirp/...".
 185        // Append the slash so hosts with a subpath work whether or not the caller added it.
 186        private static string WithTrailingSlash(string host)
 117187        {
 117188            if (host == null || host.EndsWith("/", StringComparison.Ordinal))
 1189            {
 1190                return host;
 191            }
 116192            return host + "/";
 117193        }
 194
 195        /// <summary>
 196        /// Builds the bearer token of a call that needs <paramref name="videoGrants"/>, valid for
 197        /// <see cref="Constants.DefaultTtl"/>.
 198        /// </summary>
 199        /// <param name="videoGrants">Room permissions the call needs.</param>
 200        /// <returns>The signed JWT, sent as bearer token.</returns>
 201        protected string AuthHeader(VideoGrants videoGrants)
 253202        {
 253203            var accessToken = new AccessToken(apiKey, apiSecret);
 253204            accessToken.WithGrants(videoGrants);
 253205            accessToken.WithTtl(Constants.DefaultTtl);
 206
 253207            return accessToken.ToJwt();
 253208        }
 209
 210        /// <summary>
 211        /// Builds the bearer token of a SIP call that needs <paramref name="videoGrants"/> and
 212        /// <paramref name="sipGrants"/>, valid for <see cref="Constants.DefaultTtl"/>.
 213        /// </summary>
 214        /// <param name="videoGrants">Room permissions the call needs.</param>
 215        /// <param name="sipGrants">SIP permissions the call needs.</param>
 216        /// <returns>The signed JWT, sent as bearer token.</returns>
 217        protected string AuthHeader(VideoGrants videoGrants, SIPGrants sipGrants)
 48218        {
 48219            var accessToken = new AccessToken(apiKey, apiSecret);
 48220            accessToken.WithGrants(videoGrants);
 48221            accessToken.WithSipGrants(sipGrants);
 48222            accessToken.WithTtl(Constants.DefaultTtl);
 223
 48224            return accessToken.ToJwt();
 48225        }
 226    }
 227}