feat(cms): replace track audio in edit form, gate last-track delete
Swap a track's audio by EntryKey (metadata/release/position preserved, waveform regenerated); hide per-track remove on a release's sole persisted track so it can only be replaced or release-deleted.
This commit is contained in:
@@ -71,54 +71,11 @@ public class CmsTrackService : ICmsTrackService
|
||||
IProgress<long>? progress = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
// Two-phase cancellation for the upload send:
|
||||
//
|
||||
// BODY-STREAMING phase (while bytes are on the wire):
|
||||
// idleCts fires if no progress tick arrives within the idle window. Each
|
||||
// ProgressStreamContent chunk resets CancelAfter(idle), so a slow-but-moving
|
||||
// upload never trips it; a genuinely stalled socket does.
|
||||
//
|
||||
// RESPONSE-WAIT phase (after the last byte, while the server persists):
|
||||
// The idle heartbeat goes silent once the body is fully sent. responseCts is
|
||||
// armed at that moment with a larger budget so a fully-uploaded file is never
|
||||
// killed mid-persist. idleCts is simultaneously disarmed (CancelAfter(Infinite))
|
||||
// so it cannot misfire during the response-wait.
|
||||
//
|
||||
// sendCts links both so either deadline — plus the caller's ct — cancels the send.
|
||||
using var idleCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
idleCts.CancelAfter(_uploadIdleTimeout);
|
||||
// Build the WAV part once; the two-phase send helper owns the cancellation plumbing.
|
||||
using var phase = new UploadPhase(this, ct);
|
||||
var wavContent = phase.WrapContent(wavStream, contentLength, contentType, progress);
|
||||
|
||||
// responseCts starts disarmed; the body-complete callback below arms it.
|
||||
using var responseCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
|
||||
// Umbrella token passed to SendAsync — either phase token (or the caller) can cancel.
|
||||
using var sendCts = CancellationTokenSource.CreateLinkedTokenSource(idleCts.Token, responseCts.Token);
|
||||
|
||||
// Rebuild the multipart container so the boundary is owned by HttpClient and the
|
||||
// caller-supplied stream (already buffered by the SignalR upload) is the source.
|
||||
using var multipart = new MultipartFormDataContent();
|
||||
var wavContent = new ProgressStreamContent(
|
||||
wavStream,
|
||||
contentLength,
|
||||
written =>
|
||||
{
|
||||
// One mechanism, three consumers: advance the UI meter, reset the idle heartbeat,
|
||||
// and on body-complete transition to the response-wait budget.
|
||||
progress?.Report(written);
|
||||
if (written < contentLength)
|
||||
{
|
||||
// Body still in flight — keep the idle heartbeat alive.
|
||||
idleCts.CancelAfter(_uploadIdleTimeout);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Last byte on the wire. Disarm the idle timer and start the response budget.
|
||||
idleCts.CancelAfter(Timeout.InfiniteTimeSpan);
|
||||
responseCts.CancelAfter(_uploadResponseTimeout);
|
||||
}
|
||||
});
|
||||
wavContent.Headers.ContentType = new MediaTypeHeaderValue(
|
||||
string.IsNullOrWhiteSpace(contentType) ? "audio/wav" : contentType);
|
||||
multipart.Add(wavContent, "audioFile", fileName);
|
||||
multipart.Add(new StringContent(trackName), "trackName");
|
||||
multipart.Add(new StringContent(artist), "artist");
|
||||
@@ -135,36 +92,10 @@ public class CmsTrackService : ICmsTrackService
|
||||
// for an unrecognised value). Authoritative only when this upload creates the release.
|
||||
multipart.Add(new StringContent(medium.ToString()), "medium");
|
||||
|
||||
// Use the dedicated upload client (InfiniteTimeSpan) so the two-phase CTS logic above is the
|
||||
// sole timeout authority. Non-upload operations use the bounded "DeepDrft.Content.Cms" client.
|
||||
var client = _httpClientFactory.CreateClient(UploadClientName);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, UploadPath) { Content = multipart };
|
||||
|
||||
HttpResponseMessage response;
|
||||
try
|
||||
var send = await phase.SendAsync(UploadPath, multipart, $"upload of {trackName}");
|
||||
if (send.Response is not { } response)
|
||||
{
|
||||
response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, sendCts.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
// Either idle window (body-streaming stall) or response-wait budget (server persist too slow).
|
||||
if (idleCts.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning("Upload of {TrackName} stalled — no progress for {IdleSeconds}s; aborting.",
|
||||
trackName, _uploadIdleTimeout.TotalSeconds);
|
||||
return ResultContainer<TrackDto>.CreateFailResult(
|
||||
$"Upload stalled — no data transferred for {_uploadIdleTimeout.TotalSeconds:0}s. Please retry.");
|
||||
}
|
||||
// responseCts fired: body reached the server but persist timed out.
|
||||
_logger.LogWarning("Upload of {TrackName} timed out waiting for server response after {ResponseSeconds}s.",
|
||||
trackName, _uploadResponseTimeout.TotalSeconds);
|
||||
return ResultContainer<TrackDto>.CreateFailResult(
|
||||
$"Upload timed out waiting for the server to respond after {_uploadResponseTimeout.TotalSeconds:0}s. Please retry.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Content API call failed for upload of {TrackName}", trackName);
|
||||
return ResultContainer<TrackDto>.CreateFailResult("Content API is unreachable.");
|
||||
return ResultContainer<TrackDto>.CreateFailResult(send.FailureMessage!);
|
||||
}
|
||||
|
||||
using (response)
|
||||
@@ -208,6 +139,172 @@ public class CmsTrackService : ICmsTrackService
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result> ReplaceTrackAudioAsync(
|
||||
long id,
|
||||
Stream wavStream,
|
||||
long contentLength,
|
||||
string fileName,
|
||||
string contentType,
|
||||
IProgress<long>? progress = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
// Same two-phase send plumbing as UploadTrackAsync — a WAV replace is an equally large body.
|
||||
// The request carries only the audio part; the server resolves the track by route id and
|
||||
// preserves its metadata, so no metadata fields ride along.
|
||||
using var phase = new UploadPhase(this, ct);
|
||||
var wavContent = phase.WrapContent(wavStream, contentLength, contentType, progress);
|
||||
|
||||
using var multipart = new MultipartFormDataContent();
|
||||
multipart.Add(wavContent, "audioFile", fileName);
|
||||
|
||||
var send = await phase.SendAsync($"api/track/{id}/replace-audio", multipart, $"replace of track {id}");
|
||||
if (send.Response is not { } response)
|
||||
{
|
||||
return Result.CreateFailResult(send.FailureMessage!);
|
||||
}
|
||||
|
||||
using (response)
|
||||
{
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
return Result.CreatePassResult();
|
||||
}
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
return Result.CreateFailResult("Track not found.");
|
||||
}
|
||||
|
||||
var body = await response.Content.ReadAsStringAsync(ct);
|
||||
var statusCode = (int)response.StatusCode;
|
||||
if (statusCode >= 500)
|
||||
{
|
||||
_logger.LogError("Content API returned {Status} for replace of track {TrackId}: {Body}", statusCode, id, body);
|
||||
return Result.CreateFailResult("Replace failed on the content server. Please try again.");
|
||||
}
|
||||
|
||||
// 4xx: body is user-friendly validation text from DeepDrftAPI — relay as-is.
|
||||
_logger.LogWarning("Content API rejected replace of track {TrackId}: {Status} {Body}", id, statusCode, body);
|
||||
return Result.CreateFailResult(
|
||||
string.IsNullOrWhiteSpace(body) ? $"Replace rejected ({statusCode})." : body);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Owns the two-phase cancellation for a large-body multipart send (the original upload and the
|
||||
/// audio replace share it identically):
|
||||
///
|
||||
/// BODY-STREAMING phase (while bytes are on the wire): the idle CTS fires if no progress tick
|
||||
/// arrives within the idle window. Each <see cref="ProgressStreamContent"/> chunk resets it, so a
|
||||
/// slow-but-moving body never trips it; a genuinely stalled socket does.
|
||||
///
|
||||
/// RESPONSE-WAIT phase (after the last byte, while the server persists): the idle heartbeat goes
|
||||
/// silent, so a separate, larger budget is armed at body-complete and the idle timer is disarmed,
|
||||
/// guaranteeing a fully-sent body is never killed mid-persist.
|
||||
///
|
||||
/// The send CTS links both phase tokens plus the caller's token. Single-sourcing this here keeps
|
||||
/// the idle/response-wait behaviour identical across every large-body call.
|
||||
/// </summary>
|
||||
private sealed class UploadPhase : IDisposable
|
||||
{
|
||||
private readonly CmsTrackService _owner;
|
||||
private readonly CancellationToken _callerToken;
|
||||
private readonly CancellationTokenSource _idleCts;
|
||||
private readonly CancellationTokenSource _responseCts;
|
||||
private readonly CancellationTokenSource _sendCts;
|
||||
|
||||
public UploadPhase(CmsTrackService owner, CancellationToken callerToken)
|
||||
{
|
||||
_owner = owner;
|
||||
_callerToken = callerToken;
|
||||
_idleCts = CancellationTokenSource.CreateLinkedTokenSource(callerToken);
|
||||
_idleCts.CancelAfter(owner._uploadIdleTimeout);
|
||||
// responseCts starts disarmed; the body-complete callback arms it.
|
||||
_responseCts = CancellationTokenSource.CreateLinkedTokenSource(callerToken);
|
||||
_sendCts = CancellationTokenSource.CreateLinkedTokenSource(_idleCts.Token, _responseCts.Token);
|
||||
}
|
||||
|
||||
public ProgressStreamContent WrapContent(
|
||||
Stream wavStream, long contentLength, string contentType, IProgress<long>? progress)
|
||||
{
|
||||
var content = new ProgressStreamContent(
|
||||
wavStream,
|
||||
contentLength,
|
||||
written =>
|
||||
{
|
||||
// One mechanism, three consumers: advance the UI meter, reset the idle heartbeat,
|
||||
// and on body-complete transition to the response-wait budget.
|
||||
progress?.Report(written);
|
||||
if (written < contentLength)
|
||||
{
|
||||
_idleCts.CancelAfter(_owner._uploadIdleTimeout);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Last byte on the wire. Disarm the idle timer and start the response budget.
|
||||
_idleCts.CancelAfter(Timeout.InfiniteTimeSpan);
|
||||
_responseCts.CancelAfter(_owner._uploadResponseTimeout);
|
||||
}
|
||||
});
|
||||
content.Headers.ContentType = new MediaTypeHeaderValue(
|
||||
string.IsNullOrWhiteSpace(contentType) ? "audio/wav" : contentType);
|
||||
return content;
|
||||
}
|
||||
|
||||
public async Task<LargeBodySendResult> SendAsync(
|
||||
string path, HttpContent content, string operationLabel)
|
||||
{
|
||||
// Dedicated upload client (InfiniteTimeSpan) so the two-phase CTS logic is the sole timeout
|
||||
// authority. Non-upload operations use the bounded "DeepDrft.Content.Cms" client.
|
||||
var client = _owner._httpClientFactory.CreateClient(UploadClientName);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, path) { Content = content };
|
||||
|
||||
try
|
||||
{
|
||||
var response = await client.SendAsync(
|
||||
request, HttpCompletionOption.ResponseHeadersRead, _sendCts.Token);
|
||||
return LargeBodySendResult.Ok(response);
|
||||
}
|
||||
catch (OperationCanceledException) when (!_callerToken.IsCancellationRequested)
|
||||
{
|
||||
if (_idleCts.IsCancellationRequested)
|
||||
{
|
||||
_owner._logger.LogWarning("{Operation} stalled — no progress for {IdleSeconds}s; aborting.",
|
||||
operationLabel, _owner._uploadIdleTimeout.TotalSeconds);
|
||||
return LargeBodySendResult.Fail(
|
||||
$"Upload stalled — no data transferred for {_owner._uploadIdleTimeout.TotalSeconds:0}s. Please retry.");
|
||||
}
|
||||
_owner._logger.LogWarning("{Operation} timed out waiting for server response after {ResponseSeconds}s.",
|
||||
operationLabel, _owner._uploadResponseTimeout.TotalSeconds);
|
||||
return LargeBodySendResult.Fail(
|
||||
$"Upload timed out waiting for the server to respond after {_owner._uploadResponseTimeout.TotalSeconds:0}s. Please retry.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_owner._logger.LogError(ex, "Content API call failed for {Operation}", operationLabel);
|
||||
return LargeBodySendResult.Fail("Content API is unreachable.");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_sendCts.Dispose();
|
||||
_responseCts.Dispose();
|
||||
_idleCts.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// Outcome of a two-phase send: either a live response the caller must dispose, or a user-facing
|
||||
// failure message. Exactly one is non-null.
|
||||
private readonly struct LargeBodySendResult
|
||||
{
|
||||
public HttpResponseMessage? Response { get; private init; }
|
||||
public string? FailureMessage { get; private init; }
|
||||
|
||||
public static LargeBodySendResult Ok(HttpResponseMessage response) => new() { Response = response };
|
||||
public static LargeBodySendResult Fail(string message) => new() { FailureMessage = message };
|
||||
}
|
||||
|
||||
public async Task<Result> DeleteTrackAsync(long id, CancellationToken ct = default)
|
||||
{
|
||||
var client = _httpClientFactory.CreateClient(ContentCmsClientName);
|
||||
|
||||
Reference in New Issue
Block a user