Apply retention to refined replay originals
RetentionDays (0-365, default 7) sets OriginalsExpireAt from the end of
the live, or from publication with 0 days. The replay worker purges the
segments, source and draft of published emissions and deletes emissions
never published by the deadline, marking their flow deleted. Owners can
purge published originals early with DELETE podcasts/{id}/originals.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
46fc937443
commit
e9ffbc78be
17 changed files with 5618 additions and 27 deletions
|
|
@ -62,6 +62,16 @@ public sealed record CreatePodcastRequest
|
|||
public required string Title { get; init; }
|
||||
/// <summary>Keeps the replay private until its owner edits and publishes it.</summary>
|
||||
public bool RefineReplay { get; init; }
|
||||
/// <summary>Days the originals and draft of a refined replay are kept after the live; 0 deletes them on publication.</summary>
|
||||
[Range(0, PodcastRetention.MaxDays)]
|
||||
public int RetentionDays { get; init; } = PodcastRetention.DefaultDays;
|
||||
}
|
||||
|
||||
/// <summary>Retention bounds of the originals and draft of a refined replay.</summary>
|
||||
public static class PodcastRetention
|
||||
{
|
||||
public const int DefaultDays = 7;
|
||||
public const int MaxDays = 365;
|
||||
}
|
||||
|
||||
/// <summary>Prepares or edits an emission before its manual start.</summary>
|
||||
|
|
@ -76,6 +86,9 @@ public sealed record PreparePodcastRequest
|
|||
public string? PublicAnnouncement { get; init; }
|
||||
/// <summary>Keeps the replay private until its owner edits and publishes it. Ignored for OBS.</summary>
|
||||
public bool RefineReplay { get; init; }
|
||||
/// <summary>Days the originals and draft of a refined replay are kept after the live; 0 deletes them on publication.</summary>
|
||||
[Range(0, PodcastRetention.MaxDays)]
|
||||
public int RetentionDays { get; init; } = PodcastRetention.DefaultDays;
|
||||
}
|
||||
|
||||
/// <summary>Public presentation only; never includes playback addresses or private metadata.</summary>
|
||||
|
|
@ -98,6 +111,15 @@ public sealed record PodcastResponse(
|
|||
public bool RefineReplay { get; init; }
|
||||
/// <summary>Private draft of a refined replay; present for its owner only.</summary>
|
||||
public PodcastDraftResponse? Draft { get; init; }
|
||||
/// <summary>Days the originals and draft of a refined replay are kept after the live.</summary>
|
||||
public int RetentionDays { get; init; } = PodcastRetention.DefaultDays;
|
||||
/// <summary>
|
||||
/// When the originals and draft of a refined replay will be deleted; an emission never published by then
|
||||
/// is deleted entirely.
|
||||
/// </summary>
|
||||
public DateTimeOffset? OriginalsExpireAt { get; init; }
|
||||
/// <summary>The originals and draft were deleted; only the published MP4 remains and it cannot be re-edited.</summary>
|
||||
public bool OriginalsDeleted { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>An independently decodable MPEG-TS HLS segment.</summary>
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ public sealed class PodcastController(ILiveProcessor processor, IPodcastSchedule
|
|||
var ownerId = User.GetUserId();
|
||||
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
|
||||
var response = await processor.CreateAsync(ownerId, User.Identity?.Name ?? ownerId, request.Title, ct,
|
||||
refineReplay: request.RefineReplay);
|
||||
refineReplay: request.RefineReplay, retentionDays: request.RetentionDays);
|
||||
return CreatedAtAction(nameof(Get), new { id = response.Id }, response);
|
||||
}
|
||||
|
||||
|
|
@ -198,6 +198,21 @@ public sealed class PodcastController(ILiveProcessor processor, IPodcastSchedule
|
|||
return File(await processor.OpenDraftSourceAsync(id, ownerId, ct), "video/mp4", enableRangeProcessing: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the original segments, source and draft of a published refined replay. The published MP4
|
||||
/// remains but can no longer be re-edited. Repeating the request is harmless.
|
||||
/// </summary>
|
||||
[HttpDelete("{id:guid}/originals")]
|
||||
[ProducesResponseType<PodcastResponse>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public async Task<ActionResult<PodcastResponse>> DeleteOriginals(Guid id, CancellationToken ct)
|
||||
{
|
||||
var ownerId = User.GetUserId();
|
||||
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
|
||||
await processor.DeleteOriginalsAsync(id, ownerId, ct);
|
||||
return Ok((await schedule.GetAsync(id, ownerId, ct)).Podcast);
|
||||
}
|
||||
|
||||
/// <summary>Deletes an ended broadcast and releases its owner's podcast quota.</summary>
|
||||
[HttpDelete("{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ namespace Yavsc.Api.Services;
|
|||
|
||||
public sealed class PodcastReplayWorker(
|
||||
ILiveProcessor processor, IPodcastReplayRemuxer remuxer, IPodcastReplayEditor editor,
|
||||
ILogger<PodcastReplayWorker> logger) : BackgroundService
|
||||
IServiceScopeFactory scopes, ILogger<PodcastReplayWorker> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
|
|
@ -14,6 +14,7 @@ public sealed class PodcastReplayWorker(
|
|||
{
|
||||
if (await processor.PrepareNextReplayAsync(remuxer, stoppingToken)) continue;
|
||||
if (await processor.PublishNextDraftAsync(editor, stoppingToken)) continue;
|
||||
await ApplyRetentionAsync(stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
||||
catch (Exception ex)
|
||||
|
|
@ -24,4 +25,14 @@ public sealed class PodcastReplayWorker(
|
|||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Purges expired refined replay originals and forgets the emissions that expired unpublished.</summary>
|
||||
private async Task ApplyRetentionAsync(CancellationToken ct)
|
||||
{
|
||||
var expired = await processor.PurgeExpiredOriginalsAsync(ct);
|
||||
if (expired.Count == 0) return;
|
||||
await using var scope = scopes.CreateAsyncScope();
|
||||
await scope.ServiceProvider.GetRequiredService<IPodcastScheduleService>()
|
||||
.MarkExpiredAsync(expired.Select(p => p.Id).ToArray(), ct);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ public interface IPodcastScheduleService
|
|||
Task<PodcastManifestResponse> GetAsync(Guid id, string ownerId, CancellationToken ct);
|
||||
Task<IReadOnlyList<PodcastAnnouncementResponse>> AnnouncementsAsync(CancellationToken ct);
|
||||
Task DeleteAsync(Guid id, string ownerId, CancellationToken ct);
|
||||
/// <summary>Marks the emissions whose media expired unpublished as deleted.</summary>
|
||||
Task MarkExpiredAsync(IReadOnlyCollection<Guid> ids, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcessor processor,
|
||||
|
|
@ -29,8 +31,9 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
|
|||
{
|
||||
if (string.IsNullOrWhiteSpace(request.Title) || request.Title.Trim().Length > 160
|
||||
|| request.ScheduledStartAt == default || request.PlannedDurationMinutes < 1
|
||||
|| request.PublicAnnouncement?.Length > 1023)
|
||||
throw new PodcastException(400, "Titre, debut et duree positive en minutes requis.");
|
||||
|| request.PublicAnnouncement?.Length > 1023
|
||||
|| request.RetentionDays is < 0 or > PodcastRetention.MaxDays)
|
||||
throw new PodcastException(400, "Titre, debut, duree positive en minutes et conservation de 0 a 365 jours requis.");
|
||||
await Gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
|
|
@ -59,6 +62,7 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
|
|||
flow.PlannedDurationMinutes = request.PlannedDurationMinutes;
|
||||
flow.PublicAnnouncement = request.PublicAnnouncement?.Trim() ?? "";
|
||||
flow.RefineReplay = request.RefineReplay;
|
||||
flow.RetentionDays = request.RetentionDays;
|
||||
await db.SaveChangesAsync(ct);
|
||||
await db.Entry(flow).Reference(f => f.Owner).LoadAsync(ct);
|
||||
return Planned(flow);
|
||||
|
|
@ -90,7 +94,7 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
|
|||
throw new PodcastException(404, "Les medias de cette emission sont introuvables.");
|
||||
// OBS composes and finalizes its own content: refinement only applies to PostIt captures.
|
||||
var podcast = await processor.CreateAsync(ownerId, flow.Owner.UserName ?? ownerId, flow.Title, ct, id,
|
||||
refineReplay: flow.RefineReplay && !obsConnectionId.HasValue);
|
||||
refineReplay: flow.RefineReplay && !obsConnectionId.HasValue, retentionDays: flow.RetentionDays);
|
||||
flow.StartedAt ??= podcast.CreatedAt;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Enrich(podcast, flow);
|
||||
|
|
@ -172,6 +176,20 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
|
|||
finally { Gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task MarkExpiredAsync(IReadOnlyCollection<Guid> ids, CancellationToken ct)
|
||||
{
|
||||
if (ids.Count == 0) return;
|
||||
await Gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
foreach (var flow in await db.LiveFlow.Where(f => f.PodcastId != null && ids.Contains(f.PodcastId.Value))
|
||||
.ToListAsync(ct))
|
||||
flow.PodcastDeleted = true;
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
finally { Gate.Release(); }
|
||||
}
|
||||
|
||||
private async Task<LiveFlow> OwnedAsync(Guid id, string ownerId, CancellationToken ct)
|
||||
{
|
||||
var flow = await db.LiveFlow.Include(f => f.Owner).SingleOrDefaultAsync(f => f.PodcastId == id, ct);
|
||||
|
|
@ -184,7 +202,7 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
|
|||
flow.PodcastId!.Value, flow.Title, flow.OwnerId, flow.Owner.UserName ?? flow.OwnerId,
|
||||
flow.PreparedAt!.Value, flow.PreparedAt.Value, PodcastState.Planned, 0, 0, 0)
|
||||
{
|
||||
RefineReplay = flow.RefineReplay && flow.ObsKeyHash is null
|
||||
RefineReplay = flow.RefineReplay && flow.ObsKeyHash is null, RetentionDays = flow.RetentionDays
|
||||
}, flow);
|
||||
|
||||
private static PodcastResponse Enrich(PodcastResponse podcast, LiveFlow flow) => podcast with
|
||||
|
|
|
|||
5248
src/Yavsc.Org/Migrations/20261116142650_PodcastReplayRetention.Designer.cs
generated
Normal file
5248
src/Yavsc.Org/Migrations/20261116142650_PodcastReplayRetention.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,29 @@
|
|||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Yavsc.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class PodcastReplayRetention : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "RetentionDays",
|
||||
table: "LiveFlow",
|
||||
type: "integer",
|
||||
nullable: false,
|
||||
defaultValue: 7);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "RetentionDays",
|
||||
table: "LiveFlow");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -3247,6 +3247,9 @@ namespace Yavsc.Migrations
|
|||
b.Property<bool>("RefineReplay")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("RetentionDays")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateTimeOffset?>("ScheduledStartAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ else
|
|||
{
|
||||
<p class="alert alert-info">@Localizer["Replay en préparation."]</p>
|
||||
}
|
||||
else if (podcast.SegmentCount > 0)
|
||||
else if (ready || podcast.SegmentCount > 0)
|
||||
{
|
||||
<video controls playsinline preload="none" class="w-100"
|
||||
aria-label="@podcast.Title" data-podcast-player
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ namespace Yavsc.Services
|
|||
Task<bool> AcceptStream (HttpContext context, ApplicationUser user, string destDir, string fileName);
|
||||
|
||||
Task<PodcastResponse> CreateAsync(string ownerId, string ownerName, string title, CancellationToken ct,
|
||||
Guid? id = null, bool refineReplay = false);
|
||||
Guid? id = null, bool refineReplay = false, int retentionDays = PodcastRetention.DefaultDays);
|
||||
Task<IReadOnlyList<PodcastResponse>> ListAsync(CancellationToken ct);
|
||||
Task<PodcastManifestResponse> GetAsync(Guid id, CancellationToken ct);
|
||||
Task<PodcastResponse> AppendAsync(Guid id, string ownerId, int sequence,
|
||||
|
|
@ -36,6 +36,13 @@ namespace Yavsc.Services
|
|||
Task<PodcastResponse> PublishDraftAsync(Guid id, string ownerId, int revision, CancellationToken ct);
|
||||
Task<Stream> OpenDraftSourceAsync(Guid id, string ownerId, CancellationToken ct);
|
||||
Task<bool> PublishNextDraftAsync(IPodcastReplayEditor editor, CancellationToken ct);
|
||||
/// <summary>Deletes the originals and draft of a published refined replay; the MP4 remains.</summary>
|
||||
Task<PodcastResponse> DeleteOriginalsAsync(Guid id, string ownerId, CancellationToken ct);
|
||||
/// <summary>
|
||||
/// Applies the retention of refined replays: purges the originals of published ones and deletes
|
||||
/// the emissions never published before their deadline, which are returned.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<PodcastResponse>> PurgeExpiredOriginalsAsync(CancellationToken ct);
|
||||
Task DeleteAsync(Guid id, string ownerId, CancellationToken ct);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ namespace Yavsc.Models.Streaming
|
|||
public bool PodcastDeleted { get; set; }
|
||||
/// <summary>Keeps the replay private until its owner edits and publishes it; ignored for OBS.</summary>
|
||||
public bool RefineReplay { get; set; }
|
||||
/// <summary>Days the originals and draft of a refined replay are kept after the live (0 to 365).</summary>
|
||||
public int RetentionDays { get; set; } = PodcastRetention.DefaultDays;
|
||||
[MaxLength(64), System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]
|
||||
public string? ObsKeyHash { get; set; }
|
||||
[System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]
|
||||
|
|
|
|||
|
|
@ -45,10 +45,12 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
|
|||
}
|
||||
|
||||
public async Task<PodcastResponse> CreateAsync(string ownerId, string ownerName, string title, CancellationToken ct,
|
||||
Guid? id = null, bool refineReplay = false)
|
||||
Guid? id = null, bool refineReplay = false, int retentionDays = PodcastRetention.DefaultDays)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(ownerId) || string.IsNullOrWhiteSpace(title) || title.Trim().Length > 160)
|
||||
throw new PodcastException(400, "Un titre de 1 a 160 caracteres et un utilisateur sont requis.");
|
||||
if (retentionDays is < 0 or > PodcastRetention.MaxDays)
|
||||
throw new PodcastException(400, $"La conservation des originaux va de 0 a {PodcastRetention.MaxDays} jours.");
|
||||
await _gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
|
|
@ -68,7 +70,7 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
|
|||
throw new PodcastException(413, "Nombre maximal de podcasts atteint. Supprimez un ancien replay.");
|
||||
var now = _clock.GetUtcNow();
|
||||
var podcast = new PodcastResponse(id ?? Guid.NewGuid(), title.Trim(), ownerId, ownerName,
|
||||
now, now, PodcastState.Live, 0, 0, 0) { RefineReplay = refineReplay };
|
||||
now, now, PodcastState.Live, 0, 0, 0) { RefineReplay = refineReplay, RetentionDays = retentionDays };
|
||||
var document = new Document(new(podcast, Array.Empty<PodcastSegmentResponse>()), Array.Empty<string>());
|
||||
Directory.CreateDirectory(DirectoryFor(podcast.Id));
|
||||
await SaveAsync(document, ct);
|
||||
|
|
@ -197,11 +199,13 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
|
|||
var podcast = document.Manifest.Podcast;
|
||||
if (podcast.State == PodcastState.Completed)
|
||||
return podcast;
|
||||
var now = _clock.GetUtcNow();
|
||||
var updated = podcast with
|
||||
{
|
||||
State = PodcastState.Completed, UpdatedAt = _clock.GetUtcNow(),
|
||||
State = PodcastState.Completed, UpdatedAt = now,
|
||||
Replay = podcast.Replay ?? new(PodcastReplayState.Pending),
|
||||
Draft = podcast.RefineReplay ? podcast.Draft ?? NewDraft() : null
|
||||
Draft = podcast.RefineReplay ? podcast.Draft ?? NewDraft() : null,
|
||||
OriginalsExpireAt = podcast.OriginalsExpireAt ?? EndExpiry(podcast, now)
|
||||
};
|
||||
await SaveAsync(document with { Manifest = document.Manifest with { Podcast = updated } }, ct);
|
||||
_logger.LogInformation("Podcast {PodcastId} completed with {Segments} segments", id, updated.SegmentCount);
|
||||
|
|
@ -364,6 +368,10 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
|
|||
|
||||
private static PodcastDraftResponse NewDraft() => new(PodcastDraftState.Preparing, 0, [], []);
|
||||
|
||||
/// <summary>The retention delay runs from the end of the live; with 0 days it starts on publication.</summary>
|
||||
private static DateTimeOffset? EndExpiry(PodcastResponse podcast, DateTimeOffset endedAt)
|
||||
=> podcast.RefineReplay && podcast.RetentionDays > 0 ? endedAt.AddDays(podcast.RetentionDays) : null;
|
||||
|
||||
private static bool IsRemuxQueued(PodcastResponse podcast) => podcast.RefineReplay
|
||||
? podcast.Draft?.State == PodcastDraftState.Preparing
|
||||
: podcast.State == PodcastState.Completed && podcast.Replay?.State == PodcastReplayState.Pending;
|
||||
|
|
@ -375,6 +383,8 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
|
|||
{
|
||||
var document = Owned(id, ownerId);
|
||||
var draft = document.Manifest.Podcast.Draft;
|
||||
if (document.Manifest.Podcast.OriginalsDeleted)
|
||||
throw new PodcastException(409, "Les originaux ont ete supprimes : ce replay ne peut plus etre reedite.");
|
||||
if (!document.Manifest.Podcast.RefineReplay || draft is null)
|
||||
throw new PodcastException(409, "Ce replay n'est pas en cours de raffinage.");
|
||||
if (draft.State != PodcastDraftState.Ready)
|
||||
|
|
@ -519,7 +529,9 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
|
|||
Draft = latest.Draft! with
|
||||
{
|
||||
State = PodcastDraftState.Ready, PublishedRevision = draft.Revision, Error = null
|
||||
}
|
||||
},
|
||||
OriginalsExpireAt = latest.OriginalsExpireAt
|
||||
?? (latest.RetentionDays == 0 ? _clock.GetUtcNow() : null)
|
||||
};
|
||||
await SaveAsync(current with { Manifest = current.Manifest with { Podcast = updated } }, ct);
|
||||
_logger.LogInformation("Podcast {PodcastId} draft revision {Revision} published ({Bytes} bytes)",
|
||||
|
|
@ -593,6 +605,73 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
|
|||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<PodcastResponse> DeleteOriginalsAsync(Guid id, string ownerId, CancellationToken ct)
|
||||
{
|
||||
await _gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await LoadAsync(ct);
|
||||
var document = Owned(id, ownerId);
|
||||
var podcast = document.Manifest.Podcast;
|
||||
if (podcast.OriginalsDeleted) return podcast;
|
||||
if (!podcast.RefineReplay || PublishedBytes(podcast) == 0)
|
||||
throw new PodcastException(409, "Les originaux ne peuvent etre supprimes qu'apres la publication du replay.");
|
||||
if (!CanPurge(document))
|
||||
throw new PodcastException(409, "Publication en cours. Reessayez apres sa finalisation.");
|
||||
return await PurgeOriginalsAsync(document, ct);
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<PodcastResponse>> PurgeExpiredOriginalsAsync(CancellationToken ct)
|
||||
{
|
||||
await _gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
await LoadAsync(ct);
|
||||
var now = _clock.GetUtcNow();
|
||||
var removed = new List<PodcastResponse>();
|
||||
foreach (var document in _documents.Values.Where(d => d.Manifest.Podcast is
|
||||
{ RefineReplay: true, OriginalsDeleted: false, OriginalsExpireAt: { } expiry } && expiry <= now
|
||||
&& CanPurge(d)).ToArray())
|
||||
{
|
||||
var podcast = document.Manifest.Podcast;
|
||||
if (PublishedBytes(podcast) > 0)
|
||||
{
|
||||
await PurgeOriginalsAsync(document, ct);
|
||||
continue;
|
||||
}
|
||||
// Nothing was published before the deadline: the whole emission expires.
|
||||
Directory.Delete(DirectoryFor(podcast.Id), recursive: true);
|
||||
_documents.Remove(podcast.Id);
|
||||
removed.Add(podcast);
|
||||
_logger.LogInformation("Unpublished refined podcast {PodcastId} expired and was deleted", podcast.Id);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
private bool CanPurge(Document document) => _preparingReplay != document.Manifest.Podcast.Id
|
||||
&& document.Manifest.Podcast.Draft?.State is not (PodcastDraftState.Preparing or PodcastDraftState.Publishing);
|
||||
|
||||
private async Task<PodcastResponse> PurgeOriginalsAsync(Document document, CancellationToken ct)
|
||||
{
|
||||
var podcast = document.Manifest.Podcast;
|
||||
var directory = DirectoryFor(podcast.Id);
|
||||
foreach (var segment in document.Manifest.Segments) File.Delete(SegmentPath(podcast.Id, segment.Sequence));
|
||||
File.Delete(Path.Combine(directory, SourceFileName));
|
||||
File.Delete(Path.Combine(directory, "source.tmp.mp4"));
|
||||
var updated = podcast with
|
||||
{
|
||||
SegmentCount = 0, Bytes = PublishedBytes(podcast), Draft = null,
|
||||
OriginalsExpireAt = null, OriginalsDeleted = true
|
||||
};
|
||||
await SaveAsync(new(new(updated, []), []), ct);
|
||||
_logger.LogInformation("Podcast {PodcastId} originals and draft deleted; the published MP4 remains", podcast.Id);
|
||||
return updated;
|
||||
}
|
||||
|
||||
private async Task LoadAsync(CancellationToken ct)
|
||||
{
|
||||
if (_loaded) return;
|
||||
|
|
@ -633,7 +712,8 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
|
|||
if (podcast.RefineReplay)
|
||||
podcast = podcast with
|
||||
{
|
||||
Replay = podcast.Replay ?? new(PodcastReplayState.Pending), Draft = podcast.Draft ?? NewDraft()
|
||||
Replay = podcast.Replay ?? new(PodcastReplayState.Pending), Draft = podcast.Draft ?? NewDraft(),
|
||||
OriginalsExpireAt = podcast.OriginalsExpireAt ?? EndExpiry(podcast, podcast.UpdatedAt)
|
||||
};
|
||||
await SaveAsync(document with { Manifest = document.Manifest with { Podcast = podcast } }, ct);
|
||||
_logger.LogWarning("Podcast {PodcastId} interrupted; committed segments remain playable", podcast.Id);
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ public static class PodcastVisibility
|
|||
=> podcast.RefineReplay && podcast.State != PodcastState.Live;
|
||||
|
||||
public static PodcastResponse ForViewer(PodcastResponse podcast, string? viewerId)
|
||||
=> podcast.OwnerId == viewerId ? podcast : podcast with { Draft = null };
|
||||
=> podcast.OwnerId == viewerId ? podcast : podcast with { Draft = null, OriginalsExpireAt = null };
|
||||
|
||||
public static PodcastManifestResponse ForViewer(PodcastManifestResponse manifest, string? viewerId)
|
||||
=> manifest.Podcast.OwnerId == viewerId ? manifest : manifest with
|
||||
|
|
|
|||
|
|
@ -221,6 +221,21 @@ public sealed class PodcastControllerTests(ApiWebServerFixture fixture) : IClass
|
|||
var published = (await owner.GetFromJsonAsync<PodcastManifestResponse>(path, _ct))!.Podcast;
|
||||
Assert.Equal(1, published.Draft!.PublishedRevision);
|
||||
Assert.Equal([2500L], published.Draft.Marks);
|
||||
|
||||
using (var denied = await listener.DeleteAsync($"{path}/originals", _ct))
|
||||
Assert.Equal(HttpStatusCode.Forbidden, denied.StatusCode);
|
||||
using (var purged = await owner.DeleteAsync($"{path}/originals", _ct))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.OK, purged.StatusCode);
|
||||
var podcastAfter = (await purged.Content.ReadFromJsonAsync<PodcastResponse>(_ct))!;
|
||||
Assert.True(podcastAfter.OriginalsDeleted);
|
||||
Assert.Null(podcastAfter.Draft);
|
||||
}
|
||||
using (var source = await owner.GetAsync($"{path}/draft/source.mp4", _ct))
|
||||
Assert.Equal(HttpStatusCode.Conflict, source.StatusCode);
|
||||
using (var segment = await owner.GetAsync($"{path}/segments/0.ts", _ct))
|
||||
Assert.Equal(HttpStatusCode.NotFound, segment.StatusCode);
|
||||
Assert.Equal(mp4, await listener.GetByteArrayAsync($"{path}/replay.mp4", _ct));
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
|
|||
|
|
@ -71,6 +71,45 @@ public sealed class PodcastObsTests : IAsyncDisposable
|
|||
}, null, Ct);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Planned_retention_is_kept_and_an_unpublished_expired_emission_is_forgotten()
|
||||
{
|
||||
using var scope = provider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
db.Users.Add(new() { Id = "owner", UserName = "owner", Email = "owner@example.test" });
|
||||
await db.SaveChangesAsync(Ct);
|
||||
var schedule = scope.ServiceProvider.GetRequiredService<IPodcastScheduleService>();
|
||||
PreparePodcastRequest Request(int days) => new()
|
||||
{
|
||||
Title = "Raffinee", ScheduledStartAt = clock.Now.AddDays(1), PlannedDurationMinutes = 1,
|
||||
RefineReplay = true, RetentionDays = days
|
||||
};
|
||||
Assert.Equal(400, (await Assert.ThrowsAsync<PodcastException>(
|
||||
() => schedule.PrepareAsync("owner", Request(366), null, Ct))).StatusCode);
|
||||
var plan = await schedule.PrepareAsync("owner", Request(3), null, Ct);
|
||||
Assert.Equal(3, plan.RetentionDays);
|
||||
var started = await schedule.StartAsync(plan.Id, "owner", Ct);
|
||||
Assert.Equal(3, started.RetentionDays);
|
||||
var processor = provider.GetRequiredService<ILiveProcessor>();
|
||||
var completed = await processor.CompleteAsync(plan.Id, "owner", Ct);
|
||||
Assert.Equal(clock.Now.AddDays(3), completed.OriginalsExpireAt);
|
||||
Assert.True(await processor.PrepareNextReplayAsync(new SourceRemuxer(), Ct));
|
||||
|
||||
clock.Now = clock.Now.AddDays(3);
|
||||
var expired = await processor.PurgeExpiredOriginalsAsync(Ct);
|
||||
await schedule.MarkExpiredAsync(expired.Select(p => p.Id).ToArray(), Ct);
|
||||
Assert.True((await db.LiveFlow.AsNoTracking().SingleAsync(Ct)).PodcastDeleted);
|
||||
Assert.Empty(await schedule.ListAsync("owner", Ct));
|
||||
Assert.Equal(404, (await Assert.ThrowsAsync<PodcastException>(
|
||||
() => schedule.GetAsync(plan.Id, "owner", Ct))).StatusCode);
|
||||
}
|
||||
|
||||
private sealed class SourceRemuxer : IPodcastReplayRemuxer
|
||||
{
|
||||
public Task RemuxAsync(string directory, int count, string output, long max, CancellationToken ct)
|
||||
=> File.WriteAllBytesAsync(output, [1], ct);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Activation_is_owned_rotatable_expiring_and_keeps_secrets_only_in_memory()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -16,10 +16,13 @@ public sealed class PodcastReplayTests : IDisposable
|
|||
private readonly List<LiveProcessor> _processors = [];
|
||||
private readonly CancellationToken _ct = TestContext.Current.CancellationToken;
|
||||
|
||||
private readonly Clock _clock = new();
|
||||
|
||||
private LiveProcessor New(long quota = 1024 * 1024)
|
||||
{
|
||||
var processor = new LiveProcessor(NullLoggerFactory.Instance,
|
||||
Options.Create(new PodcastOptions { RootPath = _root, MaxSegmentBytes = 1024 * 1024, MaxOwnerBytes = quota }));
|
||||
Options.Create(new PodcastOptions { RootPath = _root, MaxSegmentBytes = 1024 * 1024, MaxOwnerBytes = quota }),
|
||||
_clock);
|
||||
_processors.Add(processor);
|
||||
return processor;
|
||||
}
|
||||
|
|
@ -274,9 +277,11 @@ public sealed class PodcastReplayTests : IDisposable
|
|||
Assert.Equal("video", probe.Trim());
|
||||
}
|
||||
|
||||
private async Task<PodcastResponse> Refined(LiveProcessor processor, int sourceBytes = 10)
|
||||
private async Task<PodcastResponse> Refined(LiveProcessor processor, int sourceBytes = 10,
|
||||
int retentionDays = PodcastRetention.DefaultDays)
|
||||
{
|
||||
var podcast = await processor.CreateAsync("alice", "alice", "Refined", _ct, refineReplay: true);
|
||||
var podcast = await processor.CreateAsync("alice", "alice", "Refined", _ct, refineReplay: true,
|
||||
retentionDays: retentionDays);
|
||||
await processor.AppendAsync(podcast.Id, "alice", 0, 2, new MemoryStream(LiveProcessorTests.Packets()), _ct);
|
||||
await processor.AppendAsync(podcast.Id, "alice", 1, 2, new MemoryStream(LiveProcessorTests.Packets()), _ct);
|
||||
var completed = await processor.CompleteAsync(podcast.Id, "alice", _ct);
|
||||
|
|
@ -421,6 +426,83 @@ public sealed class PodcastReplayTests : IDisposable
|
|||
Assert.Equal(3, completed.Draft!.SourceBytes);
|
||||
}
|
||||
|
||||
private async Task<PodcastResponse> Publish(LiveProcessor processor, PodcastResponse podcast)
|
||||
{
|
||||
await processor.PublishDraftAsync(podcast.Id, "alice", podcast.Draft!.Revision, _ct);
|
||||
Assert.True(await processor.PublishNextDraftAsync(new Editor((_, _, _, _, _) => Task.CompletedTask), _ct));
|
||||
return (await processor.GetAsync(podcast.Id, _ct)).Podcast;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Retention_purges_published_originals_at_the_deadline_and_deletes_unpublished_emissions()
|
||||
{
|
||||
var processor = New();
|
||||
var ended = _clock.Now;
|
||||
var published = await Publish(processor, await Refined(processor));
|
||||
var unpublished = await Refined(processor);
|
||||
var publishing = await Refined(processor);
|
||||
Assert.Equal(ended.AddDays(7), published.OriginalsExpireAt);
|
||||
Assert.Null(PodcastVisibility.ForViewer(published, "bob").OriginalsExpireAt);
|
||||
await processor.PublishDraftAsync(publishing.Id, "alice", 0, _ct);
|
||||
|
||||
_clock.Now = ended.AddDays(7).AddTicks(-1);
|
||||
Assert.Empty(await processor.PurgeExpiredOriginalsAsync(_ct));
|
||||
Assert.False((await processor.GetAsync(published.Id, _ct)).Podcast.OriginalsDeleted);
|
||||
|
||||
_clock.Now = ended.AddDays(7);
|
||||
processor = New(); // The deadlines survive a restart.
|
||||
Assert.Equal([unpublished.Id], (await processor.PurgeExpiredOriginalsAsync(_ct)).Select(p => p.Id));
|
||||
Assert.False(Directory.Exists(Path.Combine(_root, unpublished.Id.ToString("N"))));
|
||||
Assert.Equal(404, (await Assert.ThrowsAsync<PodcastException>(
|
||||
() => processor.GetAsync(unpublished.Id, _ct))).StatusCode);
|
||||
|
||||
var purged = await processor.GetAsync(published.Id, _ct);
|
||||
Assert.True(purged.Podcast.OriginalsDeleted);
|
||||
Assert.Null(purged.Podcast.Draft);
|
||||
Assert.Null(purged.Podcast.OriginalsExpireAt);
|
||||
Assert.Empty(purged.Segments);
|
||||
Assert.Equal(0, purged.Podcast.SegmentCount);
|
||||
Assert.Equal(10, purged.Podcast.Bytes); // Only the published MP4 is still counted.
|
||||
var directory = Path.Combine(_root, published.Id.ToString("N"));
|
||||
Assert.Equal(["index.json", "replay.mp4"], Directory.GetFiles(directory).Select(Path.GetFileName).Order());
|
||||
await using (var replay = await processor.OpenReplayAsync(published.Id, _ct)) Assert.Equal(10, replay.Length);
|
||||
Assert.Equal(409, (await Assert.ThrowsAsync<PodcastException>(() => processor.SaveDraftAsync(
|
||||
published.Id, "alice", Save(0, []), _ct))).StatusCode);
|
||||
Assert.Equal(409, (await Assert.ThrowsAsync<PodcastException>(
|
||||
() => processor.OpenDraftSourceAsync(published.Id, "alice", _ct))).StatusCode);
|
||||
|
||||
// A queued publication finishes before its originals are purged.
|
||||
Assert.False((await processor.GetAsync(publishing.Id, _ct)).Podcast.OriginalsDeleted);
|
||||
Assert.True(await processor.PublishNextDraftAsync(new Editor((_, _, _, _, _) => Task.CompletedTask), _ct));
|
||||
Assert.Empty(await processor.PurgeExpiredOriginalsAsync(_ct));
|
||||
Assert.True((await processor.GetAsync(publishing.Id, _ct)).Podcast.OriginalsDeleted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Zero_day_retention_starts_on_publication_and_owner_can_delete_published_originals()
|
||||
{
|
||||
var processor = New();
|
||||
Assert.Equal(400, (await Assert.ThrowsAsync<PodcastException>(() => processor.CreateAsync(
|
||||
"alice", "alice", "Too long", _ct, refineReplay: true, retentionDays: 366))).StatusCode);
|
||||
var immediate = await Refined(processor, retentionDays: 0);
|
||||
Assert.Null(immediate.OriginalsExpireAt);
|
||||
_clock.Now = _clock.Now.AddYears(1);
|
||||
Assert.Empty(await processor.PurgeExpiredOriginalsAsync(_ct));
|
||||
Assert.Equal(409, (await Assert.ThrowsAsync<PodcastException>(
|
||||
() => processor.DeleteOriginalsAsync(immediate.Id, "alice", _ct))).StatusCode);
|
||||
Assert.Equal(_clock.Now, (await Publish(processor, immediate)).OriginalsExpireAt);
|
||||
Assert.Empty(await processor.PurgeExpiredOriginalsAsync(_ct));
|
||||
Assert.True((await processor.GetAsync(immediate.Id, _ct)).Podcast.OriginalsDeleted);
|
||||
|
||||
var kept = await Publish(processor, await Refined(processor));
|
||||
Assert.Equal(403, (await Assert.ThrowsAsync<PodcastException>(
|
||||
() => processor.DeleteOriginalsAsync(kept.Id, "bob", _ct))).StatusCode);
|
||||
var deleted = await processor.DeleteOriginalsAsync(kept.Id, "alice", _ct);
|
||||
Assert.True(deleted.OriginalsDeleted);
|
||||
Assert.Equal(deleted, await processor.DeleteOriginalsAsync(kept.Id, "alice", _ct));
|
||||
Assert.False(File.Exists(Path.Combine(_root, kept.Id.ToString("N"), "source.mp4")));
|
||||
}
|
||||
|
||||
private static Remuxer Bytes(int count) => new((_, _, output, _, ct) => File.WriteAllBytesAsync(output, new byte[count], ct));
|
||||
private sealed class Editor(Func<string, IReadOnlyList<ReplayRange>, string, long, CancellationToken, Task> render)
|
||||
: IPodcastReplayEditor
|
||||
|
|
@ -429,6 +511,12 @@ public sealed class PodcastReplayTests : IDisposable
|
|||
=> render(source, kept, output, max, ct);
|
||||
}
|
||||
|
||||
private sealed class Clock : TimeProvider
|
||||
{
|
||||
public DateTimeOffset Now { get; set; } = DateTimeOffset.UtcNow;
|
||||
public override DateTimeOffset GetUtcNow() => Now;
|
||||
}
|
||||
|
||||
private sealed class Remuxer(Func<string, int, string, long, CancellationToken, Task> remux) : IPodcastReplayRemuxer
|
||||
{
|
||||
public Task RemuxAsync(string directory, int count, string output, long max, CancellationToken ct)
|
||||
|
|
|
|||
Loading…
Reference in a new issue