mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 10:11:10 +00:00
Adds the web track streaming proxy and streaming HTTP client
This commit is contained in:
1 parent
d7c1ae60c2
commit
aab36dcd29
17 files changed
+969
-29
No files matched your search
@@ -0,0 +1,104 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the streamed response of a remote API request. It exposes the status code, the range related headers and the
|
||||
/// content stream of the response, so that a caller can forward the response to a client without ever buffering its content.
|
||||
/// </summary>
|
||||
public sealed class ApiStreamResult : IAsyncDisposable
|
||||
{
|
||||
private readonly HttpResponseMessage _response;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the status code of the response.
|
||||
/// </summary>
|
||||
public HttpStatusCode StatusCode { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the content stream of the response.
|
||||
/// </summary>
|
||||
public Stream Content { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media type of the content of the response, or <see langword="null"/> when the response declares none.
|
||||
/// </summary>
|
||||
public string? ContentType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the length of the content of the response, or <see langword="null"/> when the response declares none.
|
||||
/// </summary>
|
||||
public long? ContentLength { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the range of the content of the response, when the response is a partial content response.
|
||||
/// </summary>
|
||||
public string? ContentRange { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ranges the remote API accepts, when the response declares them.
|
||||
/// </summary>
|
||||
public string? AcceptRanges { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the entity tag of the content of the response, when the response declares one.
|
||||
/// </summary>
|
||||
public string? ETag { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the date and time the content of the response was last modified, when the response declares it.
|
||||
/// </summary>
|
||||
public DateTimeOffset? LastModified { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the caching instructions of the response, when the response declares them.
|
||||
/// </summary>
|
||||
public string? CacheControl { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApiStreamResult"/> class.
|
||||
/// </summary>
|
||||
/// <param name="response">The response returned by the remote API.</param>
|
||||
/// <param name="content">The content stream of the response.</param>
|
||||
private ApiStreamResult(HttpResponseMessage response, Stream content)
|
||||
{
|
||||
_response = response;
|
||||
Content = content;
|
||||
StatusCode = response.StatusCode;
|
||||
ContentType = response.Content.Headers.ContentType?.ToString();
|
||||
ContentLength = response.Content.Headers.ContentLength;
|
||||
ContentRange = response.Content.Headers.ContentRange?.ToString();
|
||||
AcceptRanges = response.Headers.AcceptRanges.Count > 0 ? string.Join(", ", response.Headers.AcceptRanges) : null;
|
||||
ETag = response.Headers.ETag?.ToString();
|
||||
LastModified = response.Content.Headers.LastModified;
|
||||
CacheControl = response.Headers.CacheControl?.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="ApiStreamResult"/> from a response, without buffering the content of the response.
|
||||
/// </summary>
|
||||
/// <param name="response">The response returned by the remote API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The streamed response.</returns>
|
||||
public static async Task<ApiStreamResult> CreateAsync(HttpResponseMessage response, CancellationToken cancellationToken)
|
||||
{
|
||||
Stream content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new ApiStreamResult(response, content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the content stream and the response it belongs to.
|
||||
/// </summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Content.DisposeAsync().ConfigureAwait(false);
|
||||
_response.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for typed clients that stream responses from the remote API without buffering their content.
|
||||
/// </summary>
|
||||
public interface IStreamingApiHttpClient
|
||||
{
|
||||
/// <summary>
|
||||
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the response as a stream, without ever buffering its content in memory.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="requestHeaders">The range and conditional headers of the incoming request to forward, so that the API,
|
||||
/// which is the only party that knows the entity tag and the modification time of the resource, validates them itself.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The streamed response of the API request, which the caller must dispose once it has finished copying it.</returns>
|
||||
Task<ApiStreamResult> GetStreamAsync(string endpoint, IReadOnlyDictionary<string, string> requestHeaders, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Typed client for streaming API access. Unlike <see cref="ApiHttpClient"/>, it never buffers a response in memory and is
|
||||
/// intentionally free of any retry or circuit breaker policy, because a stream is meant to be handed to the client as a whole.
|
||||
/// </summary>
|
||||
public class StreamingApiHttpClient : IStreamingApiHttpClient
|
||||
{
|
||||
private static readonly JsonSerializerOptions s_jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
Converters = { new JsonStringEnumConverter() }
|
||||
};
|
||||
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly HttpContext? _httpContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamingApiHttpClient"/> class.
|
||||
/// </summary>
|
||||
/// <param name="httpClient">Injected HttpClient for interacting with the API.</param>
|
||||
/// <param name="httpContextAccessor">Injected service for providing the current HTTP context.</param>
|
||||
/// <param name="serverConfigurationOptions">Injected server configuration application settings.</param>
|
||||
public StreamingApiHttpClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_httpContext = httpContextAccessor.HttpContext;
|
||||
// Read the API server configuration values from the configuration, and assign them to the injected client.
|
||||
ServerConfigurationDto serverConfiguration = serverConfigurationOptions.Value;
|
||||
httpClient.BaseAddress = new Uri($"{serverConfiguration.BaseAddress}:{serverConfiguration.Port}/api/v{serverConfiguration.ApiVersion}/");
|
||||
// A streamed response stays open for as long as the client keeps reading it, so the timeout is generously large, but it is bounded:
|
||||
// an upstream that accepts the request and never answers must not hold a connection and a stream permit open forever. No track, and
|
||||
// no movie, is longer than this.
|
||||
httpClient.Timeout = TimeSpan.FromHours(12);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the response
|
||||
/// as a stream, without ever buffering its content in memory.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||
/// <param name="requestHeaders">The range and conditional headers of the incoming request to forward, so that the API, which is the only party that knows the entity tag and the modification time of the resource, validates them itself.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The streamed response of the API request, which the caller must dispose once it has finished copying it.</returns>
|
||||
/// <exception cref="ApiException">Thrown if the response is not successful, with the <see cref="ProblemDetailsDto"/> if available.</exception>
|
||||
public async Task<ApiStreamResult> GetStreamAsync(string endpoint, IReadOnlyDictionary<string, string> requestHeaders, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using (HttpRequestMessage request = new(HttpMethod.Get, endpoint))
|
||||
{
|
||||
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
|
||||
if (authenticationHeader is not null)
|
||||
request.Headers.Authorization = authenticationHeader;
|
||||
// The range and the conditional headers are forwarded as they are, so that the API, and never this client, decides what a partial response contains.
|
||||
foreach (KeyValuePair<string, string> header in requestHeaders)
|
||||
request.Headers.TryAddWithoutValidation(header.Key, header.Value);
|
||||
|
||||
// Only the headers of the response are awaited, so that its content is streamed to the client instead of being copied into memory first.
|
||||
HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
|
||||
// A not modified response and a range not satisfiable response are valid outcomes of a conditional or ranged request, and their
|
||||
// headers (the entity tag, the last modified date, the content range) are the whole answer, so they are passed through instead of
|
||||
// being turned into an error, which would drop the very headers the caller needs to revalidate or recover.
|
||||
if (!response.IsSuccessStatusCode && response.StatusCode != HttpStatusCode.NotModified && response.StatusCode != HttpStatusCode.RequestedRangeNotSatisfiable)
|
||||
{
|
||||
HttpStatusCode statusCode = response.StatusCode;
|
||||
string content;
|
||||
try
|
||||
{
|
||||
content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// The response is turned into an exception, so it is disposed even when reading its error body fails, otherwise its connection would leak.
|
||||
response.Dispose();
|
||||
}
|
||||
ProblemDetailsDto? problemDetails = null;
|
||||
try
|
||||
{
|
||||
problemDetails = JsonSerializer.Deserialize<ProblemDetailsDto>(content, s_jsonOptions);
|
||||
}
|
||||
catch { /* If we can't deserialize to ProblemDetails, we'll just use the status code. */ }
|
||||
throw new ApiException(problemDetails, statusCode, request.RequestUri?.AbsolutePath);
|
||||
}
|
||||
try
|
||||
{
|
||||
return await ApiStreamResult.CreateAsync(response, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The response was already received, so it must be disposed if its content stream could not be obtained, otherwise its connection would leak.
|
||||
response.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the authentication header for the current user, if available.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// An <see cref="AuthenticationHeaderValue"/> with a Bearer token if the user's token is found, <see langword="null"/> otherwise.
|
||||
/// </returns>
|
||||
private AuthenticationHeaderValue? GetAuthenticationHeader()
|
||||
{
|
||||
string? token = _httpContext?.User?.FindFirst("Token")?.Value;
|
||||
return !string.IsNullOrEmpty(token) ? new AuthenticationHeaderValue("Bearer", token) : null;
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the playback manifest of a track, describing the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("TrackId: {TrackId} DirectPlay: {DirectPlay}")]
|
||||
public class PlaybackManifestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the track the manifest describes.
|
||||
/// </summary>
|
||||
public Guid TrackId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the duration of the audio of the track, in seconds.
|
||||
/// </summary>
|
||||
public int DurationInSeconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the container of the audio file of the track, as stored by the probe.
|
||||
/// </summary>
|
||||
public string? SourceContainer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the codec of the audio of the track, as stored by the probe.
|
||||
/// </summary>
|
||||
public string? SourceCodec { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the sample rate of the audio of the track, in Hz.
|
||||
/// </summary>
|
||||
public int SampleRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of audio channels of the track.
|
||||
/// </summary>
|
||||
public int Channels { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the bit depth of the audio of the track.
|
||||
/// </summary>
|
||||
public int? BitDepth { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ReplayGain track gain of the track, in decibels.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainTrackGain { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ReplayGain track peak of the track.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainTrackPeak { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ReplayGain album gain of the track, in decibels.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainAlbumGain { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ReplayGain album peak of the track.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainAlbumPeak { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the player can play the stored audio as it is, without the server changing its container or its codec.
|
||||
/// </summary>
|
||||
public bool DirectPlay { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the container of the audio the server delivers, when the delivery is not a direct play.
|
||||
/// </summary>
|
||||
public string? DeliveryContainer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the codec of the audio the server delivers, when the delivery is not a direct play.
|
||||
/// </summary>
|
||||
public string? DeliveryCodec { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the shape the delivered audio is addressed and seeked by, when the delivery is not a direct play.
|
||||
/// </summary>
|
||||
public PlaybackDeliveryShape? DeliveryShape { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments.
|
||||
/// </summary>
|
||||
public int? SegmentDurationSeconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the delivered audio can be seeked by the player.
|
||||
/// </summary>
|
||||
public bool Seekable { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path of the track stream. The API returns it relative to itself; this web application replaces it with
|
||||
/// the URL of its own streaming proxy, so that the browser never reaches the API server directly.
|
||||
/// </summary>
|
||||
public string StreamPath { get; set; } = string.Empty;
|
||||
}
|
||||
+40
@@ -20,6 +20,7 @@ using Microsoft.AspNetCore.Localization;
|
||||
using Microsoft.AspNetCore.Localization.Routing;
|
||||
using Microsoft.AspNetCore.Mvc.Localization;
|
||||
using Microsoft.AspNetCore.Mvc.Razor;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Polly;
|
||||
using Polly.CircuitBreaker;
|
||||
@@ -31,7 +32,9 @@ using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.RateLimiting;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -43,6 +46,11 @@ namespace Lumina.Presentation.Web.Common.DependencyInjection;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class PresentationWebLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of the rate limiting policy that bounds the number of concurrent track streams held by a single user.
|
||||
/// </summary>
|
||||
public const string TRACK_STREAM_RATE_LIMIT_POLICY = "trackStreamPolicy";
|
||||
|
||||
/// <summary>
|
||||
/// Registers the services of the Presentation Web layer into the Dependency Injection container.
|
||||
/// </summary>
|
||||
@@ -288,6 +296,26 @@ public static class PresentationWebLayerServices
|
||||
|
||||
AsyncPolicyWrap<HttpResponseMessage> policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);
|
||||
|
||||
// Bound the number of long lived streams a single user can hold open at once, mirroring the concurrency limit the API server applies to
|
||||
// its own stream route. Without it, an authenticated user could make this application open an unbounded number of parallel streams, each
|
||||
// pinning a connection towards the API for the whole duration of a track, turning this application into an exhaustion amplifier.
|
||||
services.AddRateLimiter(rateLimiterOptions =>
|
||||
{
|
||||
rateLimiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
rateLimiterOptions.AddPolicy(TRACK_STREAM_RATE_LIMIT_POLICY, httpContext =>
|
||||
{
|
||||
// The limit is partitioned per authenticated user, and it is a concurrency limit, not a per IP attempt window, so it is deliberately separate from any login throttling.
|
||||
string userId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous";
|
||||
return RateLimitPartition.GetConcurrencyLimiter(
|
||||
partitionKey: $"trackStream_{userId}",
|
||||
factory: _ => new ConcurrencyLimiterOptions
|
||||
{
|
||||
PermitLimit = 4, // Allow 4 concurrent audio streams per user, matching the API server.
|
||||
QueueLimit = 0 // Don't queue requests, a request beyond the limit is rejected instead of waiting.
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Register the HTTP typed client used for the API interaction.
|
||||
services.AddHttpClient<IApiHttpClient, ApiHttpClient>()
|
||||
.AddHttpMessageHandler<CachedAuthorizationHandler>()
|
||||
@@ -295,6 +323,18 @@ public static class PresentationWebLayerServices
|
||||
.AddPolicyHandler(retryPolicy)
|
||||
.AddPolicyHandler(circuitBreakerPolicy);
|
||||
|
||||
// Register the HTTP typed client used for streaming responses from the API. It deliberately has no retry and no circuit breaker policy,
|
||||
// because a stream cannot be transparently retried once its content has started reaching the client. It configures a bounded, generous
|
||||
// timeout itself, because a stream stays open for as long as the client keeps reading it, yet a stalled one must never be held forever.
|
||||
services.AddHttpClient<IStreamingApiHttpClient, StreamingApiHttpClient>()
|
||||
// Cap the connections a stream can pin towards the API, as a backstop on top of the per user concurrency limit of the stream route.
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
|
||||
{
|
||||
// A blackholed connection attempt must fail on its own, well before the request timeout, instead of holding a stream permit.
|
||||
ConnectTimeout = TimeSpan.FromSeconds(30),
|
||||
MaxConnectionsPerServer = 64
|
||||
});
|
||||
|
||||
services.AddScoped<CachedAuthorizationHandler>();
|
||||
services.AddScoped<CachedThemeHandler>();
|
||||
services.AddScoped<ThemeCachePreferenceService>();
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Enums.AudioLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the shapes in which delivered audio is addressed and seeked.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum PlaybackDeliveryShape
|
||||
{
|
||||
/// <summary>
|
||||
/// The delivered media is the original file itself, addressed and seeked by byte range.
|
||||
/// </summary>
|
||||
ByteRangeSeekable,
|
||||
|
||||
/// <summary>
|
||||
/// The delivered media is a sequence of fixed duration segments, addressed and seeked by time, so that finding a time never
|
||||
/// requires mapping a byte range to it.
|
||||
/// </summary>
|
||||
TimeAddressedSegments,
|
||||
}
|
||||
@@ -10,6 +10,7 @@ using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -47,6 +48,11 @@ public class ExceptionHandlingMiddleware
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
|
||||
{
|
||||
// The client went away while its request or response was being processed, so there is nobody left to answer.
|
||||
context.Abort();
|
||||
}
|
||||
catch (ApiException apiException) // threat API exceptions differently - they contain Problem Details properties
|
||||
{
|
||||
await HandleApiExceptionAsync(context, apiException);
|
||||
@@ -54,6 +60,13 @@ public class ExceptionHandlingMiddleware
|
||||
catch (Exception ex) // other cases -
|
||||
{
|
||||
_logger.LogError(ex, "Unexpected exception occurred: {Message}", ex.Message);
|
||||
// Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection
|
||||
// is aborted instead, so that the client sees a failed transfer rather than a success response it cannot trust.
|
||||
if (context.Response.HasStarted)
|
||||
{
|
||||
context.Abort();
|
||||
return;
|
||||
}
|
||||
// return a JSON result with the error details
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
@@ -77,34 +90,23 @@ public class ExceptionHandlingMiddleware
|
||||
apiException.ProblemDetails?.Detail,
|
||||
apiException.ProblemDetails?.Extensions);
|
||||
|
||||
// Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection
|
||||
// is aborted instead, so that the client sees a failed transfer rather than a redirect it could not follow or a body it would misread.
|
||||
if (context.Response.HasStarted)
|
||||
{
|
||||
context.Abort();
|
||||
return;
|
||||
}
|
||||
|
||||
// handle unauthorized errors by prompting the user to re-login
|
||||
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in)
|
||||
await HandleUnauthorizedAsync(context);
|
||||
else if (apiException.HttpStatusCode == HttpStatusCode.NotFound) //
|
||||
await HandleNotFoundAsync(context, apiException);
|
||||
else if (apiException.HttpStatusCode == HttpStatusCode.Forbidden)
|
||||
{
|
||||
if (IsApiRequest(context))
|
||||
{
|
||||
string errorMessage = BuildErrorMessage(apiException);
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
errorMessage
|
||||
});
|
||||
}
|
||||
else
|
||||
await context.ForbidAsync();
|
||||
}
|
||||
await HandleForbiddenAsync(context, apiException);
|
||||
else
|
||||
{
|
||||
string errorMessage = BuildErrorMessage(apiException);
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
errorMessage
|
||||
});
|
||||
}
|
||||
await HandleGenericApiErrorAsync(context, apiException);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -120,7 +122,7 @@ public class ExceptionHandlingMiddleware
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsApiRequest(context))
|
||||
if (IsJsonRequest(context))
|
||||
{
|
||||
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
|
||||
await WriteJsonResponseAsync(context, new
|
||||
@@ -129,7 +131,7 @@ public class ExceptionHandlingMiddleware
|
||||
errorMessage = "NotFound"
|
||||
});
|
||||
}
|
||||
else
|
||||
else if (IsNavigationRequest(context))
|
||||
{
|
||||
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
|
||||
|
||||
@@ -138,6 +140,48 @@ public class ExceptionHandlingMiddleware
|
||||
_logger.LogInformation("Redirecting user to NotFound url");
|
||||
context.Response.Redirect(notFoundUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too
|
||||
}
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.NotFound).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles forbidden exceptions.
|
||||
/// </summary>
|
||||
private async Task HandleForbiddenAsync(HttpContext context, ApiException apiException)
|
||||
{
|
||||
if (IsJsonRequest(context))
|
||||
{
|
||||
string errorMessage = BuildErrorMessage(apiException);
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
errorMessage
|
||||
});
|
||||
}
|
||||
else if (IsNavigationRequest(context))
|
||||
await context.ForbidAsync();
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.Forbidden).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the API exceptions that are neither authentication, authorization, nor not found failures.
|
||||
/// </summary>
|
||||
private async Task HandleGenericApiErrorAsync(HttpContext context, ApiException apiException)
|
||||
{
|
||||
// JSON callers and page navigations get the localized error message; any other caller, like an audio request, is answered with
|
||||
// a bare status code, because a JSON body is not a representation such a caller can consume.
|
||||
if (IsJsonRequest(context) || IsNavigationRequest(context))
|
||||
{
|
||||
string errorMessage = BuildErrorMessage(apiException);
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
errorMessage
|
||||
});
|
||||
}
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)apiException.HttpStatusCode).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -149,7 +193,7 @@ public class ExceptionHandlingMiddleware
|
||||
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false);
|
||||
context.Response.Cookies.Delete("Token");
|
||||
|
||||
if (IsApiRequest(context))
|
||||
if (IsJsonRequest(context))
|
||||
{
|
||||
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
|
||||
await WriteJsonResponseAsync(context, new
|
||||
@@ -158,7 +202,7 @@ public class ExceptionHandlingMiddleware
|
||||
errorMessage = "Unauthorized"
|
||||
});
|
||||
}
|
||||
else
|
||||
else if (IsNavigationRequest(context))
|
||||
{
|
||||
string culture = context.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
|
||||
string returnUrl = $"{context.Request.Path}{context.Request.QueryString}";
|
||||
@@ -166,6 +210,8 @@ public class ExceptionHandlingMiddleware
|
||||
_logger.LogInformation("Redirecting unauthorized user to {Url}", loginUrl);
|
||||
context.Response.Redirect(loginUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too
|
||||
}
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.Unauthorized).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -203,11 +249,38 @@ public class ExceptionHandlingMiddleware
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the current request is an API request.
|
||||
/// Checks if the current request is a programmatic request that expects a JSON response.
|
||||
/// </summary>
|
||||
private static bool IsApiRequest(HttpContext context)
|
||||
/// <remarks>
|
||||
/// Every request is classified into exactly one of three kinds: a JSON request, which this method detects, a browser navigation, which
|
||||
/// <see cref="IsNavigationRequest"/> detects, and a raw request, which is neither of the two and is answered with a bare status code.
|
||||
/// </remarks>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <returns><see langword="true"/> when the request expects JSON, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsJsonRequest(HttpContext context)
|
||||
{
|
||||
return context.Request.Headers.Accept.Any(x => x?.Contains("application/json") == true) || context.Request.Headers.XRequestedWith == "XMLHttpRequest";
|
||||
return context.Request.Headers.Accept.Any(accept => accept?.Contains("application/json", StringComparison.OrdinalIgnoreCase) == true)
|
||||
|| context.Request.Headers.XRequestedWith == "XMLHttpRequest";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the current request is a browser navigation, which is the only kind of request that can follow a redirect.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A request that explicitly asks for something other than HTML, like an audio or a media request, is answered with a bare status
|
||||
/// code: treating it as a page would redirect it to an HTML login or not-found page, which its caller cannot consume. A request that
|
||||
/// states no preference at all keeps the historical page behavior, so that callers that send no <c>Accept</c> header are not silently
|
||||
/// changed, but a request that carries no <c>Accept</c> yet asks for a byte range is treated as a raw request, because a headerless
|
||||
/// range request comes from a media client or a probe, not from a browser.
|
||||
/// </remarks>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <returns><see langword="true"/> when the request is a navigation, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsNavigationRequest(HttpContext context)
|
||||
{
|
||||
return (context.Request.Headers.Accept.Count == 0 && context.Request.Headers.Range.Count == 0)
|
||||
|| context.Request.Headers.Accept.Any(accept => accept?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true)
|
||||
|| string.Equals(context.Request.Headers["Sec-Fetch-Mode"].ToString(), "navigate", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(context.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -219,6 +292,34 @@ public class ExceptionHandlingMiddleware
|
||||
await context.Response.WriteAsJsonAsync(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the response of a raw request, which is a status code and no body.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is the third branch of the request classification, the one that answers a request that is neither a JSON request, which
|
||||
/// <see cref="IsJsonRequest"/> detects, nor a browser navigation, which <see cref="IsNavigationRequest"/> detects.
|
||||
/// </remarks>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <param name="statusCode">The status code to answer with.</param>
|
||||
private async Task WriteStatusOnlyResponseAsync(HttpContext context, int statusCode)
|
||||
{
|
||||
context.Response.StatusCode = statusCode;
|
||||
context.Response.ContentLength = 0;
|
||||
try
|
||||
{
|
||||
// Starting the response commits the status code and the headers, so that no outer middleware replaces this decision with a page,
|
||||
// and so that a caller that asked for content never receives HTML instead. A token that is never cancelled is used on purpose,
|
||||
// because a request whose token is already cancelled would otherwise throw here, inside the exception handler, and escape it.
|
||||
await context.Response.StartAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception startException)
|
||||
{
|
||||
// There is nobody left to answer, so the connection is aborted, and the failure is only recorded for diagnostics.
|
||||
_logger.LogDebug(startException, "Could not commit the status only response, the client has likely disconnected.");
|
||||
context.Abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the API exception originated from the authorization check of the currently logged in user.
|
||||
/// </summary>
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to get the playback manifest of a track.
|
||||
/// </summary>
|
||||
/// <param name="ArtistId">The unique identifier of the artist the album belongs to, taken from the route. Required.</param>
|
||||
/// <param name="AlbumId">The unique identifier of the album the track belongs to, taken from the route. Required.</param>
|
||||
/// <param name="TrackId">The unique identifier of the track whose manifest is requested, taken from the route. Required.</param>
|
||||
/// <param name="LibraryId">The Id of the media library the track belongs to. Required.</param>
|
||||
/// <param name="Capabilities">The comma separated list of the container and codec pairs the player advertises it can play directly. Optional.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId}")]
|
||||
public record GetPlaybackManifestRequest(
|
||||
string ArtistId,
|
||||
string AlbumId,
|
||||
string TrackId,
|
||||
Guid LibraryId,
|
||||
string? Capabilities
|
||||
);
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to stream the audio file of a track.
|
||||
/// </summary>
|
||||
/// <param name="ArtistId">The unique identifier of the artist the album belongs to, taken from the route. Required.</param>
|
||||
/// <param name="AlbumId">The unique identifier of the album the track belongs to, taken from the route. Required.</param>
|
||||
/// <param name="TrackId">The unique identifier of the track to stream, taken from the route. Required.</param>
|
||||
/// <param name="LibraryId">The Id of the media library the track belongs to. Required.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId}")]
|
||||
public record StreamMusicTrackRequest(
|
||||
string ArtistId,
|
||||
string AlbumId,
|
||||
string TrackId,
|
||||
Guid LibraryId
|
||||
);
|
||||
@@ -24,5 +24,7 @@ public static partial class ApiRoutes
|
||||
public const string GET_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}";
|
||||
public const string UPDATE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}";
|
||||
public const string DELETE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}";
|
||||
public const string STREAM_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream";
|
||||
public const string GET_PLAYBACK_MANIFEST = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest";
|
||||
}
|
||||
}
|
||||
@@ -28,5 +28,7 @@ public static partial class WebRoutes
|
||||
public const string GET_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-track";
|
||||
public const string SAVE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-save-track";
|
||||
public const string DELETE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-delete-track";
|
||||
public const string STREAM_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track";
|
||||
public const string GET_PLAYBACK_MANIFEST = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user