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

chore: Cleanup #1440

Merged
merged 9 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ namespace Digdir.Domain.Dialogporten.Application.Common.Behaviours;
/// <summary>
/// This behaviour is used to ensure that the domain context is valid and return the correct response to the presentation layer if it is not.
/// <para>
/// The behaviour will return <see cref="DomainError"/> if <typeparamref name="TResponse"/> implements
/// The behaviour will return <see cref="DomainError"/> if <typeparamref name="TResponse"/> implements
/// <see cref="OneOf.IOneOf"/> containing <see cref="DomainError"/> on invalid domain state.
/// </para>
/// <para>
/// The behaviour will throw a <see cref="DomainException"/> if <typeparamref name="TResponse"/> does not
/// The behaviour will throw a <see cref="DomainException"/> if <typeparamref name="TResponse"/> does not
/// implement <see cref="OneOf.IOneOf"/> containing <see cref="DomainError"/> on invalid domain state.
/// </para>
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public FluentValidationOptions(string? name, IEnumerable<IValidator<TOptions>> v
/// </summary>
/// <param name="assemblies">The assemblies to scan for validators.</param>
/// <remarks>
/// This constructor scans the provided assemblies for types that implement the
/// This constructor scans the provided assemblies for types that implement the
/// <see cref="IValidator{T}"/> interface for the specified <typeparamref name="TOptions"/> type.
/// It includes both public and internal validators in the search. <b>Use this constructor sparingly
/// as it uses reflection to find validators.</b>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,5 @@ public MappingProfile()
{
CreateMap<DialogSeenLog, SeenLogDto>()
.ForMember(dest => dest.SeenAt, opt => opt.MapFrom(src => src.CreatedAt));

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ public MappingProfile()
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.TypeId))
.ForMember(dest => dest.DeletedAt, opt => opt.MapFrom(src => src.Dialog.DeletedAt));


CreateMap<List<DialogTransmissionContent>?, ContentDto?>()
.ConvertUsing<TransmissionContentOutputConverter<ContentDto>>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ public MappingProfile()
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.TypeId))
.ForMember(dest => dest.DeletedAt, opt => opt.MapFrom(src => src.Dialog.DeletedAt));


CreateMap<List<DialogTransmissionContent>?, ContentDto?>()
.ConvertUsing<TransmissionContentOutputConverter<ContentDto>>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public sealed class SearchDialogQuery : SortablePaginationParameter<SearchDialog
public string? Process { get; init; }

/// <summary>
/// Filter by Display state
/// Filter by Display state
/// </summary>
public List<SystemLabel.Values>? SystemLabel { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,5 @@ public MappingProfile()
{
CreateMap<DialogSeenLog, SeenLogDto>()
.ForMember(dest => dest.SeenAt, opt => opt.MapFrom(src => src.CreatedAt));

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,5 @@ public MappingProfile()
{
CreateMap<DialogSeenLog, SeenLogDto>()
.ForMember(dest => dest.SeenAt, opt => opt.MapFrom(src => src.CreatedAt));

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ public MappingProfile()
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.TypeId))
.ForMember(dest => dest.DeletedAt, opt => opt.MapFrom(src => src.Dialog.DeletedAt));


CreateMap<List<DialogTransmissionContent>?, ContentDto?>()
.ConvertUsing<TransmissionContentOutputConverter<ContentDto>>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ public MappingProfile()
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.TypeId))
.ForMember(dest => dest.DeletedAt, opt => opt.MapFrom(src => src.Dialog.DeletedAt));


CreateMap<List<DialogTransmissionContent>?, ContentDto?>()
.ConvertUsing<TransmissionContentOutputConverter<ContentDto>>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,6 @@ public async Task<UpdateDialogResult> Handle(UpdateDialogCommand request, Cancel
}
private void UpdateLabel(DialogEntity dialog)
{

if (!_user.TryGetOrganizationNumber(out var organizationNumber))
{
_domainContext.AddError(new DomainFailure(nameof(organizationNumber), "Cannot find organization number for current user."));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public MassTransitSink(ISendEndpointProvider sender)
public async Task Send(IReadOnlyCollection<OutboxMessage> outboxMessages, CancellationToken cancellationToken)
{
// TODO: Configure uri
// TODO: Configure transacton
// TODO: Configure transaction
var endpoint = await _sender.GetSendEndpoint(new Uri("exchange:Digdir.Domain.Dialogporten.Service"));
await endpoint.SendBatch(
outboxMessages,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
"TableName": "OutboxMessage",

/// This is to compensate for the fact that multiple transactions can be committed at the same time.
/// If we continue to consume from the replication slot everything will be fine. However, if we
/// need to recover from a dropped replication slot we need to make sure that we don't miss
/// If we continue to consume from the replication slot everything will be fine. However, if we
/// need to recover from a dropped replication slot we need to make sure that we don't miss
/// any messages from the other concurrent transactions that we may not have been able to consume.
/// We do this at the expense of messages being consumed multiple times at the beginning of the
/// We do this at the expense of messages being consumed multiple times at the beginning of the
/// recovery process.
"ReplicationCheckpointTimeSkew": "-00:00:02",

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Digdir.Domain.Dialogporten.Domain.Common.EventPublisher;
public interface IDomainEvent : INotification
{
/// <summary>
/// The events identification. This can be used by consumers to ensure exactly once processing.
/// The events' identification. Consumers can use this to ensure exactly once processing.
/// </summary>
Guid EventId { get; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ public sealed class DomainException : ApplicationException

public IReadOnlyCollection<DomainFailure> Errors => _errors.ToList().AsReadOnly();

public DomainException(string message) : this(message, [])
{

}
public DomainException(string message) : this(message, []) { }

public DomainException(string message, IEnumerable<DomainFailure> errors) : base(message)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public void UpdateLabel(SystemLabel.Values newLabel, string userId, ActorType.Va
return;
}

// remove old label then add new one
// remove old label then add new one
if (currentLabel != SystemLabel.Values.Default)
{
_labelAssignmentLogs.Add(new()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
using Digdir.Domain.Dialogporten.Domain.Dialogs.Events;
using Digdir.Library.Entity.Abstractions;
using Digdir.Library.Entity.Abstractions.Features.Aggregate;
using Digdir.Library.Entity.Abstractions.Features.Identifiable;
using Digdir.Library.Entity.Abstractions.Features.SoftDeletable;
using Digdir.Library.Entity.Abstractions.Features.Versionable;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,9 @@

namespace Digdir.Domain.Dialogporten.Domain.Dialogs.Events;

public sealed record DialogCreatedDomainEvent(Guid DialogId, string ServiceResource, string Party, string? Process, string? PrecedingProcess) : DomainEvent, IProcessEvent;
public sealed record DialogCreatedDomainEvent(
Guid DialogId,
string ServiceResource,
string Party,
string? Process,
string? PrecedingProcess) : DomainEvent, IProcessEvent;
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,9 @@

namespace Digdir.Domain.Dialogporten.Domain.Dialogs.Events;

public sealed record DialogSeenDomainEvent(Guid DialogId, string ServiceResource, string Party, string? Process, string? PrecedingProcess) : DomainEvent, IProcessEvent;
public sealed record DialogSeenDomainEvent(
Guid DialogId,
string ServiceResource,
string Party,
string? Process,
string? PrecedingProcess) : DomainEvent, IProcessEvent;
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,9 @@

namespace Digdir.Domain.Dialogporten.Domain.Dialogs.Events;

public sealed record DialogUpdatedDomainEvent(Guid DialogId, string ServiceResource, string Party, string? Process, string? PrecedingProcess) : DomainEvent, IProcessEvent;
public sealed record DialogUpdatedDomainEvent(
Guid DialogId,
string ServiceResource,
string Party,
string? Process,
string? PrecedingProcess) : DomainEvent, IProcessEvent;
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public abstract class LocalizationSet : IImmutableEntity
public Guid Id { get; set; }
public DateTimeOffset CreatedAt { get; set; }

// === Plural principal relationships ===
// === Plural principal relationships ===
[AggregateChild]
public List<Localization> Localizations { get; set; } = [];
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Digdir.Domain.Dialogporten.GraphQL.Common.Authorization;

/// <summary>
/// This authorisation handler will bypass all requirements
/// This authorization handler will bypass all requirements
/// </summary>
public sealed class AllowAnonymousHandler : IAuthorizationHandler
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,3 @@ internal static class Constants
internal const string Authorization = "Authorization";
internal const string CurrentTokenIssuer = "CurrentIssuer";
}

Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using AutoMapper;
using Digdir.Domain.Dialogporten.Application.Features.V1.Common.Actors;
using Digdir.Domain.Dialogporten.Application.Features.V1.EndUser.Dialogs.Queries.Get;
using Digdir.Domain.Dialogporten.GraphQL.EndUser.Common;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public async Task<AuthorizedPartiesResult> GetAuthorizedParties(IPartyIdentifier
CancellationToken cancellationToken = default)
{
var authorizedPartiesRequest = new AuthorizedPartiesRequest(authenticatedParty);
// Disabled until https://github.com/digdir/dialogporten/issues/1226 is fixed
// var authorizedParties = await _partiesCache.GetOrSetAsync(authorizedPartiesRequest.GenerateCacheKey(), async token
// => await PerformAuthorizedPartiesRequest(authorizedPartiesRequest, token), token: cancellationToken);
var authorizedParties = await PerformAuthorizedPartiesRequest(authorizedPartiesRequest, cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ internal sealed class DialogDetailsAuthorizationRequest
public required Guid DialogId { get; init; }
public required string Party { get; init; }

// Each action applies to a resource. This is the main resource, or another resource indicated by a authorization attribute
// Each action applies to a resource. This is the main resource, or another resource indicated by an authorization attribute
// eg. "urn:altinn:subresource:some-sub-resource" or "urn:altinn:task:task_1"
public required List<AltinnAction> AltinnActions { get; init; }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public static List<AltinnAction> GetAltinnActions(this DialogEntity dialogEntity

private static string GetReadActionForAuthorizationAttribute(string authorizationAttribute)
{
// Resource attributes may refer to either subresources/tasks that should be considered just another
// Resource attributes may refer to either sub-resources/tasks that should be considered just another
// attribute to be matched within the same policy file, or they may refer to separate resources (and policies).
// In the former case, we need to use "transmissionread" as the action, as having "read" on the main resource would
// also give access to the subresource/task. In the latter case, we should use "read", as the resource is a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,16 @@ public LocalDevelopmentAltinnAuthorization(IDialogDbContext db)
[SuppressMessage("Performance", "CA1822:Mark members as static")]
public Task<DialogDetailsAuthorizationResult> GetDialogDetailsAuthorization(
DialogEntity dialogEntity,
CancellationToken __)
{
// Just allow everything
return Task.FromResult(new DialogDetailsAuthorizationResult { AuthorizedAltinnActions = dialogEntity.GetAltinnActions() });
}
CancellationToken __) =>
// Allow everything
Task.FromResult(new DialogDetailsAuthorizationResult { AuthorizedAltinnActions = dialogEntity.GetAltinnActions() });

public async Task<DialogSearchAuthorizationResult> GetAuthorizedResourcesForSearch(List<string> constraintParties, List<string> serviceResources,
CancellationToken cancellationToken = default)
{

// constraintParties and serviceResources are passed from the client as query parameters
// If one and/or the other is supplied, this will limit the resources and parties to the ones supplied
// If one and/or the other is supplied this will limit the resources and parties to the ones supplied
var dialogData = await _db.Dialogs
.Select(dialog => new { dialog.Party, dialog.ServiceResource })
.WhereIf(constraintParties.Count != 0, dialog => constraintParties.Contains(dialog.Party))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ private sealed class ResourceListResponse

private sealed class CompetentAuthority
{
// Altinn 2 resources does not always have an organization number as competent authority, only service owner code
// Altinn 2 resources do not always have an organization number as competent authority, only service owner code
// We filter these out anyway, but we need to allow null here
public string? Organization { get; init; }
public required string OrgCode { get; init; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public InfrastructureSettingsValidator(
.SetValidator(massTransitSettingsValidator);
}

// This is here to be able to use the validator without having access to the service provider.
// This is here to be able to use the validator without having access to the service provider.
private InfrastructureSettingsValidator() : this(
new AltinnPlatformSettingsValidator(),
new AltinnCdnPlatformSettingsValidator(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ public DateTimeOffsetConverter()
d => d.ToUniversalTime())
{
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ public IUnitOfWork WithoutAggregateSideEffects()
}

public async Task BeginTransactionAsync(CancellationToken cancellationToken = default)
{
_transaction ??= await _dialogDbContext.Database.BeginTransactionAsync(cancellationToken);
}
=> _transaction ??= await _dialogDbContext.Database.BeginTransactionAsync(cancellationToken);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Potential Transaction Leaks Identified in IOutboxReaderRepository.cs

  • BeginTransactionAsync is used outside of UnitOfWork.cs, which may lead to transaction leaks.
🔗 Analysis chain

Verify transaction management across the codebase.

While the transaction management in this class looks solid, let's verify proper usage across the codebase to prevent transaction leaks.

Also applies to: 142-157

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for proper transaction management and potential bypasses

# Check for direct DbContext usage that might bypass UnitOfWork
echo "Checking for direct DbContext usage..."
rg "DialogDbContext" --type cs -C 3 | grep -v "UnitOfWork.cs"

# Check for proper disposal of UnitOfWork
echo "Checking UnitOfWork disposal patterns..."
ast-grep --pattern 'using var unitOfWork = $_;'
ast-grep --pattern 'await using var unitOfWork = $_;'

# Check for potential transaction leaks
echo "Checking for potential transaction leaks..."
rg "BeginTransactionAsync" --type cs -C 5

Length of output: 96436


public async Task<SaveChangesResult> SaveChangesAsync(CancellationToken cancellationToken = default)
{
Expand Down
4 changes: 2 additions & 2 deletions src/Digdir.Domain.Dialogporten.Janitor/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ static void BuildAndRun(string[] args)
{
var builder = CoconaApp.CreateBuilder(args);

// Disable scope validation because cocona does not create a scope for the commands.
// Disable scope validation because Cocona does not create a scope for the commands.
// This makes sense because console applications are short-lived, and the scope of
// a command is the scope of the application.
// a command is the scope of the application.
builder.Host.UseDefaultServiceProvider(options => options.ValidateScopes = false);

builder.Configuration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace Digdir.Domain.Dialogporten.WebApi;
public static class OpenApiDocumentExtensions
{
/// <summary>
/// This is a workaround for a bug/weird behaviour in FastEndpoints where examples
/// This is a workaround for a bug/weird behavior in FastEndpoints where examples
/// to the RequestExamples array are not added to the OpenAPI document.
/// Each SwaggerConfig file implements a GetExample method that returns the example
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public interface IAggregateDeletedHandler
/// <param name="utcNow">The timestamp of the deletion event in UTC time.</param>
void OnDelete(AggregateNode self, DateTimeOffset utcNow);
}

/// <summary>
/// Defines an entity handler for handling the deletion of its own aggregate.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,9 @@ public static Guid CreateVersion7IfDefault(this Guid value) =>
/// Creates a new version 7 UUID.
/// </summary>
/// <returns>A new version 7 UUID in big endian format.</returns>
public static Guid CreateVersion7()
{
public static Guid CreateVersion7() =>
// We want Guids in big endian format. The default behavior of Medo is big endian,
// however, the implicit conversion from Medo.Uuid7 to Guid is little endian.
// "matchGuidEndianness" is set to true to ensure big endian.
return Uuid7.NewUuid7().ToGuid(matchGuidEndianness: true);
}
Uuid7.NewUuid7().ToGuid(matchGuidEndianness: true);
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ protected AbstractLookupEntity(TEnum id) : this(id, id.ToString()) { }
/// Initializes a new instance of the <see cref="AbstractLookupEntity{TSelf, TEnum}"/> class.
/// </summary>
/// <param name="id">The entity identification.</param>
/// <param name="name">A human readable name to identify the lookup type.</param>
/// <param name="name">A human-readable name to identify the lookup type.</param>
protected AbstractLookupEntity(TEnum id, string name)
{
if (!Enum.IsDefined(typeof(TEnum), id))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
/// The concrete implementing type.
/// </typeparam>
/// <typeparam name="TEnum">
/// The <see cref="Enum"/> values that represents the full
/// set of possible static entity values. Each
/// <see cref="Enum"/> value is a unique id for the
/// The <see cref="Enum"/> values that represents the full
/// set of possible static entity values. Each
/// <see cref="Enum"/> value is a unique id for the
/// <see cref="ILookupEntity"/>.
/// </typeparam>
public interface ILookupEntity<TSelf, TEnum> : ILookupEntity
Expand All @@ -21,13 +21,13 @@ public interface ILookupEntity<TSelf, TEnum> : ILookupEntity
}

/// <summary>
/// Abstraction implemented by entities that is static during the application
/// lifetime. For example type information, or states in a finite state machine.
/// Abstraction implemented by entities that is static during the application
/// lifetime. For example, type information, or states in a finite state machine.
/// </summary>
public interface ILookupEntity
{
/// <summary>
/// A human readable name to identify the lookup type.
/// A human-readable name to identify the lookup type.
/// </summary>
string Name { get; }
}
Loading
Loading