Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand on Audited Members #776

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/Http/Wolverine.Http.Marten/AggregateAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
using Marten;
using Marten.Events;
using Microsoft.AspNetCore.Http;
using Wolverine.Configuration;
using Wolverine.Http.CodeGen;
using Wolverine.Logging;
using Wolverine.Marten;
using Wolverine.Marten.Codegen;
using Wolverine.Marten.Publishing;
Expand Down Expand Up @@ -78,6 +77,10 @@ public override Variable Modify(HttpChain chain, ParameterInfo parameter, IConta
chain.Middleware.Add(new EventStoreFrame());
var loader = typeof(LoadAggregateFrame<>).CloseAndBuildAs<Frame>(this, AggregateType!);
chain.Middleware.Add(loader);
var auditedMembersNotAlreadyPresent = AuditedMember.GetAllFromType(AggregateType).Where(member => !chain.AuditedMembers
.Select(m => m.MemberName)
.Contains(member.MemberName)).ToList();
chain.Middleware.Add(new LoggerBeginScopeWithAuditForAggregateFrame(chain, container, auditedMembersNotAlreadyPresent, loader.Creates.Single()));

// Use the active document session as an IQuerySession instead of creating a new one
chain.Method.TrySetArgument(new Variable(typeof(IQuerySession), sessionCreator.ReturnVariable!.Usage));
Expand Down
39 changes: 39 additions & 0 deletions src/Http/Wolverine.Http/Logging/LoggingPolicies.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

using JasperFx.CodeGeneration;
using JasperFx.CodeGeneration.Frames;
using Lamar;
using Wolverine.Configuration;
using Wolverine.Logging;

namespace Wolverine.Http.Logging;

public class AuditLoggingPolicy : IHttpPolicy
{
public void Apply(IReadOnlyList<HttpChain> chains, GenerationRules rules, IContainer container)
=> new Wolverine.Logging.AuditLoggingPolicy().Apply(chains, rules, container);
}

public class AddConstantsToLoggingContextPolicy<TMessage> : IHttpPolicy
{
readonly (string, object)[] _loggingConstants;

public AddConstantsToLoggingContextPolicy(params (string, object)[] loggingConstants)
{
_loggingConstants = loggingConstants;
}
public void Apply(IReadOnlyList<HttpChain> chains, GenerationRules rules, IContainer container)
=> new Wolverine.Logging.AddConstantsToLoggingContextPolicy<TMessage>(_loggingConstants).Apply(chains, rules, container);
}

public static class WolverineHttpOptionsExtensions
{
public static void AddLoggingConstantsFor<TMessage>(this WolverineHttpOptions options, params (string, object)[] kvp)
{
options.Policies.Add(new AddConstantsToLoggingContextPolicy<TMessage>(kvp));
}

public static void AddAuditLogging(this WolverineHttpOptions options, params (string, object)[] kvp)
{
options.Policies.Add(new AuditLoggingPolicy());
}
}
9 changes: 6 additions & 3 deletions src/Persistence/Wolverine.Marten/AggregateHandlerAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Marten.Schema;
using Wolverine.Attributes;
using Wolverine.Configuration;
using Wolverine.Logging;
using Wolverine.Marten.Codegen;
using Wolverine.Marten.Publishing;
using Wolverine.Runtime.Handlers;
Expand Down Expand Up @@ -75,9 +76,7 @@ public override void Modify(IChain chain, GenerationRules rules, IContainer cont
AggregateType ??= DetermineAggregateType(chain);
AggregateIdMember = DetermineAggregateIdMember(AggregateType, CommandType);
VersionMember = DetermineVersionMember(CommandType);



var sessionCreator = MethodCall.For<OutboxedSessionFactory>(x => x.OpenSession(null!));
chain.Middleware.Add(sessionCreator);

Expand All @@ -89,7 +88,11 @@ public override void Modify(IChain chain, GenerationRules rules, IContainer cont
chain.Middleware.Add(new MissingAggregateCheckFrame(AggregateType, CommandType, AggregateIdMember,
loader.ReturnVariable!));
}

var auditedMembersNotAlreadyPresent = AuditedMember.GetAllFromType(AggregateType)
.Where(member => !chain.AuditedMembers
.Select(m => m.MemberName)
.Contains(member.MemberName)).ToList();
chain.Middleware.Add(new LoggerBeginScopeWithAuditForAggregateFrame(chain, container, auditedMembersNotAlreadyPresent, loader.ReturnVariable!));
// Use the active document session as an IQuerySession instead of creating a new one
firstCall.TrySetArgument(new Variable(typeof(IQuerySession), sessionCreator.ReturnVariable!.Usage));

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TestingSupport;
using Wolverine.Attributes;
using Wolverine.Logging;
using Wolverine.Runtime.Handlers;
using Xunit;
using Xunit.Abstractions;

namespace CoreTests.Compilation;

public class handler_with_logged_audit_members
{
private readonly ITestOutputHelper _output;

public handler_with_logged_audit_members(ITestOutputHelper output)
{
_output = output;
}

[Fact]
public async Task can_compile()
{
using var host = await WolverineHost.ForAsync(o => o.AddAuditLogging());

var bus = host.Services.GetRequiredService<IMessageBus>();
await bus.InvokeAsync(new SomeMessage());

var graph = host.Services.GetRequiredService<HandlerGraph>();
var chain = graph.ChainFor<SomeMessage>();

_output.WriteLine(chain.SourceCode);
}
}

public class SomeMessage
{
[Audit]public Guid Id { get; set; } = Guid.NewGuid();
[Audit]public string SomeString { get; set; } = "test";
}

public class SomeMessageHandler
{
public void Handle(SomeMessage itemCreated, ILogger logger)
{
logger.LogInformation("Some message id {Id}", itemCreated.Id);
}
}
18 changes: 3 additions & 15 deletions src/Wolverine/Configuration/Chain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ public IEnumerable<Type> ServiceDependencies(IContainer container, IReadOnlyList
/// <param name="heading"></param>
public void Audit(MemberInfo member, string? heading = null)
{
AuditedMembers.Add(new AuditedMember(member, heading ?? member.Name,
member.Name.SplitPascalCase().Replace(" ", ".").ToLowerInvariant()));
AuditedMembers.Add(AuditedMember.Create(member, heading));
}

private bool isConfigureMethod(MethodInfo method)
Expand All @@ -85,20 +84,9 @@ private bool isConfigureMethod(MethodInfo method)

protected void applyAuditAttributes(Type type)
{
foreach (var property in type.GetProperties())
foreach (var auditedMember in AuditedMember.GetAllFromType(type))
{
if (property.TryGetAttribute<AuditAttribute>(out var ratt))
{
Audit(property, ratt.Heading);
}
}

foreach (var field in type.GetFields())
{
if (field.TryGetAttribute<AuditAttribute>(out var ratt))
{
Audit(field, ratt.Heading);
}
AuditedMembers.Add(auditedMember);
}
}

Expand Down
28 changes: 27 additions & 1 deletion src/Wolverine/Logging/AuditedMember.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.Reflection;
using JasperFx.Core.Reflection;
using Wolverine.Attributes;

namespace Wolverine.Logging;

Expand All @@ -8,4 +10,28 @@ namespace Wolverine.Logging;
/// </summary>
/// <param name="Member"></param>
/// <param name="OpenTelemetryName"></param>
public record AuditedMember(MemberInfo Member, string MemberName, string OpenTelemetryName);
public record AuditedMember(MemberInfo Member, string MemberName, string OpenTelemetryName)
{
public static IEnumerable<AuditedMember> GetAllFromType(Type type)
{
foreach (var property in type.GetProperties())
{
if (property.TryGetAttribute<AuditAttribute>(out var att))
{
yield return Create(property, att.Heading);
}
}

foreach (var field in type.GetFields())
{
if (field.TryGetAttribute<AuditAttribute>(out var att))
{
yield return Create(field, att.Heading);
}
}
}
public static AuditedMember Create(MemberInfo member, string? heading) => new(
member,
heading ?? member.Name,
member.Name.ToTelemetryFriendly());
}
98 changes: 98 additions & 0 deletions src/Wolverine/Logging/LoggerBeginScopeWithAuditFrame.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System.Diagnostics;
using JasperFx.CodeGeneration;
using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
using JasperFx.Core.Reflection;
using Lamar;
using Microsoft.Extensions.Logging;
using Wolverine.Configuration;

namespace Wolverine.Logging;

public abstract class LoggerBeginScopeWithAuditBaseFrame : SyncFrame
{
private readonly Type? _inputType;
private readonly List<Variable> _loggers = [];
private readonly IEnumerable<Type> _loggerTypes;

protected LoggerBeginScopeWithAuditBaseFrame(IChain chain, IContainer container, IReadOnlyList<AuditedMember> auditedMembers, Variable? auditedVariable)
{
_loggerTypes = chain.ServiceDependencies(container, Type.EmptyTypes).Where(type => type.CanBeCastTo<ILogger>());
AuditedMembers = auditedMembers;
_inputType = chain.InputType()!;
AuditedVariable = auditedVariable;
}

protected Variable? AuditedVariable;
protected Variable? LoggingContext;
protected readonly IReadOnlyList<AuditedMember> AuditedMembers;

public override IEnumerable<Variable> FindVariables(IMethodVariables chain)
{
foreach (var loggerType in _loggerTypes)
{
var logger = chain.FindVariable(loggerType);
_loggers.Add(logger);
yield return logger;
}
LoggingContext = chain.FindVariable(typeof(LoggingContext));
if (AuditedVariable is not null || _inputType is null)
{
yield break;
}
AuditedVariable = chain.FindVariable(_inputType);
yield return AuditedVariable;
}

public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
{
if (AuditedMembers.Count > 0 && _loggers.Count > 0 && AuditedVariable is not null)
{
writer.WriteComment("Adding audited members to log context");
writer.Write($"{LoggingContext!.Usage}.{nameof(Logging.LoggingContext.AddRange)}({string.Join(", ", AuditedMembers.Select(member => $"(\"{member.MemberName}\", {AuditedVariable!.Usage}.{member.Member.Name})"))});");
writer.WriteComment("Beginning logging scopes for new context");
foreach (var logger in _loggers)
{
writer.Write(
$"using var {createRandomVariable("disposable")} = {logger.Usage}.{nameof(ILogger.BeginScope)}({LoggingContext!.Usage});");
}
}
GenerateAdditionalCode(method, writer, _loggers);
Next?.GenerateCode(method, writer);
}

protected virtual void GenerateAdditionalCode(GeneratedMethod method, ISourceWriter writer, IEnumerable<Variable> loggerVariables)
{
}
static string createRandomVariable(string prefix) => $"{prefix}_{Guid.NewGuid().ToString().Replace('-', '_')}";
}

public class LoggerBeginScopeWithAuditFrame : LoggerBeginScopeWithAuditBaseFrame
{
public LoggerBeginScopeWithAuditFrame(IChain chain, IContainer container)
: base(chain, container, chain.AuditedMembers.AsReadOnly(), null)
{
}
}

public class LoggerBeginScopeWithAuditForAggregateFrame : LoggerBeginScopeWithAuditBaseFrame
{
public LoggerBeginScopeWithAuditForAggregateFrame(IChain chain, IContainer container, IReadOnlyList<AuditedMember> members, Variable variable)
: base(chain, container, members, variable)
{
}

protected override void GenerateAdditionalCode(GeneratedMethod method, ISourceWriter writer, IEnumerable<Variable> loggerVariables)
{
if (AuditedMembers.Count == 0)
{
return;
}
writer.WriteComment("Application-specific Open Telemetry auditing");
foreach (var member in AuditedMembers)
{
writer.WriteLine(
$"{typeof(Activity).FullNameInCode()}.{nameof(Activity.Current)}?.{nameof(Activity.SetTag)}(\"{member.OpenTelemetryName}\", {AuditedVariable!.Usage}.{member.Member.Name});");
}
}
}
Loading
Loading