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

@@ -1,19 +1,20 @@
#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.Domain.Common.Exceptions;
using Lumina.Presentation.Api.Common.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Common.Middlewares;
/// <summary>
/// Middleware that ensures eventual consistency by handling domain events and publishing them after the request has completed successfully.
/// Middleware that owns the request transaction, committing it and publishing the queued domain events after a successful request, and rolling it back otherwise.
/// </summary>
public class EventualConsistencyMiddleware
{
@@ -36,9 +37,9 @@ public class EventualConsistencyMiddleware
/// </summary>
/// <param name="context">The current HTTP context.</param>
/// <param name="domainEventPublisher">The domain event publisher used to publish events.</param>
/// <param name="dbContext">The database context used to manage the transaction.</param>
/// <param name="unitOfWork">Injected unit of work that owns the request transaction.</param>
/// <param name="domainEventQueue">In memory queue containing the queued domain events.</param>
public async Task InvokeAsync(HttpContext context, IDomainEventPublisher domainEventPublisher, LuminaDbContext dbContext, IDomainEventsQueue domainEventQueue)
public async Task InvokeAsync(HttpContext context, IDomainEventPublisher domainEventPublisher, IUnitOfWork unitOfWork, IDomainEventsQueue domainEventQueue)
{
// Endpoints that serve long lived responses (for example a track stream) opt out through endpoint metadata, so that their response never
// holds the request's database transaction open; the opt out is metadata based, so it follows the endpoint even when its route changes.
@@ -48,24 +49,27 @@ public class EventualConsistencyMiddleware
return;
}
// begin a new database transaction - this will wrap any database operations performed during this HTTP request in an atomic operation
IDbContextTransaction transaction = await dbContext.Database.BeginTransactionAsync(context.RequestAborted).ConfigureAwait(false);
// register an action to be executed once the response is completed (the user already received a response for the request)
// Begin a new database transaction - this will wrap any database operations performed during this HTTP request in an atomic operation.
await unitOfWork.BeginTransactionAsync(context.RequestAborted).ConfigureAwait(false);
// Register an action to be executed once the response is completed (the user already received a response for the request).
context.Response.OnCompleted(async () =>
{
try
{
// only proceed if the response status code indicates success
// Only proceed if the response status code indicates success. The request abort token is deliberately not consulted here:
// it can already be cancelled when the callback runs, even though the operation completed successfully, and refusing to
// commit then would discard a write whose success response was already sent. An aborted request is instead reported as a
// non-success status by the exception handling middleware.
if (context.Response.StatusCode >= 200 && context.Response.StatusCode < 300)
{
// commit the transaction: because some domain events trigger jobs that end up being processed in background hosted services, and those are
// Commit the transaction: because some domain events trigger jobs that end up being processed in background hosted services, and those are
// singletons that require their own DI scope to be created, any changes made on the DbContext in this HTTP scope would not be seen on the
// DbContext created in the background service scope, because the transaction is not yet committed here; therefor, the transaction needs to be
// committed first, before any domain events are fired
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0002.md for details:
await transaction.CommitAsync().ConfigureAwait(false);
// committed first, before any domain events are fired.
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0002.md for details:
await unitOfWork.CommitTransactionAsync(CancellationToken.None).ConfigureAwait(false);
// check if domain events exist in the channel queue and publish them
// Check if domain events exist in the channel queue and publish them.
while (domainEventQueue.TryDequeue(out IDomainEvent? nextEvent))
await domainEventPublisher.PublishAsync(nextEvent);
}
@@ -74,10 +78,23 @@ public class EventualConsistencyMiddleware
{
_logger.LogCritical(ex, "Failed to perform eventual consistency");
}
catch (Exception ex) // The response is already complete, so this failure cannot reach the client. It is logged, and the transaction is still closed by the rollback below.
{
_logger.LogError(ex, "Failed to complete the request transaction for {Path}", context.Request.Path);
}
finally
{
// DisposeAsync automatically roles back any changes, if a call to CommitAsync was not performed prior
await transaction.DisposeAsync().ConfigureAwait(false);
// A commit or a rollback clears the transaction, so this only closes one that the failure above left open. It runs for
// every response, including the non-success one that never attempted a commit. Rollback must never throw out of the
// completion callback, and must never mask the failure that is already being handled.
try
{
await unitOfWork.RollbackTransactionAsync(CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to roll back the request transaction for {Path}", context.Request.Path);
}
}
});
await _next(context).ConfigureAwait(false);
@@ -41,12 +41,16 @@ public class ExceptionHandlingMiddleware
}
catch (OperationCanceledException)
{
// the request was aborted, so there is no client left to write a response to
// The request was aborted, so there is no client left to write a response to. The status is still set to a non-success value,
// because the eventual consistency middleware decides whether to commit from it, and the writes of an aborted request must be
// rolled back instead of being reported as a success.
if (!context.Response.HasStarted)
context.Response.StatusCode = StatusCodes.Status499ClientClosedRequest;
throw;
}
catch (Exception ex)
{
// once the response has started, it is no longer possible to replace it with a ProblemDetails response
// Once the response has started, it is no longer possible to replace it with a ProblemDetails response.
if (context.Response.HasStarted)
throw;
_logger.LogError(ex, "Unhandled exception occurred while processing request {Method} {Path}", context.Request.Method, context.Request.Path);
@@ -0,0 +1,24 @@
namespace Lumina.Presentation.Api.Common.Routes.Playlists;
/// <summary>
/// Class for the collection of the playlist routes of the API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the playlists of the current user.
/// </summary>
public static class Playlists
{
public const string GET_PLAYLISTS = "/users/me/playlists";
public const string CREATE_PLAYLIST = "/users/me/playlists";
public const string GET_PLAYLIST = "/users/me/playlists/{playlistId}";
public const string UPDATE_PLAYLIST = "/users/me/playlists/{playlistId}";
public const string DELETE_PLAYLIST = "/users/me/playlists/{playlistId}";
public const string ADD_PLAYLIST_ENTRY = "/users/me/playlists/{playlistId}/entries";
public const string ADD_PLAYLIST_ENTRIES = "/users/me/playlists/{playlistId}/entries-batch";
public const string ADD_PLAYLIST_SCOPE_ENTRIES = "/users/me/playlists/{playlistId}/entries-scope";
public const string REMOVE_PLAYLIST_ENTRY = "/users/me/playlists/{playlistId}/entries/{playlistEntryId}";
public const string MOVE_PLAYLIST_ENTRY = "/users/me/playlists/{playlistId}/entries/{playlistEntryId}/move";
}
}