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
7 changes: 5 additions & 2 deletions app/Sprint.Desktop.Core/Features/Setup/ISetupSnapshotStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ public interface ISetupSnapshotStore
/// <summary>Every persisted snapshot. Order is not guaranteed.</summary>
IReadOnlyList<SetupSnapshot> LoadAll();

/// <summary>Creates or replaces the snapshot identified by <see cref="SetupSnapshot.Id"/>.</summary>
void Save(SetupSnapshot snapshot);
/// <summary>The snapshot stored under <paramref name="id"/>, or null when there is none or it cannot be read.</summary>
SetupSnapshot? Load(string id);

/// <summary>Creates or replaces the snapshot identified by <see cref="SetupSnapshot.Id"/>; false when it could not be stored.</summary>
bool Save(SetupSnapshot snapshot);
}
19 changes: 15 additions & 4 deletions app/Sprint.Desktop.Core/Features/Setup/LocalSetupSnapshotStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public IReadOnlyList<SetupSnapshot> LoadAll()
List<SetupSnapshot> snapshots = new List<SetupSnapshot>();
foreach (string file in Directory.EnumerateFiles(this._root, "*.json"))
{
if (this.Load(file) is { Id.Length: > 0 } snapshot)
if (this.Read(file) is { Id.Length: > 0 } snapshot)
{
snapshots.Add(snapshot);
}
Expand All @@ -50,7 +50,14 @@ public IReadOnlyList<SetupSnapshot> LoadAll()
return snapshots;
}

public void Save(SetupSnapshot snapshot)
public SetupSnapshot? Load(string id)
{
ArgumentException.ThrowIfNullOrEmpty(id);
string path = this.PathOf(id);
return File.Exists(path) && this.Read(path) is { } snapshot && snapshot.Id == id ? snapshot : null;
}

public bool Save(SetupSnapshot snapshot)
{
ArgumentNullException.ThrowIfNull(snapshot);
if (string.IsNullOrEmpty(snapshot.Id))
Expand All @@ -60,18 +67,22 @@ public void Save(SetupSnapshot snapshot)
nameof(snapshot));
}

string path = Path.Combine(this._root, SafeFileName(snapshot.Id) + ".json");
string path = this.PathOf(snapshot.Id);
try
{
AtomicFile.Write(path, stream => JsonSerializer.Serialize(stream, snapshot, JsonOptions));
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
this._log.Error($"Failed to persist setup snapshot at {path}", ex);
return false;
}
}

private SetupSnapshot? Load(string path)
private string PathOf(string id) => Path.Combine(this._root, SafeFileName(id) + ".json");

private SetupSnapshot? Read(string path)
{
try
{
Expand Down
105 changes: 105 additions & 0 deletions app/Sprint.Desktop.Core/Features/Setup/SetupIndex.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Sprint.Desktop.Features.Diagnostics;
using Sprint.Desktop.Runtime;

namespace Sprint.Desktop.Features.Setup;

/// <summary>One setup file as the last look found it: enough to list it without reading it.</summary>
/// <param name="Path">The repository's locator for the file (<see cref="Sprint.Desktop.Api.Games.GameSetupInfo.Id"/>).</param>
/// <param name="CurrentVersion">The id of the version the file held at <paramref name="LastWriteUtc"/>.</param>
/// <param name="VehicleDescriptor">The car/class string that version declares, for the list's car and class.</param>
public sealed record IndexedSetupFile(
[property: JsonPropertyName("path")] string Path,
[property: JsonPropertyName("name")] string Name,
[property: JsonPropertyName("track")] string? Track,
[property: JsonPropertyName("lastWriteUtc")] DateTimeOffset LastWriteUtc,
[property: JsonPropertyName("currentVersion")] string CurrentVersion,
[property: JsonPropertyName("vehicle")] string? VehicleDescriptor);

/// <summary>One stored version of a setup file, without its values: those stay in its snapshot.</summary>
/// <param name="HasOriginal">Whether its snapshot keeps the file the game wrote (<see cref="SetupSnapshot.Original"/>), for export.</param>
public sealed record IndexedSetupVersion(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("sourceId")] string SourceId,
[property: JsonPropertyName("sourceLastWriteUtc")] DateTimeOffset SourceLastWriteUtc,
[property: JsonPropertyName("hasOriginal")] bool HasOriginal);

/// <summary>What <see cref="SetupIndex"/> keeps: every setup file of the last look and every stored version.</summary>
public sealed record SetupIndexContent(
[property: JsonPropertyName("format")] int Format,
[property: JsonPropertyName("files")] IReadOnlyList<IndexedSetupFile> Files,
[property: JsonPropertyName("versions")] IReadOnlyList<IndexedSetupVersion> Versions);

/// <summary>
/// <see cref="SetupLibrary"/>'s index, one small file under the data folder, so a restart reads
/// only the setups the game changed since, and a setup's values only when it is opened: without
/// it the first look parses every setup file and every stored version.
/// <para>
/// A cache, not a record: everything in it can be read again from the game's folder and the
/// stored snapshots. So a file it cannot use (missing, unreadable, another format) is simply
/// rebuilt, and an older Sprint may overwrite a newer one's index without losing anything.
/// </para>
/// </summary>
public sealed class SetupIndex
{
/// <summary>The layout this build writes; any other is rebuilt rather than read.</summary>
public const int CurrentFormat = 1;

// A file that parses but lacks a field fails to read (and so is rebuilt) instead of handing
// the library nulls its non-nullable records promise never to hold.
private static readonly JsonSerializerOptions JsonOptions = new()
{
RespectNullableAnnotations = true,
RespectRequiredConstructorParameters = true,
};

private readonly string _path;
private readonly ILog _log;

public SetupIndex(string path, ILog? log = null)
{
this._path = path ?? throw new ArgumentNullException(nameof(path));
this._log = log ?? NullLog.Instance;
}

/// <summary>The stored index, or null when there is none Sprint can use; the library rebuilds it then.</summary>
public SetupIndexContent? Load()
{
if (!File.Exists(this._path))
{
return null;
}

try
{
SetupIndexContent? content = JsonSerializer.Deserialize<SetupIndexContent>(AtomicFile.ReadAllBytes(this._path), JsonOptions);
if (content is { Format: CurrentFormat, Files: not null, Versions: not null })
{
return content;
}

this._log.Info($"Rebuilding the setup index at {this._path}: it is in another format");
return null;
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
this._log.Warn($"Rebuilding the setup index at {this._path}: it could not be read", ex);
return null;
}
}

/// <summary>Replaces the stored index. A failed write is only logged: the next start then reads more files.</summary>
public void Save(SetupIndexContent content)
{
ArgumentNullException.ThrowIfNull(content);
try
{
AtomicFile.Write(this._path, stream => JsonSerializer.Serialize(stream, content, JsonOptions));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
this._log.Warn($"Could not save the setup index at {this._path}", ex);
}
}
}
Loading