Files
Chronos/src/Chronos.Core.Windows/Devices/VolumeInfo.cs
T
Alby96 67a6d51cbe fix(archive): convert job applies exactly the confirmed plan, resumes safely and watches its space
The convert job planned every sequence again when it ran and checked only the frames
version, so a verify, a repaired upload or a tier change between the dry run and the job
let it replace photos the confirmed plan had listed as staying unchanged.

- Each sequence of a convert job now carries the digest of the photos it converts, each
  with its SHA-256 (ConvertSequencePlan.Digest, also in the plan's fingerprint). Under the
  sequence's lease, its sidecar settled, the job plans it again and goes on only while the
  digest matches; it then pins those photos (convert-<job>.pins), so photos that come in
  or are verified later stay as they are, a retry included. Stage B checks under the lease
  that every pinned photo still holds the content converted instead of holding the frames
  version, so a sequence still receiving uploads converts what was confirmed.
- A resumed job settles the journals a crash left in a sequence (a half-done replacement
  among them) before it plans, and reports a sequence its replacement completed as
  Converted, never Nothing or a partial swap.
- The passes a converted or new sequence needs are queued as soon as its outcome is
  journaled; the journal records the statuses they follow from and whether they were
  queued, so a pause, yield, stop or crash no longer loses them.
- Staged conversions of a blocked or failed sequence are kept for the retry, which
  re-verifies and takes them; maintenance keeps a convert job's staging while the job is
  queued, running or paused, and removes its journal and staging once the job is done or
  gone from the history.
- A dry run counts the sequences of a queued conversion as busy, so the same conversion
  cannot be confirmed twice.
- New sequence copies are owned by the source's owner, else by the requesting user's id
  (never the user name); a staged copy that vanished fails the sequence instead of leaving
  its photo out; the job log states how many photos stayed in the source alone.
- Free space is measured where the conversion writes: the server takes the tighter of the
  space path's volume and the archive's own (Unraid cache), the desktop asks Windows
  (GetDiskFreeSpaceEx), which also measures UNC archives; the job checks again before each
  sequence and each photo, scaling estimates by the files staged so far, and stops before
  the volume fills with what it staged kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 2d7d461c33b9f257bf57793cc7cf331d0425c14e)
2026-10-27 22:06:55 +01:00

113 lines
4.6 KiB
C#

using System.Globalization;
namespace Chronos.Core.Windows.Devices;
/// <summary>GetDriveTypeW results.</summary>
public enum VolumeDriveType
{
Unknown = 0,
NoRootDirectory = 1,
Removable = 2,
Fixed = 3,
Remote = 4,
CdRom = 5,
RamDisk = 6,
}
/// <summary>A mounted volume with the facts card import needs (BRIEF §12.4, §13).</summary>
/// <param name="RootPath">Root with trailing separator, e.g. <c>E:\</c>.</param>
/// <param name="Label">Volume label (may be empty).</param>
/// <param name="FileSystem">File system name, e.g. exFAT.</param>
/// <param name="SerialNumber">Volume serial number assigned at format time.</param>
/// <param name="TotalBytes">Capacity in bytes.</param>
/// <param name="FreeBytes">Free bytes available to the current user.</param>
/// <param name="DriveType">Drive type reported by Windows.</param>
/// <param name="HasDcim">A <c>DCIM</c> folder exists at the root (camera card).</param>
public sealed record VolumeInfo(
string RootPath,
string Label,
string FileSystem,
uint SerialNumber,
long TotalBytes,
long FreeBytes,
VolumeDriveType DriveType,
bool HasDcim)
{
private const int MaxPath = 261;
public char DriveLetter => char.ToUpperInvariant(RootPath[0]);
/// <summary>Card identity <c>{serial:X8}-{label}-{capacity}</c> (BRIEF §13); stable across readers and drive letters.</summary>
public string Identity => string.Create(CultureInfo.InvariantCulture, $"{SerialNumber:X8}-{Label}-{TotalBytes}");
/// <summary>Reads a volume; null when the root does not exist or holds no media (empty card reader).</summary>
public static unsafe VolumeInfo? TryRead(string rootPath)
{
var root = NormalizeRoot(rootPath);
var driveType = (VolumeDriveType)VolumeNative.GetDriveType(root);
if (driveType is VolumeDriveType.Unknown or VolumeDriveType.NoRootDirectory) return null;
VolumeNative.SetThreadErrorMode(VolumeNative.SEM_FAILCRITICALERRORS, out var previousMode);
try
{
var label = stackalloc char[MaxPath];
var fileSystem = stackalloc char[MaxPath];
if (!VolumeNative.GetVolumeInformation(root, label, MaxPath, out var serial, out _, out _, fileSystem, MaxPath)) return null;
if (!VolumeNative.GetDiskFreeSpaceEx(root, out var free, out var total, out _)) return null;
return new VolumeInfo(
root,
new string(label),
new string(fileSystem),
serial,
(long)total,
(long)free,
driveType,
Directory.Exists(Path.Combine(root, "DCIM")));
}
finally
{
VolumeNative.SetThreadErrorMode(previousMode, out _);
}
}
/// <summary>
/// Free bytes available to the current user on the volume holding the folder <paramref name="folder"/>, quotas counted: a
/// network share's (UNC) too, which <see cref="DriveInfo"/> cannot measure. Null when the folder cannot be reached or measured.
/// </summary>
public static long? FreeBytesAt(string folder)
{
ArgumentException.ThrowIfNullOrEmpty(folder);
// A share's folder must end with a separator.
var directory = Path.EndsInDirectorySeparator(folder) ? folder : folder + Path.DirectorySeparatorChar;
VolumeNative.SetThreadErrorMode(VolumeNative.SEM_FAILCRITICALERRORS, out var previousMode);
try
{
return VolumeNative.GetDiskFreeSpaceEx(directory, out var free, out _, out _) ? (long)Math.Min(free, long.MaxValue) : null;
}
finally
{
VolumeNative.SetThreadErrorMode(previousMode, out _);
}
}
/// <summary>Every ready fixed or removable volume, enumerated through <see cref="DriveInfo"/> (network and optical drives are skipped).</summary>
public static IReadOnlyList<VolumeInfo> ListLocal()
{
var volumes = new List<VolumeInfo>();
foreach (var drive in DriveInfo.GetDrives())
{
if (drive.DriveType is not (System.IO.DriveType.Fixed or System.IO.DriveType.Removable)) continue;
if (TryRead(drive.Name) is { } volume) volumes.Add(volume);
}
return volumes;
}
/// <summary>"e:", "E:\" or "E:\DCIM" → "E:\".</summary>
internal static string NormalizeRoot(string path)
{
var root = Path.GetPathRoot(path);
if (string.IsNullOrEmpty(root)) throw new ArgumentException("The path has no root.", nameof(path));
return root.EndsWith('\\') ? root.ToUpperInvariant() : root.ToUpperInvariant() + "\\";
}
}