public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default) { try { _logger?.LogInformation($"{nameof(AzureServiceBusTopicLiveness)} is checking the Azure Topic."); var topicClient = new TopicClient(_connectionString, _topicName); var scheduledMessageId = await topicClient.ScheduleMessageAsync( new Message(Encoding.UTF8.GetBytes(TEST_MESSAGE)), new DateTimeOffset(DateTime.UtcNow).AddHours(2)); await topicClient.CancelScheduledMessageAsync(scheduledMessageId); _logger?.LogInformation($"The {nameof(AzureServiceBusTopicLiveness)} check success."); return(LivenessResult.Healthy()); } catch (Exception ex) { _logger?.LogWarning($"The {nameof(AzureServiceBusTopicLiveness)} check fail for {_connectionString} with the exception {ex.ToString()}."); return(LivenessResult.UnHealthy(ex)); } }
/// <summary> /// This thing has exactly 2 obligations: /// 1: Cancel old callback /// 2: Create new callback /// </summary> /// <param name="dbWorkshop"></param> /// <param name="eventDate"></param> /// <param name="incomingWorkshop"></param> /// <returns></returns> public async Task ScheduleCallback(Workshop dbWorkshop, string eventDate, Workshop incomingWorkshop) { if (dbWorkshop != null && !WorkshopHelpers.TimeHasChanged(dbWorkshop, incomingWorkshop)) { var callbackExits = dbWorkshop.callbackMessageSequenceNumber != null; if (callbackExits) { // No time has changed; Nothing to do here ¯\_(ツ)_/¯ return; } } var beginDate = ParseTime(eventDate, incomingWorkshop.begintime).ToUniversalTime(); var scheduledEnqueueTimeUtc = beginDate.AddMinutes(-15); if (beginDate < DateTime.UtcNow || scheduledEnqueueTimeUtc < DateTime.UtcNow) { // Guess someone edited an old workshop _logger.LogInformation("Time was in the past"); return; } var topicClient = new TopicClient(_serviceBusConnection, "wakeuptimer", RetryPolicy.Default); if (dbWorkshop?.callbackMessageSequenceNumber is { } oldSequenceNumber) { try { await topicClient.CancelScheduledMessageAsync(oldSequenceNumber); } catch (Exception e) { _logger.LogError(e, "Error while trying to cancel event"); } } incomingWorkshop.uniqueStateId = Guid.NewGuid(); var msg = new Message { ScheduledEnqueueTimeUtc = scheduledEnqueueTimeUtc.DateTime, Body = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(new CallbackMessage { UniqueStateId = incomingWorkshop.uniqueStateId, Date = beginDate.DateTime })) }; var seq = await topicClient.ScheduleMessageAsync(msg, scheduledEnqueueTimeUtc); incomingWorkshop.callbackMessageSequenceNumber = seq; _logger.LogInformation($"Enqueued new callback message at {scheduledEnqueueTimeUtc}"); }
public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { try { var topicClient = new TopicClient(_connectionString, _topicName); var scheduledMessageId = await topicClient.ScheduleMessageAsync( new Message(Encoding.UTF8.GetBytes(TEST_MESSAGE)), new DateTimeOffset(DateTime.UtcNow).AddHours(2)); await topicClient.CancelScheduledMessageAsync(scheduledMessageId); return(HealthCheckResult.Healthy()); } catch (Exception ex) { return(new HealthCheckResult(context.Registration.FailureStatus, exception: ex)); } }
/// <summary> /// Method to run Health Check for Service Bus /// </summary> /// <param name="serviceKey"></param> /// <param name="value"></param> /// <returns></returns> public LightHealth.HealthCheck HealthCheck(string serviceKey, string value) { try { if (_topics.Count > 0) { foreach (KeyValuePair <MethodInfo, TopicAttribute> item in _topics) { if (!string.IsNullOrEmpty(item.Value.TopicName.ToString())) { TopicClient topicClient = new TopicClient(GetConnection(item), item.Value.TopicName, RetryPolicy.Default); var scheduledMessageId = topicClient.ScheduleMessageAsync( new Message(Encoding.UTF8.GetBytes("HealthCheckTestMessage")), new DateTimeOffset(DateTime.UtcNow).AddHours(2)); topicClient.CancelScheduledMessageAsync(scheduledMessageId.Result); } } } if (_queues.Count > 0) { foreach (KeyValuePair <MethodInfo, QueueAttribute> item in _queues) { if (!string.IsNullOrEmpty(item.Value.QueueName.ToString())) { QueueClient queueReceiver = new QueueClient(GetConnection(item), item.Value.QueueName, ReceiveMode.ReceiveAndDelete); var scheduledMessageId = queueReceiver.ScheduleMessageAsync( new Message(Encoding.UTF8.GetBytes("HealthCheckTestMessage")), new DateTimeOffset(DateTime.UtcNow).AddHours(2)); queueReceiver.CancelScheduledMessageAsync(scheduledMessageId.Result); } } } return(LightHealth.HealthCheck.Healthy); } catch { return(LightHealth.HealthCheck.Unhealthy); } }
public async Task <(string, bool)> IsHealthy(HttpContext context, bool isDevelopment, CancellationToken cancellationToken = default) { try { var topicClient = new TopicClient(_connectionString, _topicName); var scheduledMessageId = await topicClient.ScheduleMessageAsync( new Message(Encoding.UTF8.GetBytes(TEST_MESSAGE)), new DateTimeOffset(DateTime.UtcNow).AddHours(2) ); await topicClient.CancelScheduledMessageAsync(scheduledMessageId); return(BeatPulseKeys.BEATPULSE_HEALTHCHECK_DEFAULT_OK_MESSAGE, true); } catch (Exception ex) { var message = !isDevelopment?string.Format(BeatPulseKeys.BEATPULSE_HEALTHCHECK_DEFAULT_ERROR_MESSAGE, Name) : $"Exception {ex.GetType().Name} with message ('{ex.Message}')"; return(message, false); } }
static void Main(string[] args) { Parser.Default.ParseArguments <Options>(args) .WithParsed( options => { var connectionStringBuilder = new ServiceBusConnectionStringBuilder(options.ConnectionString); var topicClient = new TopicClient(connectionStringBuilder); foreach (var sequenceNumber in options.SequenceNumbers) { try { topicClient.CancelScheduledMessageAsync(sequenceNumber).GetAwaiter().GetResult(); } catch (MessageNotFoundException e) { Console.WriteLine(e.Message); } } }); }
private static Func <ValueTask <HealthCheckResult> > CheckServiceBusTopicConnectivity(string name, TopicClient topicClient) { return(async() => { var result = true; try { var id = await topicClient.ScheduleMessageAsync(HealthMessage, HealthMessageTestSchedule).ConfigureAwait(false); await topicClient.CancelScheduledMessageAsync(id); } catch (Exception ex) { Logger.ErrorException($"{name} failed.", ex); result = false; } return result ? HealthCheckResult.Healthy($"OK. '{topicClient.Path}/{topicClient.TopicName}' is available.") : HealthCheckResult.Unhealthy($"Failed. '{topicClient.Path}/{topicClient.TopicName}' is unavailable."); }); }
public Task CancelScheduledSend(long sequenceNumber) { return(_topicClient.CancelScheduledMessageAsync(sequenceNumber)); }