|
| 1 | +using Azure.Storage.Queues; |
| 2 | +using Microsoft.Azure.Functions.Worker; |
| 3 | +using Microsoft.EntityFrameworkCore; |
| 4 | +using Microsoft.Extensions.Logging; |
| 5 | +using NHS.MESH.Client.Contracts.Services; |
| 6 | +using ServiceLayer.Mesh.Data; |
| 7 | +using ServiceLayer.Mesh.Models; |
| 8 | + |
| 9 | +namespace ServiceLayer.Mesh.Functions |
| 10 | +{ |
| 11 | + public class DiscoveryFunction |
| 12 | + { |
| 13 | + private readonly ILogger _logger; |
| 14 | + private readonly IMeshInboxService _meshInboxService; |
| 15 | + private readonly ServiceLayerDbContext _serviceLayerDbContext; |
| 16 | + private readonly QueueClient _queueClient; |
| 17 | + |
| 18 | + public DiscoveryFunction(ILogger<DiscoveryFunction> logger, IMeshInboxService meshInboxService, ServiceLayerDbContext serviceLayerDbContext, QueueClient queueClient) |
| 19 | + { |
| 20 | + _logger = logger; |
| 21 | + _meshInboxService = meshInboxService; |
| 22 | + _serviceLayerDbContext = serviceLayerDbContext; |
| 23 | + _queueClient = queueClient; |
| 24 | + } |
| 25 | + |
| 26 | + [Function("DiscoveryFunction")] |
| 27 | + public async Task Run([TimerTrigger("%DiscoveryTimerExpression%")] TimerInfo myTimer) |
| 28 | + { |
| 29 | + _logger.LogInformation($"DiscoveryFunction started at: {DateTime.Now}"); |
| 30 | + |
| 31 | + var mailboxId = Environment.GetEnvironmentVariable("BSSMailBox") |
| 32 | + ?? throw new InvalidOperationException($"Environment variable 'BSSMailBox' is not set or is empty."); |
| 33 | + |
| 34 | + var response = await _meshInboxService.GetMessagesAsync(mailboxId); |
| 35 | + |
| 36 | + _queueClient.CreateIfNotExists(); |
| 37 | + |
| 38 | + foreach (var messageId in response.Response.Messages) |
| 39 | + { |
| 40 | + using var transaction = await _serviceLayerDbContext.Database.BeginTransactionAsync(); |
| 41 | + |
| 42 | + var existing = await _serviceLayerDbContext.MeshFiles |
| 43 | + .AnyAsync(f => f.FileId == messageId); |
| 44 | + |
| 45 | + if (!existing) |
| 46 | + { |
| 47 | + _serviceLayerDbContext.MeshFiles.Add(new MeshFile |
| 48 | + { |
| 49 | + FileId = messageId, |
| 50 | + FileType = MeshFileType.NbssAppointmentEvents, |
| 51 | + MailboxId = mailboxId, |
| 52 | + Status = MeshFileStatus.Discovered, |
| 53 | + FirstSeenUtc = DateTime.UtcNow, |
| 54 | + LastUpdatedUtc = DateTime.UtcNow |
| 55 | + }); |
| 56 | + |
| 57 | + await _serviceLayerDbContext.SaveChangesAsync(); |
| 58 | + await transaction.CommitAsync(); |
| 59 | + |
| 60 | + _queueClient.SendMessage(messageId); |
| 61 | + } |
| 62 | + else |
| 63 | + { |
| 64 | + await transaction.RollbackAsync(); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments