public async Task Subscribe(CancellationToken cancel) { byte[] buffer = new byte[1024 * 1024]; ArraySegment <byte> segment = new ArraySegment <byte>(buffer); ByteString currentRecord = await this.store.GetLastTransaction(); while (!cancel.IsCancellationRequested) { try { ClientWebSocket socket = new ClientWebSocket(); this.endpoint.Query = string.Format("from={0}", currentRecord.ToString()); logger.LogInformation("Connecting to {0}", this.endpoint.Uri); await socket.ConnectAsync(this.endpoint.Uri, cancel); while (true) { WebSocketReceiveResult result = await socket.ReceiveAsync(segment, cancel); if (result.MessageType == WebSocketMessageType.Close) { break; } ByteString record = new ByteString(buffer.Take(result.Count)); await store.AddTransactions(new[] { record }); currentRecord = new ByteString(MessageSerializer.ComputeHash(record.ToByteArray())); } } catch (Exception exception) { logger.LogError("Error in the stream subscriber: {0}", exception.ToString()); } await Task.Delay(TimeSpan.FromMinutes(1)); } }
public async Task Subscribe(CancellationToken cancel) { byte[] buffer = new byte[1024 * 1024]; ArraySegment <byte> segment = new ArraySegment <byte>(buffer); IServiceScopeFactory scopeFactory = services.GetService <IServiceScopeFactory>(); ILogger logger = services.GetRequiredService <ILogger>(); while (!cancel.IsCancellationRequested) { try { using (IServiceScope scope = scopeFactory.CreateScope()) { IStorageEngine storageEngine = scope.ServiceProvider.GetRequiredService <IStorageEngine>(); await storageEngine.Initialize(); ByteString currentRecord = await storageEngine.GetLastTransaction(); ClientWebSocket socket = new ClientWebSocket(); this.endpoint.Query = string.Format("from={0}", currentRecord.ToString()); logger.LogInformation("Connecting to {0}", this.endpoint.Uri); await socket.ConnectAsync(this.endpoint.Uri, cancel); while (true) { ByteString transaction; using (MemoryStream stream = new MemoryStream(1024)) { WebSocketReceiveResult result; do { result = await socket.ReceiveAsync(segment, cancel); if (result.MessageType == WebSocketMessageType.Close) { break; } stream.Write(segment.Array, segment.Offset, result.Count); } while (!result.EndOfMessage); stream.Seek(0, SeekOrigin.Begin); using (BinaryReader reader = new BinaryReader(stream)) { transaction = new ByteString(reader.ReadBytes((int)stream.Length)); } } await storageEngine.AddTransactions(new[] { transaction }); currentRecord = new ByteString(MessageSerializer.ComputeHash(transaction.ToByteArray())); } } } catch (Exception exception) { logger.LogError("Error in the stream subscriber: {0}", exception.ToString()); } await Task.Delay(TimeSpan.FromMinutes(1)); } }