Exemplo n.º 1
0
        public async Task CreateServiceHubContext_WithReferenceNotEqualEndpoints()
        {
            //prepare endpoints
            var totalCount      = 3;
            var selectedCount   = 2;
            var endpoints       = FakeEndpointUtils.GetFakeEndpoint(totalCount).ToArray();
            var targetEndpoints = endpoints.Take(selectedCount).Select(endpoint => new ServiceEndpoint(endpoint));

            //create services
            var services = new ServiceCollection().AddSignalRServiceManager()
                           .Configure <ServiceManagerOptions>(o =>
            {
                o.ServiceEndpoints     = endpoints;
                o.ServiceTransportType = ServiceTransportType.Persistent;
            });

            services.AddSingleton <IReadOnlyCollection <ServiceDescriptor> >(services.ToList());
            var serviceManager = services.BuildServiceProvider().GetRequiredService <IServiceManager>();

            var hubContext = (await serviceManager.CreateHubContextAsync(Hub) as IInternalServiceHubContext)
                             .WithEndpoints(targetEndpoints);
            var serviceProvider = (hubContext as ServiceHubContextImpl).ServiceProvider;
            var container       = serviceProvider.GetRequiredService <IServiceConnectionContainer>() as MultiEndpointMessageWriter;
            var innerEndpoints  = container.TargetEndpoints.ToArray();
            var hubEndpoints    = (hubContext as ServiceHubContextImpl).ServiceProvider.GetRequiredService <IServiceEndpointManager>().GetEndpoints(Hub);

            Assert.True(innerEndpoints.SequenceEqual(hubEndpoints.Take(selectedCount), ReferenceEqualityComparer.Instance));
        }
Exemplo n.º 2
0
        public async Task GenerateClientEndpoint(string userId, Claim[] claims, string appName)
        {
            var endpoints  = FakeEndpointUtils.GetFakeEndpoint(3).ToArray();
            var routerMock = new Mock <IEndpointRouter>();

            routerMock.SetupSequence(router => router.GetNegotiateEndpoint(null, endpoints))
            .Returns(endpoints[0])
            .Returns(endpoints[1])
            .Returns(endpoints[2]);
            var router   = routerMock.Object;
            var provider = new ServiceCollection().AddSignalRServiceManager()
                           .Configure <ServiceManagerOptions>(o =>
            {
                o.ApplicationName  = appName;
                o.ServiceEndpoints = endpoints;
            })
                           .AddSingleton(router).BuildServiceProvider();
            var negotiateProcessor = provider.GetRequiredService <NegotiateProcessor>();

            for (int i = 0; i < 3; i++)
            {
                var negotiationResponse = await negotiateProcessor.NegotiateAsync(HubName, null, userId, claims, _tokenLifeTime);

                var tokenString = negotiationResponse.AccessToken;
                var token       = JwtTokenHelper.JwtHandler.ReadJwtToken(tokenString);

                string expectedToken = JwtTokenHelper.GenerateJwtBearer(ClientEndpointUtils.GetExpectedClientEndpoint(HubName, appName, endpoints[i].Endpoint), ClaimsUtility.BuildJwtClaims(null, userId, () => claims), token.ValidTo, token.ValidFrom, token.ValidFrom, endpoints[i].AccessKey);

                Assert.Equal(ClientEndpointUtils.GetExpectedClientEndpoint(HubName, appName, endpoints[i].Endpoint), negotiationResponse.Url);
                Assert.Equal(expectedToken, tokenString);
            }
        }
        public async Task ColdStartNegotiateTest()
        {
            var hubName = "hub";
            ServiceCollection services = new ServiceCollection();

            services.AddSignalRServiceManager();

            //configure two fake service endpoints and one real endpoints.
            services.Configure <ServiceManagerOptions>(o =>
            {
                o.ConnectionString = TestConfiguration.Instance.ConnectionString;
                o.ServiceEndpoints = FakeEndpointUtils.GetFakeEndpoint(3).ToArray();
            });

            //enable test output
            services.AddSingleton <ILoggerFactory>(new LoggerFactory(new List <ILoggerProvider> {
                new XunitLoggerProvider(_outputHelper)
            }));
            var manager    = services.BuildServiceProvider().GetRequiredService <IServiceManager>();
            var hubContext = await manager.CreateHubContextAsync(hubName);

            var realEndpoint = new ServiceEndpoint(TestConfiguration.Instance.ConnectionString).Endpoint;

            //reduce the effect of randomness
            for (int i = 0; i < 5; i++)
            {
                var clientEndoint = await(hubContext as IInternalServiceHubContext).NegotiateAsync();
                var expectedUrl   = ClientEndpointUtils.GetExpectedClientEndpoint(hubName, null, realEndpoint);
                Assert.Equal(expectedUrl, clientEndoint.Url);
            }
        }
Exemplo n.º 4
0
        public async Task GetDiagnosticClientNegotiateResponseTest(bool isDiagnosticClient, bool hasClaims)
        {
            var endpoints = FakeEndpointUtils.GetFakeEndpoint(1).ToArray();
            var provider  = new ServiceCollection().AddSignalRServiceManager()
                            .Configure <ServiceManagerOptions>(o =>
            {
                o.ServiceEndpoints     = endpoints;
                o.ServiceTransportType = ServiceTransportType.Persistent;
            }).BuildServiceProvider();
            var userId              = "user";
            var negotiateProcessor  = provider.GetRequiredService <NegotiateProcessor>();
            var negotiationResponse = await negotiateProcessor.NegotiateAsync(
                HubName,
                new NegotiationOptions
            {
                UserId = userId,
                Claims = hasClaims ? new List <Claim> {
                    new Claim("a", "1")
                } : null,
                IsDiagnosticClient = isDiagnosticClient,
                TokenLifetime      = _tokenLifeTime
            });

            var tokenString = negotiationResponse.AccessToken;
            var handler     = new JwtSecurityTokenHandler();
            var token       = handler.ReadJwtToken(tokenString);

            Assert.True(
                isDiagnosticClient && token.Claims.Any(c => c.Type == Constants.ClaimType.DiagnosticClient && c.Value == "true") ||
                !isDiagnosticClient && !token.Claims.Any(c => c.Type == Constants.ClaimType.DiagnosticClient));
            Assert.True(
                hasClaims && token.Claims.Any(c => c.Type == "a" && c.Value == "1") ||
                !hasClaims && !token.Claims.Any(c => c.Type == "a"));
        }
Exemplo n.º 5
0
 public void ConnectionStringNull_TransientMode_Throw()
 {
     Assert.Throws <InvalidOperationException>(
         () => new ServiceCollection().AddSignalRServiceManager()
         .Configure <ServiceManagerOptions>(o => o.ServiceEndpoints = FakeEndpointUtils.GetFakeEndpoint(2).ToArray())
         .BuildServiceProvider()
         .GetRequiredService <IOptions <ServiceManagerOptions> >()
         .Value);
 }
        public void ForbidMultipleEndpointsInTransientModeFact()
        {
            Assert.Throws <NotImplementedException>(() => new ServiceManagerOptions
            {
                ConnectionString = FakeEndpointUtils.GetFakeConnectionString(1).Single(),
                ServiceEndpoints = FakeEndpointUtils.GetFakeEndpoint(1).ToArray()
            }.ValidateOptions());

            Assert.Throws <NotImplementedException>(() => new ServiceManagerOptions
            {
                ServiceEndpoints = FakeEndpointUtils.GetFakeEndpoint(2).ToArray()
            }.ValidateOptions());
        }
Exemplo n.º 7
0
        //[InlineData(ServiceTransportType.Transient)] Not implemented yet
        public async Task StrongTypedHubContextCheckEndpointHealthWithMultiEndpoints(ServiceTransportType serviceTransportType)
        {
            var serviceManager = new ServiceManagerBuilder()
                                 .WithOptions(o =>
            {
                o.ServiceTransportType = serviceTransportType;
                o.ServiceEndpoints     = FakeEndpointUtils.GetFakeEndpoint(2).ToArray();
            })
                                 .WithLoggerFactory(_loggerFactory)
                                 .BuildServiceManager();
            var hubContext = await serviceManager.CreateHubContextAsync <IChat>("hubName", default);

            await Assert.ThrowsAsync <AzureSignalRNotConnectedException>(() => hubContext.NegotiateAsync().AsTask());
        }
        public void EmptyConfiguration_NotCleanOriginalValue()
        {
            const string app       = "App";
            var          connStr   = FakeEndpointUtils.GetFakeConnectionString(1).Single();
            var          endpoints = FakeEndpointUtils.GetFakeEndpoint(2).ToArray();
            var          options   = new ServiceManagerOptions
            {
                ApplicationName  = app,
                ConnectionString = connStr,
                ServiceEndpoints = endpoints
            };
            var configuration = new ConfigurationBuilder().AddInMemoryCollection().Build();
            var setup         = new ServiceManagerOptionsSetup(configuration);

            setup.Configure(options);
            Assert.Equal(app, options.ApplicationName);
            Assert.Equal(connStr, options.ConnectionString);
            Assert.Equal(endpoints, options.ServiceEndpoints);
        }
        public async Task ServiceEndpointsSet()
        {
            var rootHubContextMock  = new Mock <ServiceHubContext>().As <IInternalServiceHubContext>();
            var childHubContextMock = new Mock <ServiceHubContext>().As <IInternalServiceHubContext>();

            rootHubContextMock.Setup(c => c.WithEndpoints(It.IsAny <ServiceEndpoint[]>())).Returns(childHubContextMock.Object);
            childHubContextMock.Setup(c => c.Clients.All.SendCoreAsync(It.IsAny <string>(), It.IsAny <object[]>(), It.IsAny <CancellationToken>())).Returns(Task.CompletedTask);
            var serviceManagerStore = Mock.Of <IServiceManagerStore>(s => s.GetOrAddByConnectionStringKey(It.IsAny <string>()).GetAsync(It.IsAny <string>()) == new ValueTask <IServiceHubContext>(rootHubContextMock.Object));
            var azureSignalRClient  = new AzureSignalRClient(serviceManagerStore, "key", "hub");
            var data = new SignalRData
            {
                Target    = "target",
                Arguments = new object[] { "arg1" },
                Endpoints = FakeEndpointUtils.GetFakeEndpoint(2).ToArray()
            };
            await azureSignalRClient.SendToAll(data);

            rootHubContextMock.Verify(c => c.WithEndpoints(data.Endpoints), Times.Once);
            rootHubContextMock.Verify(c => c.Clients.All.SendCoreAsync(It.IsAny <string>(), It.IsAny <object[]>(), It.IsAny <CancellationToken>()), Times.Never);
            childHubContextMock.Verify(c => c.Clients.All.SendCoreAsync(data.Target, data.Arguments, default), Times.Once);
        }
Exemplo n.º 10
0
        public async Task TestConfigureSignalROptions()
        {
            var builder = new HostBuilder();
            var host    = builder
                          .ConfigureWebJobs(b => b.AddSignalR())
                          .ConfigureServices(services => services.Configure <SignalROptions>(o =>
            {
                foreach (var endpoint in FakeEndpointUtils.GetFakeEndpoint(3))
                {
                    o.ServiceEndpoints.Add(endpoint);
                }
                o.ServiceTransportType = ServiceTransportType.Persistent;
                o.UseJsonObjectSerializer(new NewtonsoftJsonObjectSerializer());
            })).Build();
            var hubContext = await host.Services.GetRequiredService <IServiceManagerStore>().GetOrAddByConnectionStringKey("key").GetAsync("hubName") as ServiceHubContext;

            var resultOptions = (hubContext as ServiceHubContextImpl).ServiceProvider.GetRequiredService <IOptions <ServiceManagerOptions> >().Value;

            Assert.Equal(3, resultOptions.ServiceEndpoints.Length);
            Assert.Equal(ServiceTransportType.Persistent, resultOptions.ServiceTransportType);
            Assert.IsType <NewtonsoftJsonObjectSerializer>(resultOptions.ObjectSerializer);
        }
Exemplo n.º 11
0
        public async Task GetDiagnosticClientNegotiateResponseTest(bool isDiagnosticClient, bool hasClaims)
        {
            var endpoints  = FakeEndpointUtils.GetFakeEndpoint(1).ToArray();
            var routerMock = new Mock <IEndpointRouter>();

            routerMock
            .SetupSequence(router => router.GetNegotiateEndpoint(null, endpoints))
            .Returns(endpoints[0]);
            var router   = routerMock.Object;
            var provider = new ServiceCollection().AddSignalRServiceManager()
                           .Configure <ServiceManagerOptions>(o =>
            {
                o.ServiceEndpoints = endpoints;
            })
                           .AddSingleton(router).BuildServiceProvider();
            var userId              = "user";
            var negotiateProcessor  = provider.GetRequiredService <NegotiateProcessor>();
            var negotiationResponse = await negotiateProcessor.NegotiateAsync(
                HubName,
                null,
                userId,
                hasClaims?new List <Claim> {
                new Claim("a", "1")
            } : null,
                _tokenLifeTime,
                isDiagnosticClient);

            var tokenString = negotiationResponse.AccessToken;
            var handler     = new JwtSecurityTokenHandler();
            var token       = handler.ReadJwtToken(tokenString);

            Assert.True(
                isDiagnosticClient && token.Claims.Any(c => c.Type == Constants.ClaimType.DiagnosticClient && c.Value == "true") ||
                !isDiagnosticClient && !token.Claims.Any(c => c.Type == Constants.ClaimType.DiagnosticClient));
            Assert.True(
                hasClaims && token.Claims.Any(c => c.Type == "a" && c.Value == "1") ||
                !hasClaims && !token.Claims.Any(c => c.Type == "a"));
        }
        public static IEnumerable <object[]> GetEndpoints()
        {
            yield return(new object[] { FakeEndpointUtils.GetFakeEndpoint(2).ToArray() });

            yield return(new object[] { null });
        }
 public void AllowSingleEndpointInTransientModeFact()
 {
     new ServiceManagerOptions {
         ServiceEndpoints = FakeEndpointUtils.GetFakeEndpoint(1).ToArray()
     }.ValidateOptions();
 }