private void processHeartBeat(object sender, MsgHandlerEventArgs args) { IConnection lnc; lock (mu) { lnc = nc; } if (lnc != null) { lnc.Publish(args.Message.Reply, null); if (heartbeatMonitor != null) { heartbeatMonitor.RegisterHeartbeat(); } } }
private void HandleMessage(object _, MsgHandlerEventArgs args) { try { _dbContext.DetachEverything(); var req = MintSender.Sender.Event.Sent.Parser.ParseFrom(args.Message.Data); if (req.Service != "core_poolfreezer") { return; } // find request var id = long.Parse(req.Id); var row = (from r in _dbContext.PoolFreezeRequest where r.Id == id select r).AsTracking().LastOrDefault(); if (row == null) { throw new Exception($"Row #{id} not found"); } // completed if (row.Status == EmissionRequestStatus.Requested) { row.SumTransaction = req.Transaction; row.Status = EmissionRequestStatus.Completed; row.TimeCompleted = DateTime.UtcNow; _dbContext.SaveChanges(); Logger.Information($"Emission request #{row.Id} completed"); } // reply var rep = new MintSender.Sender.Event.SentAck() { Success = true }; args.Message.ArrivalSubcription.Connection.Publish( args.Message.Reply, rep.ToByteArray() ); } catch (Exception e) { Logger.Error(e, $"Failed to process message"); } }
private void MessageHandler(object sender, MsgHandlerEventArgs e) { Core.Log.LibVerbose("Message received"); try { (var body, var correlationId, var name) = NATSQueueRawClient.GetFromRawMessageBody(e.Message.Data); var rMsg = new NATSQMessage { CorrelationId = correlationId, Body = body, Name = name }; Task.Run(() => EnqueueMessageToProcessAsync(ProcessingTaskAsync, rMsg)); } catch (Exception ex) { Core.Log.Write(ex); } }
private void CheckRecveivedAndValidHandler(object sender, MsgHandlerEventArgs args) { System.Console.WriteLine("Received msg."); if (compare(args.Message.Data, omsg) == false) { Assert.Fail("Messages are not equal."); } if (args.Message.ArrivalSubcription != asyncSub) { Assert.Fail("Subscriptions do not match."); } lock (mu) { received = true; Monitor.Pulse(mu); } }
private static void IndexProspect(object sender, MsgHandlerEventArgs e) { Console.WriteLine($"Received message, subject: {e.Message.Subject}"); var eventMessage = MessageHelper.FromData <ProspectSignedUpEvent>(e.Message.Data); Console.WriteLine($"Indexing prospect, signed up at: {eventMessage.SignedUpAt}; event ID: {eventMessage.CorrelationId}"); var prospect = new Documents.Prospect { CompanyName = eventMessage.Prospect.CompanyName, CountryName = eventMessage.Prospect.Country.CountryName, EmailAddress = eventMessage.Prospect.EmailAddress, FullName = $"{eventMessage.Prospect.FirstName} {eventMessage.Prospect.LastName}", RoleName = eventMessage.Prospect.Role.RoleName, SignUpDate = eventMessage.SignedUpAt }; Index.CreateDocument(prospect); Console.WriteLine($"Prospect indexed; event ID: {eventMessage.CorrelationId}"); }
private static void SaveProspect(object sender, MsgHandlerEventArgs e) { Console.WriteLine($"Received message, subject: {e.Message.Subject}"); var eventMessage = MessageHelper.FromData <ProspectSignedUpEvent>(e.Message.Data); Console.WriteLine($"Saving new prospect, signed up at: {eventMessage.SignedUpAt}; event ID: {eventMessage.CorrelationId}"); var prospect = eventMessage.Prospect; using (var context = new SignUpContext()) { //reload child objects: prospect.Country = context.Countries.Single(x => x.CountryCode == prospect.Country.CountryCode); prospect.Role = context.Roles.Single(x => x.RoleCode == prospect.Role.RoleCode); context.Prospects.Add(prospect); context.SaveChanges(); } Console.WriteLine($"Prospect saved. Prospect ID: {eventMessage.Prospect.ProspectId}; event ID: {eventMessage.CorrelationId}"); }
private static void HandleGoldData(object sender, MsgHandlerEventArgs args) { var logger = CreateLogger <Program>(); var message = args.Message; try { using var md5 = MD5.Create(); logger.LogInformation("Processing Gold Data"); var hash = Encoding.UTF8.GetString(md5.ComputeHash(message.Data)); var key = $"{message.Subject}-{hash}"; if (!IsDupedMessage(logger, key)) { OutgoingNatsConnection.Publish(goldDataDeduped, message.Data); } } catch (Exception ex) { logger.LogError(ex, "Error handling gold data"); } }
private void processAck(object sender, MsgHandlerEventArgs args) { PubAck pa = new PubAck(); try { ProtocolSerializer.unmarshal(args.Message.Data, pa); } catch (Exception) { // TODO: (cls) handle this... return; } PublishAck a = removeAck(pa.Guid); if (a != null) { a.InvokeHandler(pa.Guid, pa.Error); } }
private static void HandleMarketOrder(object sender, MsgHandlerEventArgs args) { var logger = CreateLogger <Program>(); var message = args.Message; try { var marketUpload = JsonConvert.DeserializeObject <MarketUpload>(Encoding.UTF8.GetString(message.Data)); List <MarketOrder> orderArray = new List <MarketOrder>(); logger.LogInformation($"Processing {marketUpload.Orders.Count} Market Orders - {DateTime.Now.ToLongTimeString()}"); foreach (var order in marketUpload.Orders) { // Hack since albion seems to be multiplying every price by 10000? order.UnitPriceSilver /= 10000; // Make sure all caerleon markets are registered with the same ID since they have the same contents if (order.LocationId == (ushort)Location.Caerleon2) { order.LocationId = (ushort)Location.Caerleon; } // Make the hash unique while also including anything that could change var hash = $"{order.Id}|{order.LocationId}|{order.Amount}|{order.UnitPriceSilver}|{order.Expires.ToString("s")}"; var key = $"{message.Subject}-{hash}"; if (!IsDupedMessage(logger, key)) { OutgoingNatsConnection.Publish(marketOrdersDeduped, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(order))); orderArray.Add(order); } } if (orderArray.Count > 0) { logger.LogInformation($"Found {orderArray.Count} New Market Orders - {DateTime.Now.ToLongTimeString()}"); OutgoingNatsConnection.Publish(marketOrdersDedupedBulk, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(orderArray))); } } catch (Exception ex) { logger.LogError(ex, "Error handling market order"); } }
public async void ObserveMsgWith <T>(object sender, MsgHandlerEventArgs e) where T : IMessageObserver { // deserialize the microservice msg that was embedded in the nats msg var microserviceMsg = e.Message.Data.ToMicroserviceMessage(); try { // create a new scope to handle the message in. this will create a new instance of the observer class per message using (var scope = _serviceScopeFactory.CreateScope()) { // create a new instance of the message handler var msgObserver = scope.ServiceProvider.GetService <T>(); // observe the message await msgObserver.ObserveAsync(microserviceMsg).ConfigureAwait(false); } } catch (Exception ex) { Log.Error(ex.GetBaseException().Message); } }
private void MutateItem(object sender, MsgHandlerEventArgs e) { Console.WriteLine($"Received message, subject: {e.Message.Subject}"); var eventMessage = MessageHelper.FromData <ItemSavedEvent>(e.Message.Data); Console.WriteLine($"Mutating item, event ID: {eventMessage.CorrelationId}"); try { using (var context = _serviceProvider.GetService <ToDoContext>()) { var todo = context.ToDos.Find(eventMessage.Item.ToDoId); todo.Item = "Write a nice review for Learn Docker in a Month of Lunches :)"; context.SaveChanges(); } Console.WriteLine($"Item mutated; ID: {eventMessage.Item.ToDoId}; event ID: {eventMessage.CorrelationId}"); } catch (Exception ex) { Console.WriteLine($"Mutation FAILED; event ID: {eventMessage.CorrelationId}; exception: {ex}"); } }
private static void SaveViewer(object sender, MsgHandlerEventArgs e) { Log.Debug("Received message, subject: {0}", e.Message.Subject); var eventMessage = MessageHelper.FromData <ViewerSignedUpEvent>(e.Message.Data); Log.Info("Saving new viewer, signed up at: {0}; event ID: {1}", eventMessage.SignedUpAt, eventMessage.CorrelationId); var viewer = eventMessage.Viewer; using (var context = new WebinarContext()) { //reload child objects: viewer.Country = context.Countries.Single(x => x.CountryCode == viewer.Country.CountryCode); viewer.Role = context.Roles.Single(x => x.RoleCode == viewer.Role.RoleCode); var interestCodes = viewer.Interests.Select(y => y.InterestCode); viewer.Interests = context.Interests.Where(x => interestCodes.Contains(x.InterestCode)).ToList(); context.Viewers.Add(viewer); context.SaveChanges(); } Log.Info("Viewer saved. Viewer ID: {0}; event ID: {1}", eventMessage.Viewer.ViewerId, eventMessage.CorrelationId); }
private static void SaveProspect(object sender, MsgHandlerEventArgs e) { _EventCounter.Labels(_Host, "received").Inc(); Console.WriteLine($"Received message, subject: {e.Message.Subject}"); var eventMessage = MessageHelper.FromData <ProspectSignedUpEvent>(e.Message.Data); Console.WriteLine($"Saving new prospect, signed up at: {eventMessage.SignedUpAt}; event ID: {eventMessage.CorrelationId}"); var prospect = eventMessage.Prospect; try { SaveProspect(prospect); Console.WriteLine($"Prospect saved. Prospect ID: {eventMessage.Prospect.ProspectId}; event ID: {eventMessage.CorrelationId}"); _EventCounter.Labels(_Host, "processed").Inc(); } catch (Exception ex) { Console.WriteLine($"Save prospect FAILED, email address: {prospect.EmailAddress}, ex: {ex}"); _EventCounter.Labels(_Host, "failed").Inc(); } }
/// <summary> /// /// </summary> /// <param name="args"></param> /// <param name="context"></param> /// <param name="connection"></param> /// <returns></returns> public async Task ProcessResponse(MsgHandlerEventArgs args, HttpContext context, IConnection connection) { if (args.Message.Reply != null) { _log.LogTrace($"Create response to reply {args.Message.Reply}"); if (context.Response.Body.CanSeek) { context.Response.Body.Position = 0; } var response = new HttpResponseMessage { StatusCode = (HttpStatusCode)context.Response.StatusCode, Content = new StreamContent(context.Response.Body), }; response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(context.Response.ContentType); response.Content.Headers.ContentLength = context.Response.Body.Length; foreach (var header in context.Response.Headers) { response.Headers.TryAddWithoutValidation(header.Key, header.Value.AsEnumerable()); } var content = new HttpMessageContent(response); var bytes = await content.ReadAsByteArrayAsync(); _log.LogTrace($"Send response to reply {args.Message.Reply}"); connection.Publish(args.Message.Reply, bytes); _log.LogTrace($"Response to reply {args.Message.Reply} sended"); } else { _log.LogTrace($"reply is empty, response not be sended. request url {context.Request.GetDisplayUrl()}"); } }
private void processPingResponse(object sender, MsgHandlerEventArgs args) { if (IsNoResponseMsg(args.Message)) { return; } // No data can be a valid message var data = args.Message.Data; if (data?.Length > 0) { var pingResp = new PingResponse(); try { ProtocolSerializer.unmarshal(data, pingResp); } catch { // Ignore this as an invalid protocol message. return; } string err = pingResp.Error; if (err?.Length > 0) { closeDueToPing(new StanException(err)); return; } } lock (pingLock) { pingOut = 0; } }
private void IndexProspect(object sender, MsgHandlerEventArgs e) { if (_EventCounter != null) { _EventCounter.Labels(HANDLER_NAME, "processed").Inc(); } Console.WriteLine($"Received message, subject: {e.Message.Subject}"); var eventMessage = MessageHelper.FromData <ProspectSignedUpEvent>(e.Message.Data); Console.WriteLine($"Indexing prospect, signed up at: {eventMessage.SignedUpAt}; event ID: {eventMessage.CorrelationId}"); var prospect = new Documents.Prospect { CompanyName = eventMessage.Prospect.CompanyName, CountryName = eventMessage.Prospect.Country.CountryName, EmailAddress = eventMessage.Prospect.EmailAddress, FullName = $"{eventMessage.Prospect.FirstName} {eventMessage.Prospect.LastName}", RoleName = eventMessage.Prospect.Role.RoleName, SignUpDate = eventMessage.SignedUpAt }; try { _index.CreateDocument(prospect); Console.WriteLine($"Prospect indexed; event ID: {eventMessage.CorrelationId}"); } catch (Exception ex) { Console.WriteLine($"Index prospect FAILED, email address: {prospect.EmailAddress}, ex: {ex}"); if (_EventCounter != null) { _EventCounter.Labels(HANDLER_NAME, "failed").Inc(); } } }
public async void HandleMsgWith <T>(object sender, MsgHandlerEventArgs e) where T : IMessageHandler { // store the replyTo subject var replyTo = e.Message.Reply; // deserialize the microservice msg that was embedded in the nats msg var microserviceMsg = e.Message.Data.ToMicroserviceMessage(); MicroserviceMessage responseMsg = null; try { // create a new scope to handle the message in. this will create a new instance of the handler class per message using (var scope = _serviceScopeFactory.CreateScope()) { // create a new instance of the message handler var msgHandler = scope.ServiceProvider.GetService <T>(); // handle the message responseMsg = await msgHandler.HandleAsync(microserviceMsg).ConfigureAwait(false); } } catch (Exception ex) { microserviceMsg.ErrorMessage = ex.GetBaseException().Message; microserviceMsg.ResponseStatusCode = 500; Log.Error(microserviceMsg.ErrorMessage); } finally { // send the NATS message (with the response) back to the calling client if (null != responseMsg && !string.IsNullOrWhiteSpace(replyTo)) { NatsHelper.Publish(replyTo, responseMsg); } } }
private void PubSub(object sender, MsgHandlerEventArgs args) { this.WriteToTextbox(Encoding.UTF8.GetString(args.Message.Data)); }
protected abstract void OnMessageReceived(object sender, MsgHandlerEventArgs e);
private void incrReceivedMessageHandler(object sender, MsgHandlerEventArgs args) { Interlocked.Increment(ref received); }
public async Task <HttpContext> Parse(MsgHandlerEventArgs args, IFeatureCollection features) { var context = await _converter.Create(args.Message.Data, features, !_option.ForceResponseStream && args.Message.Reply == null); return(context); }
private void AuditItem(object sender, MsgHandlerEventArgs e) { var eventMessage = MessageHelper.FromData <NewItemEvent>(e.Message.Data); Console.WriteLine($"AUDIT @ {eventMessage.Item.DateAdded}: {eventMessage.Item.Item}"); }
private static void HandleMarketHistory(object sender, MsgHandlerEventArgs args) { var logger = CreateLogger <Program>(); var message = args.Message; try { using var context = new ConfiguredContext(); var upload = JsonConvert.DeserializeObject <MarketHistoriesUpload>(Encoding.UTF8.GetString(message.Data)); var aggregationType = TimeAggregation.QuarterDay; if (upload.Timescale == Timescale.Day) { aggregationType = TimeAggregation.Hourly; } // Do not use the last history timestamp because it is a partial period // It is not guaranteed to be updated so it can appear that the count in the period was way lower var marketHistoryUpdates = upload.MarketHistories.OrderBy(x => x.Timestamp).SkipLast(1); var dbHistories = context.MarketHistories.Where(x => x.ItemTypeId == upload.AlbionIdString && x.Location == upload.LocationId && x.QualityLevel == upload.QualityLevel && marketHistoryUpdates.Select(x => new DateTime((long)x.Timestamp)).Contains(x.Timestamp) && x.AggregationType == aggregationType) .ToDictionary(x => x.Timestamp); foreach (var marketHistoryUpdate in marketHistoryUpdates) { var historyDate = new DateTime((long)marketHistoryUpdate.Timestamp); dbHistories.TryGetValue(historyDate, out var dbHistory); if (dbHistory == null) { dbHistory = new MarketHistoryDB { AggregationType = aggregationType, ItemTypeId = upload.AlbionIdString, Location = upload.LocationId, QualityLevel = upload.QualityLevel, ItemAmount = marketHistoryUpdate.ItemAmount, SilverAmount = marketHistoryUpdate.SilverAmount, Timestamp = historyDate }; context.MarketHistories.Add(dbHistory); } else { dbHistory.ItemAmount = marketHistoryUpdate.ItemAmount; dbHistory.SilverAmount = marketHistoryUpdate.SilverAmount; context.MarketHistories.Update(dbHistory); } updatedHistoryCounter++; } context.SaveChanges(); logger.LogInformation(GetLogMessage(marketHistoryUpdates.Count(), "Market Histories", updatedHistoryCounter)); } catch (Exception ex) { logger.LogError(ex, "Error handling market history"); } }
private void onMessage(object sender, MsgHandlerEventArgs e) { Msg msg = e.Message; String subj = msg.Subject; Service.Log.Trace("Q=> {0}: {1}", subj, Encoding.UTF8.GetString(msg.Data)); Resource.Service.With(Resource, async() => { if (callback == null) { return; } QueryRequest qr; try { QueryRequestDto reqInput = JsonConvert.DeserializeObject <QueryRequestDto>(Encoding.UTF8.GetString(msg.Data)); if (String.IsNullOrEmpty(reqInput.Query)) { Service.OnError("Missing query in query request {0}", Resource.ResourceName); new QueryRequest(Resource, msg).RawResponse(ResService.ResponseMissingQuery); return; } qr = new QueryRequest(Resource.CloneWithQuery(reqInput.Query), msg); } catch (Exception ex) { Service.OnError("Error deserializing query request {0}: {1}", Resource.ResourceName, ex.Message); new QueryRequest(Resource, msg).RawResponse(ResService.ResponseBadRequest); return; } try { await callback(qr); } catch (ResException ex) { if (!qr.Replied) { // If a reply isn't sent yet, send an error response, // as throwing a ResException within a query callback // is considered valid behaviour. qr.Error(new ResError(ex)); return; } Service.OnError("Error handling query request {0}: {1} - {2}", qr.ResourceName, ex.Code, ex.Message); } catch (Exception ex) { if (!qr.Replied) { qr.Error(new ResError(ex)); } // Write to log as only ResExceptions are considered valid behaviour. Service.OnError("Error handling query request {0}: {1}", qr.ResourceName, ex.Message); return; } if (qr.Replied) { return; } if (qr.Events.Count == 0) { qr.RawResponse(ResService.ResponseNoQueryEvents); } else { qr.Result(new QueryResponseDto(qr.Events)); } }); }
private void HandleMessage(object _, MsgHandlerEventArgs args) { try { _dbContext.DetachEverything(); var evt = Eth2Gold.Event.OrderDeposited.Parser.ParseFrom(args.Message.Data); // find request var id = (long)evt.ExternalID; var row = (from r in _dbContext.BuyGoldEth where r.Id == id select r) .AsTracking() .LastOrDefault() ; BigInteger ethAmount = BigInteger.Zero; try { if (row == null) { throw new Exception("Order not found by given external id"); } if (!BigInteger.TryParse(evt.EthAmount, out ethAmount) || ethAmount <= 0) { throw new Exception("Failed to parse ETH amount"); } } catch (Exception e) { Logger.Error(e, $"Failed to process order #{id}"); return; } if (row.Status == BuySellGoldRequestStatus.Confirmed) { long?dealGoldPrice = row.GoldRateCents; long?dealEthPrice = row.EthRateCents; // use fresh prices (see BuyGoldCrypto()) if ((DateTime.UtcNow - row.TimeCreated) >= TimeSpan.FromHours(1)) { dealGoldPrice = null; dealEthPrice = null; } var estimation = CoreLogic.Finance.Estimation.BuyGoldCrypto( services: _services, ethereumToken: TradableCurrency.Eth, fiatCurrency: row.ExchangeCurrency, cryptoAmount: ethAmount, knownGoldRateCents: dealGoldPrice, knownCryptoRateCents: dealEthPrice ).Result; // price provider failed if (!estimation.Allowed) { Logger.Error($"Failed to process order #{id}, estimation failed"); return; } try { // history var finHistory = new DAL.Models.UserFinHistory() { Status = UserFinHistoryStatus.Completed, Type = UserFinHistoryType.GoldDeposit, Source = "ETH", SourceAmount = TextFormatter.FormatTokenAmountFixed(ethAmount, TokensPrecision.Ethereum), Destination = "GOLD", DestinationAmount = TextFormatter.FormatTokenAmountFixed(estimation.ResultGoldAmount, TokensPrecision.Sumus), Comment = "", TimeCreated = DateTime.UtcNow, UserId = row.UserId, }; _dbContext.UserFinHistory.Add(finHistory); _dbContext.SaveChanges(); row.Status = BuySellGoldRequestStatus.Success; row.TimeCompleted = DateTime.UtcNow; row.RelFinHistoryId = finHistory.Id; _dbContext.SaveChanges(); var ok = CoreLogic.Finance.SumusWallet.Refill(_services, row.UserId, estimation.ResultGoldAmount.FromSumus(), SumusToken.Gold).Result; if (!ok) { Logger.Error($"Deposit request #{row.Id} completed but wallet not refilled with {estimation.ResultGoldAmount.FromSumus()} GOLD"); } else { Logger.Information($"Deposit request #{row.Id} completed"); } } catch (Exception e) { Logger.Error(e, $"Failed to process order #{id}, while saving to DB"); return; } } // reply args.Message.ArrivalSubcription.Connection.Publish( args.Message.Reply, new Eth2Gold.Event.OrderDepositedAck().ToByteArray() ); } catch (Exception e) { Logger.Error(e, $"Failed to process message"); } }
private void OnIncomingMessage(object _, MsgHandlerEventArgs e) => InvokeObservers(e.Message);
private void HandleMessage(object _, MsgHandlerEventArgs args) { try { _dbContext.DetachEverything(); var request = MintSender.Watcher.Event.Refill.Parser.ParseFrom(args.Message.Data); if (request.Service != "core_gold_deposit") { return; } // find wallet var row = (from r in _dbContext.UserSumusWallet where r.PublicKey == request.PublicKey select r) .AsNoTracking() .LastOrDefault() ; if (row == null) { throw new Exception($"Wallet #{request.PublicKey} not found"); } // parse amount var ok = decimal.TryParse(request.Amount, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var amount); if (!ok) { throw new Exception($"Failed to parse amount"); } // truncate amount = amount.ToSumus().FromSumus(); // parse token ok = Common.Sumus.Token.ParseToken(request.Token, out var token); if (!ok) { throw new Exception($"Failed to parse token"); } // history var finHistory = new DAL.Models.UserFinHistory() { Status = UserFinHistoryStatus.Completed, Type = UserFinHistoryType.GoldDeposit, Source = "", SourceAmount = "", Destination = "GOLD", DestinationAmount = TextFormatter.FormatTokenAmountFixed(amount), Comment = "", TimeCreated = DateTime.UtcNow, UserId = row.UserId, }; _dbContext.UserFinHistory.Add(finHistory); _dbContext.SaveChanges(); // refill if (!CoreLogic.Finance.SumusWallet.Refill(_services, row.UserId, amount, token).Result) { throw new Exception($"Failed to process refilling"); } // reply args.Message.ArrivalSubcription.Connection.Publish( args.Message.Reply, new MintSender.Watcher.Event.RefillAck() { Success = true }.ToByteArray() ); } catch (Exception e) { Logger.Error(e, $"Failed to process message"); // reply args.Message.ArrivalSubcription.Connection.Publish( args.Message.Reply, new MintSender.Watcher.Event.RefillAck() { Success = false, Error = e.ToString() }.ToByteArray() ); } }