-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create webhook messages when events are saved (#1753)
- Loading branch information
Showing
41 changed files
with
255 additions
and
59 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 49 additions & 0 deletions
49
TeachingRecordSystem/src/TeachingRecordSystem.Core/Services/Webhooks/EventMapperRegistry.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
using System.Diagnostics.CodeAnalysis; | ||
using TeachingRecordSystem.Core.ApiSchema.V3; | ||
|
||
namespace TeachingRecordSystem.Core.Services.Webhooks; | ||
|
||
public class EventMapperRegistry | ||
{ | ||
private sealed record MapperKey(Type EventType, string CloudEventType, string ApiVersion); | ||
|
||
private sealed record MapperValue(Type MapperType, Type DataType); | ||
|
||
private readonly Dictionary<MapperKey, MapperValue> _mappers = DiscoverMappers(); | ||
|
||
public Type? GetMapperType(Type eventType, string cloudEventType, string apiVersion, [MaybeNull] out Type dataType) | ||
{ | ||
if (_mappers.TryGetValue(new(eventType, cloudEventType, apiVersion), out var result)) | ||
{ | ||
dataType = result.DataType; | ||
return result.MapperType; | ||
} | ||
|
||
dataType = null; | ||
return null; | ||
} | ||
|
||
private static Dictionary<MapperKey, MapperValue> DiscoverMappers() | ||
{ | ||
var mapperTypes = typeof(EventMapperRegistry).Assembly.GetTypes() | ||
.Where(t => t.IsPublic && !t.IsAbstract && t.GetInterfaces().Any(i => | ||
i.IsGenericType && i.GetGenericTypeDefinition().IsAssignableTo(typeof(IEventMapper<,>)))); | ||
|
||
var mappers = new Dictionary<MapperKey, MapperValue>(); | ||
|
||
foreach (var type in mapperTypes) | ||
{ | ||
var mapperTypeArgs = type.GetInterface(typeof(IEventMapper<,>).Name)!.GetGenericArguments(); | ||
var eventType = mapperTypeArgs[0]; | ||
var dataType = mapperTypeArgs[1]; | ||
|
||
var cloudEventType = (string)dataType.GetProperty("CloudEventType")!.GetValue(null)!; | ||
|
||
var version = type.Namespace!.Split('.').SkipWhile(ns => ns != "V3").Skip(1).First().TrimStart('V'); | ||
|
||
mappers.Add(new MapperKey(eventType, cloudEventType, version), new MapperValue(type, dataType)); | ||
} | ||
|
||
return mappers; | ||
} | ||
} |
115 changes: 115 additions & 0 deletions
115
...hingRecordSystem/src/TeachingRecordSystem.Core/Services/Webhooks/WebhookMessageFactory.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization.Metadata; | ||
using Microsoft.Extensions.Caching.Memory; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using TeachingRecordSystem.Core.ApiSchema.V3; | ||
using TeachingRecordSystem.Core.DataStore.Postgres; | ||
using TeachingRecordSystem.Core.DataStore.Postgres.Models; | ||
using TeachingRecordSystem.Core.Infrastructure.Json; | ||
|
||
namespace TeachingRecordSystem.Core.Services.Webhooks; | ||
|
||
public class WebhookMessageFactory(EventMapperRegistry eventMapperRegistry, IClock clock, IMemoryCache memoryCache) | ||
{ | ||
private static readonly TimeSpan _webhookEndpointsCacheDuration = TimeSpan.FromMinutes(1); | ||
|
||
private static readonly JsonSerializerOptions _serializerOptions = | ||
new JsonSerializerOptions(JsonSerializerDefaults.Web) | ||
{ | ||
TypeInfoResolver = new DefaultJsonTypeInfoResolver() | ||
{ | ||
Modifiers = | ||
{ | ||
Modifiers.OptionProperties | ||
} | ||
} | ||
}; | ||
|
||
public async Task<IEnumerable<WebhookMessage>> CreateMessagesAsync( | ||
TrsDbContext dbContext, | ||
EventBase @event, | ||
IServiceProvider serviceProvider) | ||
{ | ||
var endpoints = await memoryCache.GetOrCreateAsync( | ||
CacheKeys.EnabledWebhookEndpoints(), | ||
async e => | ||
{ | ||
e.SetAbsoluteExpiration(_webhookEndpointsCacheDuration); | ||
return await dbContext.WebhookEndpoints.AsNoTracking().Where(e => e.Enabled).ToArrayAsync(); | ||
}); | ||
|
||
var endpointCloudEventTypeVersions = endpoints! | ||
.SelectMany(e => | ||
e.CloudEventTypes.Select(t => (Version: e.ApiVersion, CloudEventType: t, e.WebhookEndpointId))) | ||
.GroupBy(t => (t.Version, t.CloudEventType), t => t.WebhookEndpointId) | ||
.ToDictionary(g => g.Key, g => g.AsEnumerable()); | ||
|
||
var messages = new List<WebhookMessage>(); | ||
|
||
foreach (var (version, cloudEventType) in endpointCloudEventTypeVersions.Keys) | ||
{ | ||
var mapperType = eventMapperRegistry.GetMapperType(@event.GetType(), cloudEventType, version, out var dataType); | ||
if (mapperType is null) | ||
{ | ||
continue; | ||
} | ||
|
||
var payload = await MapEventAsync(mapperType, dataType!); | ||
if (payload is null) | ||
{ | ||
continue; | ||
} | ||
|
||
var serializedPayload = JsonSerializer.SerializeToElement(payload, _serializerOptions); | ||
|
||
messages.AddRange(endpointCloudEventTypeVersions[(version, cloudEventType)].Select(epId => | ||
{ | ||
var id = Guid.NewGuid(); | ||
|
||
return new WebhookMessage | ||
{ | ||
WebhookMessageId = id, | ||
WebhookEndpointId = epId, | ||
CloudEventId = id.ToString(), | ||
CloudEventType = cloudEventType, | ||
Timestamp = clock.UtcNow, | ||
ApiVersion = version, | ||
Data = serializedPayload, | ||
NextDeliveryAttempt = clock.UtcNow, | ||
Delivered = null, | ||
DeliveryAttempts = [], | ||
DeliveryErrors = [] | ||
}; | ||
})); | ||
} | ||
|
||
return messages; | ||
|
||
Task<object?> MapEventAsync(Type mapperType, Type dataType) | ||
{ | ||
var mapper = ActivatorUtilities.CreateInstance(serviceProvider, mapperType); | ||
|
||
var eventType = @event.GetType(); | ||
|
||
var wrappedMapper = (IEventMapper)ActivatorUtilities.CreateInstance( | ||
serviceProvider, | ||
typeof(WrappedMapper<,>).MakeGenericType(eventType, dataType), | ||
mapper); | ||
|
||
return wrappedMapper.MapEventAsync(@event); | ||
} | ||
} | ||
|
||
private interface IEventMapper | ||
{ | ||
Task<object?> MapEventAsync(EventBase @event); | ||
} | ||
|
||
private class WrappedMapper<TEvent, TData>(IEventMapper<TEvent, TData> innerMapper) : IEventMapper | ||
where TEvent : EventBase | ||
where TData : IWebhookMessageData | ||
{ | ||
public async Task<object?> MapEventAsync(EventBase @event) => | ||
await innerMapper.MapEventAsync((TEvent)@event); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.