Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions docs/CACHE-RECOVERY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Cache metadata recovery

“Cache metadata needs attention” means rclone's local status API responded, but
ResoDrive could not parse one of its cache metadata files. This differs from an
unavailable status API. The drive stays protected: uncertain metadata cannot
authorize unmounting, installation preparation or a clean-cache verdict. Earlier
pending-upload counts remain visible until a complete fresh observation succeeds.

Open the drive's error-details button, then choose **Back up and recheck**. Close
applications using the drive first. Recovery requires the original, verified
rclone process and its protected loopback credentials. It does not remount the
drive, stop a process, run an upload or edit metadata itself.

For the first damaged entry, recovery:

1. Rejects linked/escaped cache paths and backup/cache overlap.
2. Takes stable copies of the metadata and cached file while denying writes and
deletion, flushes them to disk, and verifies their SHA-256 hashes.
3. Writes a manifest with the relative filename and original hashes in
`%USERPROFILE%\ResoDrive-Recovery\entry-<date>-<unique-id>`.
4. Downloads a separate server copy directly through rclone's authenticated
`operations/copyfile` endpoint, with the recovery folder as its only destination.
5. Compares the complete file hashes and rechecks the active cache and process.
Different server bytes, concurrent changes, cancellation, locks or account
cleanup stop recovery and retain any backup files already created.
6. Only for matching bytes, reads the mounted file without write access so rclone
can refresh its own metadata. The read must match the verified copy; metadata
must become valid, clean, and have the matching size before reporting success.

Rclone can defer its cache close/write for its write-back interval. Recovery waits
briefly for valid metadata; a timeout never authorizes a clean verdict. Normal
host polling independently checks the entire drive afterward. Other damaged
entries or pending uploads can therefore keep the drive's warning active.

Backups are external user exports and remain outside normal managed-cache and
Nextcloud wipe coverage. They may contain private data. Keep them until recovery
has been reviewed. Do not delete a mismatching cached copy, trim malformed JSON
to make it appear clean, or restore a backup over a live cache. If automatic
rechecking cannot finish, preserve both copies for manual comparison/recovery.

## Verification on 28 November 2026

A live malformed entry was backed up together with its cached file. A separate
read from the actual server matched the cached file's SHA-256. A read-only mount
read let rclone regenerate valid metadata. The installed host then reported
`Mounted`, `No queued uploads`, fresh upload status and no recovery requirement.
No server write, cache deletion, forced stop or manual metadata edit was used.
The private backup manifest and server-verification receipt are retained locally;
private filenames and account details are not part of this repository.

Regression tests use disposable files. They cover exact backups, different server
content, concurrent edits, cancellation, locked data, changed account/process
checks, unsafe backup locations, malformed/dirty/wrong-size post-read metadata,
preserved pending counts, and the new protocol/UI/diagnostic distinction. A real
rclone VFS/WebDAV test reproduces trailing metadata corruption and verifies
read-driven repair against a disposable local backend. It uses no production
account or wipe token. Compiled UI checks cover progress, cancellation, backup
access and layout at 100%, 150% and 200% display scale.

The complete local build passed 1,481 tests (Core 206, Windows 825, App 450),
with two optional/elevation-dependent cases skipped. All 450 App tests also passed
with one available CPU. MSI and Setup compiled with zero warnings and errors.
This verifies local tests and packaging; it is not an installed-app upgrade or
publication of a new release.
32 changes: 32 additions & 0 deletions src/ResoDrive.App/CacheRecoveryWindow.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<Window x:Class="ResoDrive.App.CacheRecoveryWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Recover cache" Width="540" MaxHeight="560" SizeToContent="Height"
ResizeMode="NoResize" ShowInTaskbar="False" WindowStartupLocation="CenterOwner"
Background="{StaticResource WindowBrush}" Foreground="{StaticResource TextBrush}">
<Grid Background="{StaticResource WindowBrush}">
<Grid.RowDefinitions><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<ScrollViewer Margin="24,20,24,24" VerticalScrollBarVisibility="Auto" MaxHeight="380">
<StackPanel>
<TextBlock x:Name="HeadingText" Text="Cache metadata needs attention" FontSize="22" FontWeight="SemiBold" TextWrapping="Wrap"/>
<TextBlock Text="ResoDrive could not read part of this drive’s cache. It cannot confirm whether every file has uploaded."
TextWrapping="Wrap" Foreground="{StaticResource MutedBrush}" Margin="0,12,0,0"/>
<TextBlock Text="Back up and recheck saves the cached file and metadata, then compares the file with a separate server copy. If they match, rclone is asked to refresh the entry. Files that differ are kept for manual recovery."
TextWrapping="Wrap" Foreground="{StaticResource MutedBrush}" Margin="0,12,0,0"/>
<TextBlock Text="Close applications using this drive before starting. Backups are kept in your user folder, outside ResoDrive’s managed cache."
TextWrapping="Wrap" Foreground="{StaticResource MutedBrush}" Margin="0,12,0,0"/>
<TextBlock x:Name="ProgressText" TextWrapping="Wrap" Margin="0,16,0,0" Visibility="Collapsed"
AutomationProperties.LiveSetting="Polite"/>
<TextBlock x:Name="BackupPathText" TextWrapping="Wrap" Foreground="{StaticResource MutedBrush}" Margin="0,10,0,0" Visibility="Collapsed"/>
</StackPanel>
</ScrollViewer>
<Border Grid.Row="1" Background="{StaticResource NavBrush}" BorderBrush="{StaticResource BorderBrush}" BorderThickness="0,1,0,0" Padding="24,12">
<Grid>
<Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<Button x:Name="BackupButton" Content="Open backup" Style="{StaticResource ButtonStyle}" HorizontalAlignment="Left" Visibility="Collapsed" Click="OpenBackup_Click"/>
<Button x:Name="CloseButton" Grid.Column="1" Content="Cancel" Style="{StaticResource ButtonStyle}" Margin="12,0,8,0" Click="Close_Click"/>
<Button x:Name="RecoverButton" Grid.Column="2" Content="Back up and recheck" Style="{StaticResource AccentButton}" Click="Recover_Click" IsDefault="True"/>
</Grid>
</Border>
</Grid>
</Window>
98 changes: 98 additions & 0 deletions src/ResoDrive.App/CacheRecoveryWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using ResoDrive.Windows;

namespace ResoDrive.App;

#pragma warning disable CA1001 // WPF owns the window; Closed disposes the source after any active operation has completed.
public partial class CacheRecoveryWindow : Window
{
private readonly Func<IProgress<string>, CancellationToken, Task<CacheRecoveryResult>> _recover;
private readonly CancellationTokenSource _cancellation = new();
private string? _backupDirectory;
private bool _running;

internal CacheRecoveryWindow(string driveName, Func<IProgress<string>, CancellationToken, Task<CacheRecoveryResult>> recover)
{
InitializeComponent();
WindowAppearance.PrepareDialog(this);
Title = $"{driveName} — Recover cache";
_recover = recover;
Closed += (_, _) => _cancellation.Dispose();
}

private async void Recover_Click(object sender, RoutedEventArgs e)
{
if (_running) return;
_running = true;
RecoverButton.IsEnabled = false;
ProgressText.Visibility = Visibility.Visible;
ProgressText.Text = "Checking the drive…";
var progress = new Progress<string>(message => ProgressText.Text = message);
try
{
var result = await Task.Run(() => _recover(progress, _cancellation.Token));
ProgressText.Text = result.Message;
_backupDirectory = result.BackupDirectory;
if (_backupDirectory is not null)
{
BackupPathText.Text = _backupDirectory;
BackupPathText.Visibility = Visibility.Visible;
BackupButton.Visibility = Visibility.Visible;
}
RecoverButton.Visibility = Visibility.Collapsed;
CloseButton.Content = "Close";
}
catch (Exception exception) when (exception is System.IO.IOException or InvalidOperationException or OperationCanceledException)
{
ProgressText.Text = "Recovery could not finish. Your cache was left in place. Check the connection and try again.";
RecoverButton.Visibility = Visibility.Collapsed;
CloseButton.Content = "Close";
}
finally
{
_running = false;
CloseButton.IsEnabled = true;
}
}

private void Close_Click(object sender, RoutedEventArgs e)
{
if (_running)
{
_cancellation.Cancel();
CloseButton.IsEnabled = false;
ProgressText.Text = "Stopping recovery. Keeping any backup files already created…";
}
else Close();
}

protected override void OnClosing(CancelEventArgs e)
{
if (_running)
{
_cancellation.Cancel();
e.Cancel = true;
}
base.OnClosing(e);
}

protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Escape)
{
Close_Click(this, new RoutedEventArgs());
e.Handled = true;
}
base.OnPreviewKeyDown(e);
}

private void OpenBackup_Click(object sender, RoutedEventArgs e)
{
if (_backupDirectory is null) return;
try { Process.Start(new ProcessStartInfo(_backupDirectory) { UseShellExecute = true }); }
catch (Exception exception) when (exception is System.IO.IOException or Win32Exception or InvalidOperationException)
{ ProgressText.Text = "The backup folder could not be opened. Its location is shown above."; }
}
}
8 changes: 8 additions & 0 deletions src/ResoDrive.App/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,14 @@ private void MountErrorDetails_Click(object sender, RoutedEventArgs e)
string.IsNullOrWhiteSpace(row.ErrorDetail))
return;

if (row.UploadStatus?.CacheMetadataInvalid == true)
{
if (!CanInteractWithHost) return;
var service = new CacheMetadataRecoveryService(_paths, _accountData);
new CacheRecoveryWindow(row.Name, (progress, token) => service.RecoverAsync(row.Id, progress, token))
{ Owner = this }.ShowDialog();
return;
}
ShowError($"{row.Name} could not be mounted", row.ErrorDetail);
}

Expand Down
10 changes: 7 additions & 3 deletions src/ResoDrive.App/Presentation/MountRow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public string UploadActivityText
{
get
{
if (UploadStatus?.CacheMetadataInvalid == true) return "Cache metadata needs attention";
if (UploadStatus?.UploadRecoveryRequired == true) return "Cache recovery required";
if (IsWaitingForConnection) return UploadPresentation.Errors(UploadStatus) > 0
? JoinStatus("Waiting for connection", UploadAttentionText) : "Waiting for connection";
Expand All @@ -50,7 +51,7 @@ public string UploadActivityText
}
}
public bool HasPendingUploads => UploadPresentation.HasPending(UploadStatus);
public bool UploadNeedsAttention => HasPendingUploads || IsTransient ||
public bool UploadNeedsAttention => UploadStatus?.CacheMetadataInvalid == true || HasPendingUploads || IsTransient ||
(ShouldStop && (UploadStatus is null || UploadStatus.UploadStatusStale));
public string ConnectionTypeDisplay => Settings.ConnectionType?.Trim().ToLowerInvariant() switch
{
Expand Down Expand Up @@ -88,7 +89,7 @@ public string UploadActivityText
? $"{StatusLine}\n{StatusText}" : StatusLine;
public string ErrorDetail => _errorDetail;
public System.Windows.Visibility ErrorVisibility =>
_lifecycle == MountLifecycle.Failed && _errorDetail.Length > 0
(_lifecycle == MountLifecycle.Failed || UploadStatus?.CacheMetadataInvalid == true) && _errorDetail.Length > 0
? System.Windows.Visibility.Visible
: System.Windows.Visibility.Collapsed;
public System.Windows.Visibility StatusVisibility =>
Expand Down Expand Up @@ -173,7 +174,9 @@ public void ApplyStatus(HostMountStatus? status)
: recognized
? nextLifecycle == MountLifecycle.Failed ? "Mount failed" : detail
: "Unknown mount state";
var nextErrorDetail = nextLifecycle == MountLifecycle.Failed ? detail : string.Empty;
var nextErrorDetail = status?.CacheMetadataInvalid == true
? "ResoDrive could not read part of this drive's cache. Back up and recheck compares the cached file with the server before asking rclone to refresh it. Files that differ are preserved for manual recovery."
: nextLifecycle == MountLifecycle.Failed ? detail : string.Empty;
if (!uploadChanged && hadStatus == _hasStatus && hostWasUnavailable == _hostUnavailable &&
previousLifecycle == nextLifecycle && _status == nextStatus &&
_errorDetail == nextErrorDetail)
Expand Down Expand Up @@ -202,6 +205,7 @@ private static bool HasSameUploadState(HostMountStatus? previous, HostMountStatu
Nullable.Equals(previous.UploadEtaSeconds, current.UploadEtaSeconds) &&
previous.UploadStatusStale == current.UploadStatusStale &&
previous.UploadStatusChecking == current.UploadStatusChecking &&
previous.CacheMetadataInvalid == current.CacheMetadataInvalid &&
previous.UploadRecoveryRequired == current.UploadRecoveryRequired &&
previous.UploadDetailsTruncated == current.UploadDetailsTruncated &&
(ReferenceEquals(previous.Uploads, current.Uploads) ||
Expand Down
1 change: 1 addition & 0 deletions src/ResoDrive.App/Presentation/UploadPresentation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ void Add(long? count)
internal static string Activity(HostMountStatus? status)
{
if (status is null) return string.Empty;
if (status.CacheMetadataInvalid) return "Cache metadata needs attention";
var recent = HasRecentProgress(status, DateTimeOffset.UtcNow);
if (status.UploadStatusChecking && !recent) return HasPending(status) ? "Waiting for upload status" : string.Empty;
if (status.UploadStatusStale && !recent) return "Upload status unavailable";
Expand Down
1 change: 1 addition & 0 deletions src/ResoDrive.Core/Domain/Lifecycle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public sealed record MountSnapshot
public long? UploadsInProgress { get; init; }
public bool UploadStatusStale { get; init; }
public bool UploadStatusChecking { get; init; }
public bool CacheMetadataInvalid { get; init; }
public long? UploadsDirty { get; init; }
public long? UploadErrors { get; init; }
public long? UploadBytesRemaining { get; init; }
Expand Down
4 changes: 3 additions & 1 deletion src/ResoDrive.Windows/Hosting/HostProtocol.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public sealed record HostMountStatus(
public DateTimeOffset? UploadObservedAt { get; init; }
public bool UploadRecoveryRequired { get; init; }
public bool UploadStatusChecking { get; init; }
public bool CacheMetadataInvalid { get; init; }
}

public sealed record HostSyncStatus(
Expand Down Expand Up @@ -112,7 +113,8 @@ public static bool AcceptsBaseDirectory(string? expected, string actual) =>
UploadDetailsTruncated = snapshot.UploadDetailsTruncated,
UploadObservedAt = snapshot.UploadObservedAt,
UploadRecoveryRequired = snapshot.UploadRecoveryRequired,
UploadStatusChecking = snapshot.UploadStatusChecking
UploadStatusChecking = snapshot.UploadStatusChecking,
CacheMetadataInvalid = snapshot.CacheMetadataInvalid
};

public static IReadOnlyList<HostMountStatus> BoundUploadDetails(IEnumerable<HostMountStatus> statuses)
Expand Down
38 changes: 26 additions & 12 deletions src/ResoDrive.Windows/Mounting/DirtyCacheReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@

namespace ResoDrive.Windows;

internal sealed class CacheMetadataException(string metadataRoot, string metadataFile, JsonException innerException)
: JsonException("Cache metadata could not be read. Back up the cached file before attempting recovery.", innerException)
{
internal string MetadataRoot { get; } = metadataRoot;
internal string MetadataFile { get; } = metadataFile;
}

internal sealed record DirtyCacheStatus(string? MetadataPath, IReadOnlyList<MountUploadFile> Files)
{
internal static DirtyCacheStatus Empty { get; } = new(null, []);
Expand Down Expand Up @@ -74,19 +81,26 @@ internal static DirtyCacheStatus Read(string metadataPath, string cacheRoot, Can
}
if (count == buffer.Length)
throw new IOException("Cache metadata changed during inspection.");
using var document = JsonDocument.Parse(buffer.AsMemory(0, count));
if (document.RootElement.ValueKind != JsonValueKind.Object ||
!document.RootElement.TryGetProperty("Dirty", out var dirty) || dirty.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
throw new JsonException("Incomplete cache metadata.");
if (!dirty.GetBoolean())
continue;
var relative = Path.GetRelativePath(root, entry).Replace('\\', '/');
relative = VfsTransferStatus.ValidateRelativeName(relative);
files.Add(new MountUploadFile
try
{
RelativePath = relative, State = MountUploadState.WaitingForClose,
TotalBytes = VfsTransferStatus.Count(document.RootElement, "Size")
});
using var document = JsonDocument.Parse(buffer.AsMemory(0, count));
if (document.RootElement.ValueKind != JsonValueKind.Object ||
!document.RootElement.TryGetProperty("Dirty", out var dirty) || dirty.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
throw new JsonException("Incomplete cache metadata.");
if (!dirty.GetBoolean())
continue;
var relative = Path.GetRelativePath(root, entry).Replace('\\', '/');
relative = VfsTransferStatus.ValidateRelativeName(relative);
files.Add(new MountUploadFile
{
RelativePath = relative, State = MountUploadState.WaitingForClose,
TotalBytes = VfsTransferStatus.Count(document.RootElement, "Size")
});
}
catch (JsonException exception)
{
throw new CacheMetadataException(root, entry, exception);
}
}
}
return new(root, files);
Expand Down
Loading