| | | 1 | | using Elsa.AI.Abstractions.Contracts; |
| | | 2 | | using Elsa.AI.Abstractions.Models; |
| | | 3 | | using Elsa.AI.Persistence.EFCore.Entities; |
| | | 4 | | using Elsa.AI.Persistence.EFCore.Helpers; |
| | | 5 | | using Microsoft.Extensions.Logging; |
| | | 6 | | |
| | | 7 | | namespace Elsa.AI.Persistence.EFCore.Stores; |
| | | 8 | | |
| | 4 | 9 | | public class EFCoreAIAuditSink(AIDbContext dbContext, ILogger<EFCoreAIAuditSink> logger) : IAIAuditEventHandler |
| | | 10 | | { |
| | | 11 | | public async ValueTask RecordAsync(AIAuditEvent auditEvent, CancellationToken cancellationToken = default) |
| | | 12 | | { |
| | 2 | 13 | | await RecordManyAsync([auditEvent], cancellationToken); |
| | 2 | 14 | | } |
| | | 15 | | |
| | | 16 | | public async ValueTask RecordManyAsync(IReadOnlyCollection<AIAuditEvent> auditEvents, CancellationToken cancellation |
| | | 17 | | { |
| | 4 | 18 | | if (auditEvents.Count == 0) |
| | 0 | 19 | | return; |
| | | 20 | | |
| | | 21 | | try |
| | | 22 | | { |
| | 19 | 23 | | foreach (var auditEvent in auditEvents) |
| | 6 | 24 | | dbContext.AuditRecords.Add(ToRecord(auditEvent)); |
| | | 25 | | |
| | 3 | 26 | | await dbContext.SaveChangesAsync(cancellationToken); |
| | 3 | 27 | | dbContext.ChangeTracker.Clear(); |
| | 3 | 28 | | } |
| | 1 | 29 | | catch (Exception e) when (ExceptionFilters.IsNonFatal(e)) |
| | | 30 | | { |
| | 1 | 31 | | dbContext.ChangeTracker.Clear(); |
| | 1 | 32 | | logger.LogWarning(e, "Failed to persist {AuditEventCount} AI audit event(s)", auditEvents.Count); |
| | 1 | 33 | | } |
| | 4 | 34 | | } |
| | | 35 | | |
| | | 36 | | private static AIAuditRecord ToRecord(AIAuditEvent auditEvent) => |
| | 6 | 37 | | new() |
| | 6 | 38 | | { |
| | 6 | 39 | | Id = auditEvent.Id, |
| | 6 | 40 | | TenantId = auditEvent.TenantId, |
| | 6 | 41 | | ActorId = auditEvent.ActorId, |
| | 6 | 42 | | ConversationId = auditEvent.ConversationId, |
| | 6 | 43 | | ProposalId = auditEvent.ProposalId, |
| | 6 | 44 | | ToolInvocationId = auditEvent.ToolInvocationId, |
| | 6 | 45 | | Type = auditEvent.Type, |
| | 6 | 46 | | Timestamp = auditEvent.Timestamp, |
| | 6 | 47 | | TraceId = auditEvent.TraceId, |
| | 6 | 48 | | Summary = auditEvent.Summary, |
| | 6 | 49 | | Data = auditEvent.Data.ToJsonString() |
| | 6 | 50 | | }; |
| | | 51 | | } |