mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-02 03:11:33 -05:00
refactor: share duplicated snapshot, history and fetch helpers
- CuttingPlanSnapshot: one private Copy carries every value and init property for WithSearchLimits, WithTabLeadOuts, WithPreservedOrder and WithTabbedPartsAvoided, keeping the defensive CrossableTabbedParts copy. - NestPhaseExtensions: DisplayName and ShortName share one attribute lookup and keep their own caches. - NestDatabase: History, DrawingHistory and DrawingSetHistory share ReadRevisionPage (count, page query, read rows) under the same lock. - NestServerClient.GetOrNullAsync: the GET, 404 check-then-null, ensure success and read flow used by the Remote* clients. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
409d30d29e
commit
1f7fd248fe
11 files changed
+126
-184
No files matched your search
@@ -39,6 +39,30 @@ public abstract class NestServerClient : IDisposable
|
||||
throw tooOld();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// GETs <paramref name="relative"/> and reads its body, or returns null on a 404 once
|
||||
/// <paramref name="throwIfServerTooOld"/> (when given) has found the server new enough.
|
||||
/// </summary>
|
||||
private protected async Task<T?> GetOrNullAsync<T>(string relative, string action,
|
||||
Func<HttpResponseMessage, CancellationToken, Task<T>> read,
|
||||
Func<CancellationToken, Task>? throwIfServerTooOld, CancellationToken cancellationToken)
|
||||
where T : class?
|
||||
{
|
||||
using var response = await _httpClient.GetAsync(Url(relative), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
if (throwIfServerTooOld is not null)
|
||||
await throwIfServerTooOld(cancellationToken);
|
||||
return null;
|
||||
}
|
||||
await NestServerHttp.EnsureSuccessAsync(response, action, cancellationToken);
|
||||
return await read(response, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>A <see cref="GetOrNullAsync"/> reader for a raw body.</summary>
|
||||
private protected static Task<byte[]> ReadBytesAsync(HttpResponseMessage response, CancellationToken cancellationToken) =>
|
||||
response.Content.ReadAsByteArrayAsync(cancellationToken);
|
||||
|
||||
private protected static void ThrowIfInvalidQuery(string? error)
|
||||
{
|
||||
if (error is not null)
|
||||
|
||||
@@ -45,14 +45,11 @@ public sealed partial class RemoteDrawingGeometry : NestServerClient
|
||||
}
|
||||
|
||||
/// <summary>The package stored under <paramref name="sha256"/>, or null when there is none.</summary>
|
||||
public async Task<byte[]?> GetPackageAsync(string sha256, CancellationToken cancellationToken = default)
|
||||
public Task<byte[]?> GetPackageAsync(string sha256, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ValidateSha(sha256);
|
||||
using var response = await _httpClient.GetAsync(Url($"api/drawing-packages/{sha256}"), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
return null;
|
||||
await NestServerHttp.EnsureSuccessAsync(response, $"download library package {sha256}", cancellationToken);
|
||||
return await response.Content.ReadAsByteArrayAsync(cancellationToken);
|
||||
return GetOrNullAsync($"api/drawing-packages/{sha256}", $"download library package {sha256}", ReadBytesAsync,
|
||||
null, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Stores a package's summary; false when the server no longer has the package.</summary>
|
||||
|
||||
@@ -66,15 +66,9 @@ public sealed class RemoteDrawingLibrary : NestServerClient, IDrawingLibraryStor
|
||||
public async Task<DrawingLibraryRecord?> GetAsync(Guid id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ValidateId(id);
|
||||
using var response = await _httpClient.GetAsync(Url($"api/drawings/{id}"), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
await ThrowIfServerTooOld(cancellationToken);
|
||||
return null;
|
||||
}
|
||||
await NestServerHttp.EnsureSuccessAsync(response, $"read library drawing {id}", cancellationToken);
|
||||
var record = await ReadRecord(response, cancellationToken);
|
||||
return record.Id == id ? record : throw new IOException("Nest server returned a different library drawing.");
|
||||
var record = await GetOrNullAsync($"api/drawings/{id}", $"read library drawing {id}", ReadRecord,
|
||||
ThrowIfServerTooOld, cancellationToken);
|
||||
return record is null || record.Id == id ? record : throw new IOException("Nest server returned a different library drawing.");
|
||||
}
|
||||
|
||||
/// <summary>The current package bytes, or null for an unknown id.</summary>
|
||||
@@ -90,16 +84,13 @@ public sealed class RemoteDrawingLibrary : NestServerClient, IDrawingLibraryStor
|
||||
{
|
||||
ValidateId(id);
|
||||
NestServerHttp.ValidatePaging(offset, limit, DrawingLibraryRules.MaxRevisionLimit);
|
||||
using var response = await _httpClient.GetAsync(
|
||||
Url($"api/drawings/{id}/revisions?{NestServerHttp.Paging(offset, limit)}"), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
await ThrowIfServerTooOld(cancellationToken);
|
||||
var page = await GetOrNullAsync($"api/drawings/{id}/revisions?{NestServerHttp.Paging(offset, limit)}",
|
||||
$"read library drawing history {id}",
|
||||
async (response, token) => await response.Content.ReadFromJsonAsync<DrawingLibraryPage>(NestServerHttp.JsonOptions, token)
|
||||
?? throw new IOException("Nest server returned an empty drawing history page."),
|
||||
ThrowIfServerTooOld, cancellationToken);
|
||||
if (page is null)
|
||||
return null;
|
||||
}
|
||||
await NestServerHttp.EnsureSuccessAsync(response, $"read library drawing history {id}", cancellationToken);
|
||||
var page = await response.Content.ReadFromJsonAsync<DrawingLibraryPage>(NestServerHttp.JsonOptions, cancellationToken)
|
||||
?? throw new IOException("Nest server returned an empty drawing history page.");
|
||||
if (page.Items is null || !NestServerHttp.IsBoundedPage(page.Items.Count, page.Total, page.Offset, page.Limit, offset, limit)
|
||||
|| !NestServerHttp.IsRevisionHistory(page.Items, id, item => item.Id, item => item.Revision))
|
||||
throw new IOException("Nest server returned an invalid or unbounded drawing history page.");
|
||||
@@ -172,17 +163,8 @@ public sealed class RemoteDrawingLibrary : NestServerClient, IDrawingLibraryStor
|
||||
ReadRecord, current => new DrawingLibraryConflictException(current), saved => (saved.Id, saved.Revision),
|
||||
ThrowIfServerTooOld, cancellationToken);
|
||||
|
||||
private async Task<byte[]?> GetBytesAsync(string relative, string action, CancellationToken cancellationToken)
|
||||
{
|
||||
using var response = await _httpClient.GetAsync(Url(relative), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
await ThrowIfServerTooOld(cancellationToken);
|
||||
return null;
|
||||
}
|
||||
await NestServerHttp.EnsureSuccessAsync(response, action, cancellationToken);
|
||||
return await response.Content.ReadAsByteArrayAsync(cancellationToken);
|
||||
}
|
||||
private Task<byte[]?> GetBytesAsync(string relative, string action, CancellationToken cancellationToken) =>
|
||||
GetOrNullAsync(relative, action, ReadBytesAsync, ThrowIfServerTooOld, cancellationToken);
|
||||
|
||||
// A 404 for one drawing is ambiguous; the query route exists on every library-aware server.
|
||||
private Task ThrowIfServerTooOld(CancellationToken cancellationToken) =>
|
||||
|
||||
@@ -170,15 +170,9 @@ public sealed class RemoteDrawingSetStore : NestServerClient, IDrawingSetStore
|
||||
public async Task<SetReleaseRecord?> GetReleaseAsync(Guid id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (id == Guid.Empty) throw new ArgumentException("A release id is required.", nameof(id));
|
||||
using var response = await _httpClient.GetAsync(Url($"api/releases/{id}"), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
await ThrowIfReleasesUnsupported(cancellationToken);
|
||||
return null;
|
||||
}
|
||||
await NestServerHttp.EnsureSuccessAsync(response, $"read release {id}", cancellationToken);
|
||||
var release = await ReadRelease(response, cancellationToken);
|
||||
if (release.Id != id)
|
||||
var release = await GetOrNullAsync($"api/releases/{id}", $"read release {id}", ReadRelease,
|
||||
ThrowIfReleasesUnsupported, cancellationToken);
|
||||
if (release is not null && release.Id != id)
|
||||
throw new IOException("Nest server returned a different release.");
|
||||
return release;
|
||||
}
|
||||
@@ -278,31 +272,19 @@ public sealed class RemoteDrawingSetStore : NestServerClient, IDrawingSetStore
|
||||
ReadSet, current => new DrawingSetSaveConflictException(current), saved => (saved.Id, saved.Revision),
|
||||
ThrowIfServerTooOld, cancellationToken);
|
||||
|
||||
private async Task<DrawingSetRecord?> GetRecordAsync(string relative, string action, CancellationToken cancellationToken)
|
||||
{
|
||||
using var response = await _httpClient.GetAsync(Url(relative), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
await ThrowIfServerTooOld(cancellationToken);
|
||||
return null;
|
||||
}
|
||||
await NestServerHttp.EnsureSuccessAsync(response, action, cancellationToken);
|
||||
return await ReadSet(response, cancellationToken);
|
||||
}
|
||||
private Task<DrawingSetRecord?> GetRecordAsync(string relative, string action, CancellationToken cancellationToken) =>
|
||||
GetOrNullAsync(relative, action, ReadSet, ThrowIfServerTooOld, cancellationToken);
|
||||
|
||||
private async Task<DrawingSetPage?> GetPageAsync(string relative, int offset, int limit, string action,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
NestServerHttp.ValidatePaging(offset, limit, DrawingLibraryRules.MaxRevisionLimit);
|
||||
using var response = await _httpClient.GetAsync(Url($"{relative}?{NestServerHttp.Paging(offset, limit)}"), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
await ThrowIfServerTooOld(cancellationToken);
|
||||
var page = await GetOrNullAsync($"{relative}?{NestServerHttp.Paging(offset, limit)}", action,
|
||||
async (response, token) => await response.Content.ReadFromJsonAsync<DrawingSetPage>(NestServerHttp.JsonOptions, token)
|
||||
?? throw new IOException("Nest server returned an empty drawing set page."),
|
||||
ThrowIfServerTooOld, cancellationToken);
|
||||
if (page is null)
|
||||
return null;
|
||||
}
|
||||
await NestServerHttp.EnsureSuccessAsync(response, action, cancellationToken);
|
||||
var page = await response.Content.ReadFromJsonAsync<DrawingSetPage>(NestServerHttp.JsonOptions, cancellationToken)
|
||||
?? throw new IOException("Nest server returned an empty drawing set page.");
|
||||
if (page.Items is null || !NestServerHttp.IsBoundedPage(page.Items.Count, page.Total, page.Offset, page.Limit, offset, limit)
|
||||
|| page.Items.Any(item => item is null))
|
||||
throw new IOException("Nest server returned an invalid or unbounded drawing set page.");
|
||||
|
||||
@@ -51,12 +51,8 @@ public sealed class RemoteNestJobs : NestServerClient
|
||||
/// <summary>The job, or null when the server does not hold it (removed after <see cref="NestJobRules.Retention"/>).</summary>
|
||||
public async Task<NestJobRecord?> GetAsync(Guid id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var response = await _httpClient.GetAsync(Url($"api/nest-jobs/{id}"), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
return null;
|
||||
await NestServerHttp.EnsureSuccessAsync(response, "read the nest job", cancellationToken);
|
||||
var record = await ReadRecordAsync(response, cancellationToken);
|
||||
return record.Id == id ? record : throw new IOException("Nest server returned a different nest job.");
|
||||
var record = await GetOrNullAsync($"api/nest-jobs/{id}", "read the nest job", ReadRecordAsync, null, cancellationToken);
|
||||
return record is null || record.Id == id ? record : throw new IOException("Nest server returned a different nest job.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -94,14 +94,10 @@ public sealed class RemoteNestRepository : NestServerClient, INestRepository
|
||||
public Task<NestRecord?> GetDeletedMetadataAsync(Guid id, CancellationToken cancellationToken = default) =>
|
||||
GetMetadataCoreAsync(id, true, cancellationToken);
|
||||
|
||||
private async Task<NestRecord?> GetMetadataCoreAsync(Guid id, bool deleted, CancellationToken cancellationToken)
|
||||
{
|
||||
using var response = await _httpClient.GetAsync(Url($"api/nests/{(deleted ? "deleted/" : "")}{id}"), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
return null;
|
||||
await NestServerHttp.EnsureSuccessAsync(response, $"get nest {id}", cancellationToken);
|
||||
return await response.Content.ReadFromJsonAsync<NestRecord>(NestServerHttp.JsonOptions, cancellationToken);
|
||||
}
|
||||
private Task<NestRecord?> GetMetadataCoreAsync(Guid id, bool deleted, CancellationToken cancellationToken) =>
|
||||
GetOrNullAsync($"api/nests/{(deleted ? "deleted/" : "")}{id}", $"get nest {id}",
|
||||
(response, token) => response.Content.ReadFromJsonAsync<NestRecord>(NestServerHttp.JsonOptions, token),
|
||||
null, cancellationToken);
|
||||
|
||||
public Task<byte[]?> GetFileAsync(Guid id, CancellationToken cancellationToken = default) =>
|
||||
GetFileCoreAsync(id, false, cancellationToken);
|
||||
@@ -109,14 +105,9 @@ public sealed class RemoteNestRepository : NestServerClient, INestRepository
|
||||
public Task<byte[]?> GetDeletedFileAsync(Guid id, CancellationToken cancellationToken = default) =>
|
||||
GetFileCoreAsync(id, true, cancellationToken);
|
||||
|
||||
private async Task<byte[]?> GetFileCoreAsync(Guid id, bool deleted, CancellationToken cancellationToken)
|
||||
{
|
||||
using var response = await _httpClient.GetAsync(Url($"api/nests/{(deleted ? "deleted/" : "")}{id}/file"), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
return null;
|
||||
await NestServerHttp.EnsureSuccessAsync(response, $"download nest {id}", cancellationToken);
|
||||
return await response.Content.ReadAsByteArrayAsync(cancellationToken);
|
||||
}
|
||||
private Task<byte[]?> GetFileCoreAsync(Guid id, bool deleted, CancellationToken cancellationToken) =>
|
||||
GetOrNullAsync($"api/nests/{(deleted ? "deleted/" : "")}{id}/file", $"download nest {id}", ReadBytesAsync,
|
||||
null, cancellationToken);
|
||||
|
||||
public async Task<NestRecord> UploadAsync(
|
||||
byte[] nestFile, NestRecord record, CancellationToken cancellationToken = default)
|
||||
@@ -203,15 +194,14 @@ public sealed class RemoteNestRepository : NestServerClient, INestRepository
|
||||
public Task<byte[]?> GetDeletedRevisionFileAsync(Guid id, int revisionNumber,
|
||||
CancellationToken cancellationToken = default) => GetHistoricalFileAsync(id, revisionNumber, true, cancellationToken);
|
||||
|
||||
private async Task<byte[]?> GetHistoricalFileAsync(Guid id, int revisionNumber, bool deleted,
|
||||
private Task<byte[]?> GetHistoricalFileAsync(Guid id, int revisionNumber, bool deleted,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ValidateId(id);
|
||||
ValidateRevision(revisionNumber);
|
||||
using var response = await _httpClient.GetAsync(Url($"api/nests/{(deleted ? "deleted/" : "")}{id}/revisions/{revisionNumber.ToString(CultureInfo.InvariantCulture)}/file"), cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound) return null;
|
||||
await NestServerHttp.EnsureSuccessAsync(response, $"download nest {id} revision {revisionNumber}", cancellationToken);
|
||||
return await response.Content.ReadAsByteArrayAsync(cancellationToken);
|
||||
return GetOrNullAsync(
|
||||
$"api/nests/{(deleted ? "deleted/" : "")}{id}/revisions/{revisionNumber.ToString(CultureInfo.InvariantCulture)}/file",
|
||||
$"download nest {id} revision {revisionNumber}", ReadBytesAsync, null, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<NestRecord> UpdateFileAsync(Guid id, byte[] nestFile, NestRecord record, int expectedRevision,
|
||||
|
||||
@@ -132,16 +132,7 @@ public sealed class CuttingPlanSnapshot
|
||||
|
||||
/// <summary>The same capture planned with rapids kept off tabbed parts already cut.</summary>
|
||||
internal CuttingPlanSnapshot WithTabbedPartsAvoided() =>
|
||||
new(Placements, StartPoint, ExpansionBudget, Failure, Findings, Regeneration,
|
||||
PreservePartOrder, MaxEntries, ExpansionObserver, PlateState, OwnedParameters,
|
||||
Dependencies, BestEffort)
|
||||
{
|
||||
SupportTabsSkipped = SupportTabsSkipped,
|
||||
CommonLineMembers = CommonLineMembers,
|
||||
CommonLineOrder = CommonLineOrder,
|
||||
AcceptsTabLeadOuts = AcceptsTabLeadOuts,
|
||||
AvoidsTabbedParts = true,
|
||||
};
|
||||
Copy(ExpansionBudget, MaxEntries, PreservePartOrder, AcceptsTabLeadOuts, startAvoidingTabbedParts: true);
|
||||
|
||||
/// <summary>
|
||||
/// Part numbers (source ordinal + 1) of the members of common-line groups cut once
|
||||
@@ -185,17 +176,7 @@ public sealed class CuttingPlanSnapshot
|
||||
// A worker-only search variant over the same owned capture. Never recapture the live plate:
|
||||
// both proposals retain the identical freshness record and confirmed settings.
|
||||
internal CuttingPlanSnapshot WithSearchLimits(int expansionBudget, int maxEntries) =>
|
||||
new(Placements, StartPoint, expansionBudget, Failure, Findings, Regeneration,
|
||||
PreservePartOrder, maxEntries, ExpansionObserver, PlateState, OwnedParameters,
|
||||
Dependencies, BestEffort)
|
||||
{
|
||||
SupportTabsSkipped = SupportTabsSkipped,
|
||||
CommonLineMembers = CommonLineMembers,
|
||||
CommonLineOrder = CommonLineOrder,
|
||||
AcceptsTabLeadOuts = AcceptsTabLeadOuts,
|
||||
AvoidsTabbedParts = AvoidsTabbedParts,
|
||||
CrossableTabbedParts = [.. CrossableTabbedParts],
|
||||
};
|
||||
Copy(expansionBudget, maxEntries, PreservePartOrder, AcceptsTabLeadOuts);
|
||||
|
||||
/// <summary>
|
||||
/// The same capture planned again accepting tab lead-outs: a regenerated tabbed outside whose
|
||||
@@ -203,17 +184,7 @@ public sealed class CuttingPlanSnapshot
|
||||
/// (<see cref="PostVerificationKind.TabLeadOut"/>) and counted as cut free, instead of refused.
|
||||
/// </summary>
|
||||
internal CuttingPlanSnapshot WithTabLeadOuts() =>
|
||||
new(Placements, StartPoint, ExpansionBudget, Failure, Findings, Regeneration,
|
||||
PreservePartOrder, MaxEntries, ExpansionObserver, PlateState, OwnedParameters,
|
||||
Dependencies, BestEffort)
|
||||
{
|
||||
SupportTabsSkipped = SupportTabsSkipped,
|
||||
CommonLineMembers = CommonLineMembers,
|
||||
CommonLineOrder = CommonLineOrder,
|
||||
AcceptsTabLeadOuts = true,
|
||||
AvoidsTabbedParts = AvoidsTabbedParts,
|
||||
CrossableTabbedParts = [.. CrossableTabbedParts],
|
||||
};
|
||||
Copy(ExpansionBudget, MaxEntries, PreservePartOrder, acceptsTabLeadOuts: true);
|
||||
|
||||
/// <summary>Whether this capture accepts tab lead-outs (see <see cref="WithTabLeadOuts"/>).</summary>
|
||||
internal bool AcceptsTabLeadOuts { get; init; }
|
||||
@@ -223,16 +194,25 @@ public sealed class CuttingPlanSnapshot
|
||||
|
||||
/// <summary>The same capture planned along its current part order.</summary>
|
||||
internal CuttingPlanSnapshot WithPreservedOrder() =>
|
||||
new(Placements, StartPoint, ExpansionBudget, Failure, Findings, Regeneration,
|
||||
preservePartOrder: true, MaxEntries, ExpansionObserver, PlateState, OwnedParameters,
|
||||
Copy(ExpansionBudget, MaxEntries, preservePartOrder: true, AcceptsTabLeadOuts);
|
||||
|
||||
/// <summary>
|
||||
/// This capture with the given search settings; every other value, init properties included,
|
||||
/// is carried over. The copy owns its own <see cref="CrossableTabbedParts"/>, which starts
|
||||
/// empty when <paramref name="startAvoidingTabbedParts"/> turns <see cref="AvoidsTabbedParts"/> on.
|
||||
/// </summary>
|
||||
private CuttingPlanSnapshot Copy(int expansionBudget, int maxEntries, bool preservePartOrder,
|
||||
bool acceptsTabLeadOuts, bool startAvoidingTabbedParts = false) =>
|
||||
new(Placements, StartPoint, expansionBudget, Failure, Findings, Regeneration,
|
||||
preservePartOrder, maxEntries, ExpansionObserver, PlateState, OwnedParameters,
|
||||
Dependencies, BestEffort)
|
||||
{
|
||||
SupportTabsSkipped = SupportTabsSkipped,
|
||||
CommonLineMembers = CommonLineMembers,
|
||||
CommonLineOrder = CommonLineOrder,
|
||||
AcceptsTabLeadOuts = AcceptsTabLeadOuts,
|
||||
AvoidsTabbedParts = AvoidsTabbedParts,
|
||||
CrossableTabbedParts = [.. CrossableTabbedParts],
|
||||
AcceptsTabLeadOuts = acceptsTabLeadOuts,
|
||||
AvoidsTabbedParts = startAvoidingTabbedParts || AvoidsTabbedParts,
|
||||
CrossableTabbedParts = startAvoidingTabbedParts ? [] : [.. CrossableTabbedParts],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -36,30 +36,18 @@ namespace OpenNest.Engine
|
||||
private static readonly ConcurrentDictionary<NestPhase, string> DisplayNames = new();
|
||||
private static readonly ConcurrentDictionary<NestPhase, string> ShortNames = new();
|
||||
|
||||
public static string DisplayName(this NestPhase phase)
|
||||
{
|
||||
return DisplayNames.GetOrAdd(
|
||||
phase,
|
||||
p =>
|
||||
{
|
||||
var field = typeof(NestPhase).GetField(p.ToString());
|
||||
var attr = field?.GetCustomAttribute<DescriptionAttribute>();
|
||||
return attr?.Description ?? p.ToString();
|
||||
}
|
||||
);
|
||||
}
|
||||
public static string DisplayName(this NestPhase phase) =>
|
||||
DisplayNames.GetOrAdd(phase, p => AttributeName<DescriptionAttribute>(p, attr => attr.Description));
|
||||
|
||||
public static string ShortName(this NestPhase phase)
|
||||
public static string ShortName(this NestPhase phase) =>
|
||||
ShortNames.GetOrAdd(phase, p => AttributeName<ShortNameAttribute>(p, attr => attr.Name));
|
||||
|
||||
// The name the phase's TAttribute gives, or the enum name without one.
|
||||
private static string AttributeName<TAttribute>(NestPhase phase, Func<TAttribute, string> name)
|
||||
where TAttribute : Attribute
|
||||
{
|
||||
return ShortNames.GetOrAdd(
|
||||
phase,
|
||||
p =>
|
||||
{
|
||||
var field = typeof(NestPhase).GetField(p.ToString());
|
||||
var attr = field?.GetCustomAttribute<ShortNameAttribute>();
|
||||
return attr?.Name ?? p.ToString();
|
||||
}
|
||||
);
|
||||
var attr = typeof(NestPhase).GetField(phase.ToString())?.GetCustomAttribute<TAttribute>();
|
||||
return (attr == null ? null : name(attr)) ?? phase.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -268,13 +268,9 @@ public sealed partial class NestDatabase
|
||||
lock (_sync)
|
||||
{
|
||||
if (GetDrawing(id) is null) return null;
|
||||
var total = CountRevisions("drawing_revisions", id);
|
||||
using var command = _connection.CreateCommand();
|
||||
command.CommandText = $"SELECT {DrawingColumns} FROM drawing_revisions WHERE id=$id ORDER BY revision DESC LIMIT $limit OFFSET $offset";
|
||||
BindRevisionPage(command, id, offset, limit);
|
||||
var records = new List<DrawingLibraryRecord>();
|
||||
using var reader = command.ExecuteReader();
|
||||
while (reader.Read()) records.Add(ReadDrawing(reader));
|
||||
var (records, total) = ReadRevisionPage("drawing_revisions",
|
||||
$"SELECT {DrawingColumns} FROM drawing_revisions WHERE id=$id ORDER BY revision DESC LIMIT $limit OFFSET $offset",
|
||||
id, offset, limit, reader => ReadDrawing(reader));
|
||||
return new DrawingLibraryPage { Items = records, Total = total, Offset = offset, Limit = limit };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,14 +186,11 @@ public sealed partial class NestDatabase
|
||||
lock (_sync)
|
||||
{
|
||||
if (GetDrawingSet(id) is null) return null;
|
||||
var total = CountRevisions("drawing_set_revisions", id);
|
||||
using var command = _connection.CreateCommand();
|
||||
command.CommandText = $"""
|
||||
var (records, total) = ReadRevisionPage("drawing_set_revisions", $"""
|
||||
SELECT {SetColumns}, {SetMemberCount} FROM drawing_set_revisions s WHERE s.id=$id
|
||||
ORDER BY s.revision DESC LIMIT $limit OFFSET $offset
|
||||
""";
|
||||
BindRevisionPage(command, id, offset, limit);
|
||||
return new DrawingSetPage { Items = ReadSets(command), Total = total, Offset = offset, Limit = limit };
|
||||
""", id, offset, limit, ReadSet);
|
||||
return new DrawingSetPage { Items = records, Total = total, Offset = offset, Limit = limit };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,24 +315,23 @@ public sealed partial class NestDatabase
|
||||
{
|
||||
var records = new List<DrawingSetRecord>();
|
||||
using var reader = command.ExecuteReader();
|
||||
while (reader.Read())
|
||||
{
|
||||
records.Add(new DrawingSetRecord
|
||||
{
|
||||
Id = Guid.Parse(reader.GetString(0)),
|
||||
Revision = reader.GetInt32(1),
|
||||
Name = reader.GetString(2),
|
||||
Customer = reader.GetString(3),
|
||||
Notes = reader.GetString(4),
|
||||
Archived = reader.GetInt32(5) != 0,
|
||||
SavedAt = DateTime.Parse(reader.GetString(6)),
|
||||
SavedBy = reader.GetString(7),
|
||||
MemberCount = reader.GetInt32(8),
|
||||
});
|
||||
}
|
||||
while (reader.Read()) records.Add(ReadSet(reader));
|
||||
return records;
|
||||
}
|
||||
|
||||
private static DrawingSetRecord ReadSet(SqliteDataReader reader) => new()
|
||||
{
|
||||
Id = Guid.Parse(reader.GetString(0)),
|
||||
Revision = reader.GetInt32(1),
|
||||
Name = reader.GetString(2),
|
||||
Customer = reader.GetString(3),
|
||||
Notes = reader.GetString(4),
|
||||
Archived = reader.GetInt32(5) != 0,
|
||||
SavedAt = DateTime.Parse(reader.GetString(6)),
|
||||
SavedBy = reader.GetString(7),
|
||||
MemberCount = reader.GetInt32(8),
|
||||
};
|
||||
|
||||
// Called only under _sync. Members of the record's own revision, each joined to its drawing's current record.
|
||||
private DrawingSetRecord WithMembers(DrawingSetRecord record)
|
||||
{
|
||||
|
||||
@@ -296,13 +296,9 @@ public sealed partial class NestDatabase : IDisposable
|
||||
lock (_sync)
|
||||
{
|
||||
if (Get(id, deleted) is null) return null;
|
||||
var total = CountRevisions("nest_revisions", id);
|
||||
using var command = _connection.CreateCommand();
|
||||
command.CommandText = $"SELECT {RecordColumns} FROM nest_revisions WHERE id=$id ORDER BY revision DESC LIMIT $limit OFFSET $offset";
|
||||
BindRevisionPage(command, id, offset, limit);
|
||||
var records = new List<NestRecord>();
|
||||
using var reader = command.ExecuteReader();
|
||||
while (reader.Read()) records.Add(ReadRecord(reader));
|
||||
var (records, total) = ReadRevisionPage("nest_revisions",
|
||||
$"SELECT {RecordColumns} FROM nest_revisions WHERE id=$id ORDER BY revision DESC LIMIT $limit OFFSET $offset",
|
||||
id, offset, limit, reader => ReadRecord(reader));
|
||||
return new NestPage { Items = records, Total = total, Offset = offset, Limit = limit };
|
||||
}
|
||||
}
|
||||
@@ -587,6 +583,21 @@ public sealed partial class NestDatabase : IDisposable
|
||||
return checked((int)(long)count.ExecuteScalar()!);
|
||||
}
|
||||
|
||||
// Called only under _sync. One page of a newest-first revision history: the revision count
|
||||
// in table and the rows query returns, read by readRow. The query binds $id, $limit and $offset.
|
||||
private (List<T> Items, int Total) ReadRevisionPage<T>(string table, string query, Guid id, int offset, int limit,
|
||||
Func<SqliteDataReader, T> readRow)
|
||||
{
|
||||
var total = CountRevisions(table, id);
|
||||
using var command = _connection.CreateCommand();
|
||||
command.CommandText = query;
|
||||
BindRevisionPage(command, id, offset, limit);
|
||||
var records = new List<T>();
|
||||
using var reader = command.ExecuteReader();
|
||||
while (reader.Read()) records.Add(readRow(reader));
|
||||
return (records, total);
|
||||
}
|
||||
|
||||
// Binds a newest-first revision page query's $id, $limit and $offset.
|
||||
private static void BindRevisionPage(SqliteCommand command, Guid id, int offset, int limit)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user