public void DispatchTransferred(SignalDispatch <TKey> signalDispatch) { string message = string.Format(MonitorMessages.DispatchTransferred , DateTime.Now.ToLongTimeString(), signalDispatch.CategoryId); Trace.WriteLine(message); }
//methods public virtual async Task <ProcessingResult> Send(SignalDispatch <TKey> item) { SlackDispatch <TKey> slackDispatch = (SlackDispatch <TKey>)item; //serialize payload var payload = new SlackPayload() { Channel = slackDispatch.Channel, Username = slackDispatch.Username, Text = slackDispatch.Text }; string payloadJson = JsonConvert.SerializeObject(payload); var data = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>("payload", payloadJson) }; //send payload using (var client = new HttpClient()) { HttpResponseMessage response = await client.PostAsync(_urlWithAccessToken, new FormUrlEncodedContent(data)); string responseString = await response.Content.ReadAsStringAsync(); bool completed = responseString == "ok"; if (!completed) { return(ProcessingResult.Fail); } } return(ProcessingResult.Success); }
protected virtual TemplateData DeserializeTemplateData(SignalDispatch <TKey> dispatch) { object templateDataObj = null; try { templateDataObj = JsonConvert.DeserializeObject(dispatch.TemplateData); } catch (Exception ex) { _logger.LogError(ex, SenderInternalMessages.Common_DeserializeError, nameof(dispatch.TemplateData), dispatch.TemplateData, nameof(SignalDispatch <TKey>), dispatch.SignalDispatchId); return(null); } Dictionary <string, string> templateDataDict = null; if (templateDataObj is Dictionary <string, string> ) { templateDataDict = (Dictionary <string, string>)templateDataObj; templateDataObj = null; } return(new TemplateData(templateDataDict, templateDataObj)); }
protected virtual bool ValidateRequiredProperties(SignalDispatch <TKey> signal, EventSettings <TKey> eventSettings) { if (eventSettings.ConsolidatorId == null) { return(false); } if (signal.CategoryId == null) { _logger.LogError(SenderInternalMessages.ConsolidationDispatchCommand_MissingArguments, nameof(signal.CategoryId), signal.SignalDispatchId); return(false); } if (signal.ReceiverSubscriberId == null) { _logger.LogError(SenderInternalMessages.ConsolidationDispatchCommand_MissingArguments, nameof(signal.ReceiverSubscriberId), signal.SignalDispatchId); return(false); } if (signal.DispatchTemplateId == null) { _logger.LogError(SenderInternalMessages.ConsolidationDispatchCommand_MissingArguments, nameof(signal.DispatchTemplateId), signal.SignalDispatchId); return(false); } return(true); }
public override void Update(SignalDispatch <TKey> item, TemplateData templateData) { var emailDispatch = (EmailDispatch <TKey>)item; emailDispatch.MessageSubject = FillTemplateProperty(SubjectProvider, SubjectTransformer, templateData); emailDispatch.MessageBody = FillTemplateProperty(BodyProvider, BodyTransformer, templateData); }
public override void Update(SignalDispatch <TKey> item, TemplateData templateData) { var dispatch = (StoredNotificationDispatch <TKey>)item; dispatch.MessageSubject = FillTemplateProperty(SubjectProvider, SubjectTransformer, templateData); dispatch.MessageBody = FillTemplateProperty(BodyProvider, BodyTransformer, templateData); }
public void DispatchSent(SignalDispatch <TKey> item, ProcessingResult sendResult, TimeSpan sendTime) { string message = string.Format(MonitorMessages.DispatchSent, DateTime.Now.ToLongTimeString(), sendResult, sendTime); Trace.WriteLine(message); }
/// <summary> /// Track SignalDispatches that are responsible for consolidation. /// Required even if single Sender instance is running and no lock is set in database. /// Tracking pending consolidations allows to choose only single consolidation root that will attach other dispatches to itself. /// </summary> /// <param name="signal"></param> /// <returns></returns> public virtual ConsolidationLock <TKey> GetOrAddLock(SignalDispatch <TKey> signal) { //Lock for signal group and this signal as ConsolidationRoot ConsolidationLock <TKey> groupLock = ToConsolidationLock(signal); bool isNewLock = _locksCache.AddIfUnique(groupLock); //Lock with same group key can be added in parallel //First added lock will be set ConsolidationRootId. groupLock = _locksCache.GetMatchingGroup(groupLock); bool isConsolidationRoot = EqualityComparer <TKey> .Default.Equals( groupLock.ConsolidationRootId, signal.SignalDispatchId); if (!isConsolidationRoot) { //Signal will not start consolidation, but will be attached to ConsolidationRoot return(groupLock); } if (!_settings.IsDbLockStorageEnabled) { return(groupLock); } if (isNewLock) { bool isDuplicate = _consolidationLockQueries.InsertOneHandleDuplicate(groupLock).Result; if (isDuplicate) { //get latest value with same group key to cache it //db can return null if some other process will clear ConsolidationLocks collection in the middle groupLock = _consolidationLockQueries.FindExistingMatch(groupLock).Result; _locksCache.ReplaceGroup(groupLock); } } if (groupLock == null) { return(null); } bool isLockedByCurrentSenderInstance = groupLock.LockedBy == _settings.LockedByInstanceId; bool isLockExpired = CheckIsExpired(groupLock, expireBeforehand: isLockedByCurrentSenderInstance); if (isLockExpired) { groupLock.LockedBy = _settings.LockedByInstanceId.Value; bool lockExtended = _consolidationLockQueries.ExtendLockTime(groupLock).Result; if (!lockExtended) { //get latest value with same group key to store it in cache //db can return null if some other process will clear ConsolidationLocks collection in the middle groupLock = _consolidationLockQueries.FindExistingMatch(groupLock).Result; } //update LockedSinceUtc or LockedSinceUtc with LockedBy _locksCache.ReplaceGroup(groupLock); } return(groupLock); }
//methods public virtual Task <ProcessingResult> Send(SignalDispatch <TKey> item) { string json = Serialize(item); string message = string.Format(MonitorMessages.TraceDispatcher_DispatchReceived , DateTime.Now.ToLongTimeString(), json); System.Diagnostics.Trace.WriteLine(message); return(Task.FromResult(ProcessingResult.Success)); }
public virtual void Fail(SignalDispatch <TKey> dispatch, DispatcherAvailability availability) { if (availability == DispatcherAvailability.Available) { return; } _failedAttemptsCount++; SetTimeoutEndUtc(); }
public override Task EnqueueDispatch(SignalDispatch <TKey> dispatch, SignalWriteConcern writeConcern = SignalWriteConcern.Default) { if (_isStarted == false) { ThrowStoppedInstanceError(); } return(base.EnqueueDispatch(dispatch, writeConcern)); }
//methods public virtual async Task <ProcessingResult> Send(SignalDispatch <TKey> item) { EmailDispatch <TKey> emailDispatch = (EmailDispatch <TKey>)item; MailMessage mailMessage = BuildMessage(emailDispatch); using (SmtpClient client = BuildSmtpClient()) { await client.SendMailAsync(mailMessage); } return(ProcessingResult.Success); }
//methods protected virtual ConsolidationLock <TKey> ToConsolidationLock(SignalDispatch <TKey> signal) { return(new ConsolidationLock <TKey> { CategoryId = signal.CategoryId.Value, DeliveryType = signal.DeliveryType, ReceiverSubscriberId = signal.ReceiverSubscriberId.Value, LockedBy = _settings.LockedByInstanceId, LockedSinceUtc = DateTime.UtcNow, ConsolidationRootId = signal.SignalDispatchId, ConsolidationRootSendDateUtc = signal.SendDateUtc }); }
//methods public virtual async Task <ProcessingResult> Send(SignalDispatch <TKey> item) { EmailDispatch <TKey> signal = (EmailDispatch <TKey>)item; using (var client = new AmazonSimpleEmailServiceClient(_credentials.AwsAccessKey, _credentials.AwsSecretKey, _credentials.RegionEndpoint)) { SendEmailRequest request = CreateAmazonRequest(signal); SendEmailResponse response = null; response = await client.SendEmailAsync(request); } return(ProcessingResult.Success); }
public void TraceDispatcher_SendTest() { var target = new TraceDispatcher <long>(); var item = new SignalDispatch <long> { DeliveryType = 1, CategoryId = 1, CreateDateUtc = DateTime.UtcNow, SendDateUtc = DateTime.UtcNow, }; ProcessingResult result = target.Send(item).Result; Assert.AreEqual(ProcessingResult.Success, result); }
//methods public virtual async Task <ProcessingResult> Send(SignalDispatch <TKey> item) { HttpDispatch <TKey> httpDispatch = (HttpDispatch <TKey>)item; HttpRequestMessage request = BuildRequest(httpDispatch); using (HttpClient httpClient = new HttpClient()) { HttpResponseMessage response = await httpClient.SendAsync(request); HandleResponse(item, response); } return(ProcessingResult.Success); }
protected virtual void Configure(IMapperConfigurationExpression configuration) { configuration.CreateMap <SignalBounce <long>, SignalBounceLong>(); configuration.CreateMap <SignalEvent <long>, SignalEventLong>(); configuration.CreateMap <StoredNotification <long>, StoredNotificationLong>(); configuration.CreateMap <SubscriberDeliveryTypeSettings <long>, SubscriberDeliveryTypeSettingsLong>(); configuration.CreateMap <SubscriberCategorySettings <long>, SubscriberCategorySettingsLong>(); configuration.CreateMap <SubscriberTopicSettings <long>, SubscriberTopicSettingsLong>(); configuration.CreateMap <SubscriberScheduleSettings <long>, SubscriberScheduleSettingsLong>(); configuration.CreateMap <EventSettings <long>, EventSettingsLong>(); configuration.CreateMap <SignalBounceLong, SignalBounce <long> >(); configuration.CreateMap <SignalEventLong, SignalEvent <long> >(); configuration.CreateMap <StoredNotificationLong, StoredNotification <long> >(); configuration.CreateMap <SubscriberDeliveryTypeSettingsLong, SubscriberDeliveryTypeSettings <long> >(); configuration.CreateMap <SubscriberCategorySettingsLong, SubscriberCategorySettings <long> >(); configuration.CreateMap <SubscriberTopicSettingsLong, SubscriberTopicSettings <long> >(); configuration.CreateMap <SubscriberScheduleSettingsLong, SubscriberScheduleSettings <long> >(); configuration.CreateMap <EventSettingsLong, EventSettings <long> >(); //Dispatch template configuration.CreateMap <DispatchTemplate <long>, DispatchTemplateLong>() .ForMember(d => d.DerivedEntityData, o => o.MapFrom <ToJsonValueResolver <DispatchTemplate <long>, DispatchTemplateLong> >()); configuration.CreateMap <DispatchTemplateLong, DispatchTemplate <long> >() .ConstructUsing((serialized, generic) => { DispatchTemplate <long> derivedInstance = (DispatchTemplate <long>)JsonConvert.DeserializeObject( serialized.DerivedEntityData, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects }); return(derivedInstance); }); //Dispatch configuration.CreateMap <SignalDispatch <long>, SignalDispatchLong>() .ForMember(d => d.DerivedEntityData, o => o.MapFrom <ToJsonValueResolver <SignalDispatch <long>, SignalDispatchLong> >()); configuration.CreateMap <SignalDispatchLong, SignalDispatch <long> >() .ConstructUsing((serialized, generic) => { SignalDispatch <long> derivedInstance = (SignalDispatch <long>)JsonConvert.DeserializeObject( serialized.DerivedEntityData, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects }); return(derivedInstance); }); }
//limitation methods public virtual void CountSendAttempt(SignalDispatch <TKey> dispatch, ProcessingResult result, DispatcherAvailability availability) { if (result == ProcessingResult.Success) { AvailableLimitCapacity--; LimitCounter.InsertTime(); Interrupter.Success(dispatch); } else if (result == ProcessingResult.Fail) { AvailableLimitCapacity--; LimitCounter.InsertTime(); Interrupter.Fail(dispatch, availability); } }
protected virtual ITemplateDataConsolidator MatchConsolidator(SignalDispatch <TKey> signal, int consolidatorId) { ITemplateDataConsolidator[] matched = _consolidators .Where(x => x.ConsolidatorId == consolidatorId) .ToArray(); if (matched.Length == 0) { _logger.LogError(SenderInternalMessages.Common_NoServiceWithKeyFound, typeof(ITemplateDataConsolidator), nameof(ITemplateDataConsolidator.ConsolidatorId), consolidatorId); } else if (matched.Length > 1) { _logger.LogError(SenderInternalMessages.Common_MoreThanOneServiceWithKeyFound, typeof(ITemplateDataConsolidator), nameof(ITemplateDataConsolidator.ConsolidatorId), consolidatorId); } return(matched.FirstOrDefault()); }
/// <summary> /// Find DispatchChannel matching a signal. /// </summary> /// <param name="signal"></param> /// <returns></returns> public virtual IDispatchChannel <TKey> Match(SignalDispatch <TKey> signal) { IDispatchChannel <TKey> channel = _channels.FirstOrDefault( p => p.DeliveryType == signal.DeliveryType); if (channel == null) { _logger.LogError(SenderInternalMessages.Common_NoServiceWithKeyFound, typeof(IDispatchChannel <TKey>), nameof(IDispatchChannel <TKey> .DeliveryType), signal.DeliveryType); } if (!channel.IsActive || channel.AvailableLimitCapacity == 0) { _logger.LogError(SenderInternalMessages.DispatchChannelRegistry_InactiveChannelRequested, signal.DeliveryType, channel.AvailableLimitCapacity); return(null); } return(channel); }
protected virtual string Serialize(SignalDispatch <TKey> item) { string json = "{}"; using (MemoryStream ms = new MemoryStream()) { Type itemType = item.GetType(); var ser = new DataContractJsonSerializer(itemType, new DataContractJsonSerializerSettings() { MaxItemsInObjectGraph = int.MaxValue }); ser.WriteObject(ms, item); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); byte[] msBytes = ms.ToArray(); json = Encoding.Default.GetString(msBytes); } return(json); }
public virtual async Task EnqueueDispatch(SignalDispatch <TKey> signalDispatch, SignalWriteConcern writeConcern) { writeConcern = _senderSettings.GetWriteConcernOrDefault(writeConcern); bool ensurePersisted = writeConcern == SignalWriteConcern.PersistentStorage; if (ensurePersisted) { if (_senderSettings.IsDbLockStorageEnabled) { signalDispatch.LockedBy = _senderSettings.LockedByInstanceId; signalDispatch.LockedSinceUtc = DateTime.UtcNow; } await _dispatchQueries.Insert(new List <SignalDispatch <TKey> > { signalDispatch }) .ConfigureAwait(false); } var signalWrapper = new SignalWrapper <SignalDispatch <TKey> >(signalDispatch, ensurePersisted); _dispatchQueue.Append(signalWrapper); _monitor.DispatchTransferred(signalDispatch); }
//methods public virtual Task <ProcessingResult> Send(SignalDispatch <TKey> item) { var signal = (StoredNotificationDispatch <TKey>)item; if (signal.ReceiverSubscriberId == null) { throw new NullReferenceException(string.Format(SenderInternalMessages.Common_MissingPropertyValue, nameof(signal.ReceiverSubscriberId), nameof(StoredNotificationDispatch <TKey>))); } var storedNotification = new StoredNotification <TKey> { MessageBody = signal.MessageBody, MessageSubject = signal.MessageSubject, CategoryId = signal.CategoryId, TopicId = signal.TopicId, SubscriberId = signal.ReceiverSubscriberId.Value, CreateDateUtc = DateTime.UtcNow }; _storedNotificationsFlushJob.Insert(storedNotification); return(Task.FromResult(ProcessingResult.Success)); }
//send methods public virtual ProcessingResult Send(SignalDispatch <TKey> dispatch) { return(Dispatcher.Send(dispatch).Result); }
public virtual void Fail(SignalDispatch <TKey> dispatch, DispatcherAvailability availability) { }
//methods public virtual void Success(SignalDispatch <TKey> dispatch) { }
public Task Dispatch(SignalDispatch <TKey> dispatch, SignalWriteConcern writeConcern = SignalWriteConcern.Default) { return(base.EnqueueDispatch(dispatch, writeConcern)); }
//methods public virtual void Success(SignalDispatch <TKey> dispatch) { _failedAttemptsCount = 0; _timeoutEndUtc = null; }
public void DispatchSent(SignalDispatch <TKey> item, ProcessingResult sendResult, TimeSpan sendTime) { Console.WriteLine(MonitorMessages.DispatchSent, DateTime.Now.ToLongTimeString(), sendResult, sendTime); }
public void DispatchTransferred(SignalDispatch <TKey> signalDispatch) { Console.WriteLine(MonitorMessages.DispatchTransferred , DateTime.Now.ToLongTimeString(), signalDispatch.CategoryId); }