refactor(data): share nest-server request helpers across remote clients

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-23 05:48:41 -05:00
1 parent eaf99fba8b
commit afc3acd418
6 files changed
+121 -117

No files matched your search

+80
View File
@@ -1,3 +1,6 @@
using System.Net;
using System.Net.Http.Json;
namespace OpenNest.Data;
/// <summary>The connection every nest server client holds: its HTTP client and the server's base address.</summary>
@@ -16,6 +19,83 @@ public abstract class NestServerClient : IDisposable
private protected Uri Url(string relative) => new(_baseUri, relative);
/// <summary>A request that applies only while the stored revision is still <paramref name="expectedRevision"/>.</summary>
private protected HttpRequestMessage Guarded(HttpMethod method, string relative, int expectedRevision)
{
var request = new HttpRequestMessage(method, Url(relative));
NestServerHttp.AddIfMatch(request, expectedRevision);
return request;
}
/// <summary>
/// Probes a route every server with the feature answers; a 404 there means the server
/// predates the feature, so <paramref name="tooOld"/> is raised.
/// </summary>
private protected async Task ThrowIfRouteMissing(string probe, Func<ServerTooOldException> tooOld,
CancellationToken cancellationToken)
{
using var response = await _httpClient.GetAsync(Url(probe), cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
throw tooOld();
}
private protected static void ThrowIfInvalidQuery(string? error)
{
if (error is not null)
throw new ArgumentException(error, "query");
}
/// <summary>
/// One page of a filtered browse: a 404 raises <paramref name="tooOld"/>, and a page that is
/// missing, over <paramref name="limit"/>, negative or holds a null item raises
/// <see cref="IOException"/> naming <paramref name="pageName"/>.
/// </summary>
private protected async Task<TPage> QueryPageAsync<TPage, TItem>(string relative, int limit, string action,
string pageName, Func<ServerTooOldException> tooOld, Func<TPage, IReadOnlyCollection<TItem>?> items,
CancellationToken cancellationToken)
where TPage : class, IBrowsePage
where TItem : class
{
using var response = await _httpClient.GetAsync(Url(relative), cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
throw tooOld();
await NestServerHttp.EnsureSuccessAsync(response, action, cancellationToken);
var page = await response.Content.ReadFromJsonAsync<TPage>(NestServerHttp.JsonOptions, cancellationToken)
?? throw new IOException($"Nest server returned an empty {pageName} page.");
var list = items(page);
if (list is null || list.Count > limit || page.Total < 0 || list.Any(item => item is null))
throw new IOException($"Nest server returned an invalid {pageName} page for a page limited to {limit}.");
return page;
}
/// <summary>
/// Sends a <see cref="Guarded"/> write and reads the stored record back. A 404 runs
/// <paramref name="throwIfServerTooOld"/> and otherwise reports the record gone; a 409 raises
/// <paramref name="conflict"/> with the current record; a reply for another record or an
/// older revision raises <see cref="IOException"/> with <paramref name="invalidMessage"/>.
/// </summary>
private protected async Task<TRecord> SendGuardedAsync<TRecord>(HttpRequestMessage request, Guid id, int expectedRevision,
string action, string missingMessage, string invalidMessage,
Func<HttpResponseMessage, CancellationToken, Task<TRecord>> read,
Func<TRecord, Exception> conflict, Func<TRecord, (Guid Id, int Revision)> identity,
Func<CancellationToken, Task> throwIfServerTooOld, CancellationToken cancellationToken)
{
using var response = await _httpClient.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
{
await throwIfServerTooOld(cancellationToken);
throw new IOException(missingMessage);
}
if (response.StatusCode == HttpStatusCode.Conflict)
throw conflict(await read(response, cancellationToken));
await NestServerHttp.EnsureSuccessAsync(response, action, cancellationToken);
var saved = await read(response, cancellationToken);
var (savedId, savedRevision) = identity(saved);
if (savedId != id || savedRevision < expectedRevision)
throw new IOException(invalidMessage);
return saved;
}
public void Dispose()
{
if (_ownsClient)
+13 -43
View File
@@ -56,19 +56,10 @@ public sealed class RemoteDrawingLibrary : NestServerClient, IDrawingLibraryStor
public async Task<DrawingLibraryPage> QueryAsync(DrawingLibraryQuery query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
var error = query.GetValidationError();
if (error is not null)
throw new ArgumentException(error, nameof(query));
using var response = await _httpClient.GetAsync(Url("api/drawings/query?" + BuildQueryString(query)), cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
throw new ServerTooOldException();
await NestServerHttp.EnsureSuccessAsync(response, "browse the drawing library", cancellationToken);
var page = await response.Content.ReadFromJsonAsync<DrawingLibraryPage>(NestServerHttp.JsonOptions, cancellationToken)
?? throw new IOException("Nest server returned an empty drawing page.");
if (page.Items is null || page.Items.Count > query.Limit || page.Total < 0 || page.Items.Any(item => item is null))
throw new IOException($"Nest server returned an invalid drawing page for a page limited to {query.Limit}.");
return page;
ThrowIfInvalidQuery(query.GetValidationError());
return await QueryPageAsync<DrawingLibraryPage, DrawingLibraryRecord>("api/drawings/query?" + BuildQueryString(query),
query.Limit, "browse the drawing library", "drawing", () => new ServerTooOldException(), page => page.Items,
cancellationToken);
}
/// <summary>The current record, including an archived one, or null for an unknown id.</summary>
@@ -173,30 +164,13 @@ public sealed class RemoteDrawingLibrary : NestServerClient, IDrawingLibraryStor
return changed;
}
private HttpRequestMessage Guarded(HttpMethod method, string relative, int expectedRevision)
{
var request = new HttpRequestMessage(method, Url(relative));
NestServerHttp.AddIfMatch(request, expectedRevision);
return request;
}
private async Task<DrawingLibraryRecord> SendGuarded(HttpRequestMessage request, Guid id, int expectedRevision,
string action, CancellationToken cancellationToken)
{
using var response = await _httpClient.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
{
await ThrowIfServerTooOld(cancellationToken);
throw new IOException($"Library drawing {id} no longer exists on the nest server.");
}
if (response.StatusCode == HttpStatusCode.Conflict)
throw new DrawingLibraryConflictException(await ReadRecord(response, cancellationToken));
await NestServerHttp.EnsureSuccessAsync(response, action, cancellationToken);
var saved = await ReadRecord(response, cancellationToken);
if (saved.Id != id || saved.Revision < expectedRevision)
throw new IOException("Nest server returned an invalid library drawing revision. Reload the library before saving again.");
return saved;
}
private Task<DrawingLibraryRecord> SendGuarded(HttpRequestMessage request, Guid id, int expectedRevision,
string action, CancellationToken cancellationToken) =>
SendGuardedAsync(request, id, expectedRevision, action,
$"Library drawing {id} no longer exists on the nest server.",
"Nest server returned an invalid library drawing revision. Reload the library before saving again.",
ReadRecord, current => new DrawingLibraryConflictException(current), saved => (saved.Id, saved.Revision),
ThrowIfServerTooOld, cancellationToken);
private async Task<byte[]?> GetBytesAsync(string relative, string action, CancellationToken cancellationToken)
{
@@ -211,12 +185,8 @@ public sealed class RemoteDrawingLibrary : NestServerClient, IDrawingLibraryStor
}
// A 404 for one drawing is ambiguous; the query route exists on every library-aware server.
private async Task ThrowIfServerTooOld(CancellationToken cancellationToken)
{
using var probe = await _httpClient.GetAsync(Url("api/drawings/query?limit=1"), cancellationToken);
if (probe.StatusCode == HttpStatusCode.NotFound)
throw new ServerTooOldException();
}
private Task ThrowIfServerTooOld(CancellationToken cancellationToken) =>
ThrowIfRouteMissing("api/drawings/query?limit=1", () => new ServerTooOldException(), cancellationToken);
private static void ValidateUpload(DrawingLibraryRecord record, byte[] package)
{
+15 -49
View File
@@ -37,19 +37,10 @@ public sealed class RemoteDrawingSetStore : NestServerClient, IDrawingSetStore
public async Task<DrawingSetPage> QueryAsync(DrawingSetQuery query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
var error = query.GetValidationError();
if (error is not null)
throw new ArgumentException(error, nameof(query));
using var response = await _httpClient.GetAsync(Url("api/sets/query?" + BuildQueryString(query)), cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
throw new ServerTooOldException(Feature);
await NestServerHttp.EnsureSuccessAsync(response, "browse drawing sets", 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 || page.Items.Count > query.Limit || page.Total < 0 || page.Items.Any(item => item is null))
throw new IOException($"Nest server returned an invalid drawing set page for a page limited to {query.Limit}.");
return page;
ThrowIfInvalidQuery(query.GetValidationError());
return await QueryPageAsync<DrawingSetPage, DrawingSetRecord>("api/sets/query?" + BuildQueryString(query),
query.Limit, "browse drawing sets", "drawing set", () => new ServerTooOldException(Feature), page => page.Items,
cancellationToken);
}
public async Task<DrawingSetRecord?> GetAsync(Guid id, CancellationToken cancellationToken = default)
@@ -279,30 +270,13 @@ public sealed class RemoteDrawingSetStore : NestServerClient, IDrawingSetStore
return changed;
}
private HttpRequestMessage Guarded(HttpMethod method, string relative, int expectedRevision)
{
var request = new HttpRequestMessage(method, Url(relative));
NestServerHttp.AddIfMatch(request, expectedRevision);
return request;
}
private async Task<DrawingSetRecord> SendGuarded(HttpRequestMessage request, Guid id, int expectedRevision,
string action, CancellationToken cancellationToken)
{
using var response = await _httpClient.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
{
await ThrowIfServerTooOld(cancellationToken);
throw new IOException($"Drawing set {id} no longer exists on the nest server.");
}
if (response.StatusCode == HttpStatusCode.Conflict)
throw new DrawingSetSaveConflictException(await ReadSet(response, cancellationToken));
await NestServerHttp.EnsureSuccessAsync(response, action, cancellationToken);
var saved = await ReadSet(response, cancellationToken);
if (saved.Id != id || saved.Revision < expectedRevision)
throw new IOException("Nest server returned an invalid drawing set revision. Reload the set before saving again.");
return saved;
}
private Task<DrawingSetRecord> SendGuarded(HttpRequestMessage request, Guid id, int expectedRevision,
string action, CancellationToken cancellationToken) =>
SendGuardedAsync(request, id, expectedRevision, action,
$"Drawing set {id} no longer exists on the nest server.",
"Nest server returned an invalid drawing set revision. Reload the set before saving again.",
ReadSet, current => new DrawingSetSaveConflictException(current), saved => (saved.Id, saved.Revision),
ThrowIfServerTooOld, cancellationToken);
private async Task<DrawingSetRecord?> GetRecordAsync(string relative, string action, CancellationToken cancellationToken)
{
@@ -337,19 +311,11 @@ public sealed class RemoteDrawingSetStore : NestServerClient, IDrawingSetStore
// A 404 for one set or nest is ambiguous; the query route exists on every set-aware server.
// A server from before v9 has no /api/releases at all, so a 404 there is not "unknown release".
private async Task ThrowIfReleasesUnsupported(CancellationToken cancellationToken)
{
using var probe = await _httpClient.GetAsync(Url("api/releases/query?limit=1"), cancellationToken);
if (probe.StatusCode == HttpStatusCode.NotFound)
throw new ServerTooOldException(ReleaseFeature);
}
private Task ThrowIfReleasesUnsupported(CancellationToken cancellationToken) =>
ThrowIfRouteMissing("api/releases/query?limit=1", () => new ServerTooOldException(ReleaseFeature), cancellationToken);
private async Task ThrowIfServerTooOld(CancellationToken cancellationToken)
{
using var probe = await _httpClient.GetAsync(Url("api/sets/query?limit=1"), cancellationToken);
if (probe.StatusCode == HttpStatusCode.NotFound)
throw new ServerTooOldException(Feature);
}
private Task ThrowIfServerTooOld(CancellationToken cancellationToken) =>
ThrowIfRouteMissing("api/sets/query?limit=1", () => new ServerTooOldException(Feature), cancellationToken);
private static bool HasJoinedMembers(DrawingSetRecord record) =>
record.Members is not null
+3 -7
View File
@@ -100,11 +100,8 @@ public sealed class RemoteNestJobs : NestServerClient
private async Task<NestJobRecord?> ReviewAsync(NestJobRecord job, string action, string reviewedBy, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(job);
using var request = new HttpRequestMessage(HttpMethod.Post, Url($"api/nest-jobs/{job.Id}/{action}"))
{
Content = JsonContent.Create(new NestJobReviewRequest { ReviewedBy = reviewedBy ?? "" }, options: NestServerHttp.JsonOptions),
};
NestServerHttp.AddIfMatch(request, checked((int)job.Revision));
using var request = Guarded(HttpMethod.Post, $"api/nest-jobs/{job.Id}/{action}", checked((int)job.Revision));
request.Content = JsonContent.Create(new NestJobReviewRequest { ReviewedBy = reviewedBy ?? "" }, options: NestServerHttp.JsonOptions);
using var response = await _httpClient.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
return await GetAsync(job.Id, cancellationToken) is null ? null : throw new ServerTooOldException("keeping server nests once");
@@ -121,8 +118,7 @@ public sealed class RemoteNestJobs : NestServerClient
public async Task<bool> DeleteAsync(NestJobRecord job, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(job);
using var request = new HttpRequestMessage(HttpMethod.Delete, Url($"api/nest-jobs/{job.Id}"));
NestServerHttp.AddIfMatch(request, checked((int)job.Revision));
using var request = Guarded(HttpMethod.Delete, $"api/nest-jobs/{job.Id}", checked((int)job.Revision));
using var response = await _httpClient.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
return false;
+6 -10
View File
@@ -225,8 +225,7 @@ public sealed class RemoteNestRepository : NestServerClient, INestRepository
var history = await GetRevisionsAsync(id, limit: 1, cancellationToken: cancellationToken);
if (history.Items.Count == 0)
throw new IOException("Nest server returned no revision history. Upgrade the nest server and reload before saving.");
using var request = new HttpRequestMessage(HttpMethod.Put, Url($"api/nests/{id}/file"));
NestServerHttp.AddIfMatch(request, expectedRevision);
using var request = Guarded(HttpMethod.Put, $"api/nests/{id}/file", expectedRevision);
request.Content = BuildMultipart(nestFile, record);
using var response = await _httpClient.SendAsync(request, cancellationToken);
await NestServerHttp.EnsureSuccessAsync(response, $"update nest {id}; reload the current version or Save As after a conflict", cancellationToken);
@@ -242,8 +241,7 @@ public sealed class RemoteNestRepository : NestServerClient, INestRepository
ValidateId(id);
ValidateRevision(expectedRevision);
await GetRevisionsAsync(id, limit: 1, cancellationToken: cancellationToken);
using var request = new HttpRequestMessage(HttpMethod.Put, Url($"api/nests/{id}/metadata"));
NestServerHttp.AddIfMatch(request, expectedRevision);
using var request = Guarded(HttpMethod.Put, $"api/nests/{id}/metadata", expectedRevision);
request.Content = JsonContent.Create(record, options: NestServerHttp.JsonOptions);
using var response = await _httpClient.SendAsync(request, cancellationToken);
await NestServerHttp.EnsureSuccessAsync(response, $"edit nest {id}; reload after a conflict", cancellationToken);
@@ -257,9 +255,8 @@ public sealed class RemoteNestRepository : NestServerClient, INestRepository
ValidateRevision(sourceRevision);
ValidateRevision(expectedRevision);
await GetRevisionsAsync(id, limit: 1, cancellationToken: cancellationToken);
using var request = new HttpRequestMessage(HttpMethod.Post,
Url($"api/nests/{id}/revisions/{sourceRevision.ToString(CultureInfo.InvariantCulture)}/restore"));
NestServerHttp.AddIfMatch(request, expectedRevision);
using var request = Guarded(HttpMethod.Post,
$"api/nests/{id}/revisions/{sourceRevision.ToString(CultureInfo.InvariantCulture)}/restore", expectedRevision);
using var response = await _httpClient.SendAsync(request, cancellationToken);
await NestServerHttp.EnsureSuccessAsync(response, $"restore nest {id}; reload after a conflict", cancellationToken);
return await ReadRecord(response, cancellationToken);
@@ -278,9 +275,8 @@ public sealed class RemoteNestRepository : NestServerClient, INestRepository
ValidateRevision(expectedRevision);
// A legacy server cannot be trusted to preserve history on DELETE.
await GetHistoryAsync(id, 0, 1, !deleted, cancellationToken);
using var request = new HttpRequestMessage(deleted ? HttpMethod.Delete : HttpMethod.Post,
Url(deleted ? $"api/nests/{id}" : $"api/nests/deleted/{id}/recover"));
NestServerHttp.AddIfMatch(request, expectedRevision);
using var request = Guarded(deleted ? HttpMethod.Delete : HttpMethod.Post,
deleted ? $"api/nests/{id}" : $"api/nests/deleted/{id}/recover", expectedRevision);
using var response = await _httpClient.SendAsync(request, cancellationToken);
await NestServerHttp.EnsureSuccessAsync(response, $"change nest visibility {id}; reload after a conflict", cancellationToken);
return await ReadRecord(response, cancellationToken);
+4 -8
View File
@@ -63,11 +63,8 @@ public sealed class RemoteSharedSettings : NestServerClient
CancellationToken cancellationToken = default)
{
Validate(kind, key, write);
using var request = new HttpRequestMessage(HttpMethod.Put, Url(Path(kind, key)))
{
Content = JsonContent.Create(write, options: NestServerHttp.JsonOptions),
};
NestServerHttp.AddIfMatch(request, expectedRevision);
using var request = Guarded(HttpMethod.Put, Path(kind, key), expectedRevision);
request.Content = JsonContent.Create(write, options: NestServerHttp.JsonOptions);
using var response = await _httpClient.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
throw new SharedSettingMissingException(kind, key);
@@ -80,9 +77,8 @@ public sealed class RemoteSharedSettings : NestServerClient
{
if (SharedSettingRules.NormalizeKey(kind, key) is null)
throw new ArgumentException($"Invalid {kind} settings key.", nameof(key));
using var request = new HttpRequestMessage(HttpMethod.Delete,
Url(Path(kind, key) + "?savedBy=" + Uri.EscapeDataString(savedBy ?? "")));
NestServerHttp.AddIfMatch(request, expectedRevision);
using var request = Guarded(HttpMethod.Delete,
Path(kind, key) + "?savedBy=" + Uri.EscapeDataString(savedBy ?? ""), expectedRevision);
using var response = await _httpClient.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
return;