private static void DoesCompress(IStreamCompressor compressor, string text) { var zipBytes = compressor.Compress(text); var unzip = compressor.Decompress(zipBytes); Assert.That(unzip, Is.EqualTo(text)); }
public static void GetBlobSettings(IDictionary <string, string> parameters, out IStreamCompressor compression, out int length) { length = ParseLength(parameters); string compr = null; if (parameters != null) { parameters.TryGetValue("compression", out compr); } if (string.IsNullOrEmpty(compr)) { compression = null; } else if (compr.Equals("gzip", StringComparison.OrdinalIgnoreCase)) { compression = GZipCompressor.Instance; } else { System.Type compressor = System.Type.GetType(compr); compression = (IStreamCompressor)Activator.CreateInstance(compressor); var parameterized = compression as IParameterizedType; if (parameterized != null) { parameterized.SetParameterValues(parameters); } } }
public ClientWebSocketConnector(IServiceProvider serviceProvider, IStreamCompressor compressor, ILoggerFactory loggerFactory) { _serviceProvider = serviceProvider; _compressor = compressor; _loggerFactory = loggerFactory; }
/// <summary> /// Initializes a new instance of the <see cref="ByteArraySerializer"/> class. /// </summary> /// <param name="compressionOption">The compression option.</param> public ByteArraySerializer(CompressionOption compressionOption) { _serializer = new WireSerializer(); _memoryManager = new RecyclableMemoryStreamManager(); _compressionOption = compressionOption; _streamCompressor = GetCompressor(compressionOption); }
public static async Task <WebSocketMessageContext> ToBinaryContextAsync(this WebSocketReceiveResult result, IStreamCompressor compressor, byte[] input) { if (result == null) { throw new ArgumentNullException(nameof(result)); } var content = input.Split(); byte[] header = content.Item1; byte[] body = content.Item2; var webSocketContext = new WebSocketMessageContext(); bool isCompressed = GZipHelper.IsGZipBody(body); if (isCompressed) { body = await compressor.DeCompressAsync(body); } using (var ms = new MemoryStream(header)) using (var sr = new StreamReader(ms)) { var data = await sr.ReadToEndAsync(); if (data != null) { try { webSocketContext.Header = JsonConvert.DeserializeObject <Dictionary <string, object> >(data); } catch (Exception ex) { webSocketContext.Header = new Dictionary <string, object> { ["Exception"] = ex.Message, ["Unknown"] = "Unknown binary message!" }; } } } using (var ms = new MemoryStream(body)) using (var sr = new StreamReader(ms)) { var data = await sr.ReadToEndAsync(); webSocketContext.Value = data; } webSocketContext.Length = input.Length; webSocketContext.MessageType = WebSocketMessageType.Binary; webSocketContext.Command = WebSocketCommands.DataSend; return(webSocketContext); }
public ClientWebSocketConnectorOfT(IServiceProvider serviceProvider, IClientInvocatorContextFactory <TInvocator> invocatorContextFactory, IStreamCompressor compressor, ILoggerFactory loggerFactory) : base(serviceProvider, compressor, loggerFactory) { _invocatorContextFactory = invocatorContextFactory ?? throw new ArgumentNullException(nameof(invocatorContextFactory)); InvocatorContext = _invocatorContextFactory.CreateInvocatorContext(); }
public HttpRpcClientBuilder UsingStreamCompressor(IStreamCompressor streamCompressor) { if (this.streamCompressor != null) { throw new InvalidOperationException("Stream compressor has already been configured."); } this.streamCompressor = streamCompressor; return(this); }
public ConnectionManagerOfT(IServiceProvider serviceProvider, IServerInvocatorContextFactory <TInvocator> invocatorContextFactory, IStreamCompressor compressor, IHandshakeStateTransport initState, IHeaderProvider headerProvider, ILoggerFactory loggerFactory) : base(serviceProvider, compressor, initState, headerProvider, loggerFactory) { _invocatorContextFactory = invocatorContextFactory ?? throw new ArgumentNullException(nameof(invocatorContextFactory)); InvocatorContext = _invocatorContextFactory.CreateInvocatorContext(); }
public CompressContent(HttpContent content, IStreamCompressor compressor) { this.content = content; this.compressor = compressor; foreach (var header in content.Headers) { Headers.TryAddWithoutValidation(header.Key, header.Value); } Headers.ContentEncoding.Add(compressor.Encoding); }
public async Task Invoke(HttpContext httpContext, IConnectionManager manager, IStreamCompressor compressor, ILoggerFactory loggerFactory) { if (httpContext.WebSockets.IsWebSocketRequest) { string connectionId = string.Empty; string connectorName = string.Empty; StringValues headerValue = ""; if (httpContext.Request.Headers.TryGetValue(NCSConstants.ConnectorName, out headerValue)) { connectorName = headerValue.ToString(); } if (httpContext.Request.Headers.TryGetValue(NCSConstants.ConnectionId, out headerValue)) { connectionId = headerValue.ToString(); } if (string.IsNullOrEmpty(connectorName)) { if (httpContext.Request.Query.ContainsKey(NCSConstants.ConnectorName)) { connectorName = httpContext.Request.Query[NCSConstants.ConnectorName]; } } if (string.IsNullOrEmpty(connectionId)) { if (httpContext.Request.Query.ContainsKey(NCSConstants.ConnectionId)) { connectionId = httpContext.Request.Query[NCSConstants.ConnectionId]; Guid connectionIdGuid = Guid.Empty; if (!Guid.TryParse(connectionId, out connectionIdGuid)) { connectionId = string.Empty; } } } var webSocket = await httpContext.WebSockets.AcceptWebSocketAsync(); if (string.IsNullOrEmpty(connectionId)) { connectionId = Guid.NewGuid().ToString("N"); } await manager.ConnectAsync(webSocket, connectionId : connectionId, connectorName : connectorName, cancellationToken : _cancellationToken); } else { await _next(httpContext); } }
public ConnectionManager(IServiceProvider serviceProvider, IStreamCompressor compressor, TransportLifetimeManager lifetimeManager, IHandshakeStateTransport initState, ILoggerFactory loggerFactory) { _serviceProvider = serviceProvider; _compressor = compressor; _lifetimeManager = lifetimeManager; _initState = initState; _loggerFactory = loggerFactory; Connections = new ConcurrentDictionary <string, WebSocketTransport>(StringComparer.OrdinalIgnoreCase); }
public ClientWebSocketConnectorOfInvocator(IServiceProvider serviceProvider, IOptions <ProxyOptions <TInvocator> > options, IStreamCompressor compressor, ILoggerFactory loggerFactory) : base(serviceProvider, compressor, loggerFactory) { if (options == null) { throw new ArgumentNullException(nameof(options)); } Options = options.Value; }
internal static void GetBlobSettings(IDictionary<string, string> parameters, out IStreamCompressor compression) { string compr = parameters == null ? null : parameters["compression"] as string; if (string.IsNullOrEmpty(compr)) compression = null; else if (compr.Equals("gzip", StringComparison.OrdinalIgnoreCase)) compression = GZipCompressor.Instance; else { System.Type compressor = System.Type.GetType(compr); compression = (IStreamCompressor)System.Activator.CreateInstance(compressor); IParameterizedType parameterized = compression as IParameterizedType; if (parameterized != null) parameterized.SetParameterValues(parameters); } }
public static void GetClobSettings(IDictionary<string, string> parameters, out Encoding encoding, out IStreamCompressor compression, out int length) { length = ParseLength(parameters); string compr = parameters == null ? null : parameters["compression"]; if (string.IsNullOrEmpty(compr)) compression = null; else if (compr.Equals("gzip", StringComparison.OrdinalIgnoreCase)) compression = GZipCompressor.Instance; else { System.Type compressor = System.Type.GetType(compr); compression = (IStreamCompressor) Activator.CreateInstance(compressor); var parameterized = compression as IParameterizedType; if (parameterized != null) parameterized.SetParameterValues(parameters); } string enc = parameters == null ? null : parameters["encoding"]; encoding = !string.IsNullOrEmpty(enc) ? Encoding.GetEncoding(enc) : null; }
private Stream BuildWritableResponseStream(HttpContext httpContext) { httpContext.Response.ContentType = "application/json"; string acceptEncoding = httpContext.Request.Headers["Accept-Encoding"]; if (!string.IsNullOrWhiteSpace(acceptEncoding)) { IStreamCompressor compressor = httpContext.RequestServices.GetService <IStreamCompressor>(); if (compressor != null) { string[] encodings = acceptEncoding.Split(RpcHttpRouter.encodingSeperators, StringSplitOptions.RemoveEmptyEntries); foreach (string encoding in encodings) { if (compressor.TryGetCompressionStream(httpContext.Response.Body, encoding, CompressionMode.Compress, out Stream compressedStream)) { httpContext.Response.Headers.Add("Content-Encoding", encoding); return(compressedStream); } } } } return(httpContext.Response.Body); }
public XmlTextCompressor(IStreamCompressor compressor) : this() { _compressor = compressor; }
public XmlTextCompressor(IStreamCompressor compressor) : this() { this.compressor = compressor; }
public FileCompression(IFileSystem fileSystem, IStreamCompressor compressor, IStreamDecompressor decompressor) { this.fileSystem = fileSystem; this.compressor = compressor; this.decompressor = decompressor; }
public ExternalClob(IExternalBlobConnection connection, byte[] identifier, Encoding encoding, IStreamCompressor compression) : this(connection, identifier, encoding) { this.compression = compression; }
/// <summary> /// Takes a route/http contexts and attempts to parse, invoke, respond to an Rpc request /// </summary> /// <param name="context">Route context</param> /// <returns>Task for async routing</returns> public async Task RouteAsync(RouteContext context) { ILogger <RpcHttpRouter> logger = context.HttpContext.RequestServices.GetService <ILogger <RpcHttpRouter> >(); try { RpcPath requestPath; if (!context.HttpContext.Request.Path.HasValue) { requestPath = RpcPath.Default; } else { if (!RpcPath.TryParse(context.HttpContext.Request.Path.Value, out requestPath)) { logger?.LogInformation($"Could not parse the path '{context.HttpContext.Request.Path.Value}' for the " + $"request into an rpc path. Skipping rpc router middleware."); return; } } if (!requestPath.TryRemoveBasePath(this.routeProvider.BaseRequestPath, out requestPath)) { logger?.LogTrace("Request did not match the base request path. Skipping rpc router."); return; } logger?.LogInformation($"Rpc request with route '{requestPath}' started."); string jsonString; if (context.HttpContext.Request.Body == null) { jsonString = null; } else { using (StreamReader streamReader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { try { jsonString = await streamReader.ReadToEndAsync(); } catch (TaskCanceledException ex) { throw new RpcCanceledRequestException("Cancelled while reading the request.", ex); } jsonString = jsonString.Trim(); } } IRpcRequestHandler requestHandler = context.HttpContext.RequestServices.GetRequiredService <IRpcRequestHandler>(); var routeContext = DefaultRouteContext.FromHttpContext(context.HttpContext, this.routeProvider); string responseJson = await requestHandler.HandleRequestAsync(requestPath, jsonString, routeContext); if (responseJson == null) { //No response required, but status code must be 204 context.HttpContext.Response.StatusCode = 204; context.MarkAsHandled(); return; } context.HttpContext.Response.ContentType = "application/json"; bool responseSet = false; string acceptEncoding = context.HttpContext.Request.Headers["Accept-Encoding"]; if (!string.IsNullOrWhiteSpace(acceptEncoding)) { IStreamCompressor compressor = context.HttpContext.RequestServices.GetService <IStreamCompressor>(); if (compressor != null) { string[] encodings = acceptEncoding.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string encoding in encodings) { bool haveType = Enum.TryParse(encoding, true, out CompressionType compressionType); if (!haveType) { continue; } context.HttpContext.Response.Headers.Add("Content-Encoding", new[] { encoding }); using (Stream responseStream = new MemoryStream(Encoding.UTF8.GetBytes(responseJson))) { compressor.Compress(responseStream, context.HttpContext.Response.Body, compressionType); } responseSet = true; break; } } } if (!responseSet) { await context.HttpContext.Response.WriteAsync(responseJson); } context.MarkAsHandled(); logger?.LogInformation("Rpc request complete"); } catch (Exception ex) { string errorMessage = "Unknown exception occurred when trying to process Rpc request. Marking route unhandled"; logger?.LogException(ex, errorMessage); context.MarkAsHandled(); } }
public ExternalBlob(IExternalBlobConnection connection, byte[] identifier, IStreamCompressor compression) : this(connection, identifier) { _compression = compression; }
public CompressedClob(byte[] data, Encoding encoding, IStreamCompressor compression) : this(data, encoding) { this.compression = compression; }
public CompressedBlob(byte[] data, IStreamCompressor compression) { if (data == null) throw new ArgumentNullException("data"); if (compression == null) throw new ArgumentNullException("compression", "Use ArrayBlob instead."); this.data = data; }