Skip to content
Merged
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
18 changes: 18 additions & 0 deletions user-management/CodeAnalysis.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(MSBuildProjectExtension)' == '.csproj' ">
<EnableNETAnalyzers>true</EnableNETAnalyzers>
</PropertyGroup>
<ItemGroup Condition=" '$(MSBuildProjectExtension)' == '.csproj' ">
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="9.0.0" />
</ItemGroup>
<PropertyGroup Condition=" '$(MSBuildProjectExtension)' == '.csproj' ">
<AnalysisMode>All</AnalysisMode>
<AnalysisLevel>9.0</AnalysisLevel>
<_SkipUpgradeNetAnalyzersNuGetWarning>false</_SkipUpgradeNetAnalyzersNuGetWarning>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
<!-- CA2007 is calling .ConfigureAwait(false), which isn't required for non-libraries -->
<NoWarn>$(NoWarn);CA2007</NoWarn>
</PropertyGroup>
</Project>
15 changes: 15 additions & 0 deletions user-management/Directory.build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project>
<PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<!-- Configure code analysis. -->
<AnalysisLevel>latest</AnalysisLevel>
<AnalysisMode>All</AnalysisMode>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>
<Import Project="$(MSBuildThisFileDirectory)\CodeAnalysis.props"
Condition=" '$(SkipCodeAnalysis)' != 'True' " />
</Project>
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Stickerlandia.UserManagement.Core;
using Stickerlandia.UserManagement.Core.Outbox;

namespace Stickerlandia.UserManagement.Agnostic;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2025 Datadog, Inc.

using System.Text;
// Catching generic exceptions is not recommended, but in this case we want to catch all exceptions so that a failure in outbox processing does not crash the application.
#pragma warning disable CA1031

using System.Text.Json;
using Confluent.Kafka;
using Datadog.Trace;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Saunter.Attributes;
using Stickerlandia.UserManagement.Core.Observability;
using Stickerlandia.UserManagement.Core;
using Stickerlandia.UserManagement.Core.StickerClaimedEvent;

Expand All @@ -22,18 +25,17 @@ public class KafakStickerClaimedWorker(
ProducerConfig producerConfig)
: IMessagingWorker
{
private readonly ProducerConfig _producerConfig = producerConfig;
private const string topic = "users.stickerClaimed.v1";
private const string dlqTopic = "users.stickerClaimed.v1.dlq";

[Channel("users.stickerClaimed.v1")]
[SubscribeOperation(typeof(StickerClaimedEventV1))]
private async Task<bool> ProcessMessageAsync(StickerClaimedEventHandler handler,
private async Task<bool> ProcessMessageAsync(StickerClaimedHandler handler,
ConsumeResult<string, string> consumeResult)
{
using var processSpan = Tracer.Instance.StartActive($"process users.stickerClaimed.v1");

logger.LogInformation("Received message: {body}", consumeResult.Message.Value);
Log.ReceivedMessage(logger, "kafka");

var evtData = JsonSerializer.Deserialize<StickerClaimedEventV1>(consumeResult.Message.Value);

Expand All @@ -45,7 +47,7 @@ private async Task<bool> ProcessMessageAsync(StickerClaimedEventHandler handler,
}
catch (InvalidUserException ex)
{
logger.LogWarning("Invalid user in sticker claimed event: {Message}", ex.Message);
Log.InvalidUser(logger, ex);

SendToDLQ(consumeResult, evtData);
}
Expand All @@ -62,17 +64,17 @@ private void SendToDLQ(ConsumeResult<string, string> consumeResult, StickerClaim
(deliveryReport) =>
{
if (deliveryReport.Error.Code != ErrorCode.NoError)
logger.LogError($"Failed to deliver message: {deliveryReport.Error.Reason}");
Log.MessageDeliveryFailure(logger, deliveryReport.Error.Reason, null);
else
logger.LogWarning($"Produced event to topic {dlqTopic}");
Log.MessageSentToDlq(logger, "", null);
});

producer.Flush(TimeSpan.FromSeconds(10));
}

public Task StartAsync()
{
logger.LogInformation("Starting Kafka processor");
Log.StartingMessageProcessor(logger, "kafka");

return Task.CompletedTask;
}
Expand All @@ -84,12 +86,12 @@ public async Task PollAsync(CancellationToken stoppingToken)
return;

using var scope = serviceScopeFactory.CreateScope();
var handler = scope.ServiceProvider.GetRequiredService<StickerClaimedEventHandler>();
var handler = scope.ServiceProvider.GetRequiredService<StickerClaimedHandler>();

try
{
using var consumer = new ConsumerBuilder<string, string>(consumerConfig)
.SetErrorHandler((_, e) => logger.LogError("Kafka error: {Error}", e.Reason))
.SetErrorHandler((_, e) => Log.MessageProcessingException(logger, e.Reason, null))
.Build();

consumer.Subscribe(topic);
Expand All @@ -107,16 +109,16 @@ public async Task PollAsync(CancellationToken stoppingToken)
}
catch (ConsumeException ex)
{
logger.LogError(ex, "Error consuming message");
Log.MessageProcessingException(logger, "Error consuming message", ex);
}
catch (OperationCanceledException)
{
// This is expected when the token is canceled
logger.LogInformation("Polling canceled");
Log.TokenCancelled(logger);
}
catch (Exception ex)
{
logger.LogError(ex, "Error processing message");
Log.MessageProcessingException(logger, "Error consuming message", ex);
}
finally
{
Expand All @@ -126,7 +128,8 @@ public async Task PollAsync(CancellationToken stoppingToken)
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create Kafka consumer");
Log.FailureStartingWorker(logger, "kafka", ex);
throw;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Datadog.Trace;
using Microsoft.Extensions.Logging;
using Saunter.Attributes;
using Stickerlandia.UserManagement.Core.Observability;
using Stickerlandia.UserManagement.Core;
using Stickerlandia.UserManagement.Core.RegisterUser;

Expand All @@ -20,19 +21,21 @@ public class KafkaEventPublisher(ProducerConfig config, ILogger<KafkaEventPublis
[PublishOperation(typeof(UserRegisteredEvent))]
public async Task PublishUserRegisteredEventV1(UserRegisteredEvent userRegisteredEvent)
{
ArgumentNullException.ThrowIfNull(userRegisteredEvent, nameof(userRegisteredEvent));

var cloudEvent = new CloudEvent(CloudEventsSpecVersion.V1_0)
{
Id = Guid.NewGuid().ToString(),
Source = new Uri("https://stickerlandia.com"),
Type = userRegisteredEvent.EventName,
Time = DateTime.UtcNow,
Data = userRegisteredEvent,
Data = userRegisteredEvent
};
await this.Publish(cloudEvent);

await Publish(cloudEvent);
}

private Task Publish(CloudEvent cloudEvent)
private async Task Publish(CloudEvent cloudEvent)
{
var activeSpan = Tracer.Instance.ActiveScope?.Span;
IScope? processScope = null;
Expand All @@ -41,42 +44,58 @@ private Task Publish(CloudEvent cloudEvent)
{
if (activeSpan != null)
{
processScope = Tracer.Instance.StartActive($"publish {cloudEvent.Type}", new SpanCreationSettings()
processScope = Tracer.Instance.StartActive($"publish {cloudEvent.Type}", new SpanCreationSettings
{
Parent = activeSpan.Context
});

cloudEvent.SetAttributeFromString("traceparent", $"00-{activeSpan.TraceId}-{activeSpan.SpanId}[01");
}

var formatter = new JsonEventFormatter<UserRegisteredEvent>();
var data = formatter.EncodeBinaryModeEventData(cloudEvent);

using var producer = new ProducerBuilder<string, string>(config).Build();

try
{
var deliveryReport = await producer.ProduceAsync(cloudEvent.Type,
new Message<string, string> { Key = cloudEvent.Id!, Value = Encoding.UTF8.GetString(data.Span) },
default);

producer.Produce(cloudEvent.Type, new Message<string, string> { Key = cloudEvent.Id!, Value = Encoding.UTF8.GetString(data.Span) },
(deliveryReport) =>
if (deliveryReport.Status == PersistenceStatus.PossiblyPersisted) {
// Handle potential timeout errors
throw new MessageProcessingException("Kafka message possibly persisted, but not confirmed.");
}
else if (deliveryReport.Status == PersistenceStatus.NotPersisted) {
// Handle message not persisted errors.
throw new MessageProcessingException($"Message not persisted: {deliveryReport.TopicPartitionOffset}");
}
}
catch (ProduceException<string, string> ex)
{
switch (ex.Error.Code)
{
if (deliveryReport.Error.Code != ErrorCode.NoError) {
logger.LogError($"Failed to deliver message: {deliveryReport.Error.Reason}");
}
else {
logger.LogInformation($"Produced event to topic {cloudEvent.Type}");
}
});

case ErrorCode.ClusterAuthorizationFailed:
throw new MessageProcessingException("Cluster authorization failed", ex);
case ErrorCode.BrokerNotAvailable:
throw new MessageProcessingException("Broker not available", ex);
default:
throw new MessageProcessingException("Error publishing messages", ex);
}
}

producer.Flush(TimeSpan.FromSeconds(10));
}
catch (Exception ex)
{
logger.LogError(ex, "Failure publishing message");
Log.MessagePublishingError(logger, "Error publishing message", ex);
processScope?.Span.SetException(ex);
throw;
}
finally
{
processScope?.Close();
}

return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,15 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using Stickerlandia.UserManagement.Core;

namespace Stickerlandia.UserManagement.Agnostic;

public class MicrosoftIdentityAuthService(
ILogger<MicrosoftIdentityAuthService> logger,
IOpenIddictApplicationManager applicationManager,
IOpenIddictScopeManager scopeManager,
UserManagementDbContext dbContext,
UserManager<PostgresUserAccount> userManager) : IAuthService
{
public async Task<ClaimsIdentity?> VerifyClient(string clientId)
Expand All @@ -40,7 +35,7 @@ public class MicrosoftIdentityAuthService(
{
// Allow the "name" claim to be stored in both the access and identity tokens
// when the "profile" scope was granted (by calling principal.SetScopes(...)).
OpenIddictConstants.Claims.Name when claim.Subject.HasScope(OpenIddictConstants.Permissions.Scopes
OpenIddictConstants.Claims.Name when claim.Subject!.HasScope(OpenIddictConstants.Permissions.Scopes
.Profile)
=> [OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken],

Expand Down Expand Up @@ -78,7 +73,7 @@ OpenIddictConstants.Claims.Name when claim.Subject.HasScope(OpenIddictConstants.
identity.AddClaim(new Claim(OpenIddictConstants.Claims.Name, user.Id));
identity.AddClaim(new Claim(OpenIddictConstants.Claims.Subject, user.Id));
identity.AddClaim(new Claim(OpenIddictConstants.Claims.Audience, "Resource"));
identity.AddClaim(new Claim(OpenIddictConstants.Claims.Email, user.Email));
identity.AddClaim(new Claim(OpenIddictConstants.Claims.Email, user.Email ?? ""));
identity.AddClaim(new Claim(OpenIddictConstants.Claims.Username, user.Id));

// Setting destinations of claims i.e. identity token or access token
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

// Disable warnings for the migration code, it is auto-generated and may not follow all conventions.
#pragma warning disable
#nullable disable

namespace Stickerlandia.UserManagement.Agnostic.Migrations
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2025 Datadog, Inc.

using Microsoft.Extensions.Logging;
using Stickerlandia.UserManagement.Core;

namespace Stickerlandia.UserManagement.Agnostic.Observability;

public static partial class Log
{
}
Loading