Adds playlist management and playback

This commit is contained in:
BinaryAlley committed 2026-10-21 16:30:58 +03:00
1 parent 009a0c8156
commit 9889c86c76
296 files changed
+18830 -367

No files matched your search

@@ -25,7 +25,7 @@ public class SqliteGuidTypeHandlerTests
}
[Fact]
public void SetValue_WhenCalled_ShouldStoreTheGuidAsItsTextRepresentation()
public void SetValue_WhenCalled_ShouldStoreTheGuidAsItsUpperCaseTextRepresentation()
{
// Arrange
IDbDataParameter parameter = Substitute.For<IDbDataParameter>();
@@ -35,7 +35,7 @@ public class SqliteGuidTypeHandlerTests
_sut.SetValue(parameter, guid);
// Assert
Assert.Equal(guid.ToString(), (string?)parameter.Value);
Assert.Equal(guid.ToString().ToUpperInvariant(), (string?)parameter.Value);
}
[Fact]
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate;
/// <summary>
/// Contains unit tests for the <see cref="Playlist"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistTests
{
[Fact]
public void Delete_WhenCalled_ShouldMarkThePlaylistAsDeletedAndRaiseOneEvent()
{
// Arrange
Result<Playlist> createResult = Playlist.Create(
UserId.Create(Guid.NewGuid()),
"Playlist",
Optional<string>.None(),
PlaylistType.Music);
Assert.False(createResult.IsFailure);
Playlist playlist = createResult.Value;
Assert.False(playlist.IsDeleted);
// Act
Result<Deleted> result = playlist.Delete();
List<IDomainEvent> domainEvents = playlist.GetDomainEvents();
// Assert
Assert.False(result.IsFailure);
Assert.True(playlist.IsDeleted);
Assert.Single(domainEvents);
Assert.IsType<PlaylistDeletedDomainEvent>(domainEvents[0]);
}
[Fact]
public void Delete_WhenCalledAgain_ShouldNotRaiseAnotherEvent()
{
// Arrange
Result<Playlist> createResult = Playlist.Create(
UserId.Create(Guid.NewGuid()),
"Playlist",
Optional<string>.None(),
PlaylistType.Music);
Assert.False(createResult.IsFailure);
Playlist playlist = createResult.Value;
playlist.Delete();
// Act
Result<Deleted> result = playlist.Delete();
List<IDomainEvent> domainEvents = playlist.GetDomainEvents();
// Assert
Assert.False(result.IsFailure);
Assert.True(playlist.IsDeleted);
Assert.Single(domainEvents);
}
}
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
@@ -29,7 +28,6 @@ public class LibraryOwnershipPolicyTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IUserRepository _mockUserRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly LibraryOwnershipPolicy _sut;
private readonly AuthorizationServiceFixture _authorizationServiceFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
@@ -42,9 +40,7 @@ public class LibraryOwnershipPolicyTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUserRepository = Substitute.For<IUserRepository>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_sut = new LibraryOwnershipPolicy(_mockUnitOfWork);
}
@@ -61,7 +57,6 @@ public class LibraryOwnershipPolicyTests
// Assert
Assert.False(result);
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
@@ -78,7 +73,6 @@ public class LibraryOwnershipPolicyTests
// Assert
Assert.False(result);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
@@ -95,7 +89,6 @@ public class LibraryOwnershipPolicyTests
// Assert
Assert.False(result);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
@@ -116,45 +109,6 @@ public class LibraryOwnershipPolicyTests
// Assert
Assert.True(result);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task EvaluateAsync_WhenLibraryDoesNotExist_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(regularUser));
_mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result<LibraryEntity?>.Success(null));
// Act
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task EvaluateAsync_WhenGetLibraryFails_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(regularUser));
_mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve library"));
// Act
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
@@ -164,11 +118,10 @@ public class LibraryOwnershipPolicyTests
Guid userId = Guid.NewGuid();
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
LibraryEntity library = _libraryEntityFixture.Create(userId: userId);
regularUser.Libraries.Add(library);
LibraryOwnershipPolicyContext context = new(library.Id);
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(regularUser));
_mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
// Act
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
@@ -187,8 +140,6 @@ public class LibraryOwnershipPolicyTests
LibraryOwnershipPolicyContext context = new(library.Id);
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(regularUser));
_mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
// Act
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
@@ -196,4 +147,26 @@ public class LibraryOwnershipPolicyTests
// Assert
Assert.False(result);
}
[Fact]
public async Task EvaluateAsync_WhenMultipleLibrariesAreEvaluated_ShouldReadTheUserOnlyOnce()
{
// Arrange
Guid userId = Guid.NewGuid();
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
LibraryEntity ownedLibrary = _libraryEntityFixture.Create(userId: userId);
regularUser.Libraries.Add(ownedLibrary);
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(regularUser));
// Act
// The policy is scoped to one request, so both library checks in that scope must share a single user read.
bool canAccessOwnedLibrary = await _sut.EvaluateAsync(userId, new LibraryOwnershipPolicyContext(ownedLibrary.Id), CancellationToken.None);
bool canAccessOtherLibrary = await _sut.EvaluateAsync(userId, new LibraryOwnershipPolicyContext(Guid.NewGuid()), CancellationToken.None);
// Assert
Assert.True(canAccessOwnedLibrary);
Assert.False(canAccessOtherLibrary);
await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>());
}
}
@@ -1,10 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Events;
using Lumina.Presentation.Api.Common.Http;
using Lumina.Presentation.Api.Common.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -52,4 +64,186 @@ public class EventualConsistencyMiddlewareTests
// Assert
Assert.True(_nextInvoked);
}
[Fact]
public async Task InvokeAsync_WhenTheClientAbortsAfterASuccessfulOperation_ShouldStillCommitTheTransaction()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-abort-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext dbContext = CreateContext(anchorConnection);
using UnitOfWork unitOfWork = new(dbContext);
await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);");
CapturingHttpResponseFeature responseFeature = new();
DefaultHttpContext httpContext = new();
httpContext.Features.Set<IHttpResponseFeature>(responseFeature);
httpContext.Request.Path = "/api/v1/probe";
httpContext.Response.StatusCode = StatusCodes.Status200OK;
using CancellationTokenSource cancellationTokenSource = new();
httpContext.RequestAborted = cancellationTokenSource.Token;
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
EventualConsistencyMiddleware sut = new(
async requestContext =>
{
await dbContext.Database.ExecuteSqlRawAsync("INSERT INTO CommitProbe (Id) VALUES (1);");
// The abort happens after the operation has completed, which is exactly when the response token can already be cancelled as the completion callback runs.
cancellationTokenSource.Cancel();
},
mockLogger);
IDomainEventPublisher mockPublisher = Substitute.For<IDomainEventPublisher>();
IDomainEventsQueue mockQueue = Substitute.For<IDomainEventsQueue>();
// Act
await sut.InvokeAsync(httpContext, mockPublisher, unitOfWork, mockQueue);
await responseFeature.InvokeCompletedCallbacksAsync();
// Assert
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
int committedCount = await verificationContext.Database
.SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM CommitProbe")
.SingleAsync();
Assert.Equal(1, committedCount);
}
[Fact]
public async Task InvokeAsync_WhenTheResponseIsNotSuccessful_ShouldRollBackTheTransactionAndTheEvents()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-rollback-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
using LuminaDbContext dbContext = CreateContext(anchorConnection);
using UnitOfWork unitOfWork = new(dbContext);
await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);");
CapturingHttpResponseFeature responseFeature = new();
DefaultHttpContext httpContext = new();
httpContext.Features.Set<IHttpResponseFeature>(responseFeature);
httpContext.Request.Path = "/api/v1/probe";
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
EventualConsistencyMiddleware sut = new(
async requestContext =>
{
await dbContext.Database.ExecuteSqlRawAsync("INSERT INTO CommitProbe (Id) VALUES (1);");
// A client abort is reported by the exception handling middleware as a non-success status, even though the request reached the database.
requestContext.Response.StatusCode = StatusCodes.Status499ClientClosedRequest;
},
mockLogger);
IDomainEventPublisher mockPublisher = Substitute.For<IDomainEventPublisher>();
IDomainEventsQueue mockQueue = Substitute.For<IDomainEventsQueue>();
// Act
await sut.InvokeAsync(httpContext, mockPublisher, unitOfWork, mockQueue);
await responseFeature.InvokeCompletedCallbacksAsync();
// Assert
using LuminaDbContext verificationContext = CreateContext(anchorConnection);
int committedCount = await verificationContext.Database
.SqlQueryRaw<int>("SELECT COUNT(*) AS \"Value\" FROM CommitProbe")
.SingleAsync();
Assert.Equal(0, committedCount);
await mockPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task InvokeAsync_WhenTheCommitFails_ShouldRollBackTheTransactionAndLogTheFailure()
{
// Arrange
CapturingHttpResponseFeature responseFeature = new();
DefaultHttpContext httpContext = new();
httpContext.Features.Set<IHttpResponseFeature>(responseFeature);
httpContext.Request.Path = "/api/v1/probe";
httpContext.Response.StatusCode = StatusCodes.Status200OK;
ILogger<EventualConsistencyMiddleware> mockLogger = Substitute.For<ILogger<EventualConsistencyMiddleware>>();
EventualConsistencyMiddleware sut = new(_ => Task.CompletedTask, mockLogger);
IUnitOfWork mockUnitOfWork = Substitute.For<IUnitOfWork>();
mockUnitOfWork
.CommitTransactionAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromException(new InvalidOperationException("commit failed")));
IDomainEventPublisher mockPublisher = Substitute.For<IDomainEventPublisher>();
IDomainEventsQueue mockQueue = Substitute.For<IDomainEventsQueue>();
// Act
await sut.InvokeAsync(httpContext, mockPublisher, mockUnitOfWork, mockQueue);
await responseFeature.InvokeCompletedCallbacksAsync();
// Assert
// The completion callback must never leave a transaction open after a failed commit, and it must never publish events that belong to a transaction that did not commit.
await mockUnitOfWork.Received(1).RollbackTransactionAsync(Arg.Any<CancellationToken>());
await mockPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates a context backed by the provided in-memory SQLite connection.
/// </summary>
/// <param name="anchorConnection">The open in-memory SQLite connection that keeps the database alive for the duration of the test.</param>
/// <returns>The created context.</returns>
private static LuminaDbContext CreateContext(SqliteConnection anchorConnection)
{
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>()
.UseSqlite(anchorConnection.ConnectionString)
.Options);
context.Database.EnsureCreated();
return context;
}
/// <summary>
/// Response feature that captures the completed callbacks so a test can run them when the response ends.
/// </summary>
private sealed class CapturingHttpResponseFeature : IHttpResponseFeature
{
private readonly List<Func<Task>> _completedCallbacks = [];
/// <summary>
/// Gets or sets the HTTP status code of the response.
/// </summary>
public int StatusCode { get; set; } = StatusCodes.Status200OK;
/// <summary>
/// Gets or sets the reason phrase of the response.
/// </summary>
public string? ReasonPhrase { get; set; }
/// <summary>
/// Gets or sets the response headers.
/// </summary>
public IHeaderDictionary Headers { get; set; } = new HeaderDictionary();
/// <summary>
/// Gets or sets the response body stream.
/// </summary>
public Stream Body { get; set; } = Stream.Null;
/// <summary>
/// Gets a value indicating whether the response has already started.
/// </summary>
public bool HasStarted => false;
/// <summary>
/// Registers a callback to be invoked when the response is about to start.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <param name="state">The state passed to the callback.</param>
public void OnStarting(Func<object, Task> callback, object state)
{
}
/// <summary>
/// Registers a callback to be invoked when the response has completed.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <param name="state">The state passed to the callback.</param>
public void OnCompleted(Func<object, Task> callback, object state)
{
_completedCallbacks.Add(() => callback(state));
}
/// <summary>
/// Invokes every callback that was registered through <see cref="OnCompleted"/>.
/// </summary>
/// <returns>A task representing the asynchronous operation.</returns>
public async Task InvokeCompletedCallbacksAsync()
{
foreach (Func<Task> callback in _completedCallbacks)
await callback();
}
}
}
@@ -112,7 +112,7 @@ public class ExceptionHandlingMiddlewareTests
}
[Fact]
public async Task InvokeAsync_WhenNextThrowsOperationCanceledException_ShouldRethrow()
public async Task InvokeAsync_WhenNextThrowsOperationCanceledException_ShouldRethrowAndReportTheRequestAsAborted()
{
// Arrange
DefaultHttpContext context = new()
@@ -125,7 +125,8 @@ public class ExceptionHandlingMiddlewareTests
await Assert.ThrowsAsync<OperationCanceledException>(() => _sut.InvokeAsync(context));
// Assert
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
// An aborted request is still reported as a non-success status, so the eventual consistency middleware rolls its writes back.
Assert.Equal(StatusCodes.Status499ClientClosedRequest, context.Response.StatusCode);
Assert.Equal(0, context.Response.Body.Length);
}