/
EventHubTrigger.cs
52 lines (49 loc) · 2.25 KB
/
EventHubTrigger.cs
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
44
45
46
47
48
49
50
51
52
using Microsoft.Azure.EventHubs;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.ServiceBus;
using Polly;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace OrderedEventHubs
{
public static class EventHubTrigger
{
private static ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(Environment.GetEnvironmentVariable("Redis"));
private static IDatabase db = redis.GetDatabase();
[FunctionName("EventHubTrigger")]
public static async Task RunAsync(
[EventHubTrigger(eventHubName: "events", Connection = "EventHub")] EventData[] eventDataSet,
TraceWriter log,
[Queue("deadletter")] IAsyncCollector<string> queue)
{
log.Info($"Triggered batch of size {eventDataSet.Length}");
foreach (var eventData in eventDataSet) {
var result = await Policy
.Handle<Exception>()
.RetryAsync(3, onRetryAsync: async (exception, retryCount, context) =>
{
await db.ListRightPushAsync("events:" + context["partitionKey"], (string)context["counter"] + $"CAUGHT{retryCount}");
})
.ExecuteAndCaptureAsync(async () =>
{
if (int.Parse((string)eventData.Properties["counter"]) % 100 == 0)
{
throw new SystemException("Some Exception");
}
await db.ListRightPushAsync("events:" + eventData.Properties["partitionKey"], (string)eventData.Properties["counter"]);
},
new Dictionary<string, object>() { { "partitionKey", eventData.Properties["partitionKey"] }, { "counter", eventData.Properties["counter"] } });
if(result.Outcome == OutcomeType.Failure)
{
await db.ListRightPushAsync("events:" + eventData.Properties["partitionKey"], (string)eventData.Properties["counter"] + "FAILED");
await queue.AddAsync(Encoding.UTF8.GetString(eventData.Body.Array));
await queue.FlushAsync();
}
}
}
}
}