public async Task SendMessage_SingleMessage_ShouldWriteOnResponseStream() { // Arrange var message = new Message() { Id = EnvelopeId.NewId(), Content = "Hello world" }; var target = GetTarget(); // Act await target.SendMessageAsync(message, CancellationTokenSource.Token); // Assert ResponseBody.Position.ShouldBePositive(); ResponseBody.Position = 0; using var reader = new StreamReader(ResponseBody, Encoding.UTF8); var json = await reader.ReadToEndAsync(); var actualEnvelope = EnvelopeSerializer.Deserialize(json); var actualMessage = actualEnvelope.ShouldBeOfType <Message>(); actualMessage.Id.ShouldBe(message.Id); actualMessage.Type.ShouldBe(message.Type); actualMessage.Content.ToString().ShouldBe(message.Content.ToString()); }
public async Task SendCommand_SingleCommand_ShouldWriteOnResponseStream() { // Arrange var message = new Command() { Id = EnvelopeId.NewId(), Method = CommandMethod.Set, Uri = "/greeting", Resource = "Hello world" }; var target = GetTarget(); // Act await target.SendCommandAsync(message, CancellationTokenSource.Token); // Assert ResponseBody.Position.ShouldBePositive(); ResponseBody.Position = 0; using var reader = new StreamReader(ResponseBody, Encoding.UTF8); var json = await reader.ReadToEndAsync(); var actualEnvelope = EnvelopeSerializer.Deserialize(json); var actualCommand = actualEnvelope.ShouldBeOfType <Command>(); actualCommand.Id.ShouldBe(message.Id); actualCommand.Method.ShouldBe(message.Method); actualCommand.Uri.ShouldBe(message.Uri); actualCommand.Type.ShouldBe(message.Type); actualCommand.Resource.ToString().ShouldBe(message.Resource.ToString()); }
public async Task SetUp() { ListenerUri = CreateListenerUri(); EnvelopeSerializer = new EnvelopeSerializer(new DocumentTypeResolver().WithMessagingDocuments()); CancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15)); await SetUpImpl(); }
public async Task SendNotification_SingleNotification_ShouldWriteOnResponseStream() { // Arrange var notification = new Notification() { Id = EnvelopeId.NewId(), Event = Event.Received }; var target = GetTarget(); // Act await target.SendNotificationAsync(notification, CancellationTokenSource.Token); // Assert ResponseBody.Position.ShouldBePositive(); ResponseBody.Position = 0; using var reader = new StreamReader(ResponseBody, Encoding.UTF8); var json = await reader.ReadToEndAsync(); var actualEnvelope = EnvelopeSerializer.Deserialize(json); var actualNotification = actualEnvelope.ShouldBeOfType <Notification>(); actualNotification.Id.ShouldBe(notification.Id); actualNotification.Event.ShouldBe(notification.Event); }
public void Preference(string mimetypes) { _graph = new ChannelGraph(); _graph.AcceptedContentTypes.AddRange(mimetypes.ToDelimitedArray(';')); _envelopeSerializer = new EnvelopeSerializer(_graph, _serializers); }
public async Task <IServiceContainer> StartAsync(Action <IServiceContainer> serviceOverrides = null, CancellationToken cancellationToken = default(CancellationToken)) { var applicationFileName = Bootstrapper.DefaultApplicationFileName; var application = Application.ParseFromJsonFile(Path.Combine(GetAssemblyRoot(), applicationFileName)); var typeResolver = new AggregateTypeResolver(new TypeResolver(new AssemblyProvider(_assembly)), _typeResolver); var localServiceProvider = BuildServiceContainer(application, typeResolver); localServiceProvider.RegisterService(typeof(IServiceProvider), localServiceProvider); localServiceProvider.RegisterService(typeof(IServiceContainer), localServiceProvider); localServiceProvider.RegisterService(typeof(Application), application); Bootstrapper.RegisterSettingsContainer(application, localServiceProvider, typeResolver); var serializer = new EnvelopeSerializer(new DocumentTypeResolver().WithMessagingDocuments()); _onDemandClientChannel = new InternalOnDemandClientChannel(serializer, application); _client = await Bootstrapper.BuildClientAsync( application, () => new BlipClient(new InternalOnDemandClientChannel(serializer, application)), localServiceProvider, typeResolver, cancellationToken, serviceOverrides); // The listener should be active? _blipChannelListener = new BlipChannelListener(_client, !application.DisableNotify); await _client.StartAsync(_blipChannelListener, cancellationToken).ConfigureAwait(false); await Bootstrapper.BuildStartupAsync(application, localServiceProvider, typeResolver); Identity = Identity.Parse($"{application.Identifier}@{application.Domain ?? "msging.net"}"); return(localServiceProvider); }
public FakeEnvelopeSerializer(int count) { _envelopes = Enumerable .Range(0, count) .Select <int, Envelope>(i => { if (i % 5 == 0) { return(Dummy.CreateMessage(Dummy.CreateTextContent())); } if (i % 3 == 0) { return(Dummy.CreateCommand(Dummy.CreateAccount())); } if (i % 2 == 0) { return(Dummy.CreateNotification(Event.Received)); } return(Dummy.CreateMessage(Dummy.CreateSelect())); }) .ToArray(); var jsonSerializer = new EnvelopeSerializer(new DocumentTypeResolver().WithMessagingDocuments()); _serializedEnvelopes = _envelopes.Select(e => jsonSerializer.Serialize(e)).ToArray(); }
protected void SetUp(Uri listenerUri) { ListenerUri = listenerUri; EnvelopeSerializer = new EnvelopeSerializer(new DocumentTypeResolver().WithMessagingDocuments()); TraceWriter = new Mock <ITraceWriter>(); CancellationToken = TimeSpan.FromSeconds(30).ToCancellationToken(); }
/// <summary> /// Creates or updates a Service Collection to include BLiP's extensions and any custom Documents /// </summary> /// <param name="authKey"></param> /// <param name="documents"></param> /// <param name="serviceCollection"></param> /// <returns></returns> public IServiceCollection BuildServiceCollection(string authKey, List <Document> documents = null, IServiceCollection serviceCollection = null) { if (serviceCollection == null) { serviceCollection = new ServiceCollection(); } var documentResolver = new DocumentTypeResolver(); documentResolver.WithBlipDocuments(); if (documents != null) { foreach (Document d in documents) { documentResolver.RegisterDocument(d.GetType()); } } var envelopeSerializer = new EnvelopeSerializer(documentResolver); var client = new RestClient("https://msging.net/") { JsonSerializerSettings = envelopeSerializer.Settings }.For <IBlipHttpClient>(); client.Authorization = new AuthenticationHeaderValue("Key", authKey); var sender = new BlipHttpClient(client); serviceCollection.AddSingleton <ISender>(sender); serviceCollection.RegisterBlipExtensions(); return(serviceCollection); }
static ITransportListener GetTransportListenerForUri(Uri uri) { var serializer = new EnvelopeSerializer(new DocumentTypeResolver()); switch (uri.Scheme) { case "net.tcp": X509Certificate2 serverCertificate = null; // You should provide a certificate for TLS return(new TcpTransportListener( uri, serverCertificate, serializer, 1024, 2048)); //case "ws": //case "wss": // return new WebSocketTransportListener( // uri, // null, // serializer); // //case "redis": // return new RedisTransportListener(uri, serializer); default: throw new NotSupportedException($"Unsupported URI scheme '{uri.Scheme}'"); } }
public async Task SendHugeEnvelope() { try { var sw = Stopwatch.StartNew(); var serializer = new EnvelopeSerializer(new DocumentTypeResolver().WithMessagingDocuments()); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory); var content = File.ReadAllLines(Path.Combine(path, "huge-json.txt")); var envelope = serializer.Deserialize(string.Join("", content)); await _clientTransport.SendAsync(envelope, _cancellationToken); await _serverTransport.ReceiveAsync(_cancellationToken); sw.Stop(); // Assert sw.ElapsedMilliseconds.ShouldBeLessThan(100); } catch (Exception ex) { Trace.TraceError(ex.ToString()); } }
// POST api/values public void Post([FromBody] JObject jsonObject) { var envelopeSerializer = new EnvelopeSerializer(); var notification = envelopeSerializer.Deserialize(jsonObject.ToString()); Console.WriteLine("Received Notification"); }
public void SetUp() { ListenerUri = CreateListenerUri(); EnvelopeSerializer = new EnvelopeSerializer(new DocumentTypeResolver().WithMessagingDocuments()); TraceWriter = new Mock <ITraceWriter>(); CancellationToken = TimeSpan.FromSeconds(5).ToCancellationToken(); Target = CreateTransportListener(); }
private ISender BuildTcpClient(string authKey, EnvelopeSerializer envelopeSerializer) { return(new BlipClientBuilder(new TcpTransportFactory(envelopeSerializer)) .UsingAuthorizationKey(authKey) .UsingRoutingRule(RoutingRule.Instance) .WithChannelCount(2) .UsingHostName(_domain) .Build()); }
/// <inheritdoc /> /// <exception cref="InvalidOperationException">Thrown when the transport is not connected.</exception> public override async Task <Envelope> ReceiveAsync(CancellationToken cancellationToken) { ThrowIfNotConnected(); var envelopeSerialized = await EnvelopeChannel.Reader.ReadAsync(cancellationToken); await TraceWriter.TraceIfEnabledAsync(envelopeSerialized, DataOperation.Receive).ConfigureAwait(false); return(EnvelopeSerializer.Deserialize(envelopeSerialized)); }
private ISender BuildHttpClient(string authKey, EnvelopeSerializer envelopeSerializer) { var client = new RestClient(MSGING_BASE_URL(_domain)) { JsonSerializerSettings = envelopeSerializer.Settings }.For <IBlipHttpClient>(); client.Authorization = new AuthenticationHeaderValue(KEY_PREFIX, authKey); return(new BlipHttpClient(client)); }
public async Task Start() { ChannelNamespace = EnvelopeId.NewId(); ListenerUri = new Uri("redis://localhost"); EnvelopeSerializer = new EnvelopeSerializer(new DocumentTypeResolver().WithMessagingDocuments()); TraceWriter = new Mock <ITraceWriter>(); Listener = new RedisTransportListener(ListenerUri, EnvelopeSerializer, TraceWriter.Object, channelNamespace: ChannelNamespace); CancellationToken = TimeSpan.FromSeconds(5).ToCancellationToken(); _redisFixture = new RedisFixture(); await Listener.StartAsync(CancellationToken); }
public EnvelopeSerializerTester() { messageSerializers = new IMessageSerializer[] { new JsonMessageSerializer(new JsonSerializerSettings()) }; theGraph = new ChannelGraph(); theSerializer = new EnvelopeSerializer(theGraph, messageSerializers); theAddress = new Address { City = "Jasper", State = "Missouri" }; }
/// <inheritdoc /> /// <exception cref="ObjectDisposedException">This instance has already been disposed.</exception> public override async Task SendAsync(Envelope envelope, CancellationToken cancellationToken) { ThrowIfNotConnected(); await base.SendAsync(envelope, cancellationToken).ConfigureAwait(false); string serializedEnvelope = EnvelopeSerializer.Serialize(envelope); await TraceWriter.TraceIfEnabledAsync(serializedEnvelope, DataOperation.Send).ConfigureAwait(false); await _hubConnection.SendAsync(FROM_CLIENT_METHOD, serializedEnvelope, cancellationToken).ConfigureAwait(false); }
public void SetUp() { messageSerializers = new IMessageSerializer[] { new BinarySerializer(), new BasicJsonMessageSerializer(), new XmlMessageSerializer() }; theGraph = new ChannelGraph(); theSerializer = new EnvelopeSerializer(theGraph, messageSerializers); theAddress = new Address { City = "Jasper", State = "Missouri" }; }
private EnvelopeSerializer CreateEnvelopeSerializer(List <Document> documents = null) { var documentResolver = new DocumentTypeResolver(); documentResolver.WithBlipDocuments(); documents?.ForEach(d => documentResolver.RegisterDocument(d.GetType())); var envelopeSerializer = new EnvelopeSerializer(documentResolver); return(envelopeSerializer); }
/// <summary> /// Builds an ISender using the given auth key and custom documents previously set /// </summary> /// <param name="authKey"></param> /// <param name="documentTypeResolver"></param> /// <returns></returns> public ISender BuildBlipHttpClient(string authKey, IDocumentTypeResolver documentTypeResolver) { var envelopeSerializer = new EnvelopeSerializer(documentTypeResolver); var client = new RestClient("https://msging.net/") { JsonSerializerSettings = envelopeSerializer.Settings }.For <IBlipHttpClient>(); client.Authorization = new AuthenticationHeaderValue("Key", authKey); return(new BlipHttpClient(client)); }
private ISender BuildTcpClient(string authKey, EnvelopeSerializer envelopeSerializer = default) { var domain = _domain.Equals(OLD_DOMAIN) ? NEW_TCP_DOMAIN : _domain; return(new BlipClientBuilder(new TcpTransportFactory(envelopeSerializer)) .UsingAuthorizationKey(authKey) .UsingRoutingRule(RoutingRule.Instance) .WithChannelCount(2) .UsingHostName(domain) .Build()); }
/// <inheritdoc /> /// <exception cref="InvalidOperationException">Thrown when the transport is not connected.</exception> public override async Task SendAsync(Envelope envelope, CancellationToken cancellationToken) { ThrowIfNotConnected(); await base.SendAsync(envelope, cancellationToken).ConfigureAwait(false); string serializedEnvelope = EnvelopeSerializer.Serialize(envelope); await TraceWriter.TraceIfEnabledAsync(serializedEnvelope, DataOperation.Send).ConfigureAwait(false); var client = _hubContext.Clients.Client(_connectionId); await client.SendAsync(FROM_SERVER_METHOD, serializedEnvelope).ConfigureAwait(false); }
/// <summary> /// Builds an ISender using the given auth key /// </summary> /// <param name="authKey"></param> /// <returns></returns> public ISender BuildBlipHttpClient(string authKey) { if (authKey.StartsWith("Key ")) { authKey = authKey.Replace("Key ", ""); } var documentResolver = new DocumentTypeResolver(); documentResolver.WithBlipDocuments(); var envelopeSerializer = new EnvelopeSerializer(documentResolver); var client = new RestClient("https://msging.net/") { JsonSerializerSettings = envelopeSerializer.Settings }.For <IBlipHttpClient>(); client.Authorization = new AuthenticationHeaderValue("Key", authKey); return(new BlipHttpClient(client)); }
public async Task Send100HugeEnvelopesAsync() { // Arrange var count = 100; var serializer = new EnvelopeSerializer(new DocumentTypeResolver().WithMessagingDocuments()); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory); var content = File.ReadAllLines(Path.Combine(path, "huge.json")); var hugeEnvelope = (Command)serializer.Deserialize(string.Join("", content)); var envelopes = Enumerable .Range(0, count) .Select(i => { var command = hugeEnvelope.ShallowCopy(); command.Id = $"envelope_{i}"; return(command); }); var receivedEnvelopes = Enumerable .Range(0, count) .Select(i => _serverTransport.ReceiveAsync(_cancellationToken)) .ToArray(); // Act var sw = Stopwatch.StartNew(); foreach (var envelope in envelopes) { await _clientTransport.SendAsync(envelope, _cancellationToken); } await Task.WhenAll(receivedEnvelopes); sw.Stop(); // Assert sw.ElapsedMilliseconds.ShouldBeLessThan(count * 100); }
/// <summary> /// Creates or updates a Service Collection to include BLiP's extensions and any custom Documents, including an <c>ISender</c> /// </summary> /// <param name="authKey"></param> /// <param name="protocol"></param> /// <param name="documents"></param> /// <param name="serviceCollection"></param> public IServiceCollection BuildServiceCollection(string authKey, BlipProtocol protocol, List <Document> documents = null, IServiceCollection serviceCollection = null) { serviceCollection = serviceCollection ?? new ServiceCollection(); var documentResolver = new DocumentTypeResolver(); documentResolver.WithBlipDocuments(); documents?.ForEach(d => documentResolver.RegisterDocument(d.GetType())); var envelopeSerializer = new EnvelopeSerializer(documentResolver); serviceCollection.AddSingleton <IEnvelopeSerializer>(envelopeSerializer); var sender = BuildBlipClient(authKey, protocol); serviceCollection.AddSingleton(sender); serviceCollection.RegisterBlipExtensions(); return(serviceCollection); }
private ISender BuildHttpClient(string authKey, List <Document> documents = null) { if (authKey.StartsWith(KEY_PREFIX)) { authKey = authKey.Replace(KEY_PREFIX, string.Empty).Trim(); } var documentResolver = new DocumentTypeResolver(); documentResolver.WithBlipDocuments(); documents?.ForEach(d => documentResolver.RegisterDocument(d.GetType())); var envelopeSerializer = new EnvelopeSerializer(documentResolver); var client = new RestClient(MSGING_BASE_URL) { JsonSerializerSettings = envelopeSerializer.Settings }.For <IBlipHttpClient>(); client.Authorization = new AuthenticationHeaderValue(KEY_PREFIX, authKey); return(new BlipHttpClient(client)); }
protected void SetUp(TransportEndPoint transportEndPoint = null) { TransportEndPoint = transportEndPoint ?? new TransportEndPoint(); Options = new LimeOptions() { EndPoints = new List <TransportEndPoint>() { TransportEndPoint } }; EnvelopeSerializer = new EnvelopeSerializer(new DocumentTypeResolver()); ServiceScopeFactory = new Mock <IServiceScopeFactory>(); TransportListener = new TransportListener( Microsoft.Extensions.Options.Options.Create(Options), ServiceScopeFactory.Object, new ChannelProvider(), new Logger <TransportListener>(new LoggerFactory())); CancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30)); Scope = new Mock <IServiceScope>(); ServiceScopeFactory .Setup(s => s.CreateScope()) .Returns(Scope.Object); ServiceProvider = new Mock <IServiceProvider>(); Scope .SetupGet(s => s.ServiceProvider) .Returns(ServiceProvider.Object); ServiceProvider .Setup(s => s.GetService(typeof(ChannelContextProvider))) .Returns(() => { var provider = new ChannelContextProvider(); ChannelContextProviders.Add(provider); return(provider); }); SenderChannel = new Mock <ISenderChannel>(); ChannelContextProviders = new List <ChannelContextProvider>(); }
public static IServiceCollection AddBlip(this IServiceCollection serviceCollection) { var applicationJsonPath = Path.Combine( Path.GetDirectoryName( Assembly.GetEntryAssembly().Location), Bootstrapper.DefaultApplicationFileName); if (!File.Exists(applicationJsonPath)) { throw new InvalidOperationException($"Could not find the application file in '{applicationJsonPath}'"); } var application = Application.ParseFromJsonFile(applicationJsonPath); if (string.IsNullOrEmpty(application.Identifier)) { var rawApplicationJson = File.ReadAllText(applicationJsonPath); var applicationJson = JObject.Parse(rawApplicationJson); var authorizationHeader = applicationJson["authorization"]?.ToString(); if (authorizationHeader != null) { var authorization = authorizationHeader.Split(' ')[1].FromBase64(); var identifierAndAccessKey = authorization.Split(':'); application.Identifier = identifierAndAccessKey[0]; application.AccessKey = identifierAndAccessKey[1].ToBase64(); } } var workingDir = Path.GetDirectoryName(applicationJsonPath); if (string.IsNullOrWhiteSpace(workingDir)) { workingDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); } var envelopeBuffer = new EnvelopeBuffer(); var envelopeSerializer = new EnvelopeSerializer(new DocumentTypeResolver().WithMessagingDocuments()); var clientBuilder = new BlipClientBuilder( new WebTransportFactory(envelopeBuffer, envelopeSerializer, application)); IStoppable stoppable; using (var cts = new CancellationTokenSource(StartTimeout)) { stoppable = Bootstrapper .StartAsync( cts.Token, application, clientBuilder, new TypeResolver(workingDir)) .GetAwaiter() .GetResult(); } serviceCollection.AddSingleton(application); serviceCollection.AddSingleton(stoppable); serviceCollection.AddSingleton <IEnvelopeBuffer>(envelopeBuffer); serviceCollection.AddSingleton <IEnvelopeSerializer>(envelopeSerializer); return(serviceCollection); }