using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
///
/// The .part files a crash left in a destination (spec ยง4.10): removed only in the folders where the items of
/// an unfinished job were to be written, never by a scan of the destination, never in a folder of no item. Only our
/// own temporary names (.febe-*.part, the probes included) are touched.
///
public static class ExportLeftovers
{
private const int PageSize = 1000;
/// Removes our temporary files in the folders of the items of . Returns how many.
public static async Task CleanAsync(ExportEnvironment env, ExportRun run, ExportDestination destination, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(env);
ArgumentNullException.ThrowIfNull(run);
ArgumentNullException.ThrowIfNull(destination);
if (ExportRoots.MountProblem(env.Root, destination.RootPath) is not null || !await AnswersAsync(env, destination.RootPath, ct).ConfigureAwait(false))
{
return 0;
}
var folders = new HashSet(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
long after = 0;
while (true)
{
var page = await env.Storage.Exports.ListItemsAsync(new ExportItemQuery { RunId = run.Id, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false);
if (page.Count == 0)
{
break;
}
after = page[^1].Id;
foreach (var item in page)
{
if (item.RelativePath is { } relative && item.State is ExportItemState.Pending or ExportItemState.Failed)
{
try
{
if (Path.GetDirectoryName(LibraryLayout.FullPath(destination.RootPath, relative)) is { } folder)
{
folders.Add(folder);
}
}
catch (ArgumentException)
{
// A path that would leave the root: nothing of ours can be there.
}
}
}
}
var removed = 0;
foreach (var folder in folders)
{
ct.ThrowIfCancellationRequested();
try
{
removed += await Task.Run(() => SafeFileWriter.CleanupTemporaryFiles(folder, recursive: false), ct).WaitAsync(env.FolderCheckTimeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
return removed; // the disk stopped answering: the next resume tries again
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Best effort: a leftover .part takes some space, nothing more.
}
}
return removed;
}
private static async Task AnswersAsync(ExportEnvironment env, string root, CancellationToken ct)
{
try
{
return await Task.Run(() => Directory.Exists(root), ct).WaitAsync(env.FolderCheckTimeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
return false;
}
}
}