Monday, June 17, 2024

Webhook to Subscribe to Event Grid System Topics in Azure Storage Account

In this post, let's see how we can subscribe to Event Grid System Topics in Azure Storage AccountEvent Grid System Topics are events published by Azure services. We can configure different subscribers, but in this case for the demo purposes, I am using a Web Hook, which will basically be an Azure Function running locally. 

The Azure Function is referencing the package: Microsoft.Azure.Functions.Worker.Extensions.EventGrid and has the following simple HTTP Trigger.
using Azure.Messaging.EventGrid;
using Azure.Messaging.EventGrid.SystemEvents;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using System.Net;

namespace FunctionApp1;

public class HttpFunction
{
    private readonly ILogger<HttpFunction> _logger;

    public HttpFunction(ILogger<HttpFunctionlogger)
    {
        _logger = logger;
    }

    [Function(nameof(EventWebhook))]
    public async Task<HttpResponseDataEventWebhook(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestData req)
    {
        _logger.LogInformation("C# HTTP trigger function processed a request.");

        using var memoryStream = new MemoryStream();
        await req.Body.CopyToAsync(memoryStream);

        EventGridEvent[] eventGridEvents = EventGridEvent.ParseMany(BinaryData.FromBytes(memoryStream.ToArray()));

        foreach (EventGridEvent eventGridEvent in eventGridEvents)
        {
            // Handle system events
            if (eventGridEvent.TryGetSystemEventData(out object eventData)
                && eventData is SubscriptionValidationEventData subscriptionValidationEventData)
            {
                // Do any additional validation (as required) and then return back ValidationCode
                var responseContent = new
                {
                    ValidationResponse = subscriptionValidationEventData.ValidationCode
                };

                HttpResponseData responseData = req.CreateResponse(HttpStatusCode.OK);
                await responseData.WriteAsJsonAsync(responseContent);
                return responseData;
            }
        }

        // TODO: Handle custom events

        return req.CreateResponse(HttpStatusCode.Accepted);
    }
}
Note: I am running the Azure Function in a Dev Tunnel, so the locally running Azure Function can be accessed over the Internet (which is very important when creating an Event Subscription).
Azure Function Local Dev tunnel
Now let's create the Event Subscription in the Storage Account.
Storage Account: Events
Now I am selecting Web Hook Event Subscription.
Create Event Subscription
There I have given names for the Event Subscription and the Event Grid System Topic. Now I am configuring for which storage account events I need to subscribe to by selecting Event Types
Event Types
Here for the demo purposes, I am only interested in Blob Created and Blob Deleted.

Now lastly we need to configure the Web Hook endpoint.
Web Hook Configuration
Here I am providing the publicly accessible endpoint of the EventWebhook I have in Azure Function. 
Web Hook Configuration
Finally, I am clicking Create on Create Event Subscription page.

We can see Azure is sending a request to the Webhook to make sure it's reachable and valid. This is important, otherwise, event subscription deployment will fail.
System Event
I am handling the system event and returning the response. 

And now I can see, the Event Subscription is successfully deployed.
Event Subscription Deployed Successfully
Now to test this functionality, I am creating a new blob in my target storage account. I can see Azure is sending a BlobCreated event.
BlobCreated Event
And when a Blob is Deleted, Azure sends a BlobDeleted event.
BlobDeleted Event
Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment