aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio_22/Tango.Portal.Chat.Web/Services/AlertsQueryService.cs
blob: 6ecff5be96ecb344ca5396aae097e047b0dd5576 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using Azure.Data.Tables;
using Microsoft.Extensions.Options;
using Tango.Portal.Chat.Web.Models;

namespace Tango.Portal.Chat.Web.Services
{
    public sealed class AlertsQueryService
    {
        private readonly TableClient _tableClient;

        public AlertsQueryService(IOptions<AzureStorageOptions> options)
        {
            var tableServiceClient = new TableServiceClient(options.Value.ConnectionString);
            _tableClient = tableServiceClient.GetTableClient("AlertsQueries");
        }

        public async Task EnsureTableExistsAsync(CancellationToken cancellationToken = default)
        {
            await _tableClient.CreateIfNotExistsAsync(cancellationToken);
        }

        public async Task<List<AlertsQuery>> GetEnabledQueriesAsync(CancellationToken cancellationToken = default)
        {
            var queries = new List<AlertsQuery>();
            var now = DateTime.UtcNow;

            await foreach (var entity in _tableClient.QueryAsync<AlertsQuery>(
                filter: $"PartitionKey eq 'Queries' and Enable eq true and ExecutesOn le datetime'{now:yyyy-MM-ddTHH:mm:ss.fffZ}'",
                cancellationToken: cancellationToken))
            {
                queries.Add(entity);
            }

            return queries;
        }

        public async Task UpdateExecutionTimeAsync(AlertsQuery query, CancellationToken cancellationToken = default)
        {
            query.ExecutesOn = DateTime.UtcNow.AddMinutes(query.IntervalMinutes);
            await _tableClient.UpdateEntityAsync(query, query.ETag, cancellationToken: cancellationToken);
        }
    }
}