diff --git a/AGENTS.md b/AGENTS.md index a0b30dc6..92170625 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,7 +78,7 @@ Read the relevant contract before changing its behavior: - [Pre-post verification](docs/post-verification.md) - [Machine cutting defaults](docs/machine-cutting-defaults.md): the nest's machine supplies leads, kerf and cut-off settings for plates without their own parameters - [Shared settings](docs/shared-settings.md): in Database mode machines, post settings, clamps and nest defaults come from the server once it holds them; offline uses the last copy read, read-only -- [Server nesting](docs/server-nesting.md): Database-mode Auto Nest queued to the server's worker container (`OPENNEST_ROLE=worker`), one job at a time with no time limit; the desktop replays the recorded engine answers to validate and bind locally. The HTTP server stays off Engine/IO +- [Server nesting](docs/server-nesting.md): Database-mode Auto Nest queued to the server's worker container (`OPENNEST_ROLE=worker`), one job at a time with no time limit, streaming progress and the best plan so far over SSE; the desktop replays the recorded engine answers to validate and bind locally. The HTTP server stays off Engine/IO - [Cut-time estimates](docs/cut-time-estimates.md): simulator/Calculate Cut Time acceleration planner and placeholder machine limits - [Cincinnati CL](docs/cincinnati-post-output.md) and [CI Fiber](docs/cincinnati-ci-fiber-post-output.md) - [Fill verification](docs/performance/fill-verification.md): opt-in benchmarks, frozen oracles, Debug-only counters and predictor initialization. Zero Release counters do not prove work removal. diff --git a/OpenNest.Data/NestJobRecord.cs b/OpenNest.Data/NestJobRecord.cs index a0b75b7c..980d0272 100644 --- a/OpenNest.Data/NestJobRecord.cs +++ b/OpenNest.Data/NestJobRecord.cs @@ -44,6 +44,21 @@ public sealed class NestJobRecord public long PackageSize { get; set; } + /// + /// Bumped by every change a watcher shows (state, cancel request, progress, plan); the + /// event stream's ids. Heartbeats leave it alone. + /// + public long Revision { get; set; } + + /// The the best plan so far was stored at; zero when there is none. + public long PlanRevision { get; set; } + + /// + /// The worker's latest progress report while the job runs (RemoteNestProgress JSON, + /// opaque to the server); empty when there is none. + /// + public string Progress { get; set; } = ""; + public bool IsFinished => State is NestJobState.Succeeded or NestJobState.Failed or NestJobState.Cancelled; } @@ -72,6 +87,35 @@ public sealed class NestJobHeartbeat public bool CancelRequested { get; set; } } +/// What a job's event stream (GET /api/nest-jobs/{id}/events) sent. +public enum NestJobEventKind +{ + /// The stream is open; nothing has necessarily changed. + Open, + + /// The job itself: . The last one of a stream is final. + Job, + + /// A new best plan so far: , sent before the job event that names it. + Plan, + + /// The server no longer holds the job. + Gone, +} + +public sealed class NestJobEvent +{ + public NestJobEventKind Kind { get; init; } + + /// The event id: the job's , or the plan's for a plan. + public long Id { get; init; } + + public NestJobRecord? Job { get; init; } + + /// The worker's plan (RemoteNestPlan JSON, opaque to the server). + public string Plan { get; init; } = ""; +} + /// Limits and timings both sides of server nesting share. public static class NestJobRules { @@ -89,6 +133,24 @@ public static class NestJobRules /// How often a worker reports; well inside . public static readonly TimeSpan HeartbeatInterval = TimeSpan.FromSeconds(20); + /// Largest progress report a worker may store. + public const long MaxProgressBytes = 64L * 1024; + + /// Largest best-plan-so-far a worker may store. + public const long MaxPlanBytes = 16L * 1024 * 1024; + + /// + /// How often a worker at most stores progress and plans (only the latest of each is sent), + /// and checks for a cancel request between reports. + /// + public static readonly TimeSpan ProgressInterval = TimeSpan.FromSeconds(2); + + /// How often an idle event stream sends a comment, so a dropped connection shows. + public static readonly TimeSpan StreamKeepAlive = TimeSpan.FromSeconds(15); + + /// A stream silent this long (several missed keep-alives) is treated as dropped. + public static readonly TimeSpan StreamIdleTimeout = TimeSpan.FromSeconds(45); + /// Workers that stop responding this many times fail the job instead of retrying it. public const int MaxAttempts = 3; diff --git a/OpenNest.Data/NestJobWatch.cs b/OpenNest.Data/NestJobWatch.cs new file mode 100644 index 00000000..e76c62e6 --- /dev/null +++ b/OpenNest.Data/NestJobWatch.cs @@ -0,0 +1,113 @@ +namespace OpenNest.Data; + +/// +/// Follows one server nest job to its final state for a desktop: the job's event stream +/// while it holds, polling while it does not. A dropped stream is followed by one poll (so +/// nothing is missed), then reconnects with the last event id; a server without the stream is +/// polled throughout. Reports go to sinks, so a UI receives them +/// on its own thread. See docs/server-nesting.md. +/// +public sealed class NestJobWatch +{ + private readonly RemoteNestJobs _jobs; + + public NestJobWatch(RemoteNestJobs jobs) + { + _jobs = jobs ?? throw new ArgumentNullException(nameof(jobs)); + } + + /// How long to wait between polls, and before reconnecting a dropped stream. + public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(2); + + public TimeSpan IdleTimeout { get; init; } = NestJobRules.StreamIdleTimeout; + + /// Each new state of the job, the first being the one was given. + public IProgress? Job { get; init; } + + /// Each new best plan so far (RemoteNestPlan JSON). + public IProgress? Plan { get; init; } + + /// Why the job's updates are late, or empty once they arrive again. The job keeps running meanwhile. + public IProgress? Problem { get; init; } + + /// Waits for to finish and returns its final state. + public async Task RunAsync(NestJobRecord job, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(job); + Job?.Report(job); + var lastId = 0L; + var planRevision = 0L; + var streaming = true; + while (!job.IsFinished) + { + cancellationToken.ThrowIfCancellationRequested(); + if (streaming) + { + try + { + await foreach (var update in _jobs.WatchAsync(job.Id, lastId, IdleTimeout, cancellationToken)) + { + switch (update.Kind) + { + case NestJobEventKind.Open: + Problem?.Report(""); + break; + case NestJobEventKind.Gone: + throw Gone(); + case NestJobEventKind.Plan: + lastId = System.Math.Max(lastId, update.Id); + planRevision = update.Id; + Plan?.Report(update.Plan); + break; + case NestJobEventKind.Job: + lastId = System.Math.Max(lastId, update.Id); + job = update.Job!; + Job?.Report(job); + if (job.IsFinished) + return job; + break; + } + } + Problem?.Report("The nest server's job updates stopped; reconnecting"); + } + catch (ServerTooOldException) + { + streaming = false; + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested + && ex is IOException or HttpRequestException or TaskCanceledException) + { + Problem?.Report($"Waiting for the nest server: {ex.Message}"); + } + } + + // Between streams, or instead of them on a server without one: one poll. + try + { + var polled = await _jobs.GetAsync(job.Id, cancellationToken) ?? throw Gone(); + if (polled.PlanRevision > planRevision && await _jobs.GetPlanAsync(job.Id, cancellationToken) is { } plan + && plan.Revision > planRevision) + { + planRevision = plan.Revision; + Plan?.Report(plan.Plan); + } + if (polled.Revision != job.Revision || polled.QueuePosition != job.QueuePosition || polled.IsFinished) + Job?.Report(polled); + job = polled; + if (!streaming) + Problem?.Report(""); + if (job.IsFinished) + return job; + } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested + && ex is IOException or HttpRequestException or TaskCanceledException) + { + Problem?.Report($"Waiting for the nest server: {ex.Message}"); + } + await Task.Delay(PollInterval, cancellationToken); + } + return job; + } + + private static InvalidOperationException Gone() => new("The nest server no longer has this job."); +} diff --git a/OpenNest.Data/RemoteNestJobs.cs b/OpenNest.Data/RemoteNestJobs.cs index 0f162b1f..253d528b 100644 --- a/OpenNest.Data/RemoteNestJobs.cs +++ b/OpenNest.Data/RemoteNestJobs.cs @@ -1,6 +1,8 @@ +using System.Globalization; using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; +using System.Runtime.CompilerServices; using System.Text; using System.Text.Json; @@ -65,6 +67,112 @@ public sealed class RemoteNestJobs : NestServerClient return await response.Content.ReadAsStringAsync(cancellationToken); } + /// The header naming the revision GET .../plan returned. + public const string PlanRevisionHeader = "X-Plan-Revision"; + + /// The best plan so far and the revision it was stored at, or null when the job has none. + public async Task<(string Plan, long Revision)?> GetPlanAsync(Guid id, CancellationToken cancellationToken = default) + { + using var response = await _httpClient.GetAsync(Url($"api/nest-jobs/{id}/plan"), cancellationToken); + if (response.StatusCode is HttpStatusCode.NoContent or HttpStatusCode.NotFound) + return null; + await NestServerHttp.EnsureSuccessAsync(response, "read the nest job's plan", cancellationToken); + var revision = response.Headers.TryGetValues(PlanRevisionHeader, out var values) + && long.TryParse(values.FirstOrDefault(), NumberStyles.None, CultureInfo.InvariantCulture, out var value) ? value : 0; + return (await response.Content.ReadAsStringAsync(cancellationToken), revision); + } + + /// + /// The job's event stream: an event, then each plan and + /// job change after (zero: the current job at once), ending + /// after the job event that is final, or with . A stream + /// that ends without either, or stays silent for , dropped: + /// reconnect with the last id seen. A server without the stream raises . + /// + public async IAsyncEnumerable WatchAsync(Guid id, long lastEventId = 0, TimeSpan? idleTimeout = null, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + using var request = new HttpRequestMessage(HttpMethod.Get, Url($"api/nest-jobs/{id}/events")); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); + if (lastEventId > 0) + request.Headers.TryAddWithoutValidation("Last-Event-ID", lastEventId.ToString(CultureInfo.InvariantCulture)); + using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + if (response.StatusCode == HttpStatusCode.NotFound) + { + if (await GetAsync(id, cancellationToken) is null) + { + yield return new NestJobEvent { Kind = NestJobEventKind.Gone }; + yield break; + } + throw new ServerTooOldException("server nesting progress"); + } + await NestServerHttp.EnsureSuccessAsync(response, "watch the nest job", cancellationToken); + yield return new NestJobEvent { Kind = NestJobEventKind.Open }; + + using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + using var reader = new StreamReader(stream, Encoding.UTF8); + var idle = idleTimeout ?? NestJobRules.StreamIdleTimeout; + var type = ""; + var eventId = 0L; + var data = new StringBuilder(); + while (true) + { + string? line; + using (var silence = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) + { + silence.CancelAfter(idle); + try { line = await reader.ReadLineAsync(silence.Token); } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new IOException("The nest server stopped sending job updates."); + } + } + if (line is null) + yield break; + if (line.Length > 0) + { + if (line[0] == ':') + continue; + var colon = line.IndexOf(':'); + var field = colon < 0 ? line : line[..colon]; + var value = colon < 0 ? "" : line[(colon + 1)..]; + if (value.StartsWith(' ')) + value = value[1..]; + switch (field) + { + case "event": type = value; break; + case "id": long.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out eventId); break; + case "data": + if (data.Length > 0) + data.Append('\n'); + data.Append(value); + break; + } + continue; + } + + // A blank line dispatches the event. + var text = data.ToString(); + var kind = type; + data.Clear(); + type = ""; + switch (kind) + { + case "job": + var job = JsonSerializer.Deserialize(text, NestServerHttp.JsonOptions) + ?? throw new IOException("Nest server sent an empty nest job."); + yield return new NestJobEvent { Kind = NestJobEventKind.Job, Id = eventId, Job = job }; + break; + case "plan": + yield return new NestJobEvent { Kind = NestJobEventKind.Plan, Id = eventId, Plan = text }; + break; + case "gone": + yield return new NestJobEvent { Kind = NestJobEventKind.Gone, Id = eventId }; + yield break; + } + } + } + /// Stops the job: a queued job is cancelled at once, a running one at its worker's next heartbeat. public async Task CancelAsync(Guid id, CancellationToken cancellationToken = default) { @@ -108,6 +216,29 @@ public sealed class RemoteNestJobs : NestServerClient ?? throw new IOException("Nest server returned an empty heartbeat."); } + /// + /// Stores the worker's latest progress report (and renews the lease). Null when the worker + /// no longer holds the job; otherwise whether someone asked to stop it. + /// + public Task ReportProgressAsync(Guid id, string workerId, string progress, CancellationToken cancellationToken = default) => + PutReportAsync($"api/nest-jobs/{id}/progress", workerId, progress, "report the nest job's progress", cancellationToken); + + /// Stores the best plan so far, as does a progress report. + public Task ReportPlanAsync(Guid id, string workerId, string plan, CancellationToken cancellationToken = default) => + PutReportAsync($"api/nest-jobs/{id}/plan", workerId, plan, "report the nest job's plan", cancellationToken); + + private async Task PutReportAsync(string path, string workerId, string json, string action, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(json); + using var content = new StringContent(json, Encoding.UTF8, "application/json"); + using var response = await _httpClient.PutAsync(Url($"{path}?workerId={Uri.EscapeDataString(workerId)}"), content, cancellationToken); + if (response.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.NotFound) + return null; + await NestServerHttp.EnsureSuccessAsync(response, action, cancellationToken); + return await response.Content.ReadFromJsonAsync(NestServerHttp.JsonOptions, cancellationToken) + ?? throw new IOException("Nest server returned an empty answer."); + } + /// Stores the result. False when the worker no longer holds the job. public async Task CompleteAsync(Guid id, string workerId, string result, CancellationToken cancellationToken = default) { diff --git a/OpenNest.Engine.Tests/Jobs/RemoteNestProgressTests.cs b/OpenNest.Engine.Tests/Jobs/RemoteNestProgressTests.cs new file mode 100644 index 00000000..008f4167 --- /dev/null +++ b/OpenNest.Engine.Tests/Jobs/RemoteNestProgressTests.cs @@ -0,0 +1,130 @@ +using OpenNest.Engine.Jobs; +using OpenNest.Engine.Jobs.Remote; +using OpenNest.Geometry; + +namespace OpenNest.Engine.Tests.Jobs; + +/// +/// The nest server worker's live progress: the recording engine passes each solve's progress +/// on, and a plan sent over the wire is drawn on the desktop as the same sheets a local run +/// shows in its best-plan-so-far strip. +/// +public class RemoteNestProgressTests +{ + private sealed class Collect : IProgress + { + public readonly List Reports = new(); + + public void Report(NestJobProgress value) + { + lock (Reports) + Reports.Add(value); + } + } + + private static NestPipelineRequest Request(string engine) + { + var template = new Plate(48, 96) { EdgeSpacing = new Spacing(0.25, 0.25, 0.25, 0.25), PartSpacing = 0.25 }; + return new NestPipelineRequest(engine, + [ + new NestItem { Drawing = new Drawing("bracket", TestDrawingFactory.Rectangle(10, 20)), Quantity = 9 }, + new NestItem { Drawing = new Drawing("ell", TestDrawingFactory.LShape()), Quantity = 6, Priority = 1 }, + ], + NestStockBuilder.FromTemplate(template, null), + new NestJobOptions(maxPlates: 5)); + } + + private static IEnumerable<(string Name, double X, double Y, double Rotation)> Poses(IEnumerable sheets) => + sheets.SelectMany(s => s.Parts.Select(p => (p.BaseDrawing.Name, p.Location.X, p.Location.Y, p.Rotation))); + + [Theory] + [InlineData("Rectangles")] + [InlineData("Default")] + public void AWirePlanDrawsAsTheLocalPlanSheets(string engine) + { + var request = Request(engine); + var local = new Collect(); + NestPipeline.Run(request, local); + var plans = local.Reports.Where(r => r.Stage == NestJobStage.PlanImproved && r.PlanSheets != null).ToList(); + Assert.NotEmpty(plans); + + var preview = new RemoteNestPlanPreview(request); + foreach (var plan in plans) + { + var sheets = preview.Sheets(RemoteNestPlan.From(plan.Plan).ToJson()); + Assert.NotNull(sheets); + Assert.Equal(plan.PlanSheets.Select(s => (s.Stock.Id, s.Quantity)), sheets.Select(s => (s.Stock.Id, s.Quantity))); + Assert.Equal(Poses(plan.PlanSheets), Poses(sheets)); + // Detached drawings: the caller's are never touched. + Assert.All(sheets.SelectMany(s => s.Parts), p => Assert.DoesNotContain(request.Items, i => ReferenceEquals(i.Drawing, p.BaseDrawing))); + } + } + + [Fact] + public void ACutoutTrialPlanDrawsItsFrameProxies() + { + // A frame whose window takes the strap: the trial's plans name a frame proxy, which the + // preview bundles on the desktop the first time it sees one. + var frame = TestDrawingFactory.Rectangle(20, 20); + frame.Codes.Add(new OpenNest.CNC.RapidMove(4, 3)); + frame.Codes.Add(new OpenNest.CNC.LinearMove(16, 3)); + frame.Codes.Add(new OpenNest.CNC.LinearMove(16, 17)); + frame.Codes.Add(new OpenNest.CNC.LinearMove(4, 17)); + frame.Codes.Add(new OpenNest.CNC.LinearMove(4, 3)); + var request = new NestPipelineRequest("Default", + [ + new NestItem { Drawing = new Drawing("frame", frame), Quantity = 2 }, + new NestItem { Drawing = new Drawing("strap", TestDrawingFactory.Rectangle(13, 1.25)), Quantity = 2 }, + ], + new[] { new NestPlateStock("sheet", new Size(48, 48), 2, 0.25) }); + var tap = new Collect(); + NestPipeline.Run(new RecordingNestingEngine(NestingEngineRegistry.Create("Default")) { Progress = tap }, "Default", request); + var proxyPlans = tap.Reports.Where(r => r.Stage == NestJobStage.PlanImproved && r.Plan != null + && r.Plan.Plates.Any(p => p.Placements.Any(x => x.PartId.StartsWith("__cutout-proxy-")))).ToList(); + Assert.NotEmpty(proxyPlans); + + var preview = new RemoteNestPlanPreview(request); + var sheets = preview.Sheets(RemoteNestPlan.From(proxyPlans[^1].Plan).ToJson()); + + Assert.NotNull(sheets); + Assert.Equal(proxyPlans[^1].Plan.Plates.Sum(p => p.Placements.Count), sheets.Sum(s => s.Quantity * s.Parts.Count)); + } + + [Fact] + public void UnreadableOrForeignPlansDrawNothing() + { + var preview = new RemoteNestPlanPreview(Request("Rectangles")); + Assert.Null(preview.Sheets("")); + Assert.Null(preview.Sheets("not json")); + Assert.Null(preview.Sheets("""{"version":99,"plan":{"plates":[]}}""")); + var stranger = new NestJobResult(NestJobStatus.Complete, NestJobStopReason.Completed, + [new NestJobPlateResult(0, Request("Rectangles").Stock[0], [new NestJobPlacement("part-7", 0, 1, 1, 0)])], + [], []); + Assert.Null(preview.Sheets(RemoteNestPlan.From(stranger).ToJson())); + } + + [Fact] + public void TheRecorderPassesEachSolvesProgressOn() + { + var request = Request("Rectangles"); + var tap = new Collect(); + var recorder = new RecordingNestingEngine(NestingEngineRegistry.Create(request.EngineName)) { Progress = tap }; + + NestPipeline.Run(recorder, request.EngineName, request); + + Assert.Contains(tap.Reports, r => r.Stage == NestJobStage.PlanImproved && r.Plan != null); + // Before the pipeline draws it: the worker sends placements, not parts. + Assert.All(tap.Reports, r => Assert.Null(r.PlanSheets)); + } + + [Fact] + public void AProgressReportSurvivesTheWire() + { + var report = new NestJobProgress(NestJobStage.PlateCommitted, "stock-1", 2, 3, 41); + var back = RemoteNestProgress.FromJson(RemoteNestProgress.From(report).ToJson())!.ToProgress(); + + Assert.Equal(report, back); + Assert.Null(RemoteNestProgress.FromJson("")); + Assert.Null(RemoteNestProgress.FromJson("{\"version\":2}")); + } +} diff --git a/OpenNest.Engine/Jobs/Cutouts/CutoutPipelinePrepass.cs b/OpenNest.Engine/Jobs/Cutouts/CutoutPipelinePrepass.cs index f4951823..2f9598c8 100644 --- a/OpenNest.Engine/Jobs/Cutouts/CutoutPipelinePrepass.cs +++ b/OpenNest.Engine/Jobs/Cutouts/CutoutPipelinePrepass.cs @@ -25,6 +25,13 @@ internal sealed class CutoutPipelinePrepass /// Most parts on one frame-in-frame chain: flange, washer, smaller washer, slug. internal const int MaxLevels = 4; + /// Every frame proxy's part id starts with this; ordinary parts never do. + internal const string ProxyPrefix = "__cutout-proxy-"; + + /// True for a job holding frame proxies: a bundled cutout trial's engine job. + internal static bool HasProxies(NestJob job) => + job.Parts.Any(p => p.Id.StartsWith(ProxyPrefix, StringComparison.Ordinal)); + // Levels: parts on the deepest chain through the frame; Area: the outlines of the frame and // everything seated in it, which is what taking the bundle spares the sheet. private sealed record Bundle(string FrameId, IReadOnlyList LocalInserts, @@ -136,7 +143,7 @@ internal sealed class CutoutPipelinePrepass } if (chosen == null || chosen.Count == 0) break; - var proxyId = $"__cutout-proxy-{frame.Id}-{instance}"; + var proxyId = $"{ProxyPrefix}{frame.Id}-{instance}"; if (requirements.ContainsKey(proxyId)) throw new InvalidOperationException("Cutout proxy ID collides with a requirement."); var levels = 1 + chosen.Max(p => bundles.TryGetValue(p.PartId, out var b) ? b.Levels : 1); diff --git a/OpenNest.Engine/Jobs/NestPipeline.cs b/OpenNest.Engine/Jobs/NestPipeline.cs index 09968aa0..9fa474fe 100644 --- a/OpenNest.Engine/Jobs/NestPipeline.cs +++ b/OpenNest.Engine/Jobs/NestPipeline.cs @@ -102,7 +102,9 @@ public sealed class NestPipelineResult /// public static class NestPipeline { - private sealed class PreviewProgress(IProgress inner) : IProgress + /// A bundled cutout trial's progress: its commits count proxies, not physical + /// parts, so only candidates and plans pass, with no committed counts. + internal sealed class PreviewProgress(IProgress inner) : IProgress { public void Report(NestJobProgress value) { @@ -133,42 +135,50 @@ public static class NestPipeline // A plan naming unknown parts has nothing to draw; validation reports it later. if (value.Plan.Plates.Any(s => s.Placements.Any(p => p.PartId == null || !parts.ContainsKey(p.PartId)))) return; - value = value with { PlanSheets = Sheets(value.Plan) }; + value = value with { PlanSheets = PlanSheets(value.Plan, parts, callerDrawings, drawings, token) }; } } inner.Report(value); } + } - private IReadOnlyList Sheets(NestJobResult plan) + /// + /// A plan as displayable sheets: identical sheets once with their count, parts on detached + /// drawings built from ' geometry and kept in + /// (one per part id), named and colored like the caller's. Every placement must name one of + /// . + /// + internal static IReadOnlyList PlanSheets(NestJobResult plan, + IReadOnlyDictionary parts, IReadOnlyDictionary callerDrawings, + Dictionary drawings, CancellationToken token) + { + var sheets = new List(); + foreach (var group in RepeatedPlateGrouping.Create(plan.Plates, true, token)) { - var sheets = new List(); - foreach (var group in RepeatedPlateGrouping.Create(plan.Plates, true, token)) + var placed = new List(group.Sheet.Placements.Count); + foreach (var pose in group.Sheet.Placements) { - var placed = new List(group.Sheet.Placements.Count); - foreach (var pose in group.Sheet.Placements) + if (!drawings.TryGetValue(pose.PartId, out var drawing)) { - if (!drawings.TryGetValue(pose.PartId, out var drawing)) + drawing = DrawingJobMapper.CreateDrawing(parts[pose.PartId]); + // Borrow the caller's name and color for display; bundled frames keep their own. + if (callerDrawings.TryGetValue(pose.PartId, out var caller)) { - drawing = DrawingJobMapper.CreateDrawing(parts[pose.PartId]); - // Borrow the caller's name and color for display; bundled frames keep their own. - if (callerDrawings.TryGetValue(pose.PartId, out var caller)) - { - drawing.Name = caller.Name; - drawing.Color = caller.Color; - } - drawings[pose.PartId] = drawing; + drawing.Name = caller.Name; + drawing.Color = caller.Color; } - // Same pose mapping as NestResultMaterializer: rotate in the snapshot frame, then move. - var part = new Part(drawing); - part.Rotate(pose.Rotation); - part.Location = new Geometry.Vector(pose.X, pose.Y); - part.UpdateBounds(); - placed.Add(part); + drawings[pose.PartId] = drawing; } - sheets.Add(new ProposedPlate(group.Sheet.PlateIndex, group.Sheet.Stock, placed) { Quantity = group.Quantity }); + // Same pose mapping as NestResultMaterializer: rotate in the snapshot frame, then move. + var part = new Part(drawing); + part.Rotate(pose.Rotation); + part.Location = new Geometry.Vector(pose.X, pose.Y); + part.UpdateBounds(); + placed.Add(part); } - return sheets; + sheets.Add(new ProposedPlate(group.Sheet.PlateIndex, group.Sheet.Stock, placed) { Quantity = group.Quantity }); } + return sheets; } /// Resolves through @@ -267,6 +277,16 @@ public static class NestPipeline ) { ArgumentNullException.ThrowIfNull(engine); + return CreateJob(request, token); + } + + /// The job the pipeline builds for (before any cutout + /// bundling), and the caller drawing behind each part id. + internal static (NestJob Job, Dictionary Drawings) CreateJob( + NestPipelineRequest request, + CancellationToken token + ) + { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items); ArgumentNullException.ThrowIfNull(request.Stock); diff --git a/OpenNest.Engine/Jobs/Remote/NestSolveTranscript.cs b/OpenNest.Engine/Jobs/Remote/NestSolveTranscript.cs index 58150e27..99d56651 100644 --- a/OpenNest.Engine/Jobs/Remote/NestSolveTranscript.cs +++ b/OpenNest.Engine/Jobs/Remote/NestSolveTranscript.cs @@ -18,7 +18,7 @@ public sealed class NestSolveTranscript { public const int CurrentVersion = 1; - private static readonly JsonSerializerOptions Options = new() + internal static readonly JsonSerializerOptions Options = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, diff --git a/OpenNest.Engine/Jobs/Remote/RecordingNestingEngine.cs b/OpenNest.Engine/Jobs/Remote/RecordingNestingEngine.cs index b99d3e49..117a5e3c 100644 --- a/OpenNest.Engine/Jobs/Remote/RecordingNestingEngine.cs +++ b/OpenNest.Engine/Jobs/Remote/RecordingNestingEngine.cs @@ -1,5 +1,6 @@ using System; using System.Threading; +using OpenNest.Engine.Jobs.Cutouts; namespace OpenNest.Engine.Jobs.Remote; @@ -19,8 +20,20 @@ public sealed class RecordingNestingEngine : INestingEngine public NestSolveTranscript Transcript { get; } = new(); + /// + /// Also receives each solve's own progress, before the pipeline turns plans into sheets: + /// the worker's live reports. A bundled cutout trial's commits count proxies, so it passes + /// only candidates and plans, as the pipeline's own progress does. + /// + public IProgress Progress { get; init; } + public NestJobResult Solve(NestJob job, IProgress progress = null, CancellationToken token = default) { + if (Progress != null) + { + var tap = CutoutPipelinePrepass.HasProxies(job) ? new NestPipeline.PreviewProgress(Progress) : Progress; + progress = progress == null ? tap : new BothProgress(progress, tap); + } var result = inner.Solve(job, progress, token); if (result != null) { @@ -29,4 +42,14 @@ public sealed class RecordingNestingEngine : INestingEngine } return result; } + + private sealed class BothProgress(IProgress first, IProgress second) + : IProgress + { + public void Report(NestJobProgress value) + { + first.Report(value); + second.Report(value); + } + } } diff --git a/OpenNest.Engine/Jobs/Remote/RemoteNestProgress.cs b/OpenNest.Engine/Jobs/Remote/RemoteNestProgress.cs new file mode 100644 index 00000000..809dd5d3 --- /dev/null +++ b/OpenNest.Engine/Jobs/Remote/RemoteNestProgress.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Threading; +using OpenNest.Engine.Jobs.Cutouts; + +namespace OpenNest.Engine.Jobs.Remote; + +/// +/// The nest server worker's latest progress report for a running job: the stage of the solve +/// in progress, without its plan (plans travel as ). Committed +/// counts follow : authoritative only after a commit. +/// +public sealed class RemoteNestProgress +{ + public const int CurrentVersion = 1; + + public int Version { get; set; } = CurrentVersion; + public NestJobStage Stage { get; set; } + public string StockId { get; set; } = ""; + public int PlateIndex { get; set; } + public int CommittedPlates { get; set; } + public int CommittedParts { get; set; } + + public static RemoteNestProgress From(NestJobProgress progress) + { + ArgumentNullException.ThrowIfNull(progress); + return new RemoteNestProgress + { + Stage = progress.Stage, + StockId = progress.StockId ?? "", + PlateIndex = progress.PlateIndex, + CommittedPlates = progress.CommittedPlates, + CommittedParts = progress.CommittedParts, + }; + } + + public NestJobProgress ToProgress() => new(Stage, StockId, PlateIndex, CommittedPlates, CommittedParts); + + public string ToJson() => JsonSerializer.Serialize(this, NestSolveTranscript.Options); + + /// The report, or null when is empty or not one this build reads. + public static RemoteNestProgress FromJson(string json) + { + if (string.IsNullOrWhiteSpace(json)) + return null; + try + { + var progress = JsonSerializer.Deserialize(json, NestSolveTranscript.Options); + return progress?.Version == CurrentVersion ? progress : null; + } + catch (JsonException) + { + return null; + } + } +} + +/// +/// The engine's best whole-job plan so far on the worker (), +/// as raw placements. The desktop draws it with ; like a local +/// plan it is unvalidated and never kept. +/// +public sealed class RemoteNestPlan +{ + public const int CurrentVersion = 1; + + public int Version { get; set; } = CurrentVersion; + public NestSolveTranscript.ResultJson Plan { get; set; } + + public static RemoteNestPlan From(NestJobResult plan) + { + ArgumentNullException.ThrowIfNull(plan); + return new RemoteNestPlan { Plan = NestSolveTranscript.ResultJson.From(plan) }; + } + + public string ToJson() => JsonSerializer.Serialize(this, NestSolveTranscript.Options); + + /// The plan, or null when is not one this build reads. + public static RemoteNestPlan FromJson(string json) + { + if (string.IsNullOrWhiteSpace(json)) + return null; + try + { + var plan = JsonSerializer.Deserialize(json, NestSolveTranscript.Options); + return plan?.Version == CurrentVersion && plan.Plan?.Plates != null ? plan : null; + } + catch (JsonException) + { + return null; + } + } +} + +/// +/// Draws the worker's best plan so far on the desktop, the way a local run's +/// are drawn: the request's job is rebuilt here (the +/// same part ids the worker solved), and parts go on detached drawings built from its geometry, +/// so nothing touches the caller's drawings or quantities. A bundled cutout trial's frame proxies +/// are bundled here too, once, the first time a plan names one. Not thread-safe: use one +/// preview from one thread at a time. +/// +public sealed class RemoteNestPlanPreview +{ + private readonly NestJob job; + private readonly IReadOnlyDictionary callerDrawings; + private readonly Dictionary parts; + private readonly Dictionary drawings = new(StringComparer.Ordinal); + private bool bundled; + + public RemoteNestPlanPreview(NestPipelineRequest request, CancellationToken token = default) + { + (job, var byPart) = NestPipeline.CreateJob(request, token); + callerDrawings = byPart; + parts = job.Parts.ToDictionary(p => p.Id, StringComparer.Ordinal); + } + + /// The plan as sheets, or null when is unreadable or + /// names parts this request does not have. + public IReadOnlyList Sheets(string planJson, CancellationToken token = default) + { + if (RemoteNestPlan.FromJson(planJson)?.Plan is not { } plan) + return null; + if (!Known(plan) && !bundled) + { + bundled = true; + if (CutoutPipelinePrepass.Prepare(job, token)?.EngineJob is { } engineJob) + { + foreach (var part in engineJob.Parts) + parts.TryAdd(part.Id, part); + } + } + if (!Known(plan)) + return null; + try + { + return NestPipeline.PlanSheets(plan.ToResult(job), parts, callerDrawings, drawings, token); + } + catch (FormatException) + { + return null; + } + } + + private bool Known(NestSolveTranscript.ResultJson plan) => + plan.Plates.All(s => s?.Placements != null && s.Placements.All(p => p.PartId != null && parts.ContainsKey(p.PartId))); +} diff --git a/OpenNest.Server.Tests/DrawingLibraryDatabaseTests.cs b/OpenNest.Server.Tests/DrawingLibraryDatabaseTests.cs index 3753c60c..3a454822 100644 --- a/OpenNest.Server.Tests/DrawingLibraryDatabaseTests.cs +++ b/OpenNest.Server.Tests/DrawingLibraryDatabaseTests.cs @@ -23,7 +23,7 @@ public sealed class DrawingLibraryDatabaseTests using (var database = new NestDatabase(factory.DatabasePath, pooling: false)) Assert.Empty(database.QueryDrawings(new DrawingLibraryQuery { IncludeArchived = true }).Items); Assert.Equal(before, NestDigest(factory.DatabasePath)); - Assert.Equal(15L, Scalar(factory.DatabasePath, "PRAGMA user_version")); + Assert.Equal(16L, Scalar(factory.DatabasePath, "PRAGMA user_version")); } using var upgraded = new NestDatabase(factory.DatabasePath, pooling: false); @@ -44,7 +44,7 @@ public sealed class DrawingLibraryDatabaseTests using (var database = new NestDatabase(factory.DatabasePath, pooling: false)) { - Assert.Equal(15L, Scalar(factory.DatabasePath, "PRAGMA user_version")); + Assert.Equal(16L, Scalar(factory.DatabasePath, "PRAGMA user_version")); Assert.Equal(before, NestDigest(factory.DatabasePath)); // Two distinct blobs across four revisions: the bracket's notes edit and the // plate both reuse the bracket's first package. @@ -81,7 +81,7 @@ public sealed class DrawingLibraryDatabaseTests { using var factory = new ServerFactory(); using (new NestDatabase(factory.DatabasePath, pooling: false)) { } - Execute(factory.DatabasePath, "PRAGMA user_version=16"); + Execute(factory.DatabasePath, "PRAGMA user_version=17"); Assert.Throws(() => new NestDatabase(factory.DatabasePath, pooling: false)); } diff --git a/OpenNest.Server.Tests/DrawingSetDatabaseTests.cs b/OpenNest.Server.Tests/DrawingSetDatabaseTests.cs index 6aec604f..14c528ec 100644 --- a/OpenNest.Server.Tests/DrawingSetDatabaseTests.cs +++ b/OpenNest.Server.Tests/DrawingSetDatabaseTests.cs @@ -23,7 +23,7 @@ public sealed class DrawingSetDatabaseTests using (var database = new NestDatabase(factory.DatabasePath, pooling: false)) Assert.Empty(database.QueryDrawingSets(new DrawingSetQuery { IncludeArchived = true }).Items); Assert.Equal(before, Digest(factory.DatabasePath)); - Assert.Equal(15L, Scalar(factory.DatabasePath, "PRAGMA user_version")); + Assert.Equal(16L, Scalar(factory.DatabasePath, "PRAGMA user_version")); } using var upgraded = new NestDatabase(factory.DatabasePath, pooling: false); @@ -48,7 +48,7 @@ public sealed class DrawingSetDatabaseTests Assert.Equal(before, Digest(factory.DatabasePath)); Execute(factory.DatabasePath, "DROP TABLE ix_drawing_set_members_drawing"); using var database = new NestDatabase(factory.DatabasePath, pooling: false); - Assert.Equal(15L, Scalar(factory.DatabasePath, "PRAGMA user_version")); + Assert.Equal(16L, Scalar(factory.DatabasePath, "PRAGMA user_version")); } [Fact] diff --git a/OpenNest.Server.Tests/MaterialListTests.cs b/OpenNest.Server.Tests/MaterialListTests.cs index 637bc44d..90e7336e 100644 --- a/OpenNest.Server.Tests/MaterialListTests.cs +++ b/OpenNest.Server.Tests/MaterialListTests.cs @@ -25,7 +25,7 @@ public sealed class MaterialListTests using var upgraded = new NestDatabase(factory.DatabasePath, pooling: false); - Assert.Equal(15L, Scalar(factory.DatabasePath, "PRAGMA user_version")); + Assert.Equal(16L, Scalar(factory.DatabasePath, "PRAGMA user_version")); Assert.Empty(upgraded.ListMaterials()); Assert.Equal((" Stainless ", "304"), (upgraded.Get(nest)!.Material, upgraded.Get(nest)!.MaterialGrade)); Assert.Equal(drawing.MaterialName, upgraded.GetDrawing(drawing.Id)!.MaterialName); diff --git a/OpenNest.Server.Tests/NestJobEventsTests.cs b/OpenNest.Server.Tests/NestJobEventsTests.cs new file mode 100644 index 00000000..30f7d615 --- /dev/null +++ b/OpenNest.Server.Tests/NestJobEventsTests.cs @@ -0,0 +1,364 @@ +using System.Net; +using System.Threading.Channels; +using Microsoft.Extensions.Logging.Abstractions; +using OpenNest.Api; +using OpenNest.Data; +using OpenNest.Engine; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.Jobs.Remote; +using OpenNest.Geometry; +using OpenNest.Server.Worker; + +namespace OpenNest.Server.Tests; + +/// +/// Live progress for server nesting: the worker's reports, each job's event stream (order, +/// the final event, reconnecting with Last-Event-ID), the desktop's watch with its polling +/// fallback, and how soon a worker sees a cancel request. +/// +public class NestJobEventsTests +{ + private static readonly TimeSpan Wait = TimeSpan.FromSeconds(20); + + private static NestPipelineRequest Request() + { + var program = new OpenNest.CNC.Program(); + program.MoveTo(0, 0); + program.LineTo(10, 0); + program.LineTo(10, 20); + program.LineTo(0, 20); + program.LineTo(0, 0); + var template = new Plate(48, 96) { EdgeSpacing = new Spacing(0.25, 0.25, 0.25, 0.25), PartSpacing = 0.25 }; + return new NestPipelineRequest("Rectangles", + new[] { new NestItem { Drawing = new Drawing("bracket", program), Quantity = 9 } }, + NestStockBuilder.FromTemplate(template, null), + new NestJobOptions(maxPlates: 5)); + } + + private static NestJobSubmission Describe() => new() { Title = "N26-0042", EngineName = "Rectangles", SubmittedBy = "aj@pc" }; + + private static RemoteNestJobs Client(ServerFactory factory, DelegatingHandler? handler = null) + { + var http = handler is null ? factory.CreateClient() : factory.CreateDefaultClient(handler); + return new RemoteNestJobs(http, http.BaseAddress!.ToString()); + } + + /// Reads a stream into a channel, so a test can act between events. + private static (ChannelReader Events, Task Done) Listen(RemoteNestJobs jobs, Guid id, long lastEventId = 0) + { + var channel = Channel.CreateUnbounded(); + var done = Task.Run(async () => + { + try + { + await foreach (var update in jobs.WatchAsync(id, lastEventId)) + await channel.Writer.WriteAsync(update); + channel.Writer.Complete(); + } + catch (Exception ex) + { + channel.Writer.Complete(ex); + } + }); + return (channel.Reader, done); + } + + private static async Task Next(ChannelReader events) + { + using var timeout = new CancellationTokenSource(Wait); + return await events.ReadAsync(timeout.Token); + } + + private static async Task NextJob(ChannelReader events) + { + var update = await Next(events); + Assert.Equal(NestJobEventKind.Job, update.Kind); + return update; + } + + [Fact] + public async Task TheStreamSendsEachChangeInOrderAndEndsAtTheFinalState() + { + using var factory = new ServerFactory(); + var jobs = Client(factory); + var job = await jobs.SubmitAsync(Describe(), new byte[] { 1 }); + var (events, done) = Listen(jobs, job.Id); + + Assert.Equal(NestJobEventKind.Open, (await Next(events)).Kind); + var queued = await NextJob(events); + Assert.Equal(NestJobState.Queued, queued.Job!.State); + + await jobs.ClaimAsync("w1"); + var running = await NextJob(events); + Assert.Equal(NestJobState.Running, running.Job!.State); + + var progress = RemoteNestProgress.From(new NestJobProgress(NestJobStage.PlateCommitted, "s", 0, 1, 9)).ToJson(); + Assert.False((await jobs.ReportProgressAsync(job.Id, "w1", progress))!.CancelRequested); + var reported = await NextJob(events); + Assert.Equal(progress, reported.Job!.Progress); + + Assert.NotNull(await jobs.ReportPlanAsync(job.Id, "w1", "{\"plan\":1}")); + var plan = await Next(events); + Assert.Equal(NestJobEventKind.Plan, plan.Kind); + Assert.Equal("{\"plan\":1}", plan.Plan); + var planned = await NextJob(events); + Assert.Equal(plan.Id, planned.Job!.PlanRevision); + Assert.Equal(plan.Id, planned.Id); + + Assert.True(await jobs.CompleteAsync(job.Id, "w1", "{}")); + var final = await NextJob(events); + Assert.Equal(NestJobState.Succeeded, final.Job!.State); + + // Nothing after the final state: the server ended the stream. + await done.WaitAsync(Wait); + Assert.False(await events.WaitToReadAsync()); + var ids = new[] { queued, running, reported, planned, final }.Select(e => e.Id).ToList(); + Assert.Equal(ids.OrderBy(i => i).Distinct(), ids); + } + + [Fact] + public async Task AReconnectSkipsWhatItAlreadyHas() + { + using var factory = new ServerFactory(); + var jobs = Client(factory); + var job = await jobs.SubmitAsync(Describe(), new byte[] { 1 }); + await jobs.ClaimAsync("w1"); + await jobs.ReportPlanAsync(job.Id, "w1", "{\"plan\":1}"); + var current = (await jobs.GetAsync(job.Id))!; + + // Up to date: only the stream opening, then whatever changes next. + var (events, _) = Listen(jobs, job.Id, current.Revision); + Assert.Equal(NestJobEventKind.Open, (await Next(events)).Kind); + await jobs.ReportProgressAsync(job.Id, "w1", "{\"version\":1}"); + var next = await NextJob(events); + Assert.Equal(current.Revision + 1, next.Id); + + // Behind the plan: the plan again, then the job. + var (behind, _) = Listen(jobs, job.Id, current.PlanRevision - 1); + Assert.Equal(NestJobEventKind.Open, (await Next(behind)).Kind); + Assert.Equal(NestJobEventKind.Plan, (await Next(behind)).Kind); + Assert.Equal(next.Id, (await NextJob(behind)).Id); + + // A finished job sends its final state even to a stream that has it, then ends. + await jobs.CompleteAsync(job.Id, "w1", "{}"); + var finished = (await jobs.GetAsync(job.Id))!; + var (late, lateDone) = Listen(jobs, job.Id, finished.Revision); + Assert.Equal(NestJobEventKind.Open, (await Next(late)).Kind); + Assert.Equal(NestJobState.Succeeded, (await NextJob(late)).Job!.State); + await lateDone.WaitAsync(Wait); + } + + [Fact] + public async Task UnknownJobsHaveNoStream() + { + using var factory = new ServerFactory(); + var jobs = Client(factory); + var events = new List(); + await foreach (var update in jobs.WatchAsync(Guid.NewGuid())) + events.Add(update); + Assert.Equal(NestJobEventKind.Gone, Assert.Single(events).Kind); + Assert.Null(await jobs.GetPlanAsync(Guid.NewGuid())); + } + + [Fact] + public async Task OnlyTheWorkerHoldingAJobReportsOnIt() + { + using var factory = new ServerFactory(); + var jobs = Client(factory); + var job = await jobs.SubmitAsync(Describe(), new byte[] { 1 }); + Assert.Null(await jobs.ReportProgressAsync(job.Id, "w1", "{}")); + await jobs.ClaimAsync("w1"); + Assert.Null(await jobs.ReportPlanAsync(job.Id, "w2", "{}")); + Assert.Null(await jobs.GetPlanAsync(job.Id)); + + await jobs.ReportPlanAsync(job.Id, "w1", "{\"a\":1}"); + Assert.Equal("{\"a\":1}", (await jobs.GetPlanAsync(job.Id))!.Value.Plan); + await jobs.CancelAsync(job.Id); + Assert.True((await jobs.ReportProgressAsync(job.Id, "w1", "{}"))!.CancelRequested); + + // Giving the job back starts the next attempt without the last one's plan or stage. + await jobs.ReleaseAsync(job.Id, "w1"); + var back = (await jobs.GetAsync(job.Id))!; + Assert.Equal(NestJobState.Cancelled, back.State); + Assert.Null(await jobs.GetPlanAsync(job.Id)); + Assert.Equal("", back.Progress); + } + + /// Lets a test break the event stream or hide it, as a proxy or an older server would. + private sealed class StreamTamper : DelegatingHandler + { + public bool Hide { get; set; } + + /// The first this many streams drop right after their first job event. + public int Cuts { get; set; } + public List LastEventIds { get; } = new(); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.RequestUri!.AbsolutePath.EndsWith("/events")) + { + LastEventIds.Add(request.Headers.TryGetValues("Last-Event-ID", out var ids) ? ids.Single() : null); + if (Hide) + return new HttpResponseMessage(HttpStatusCode.NotFound); + var response = await base.SendAsync(request, cancellationToken); + if (Cuts-- > 0) + response.Content = new StreamContent(new CutStream(await response.Content.ReadAsStreamAsync(cancellationToken))); + return response; + } + return await base.SendAsync(request, cancellationToken); + } + } + + private sealed class CutStream(Stream inner) : Stream + { + private readonly System.Text.StringBuilder seen = new(); + private int read; + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => read; set => throw new NotSupportedException(); } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count).GetAwaiter().GetResult(); + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var text = seen.ToString(); + var job = text.IndexOf("event: job", StringComparison.Ordinal); + if (job >= 0 && text.IndexOf("\n\n", job, StringComparison.Ordinal) >= 0) + throw new IOException("Connection reset."); + // A byte at a time, so nothing past the first job event is delivered. + var n = await inner.ReadAsync(buffer[..System.Math.Min(buffer.Length, 1)], cancellationToken); + seen.Append(System.Text.Encoding.UTF8.GetString(buffer.Span[..n])); + read += n; + return n; + } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + protected override void Dispose(bool disposing) + { + if (disposing) + inner.Dispose(); + base.Dispose(disposing); + } + } + + private sealed class Sink : IProgress + { + public readonly List Items = new(); + + public void Report(T value) + { + lock (Items) + Items.Add(value); + } + } + + private static async Task WatchWhileTheWorkerRuns(ServerFactory factory, StreamTamper tamper, + Sink seen, Sink plans) + { + var desktop = Client(factory, tamper); + var job = await desktop.SubmitAsync(Describe(), NestJobPackage.Write(Request())); + var watch = new NestJobWatch(desktop) { PollInterval = TimeSpan.FromMilliseconds(50), Job = seen, Plan = plans }; + var watching = watch.RunAsync(job); + + var worker = Client(factory); + await worker.ClaimAsync("w1"); + await worker.ReportPlanAsync(job.Id, "w1", "{\"plan\":1}"); + await worker.ReportProgressAsync(job.Id, "w1", "{\"version\":1}"); + await worker.CompleteAsync(job.Id, "w1", "{}"); + return await watching.WaitAsync(Wait); + } + + [Fact] + public async Task TheWatchReconnectsADroppedStreamFromItsLastEvent() + { + using var factory = new ServerFactory(); + // The first two streams drop after their first job event. + var tamper = new StreamTamper { Cuts = 2 }; + var seen = new Sink(); + var plans = new Sink(); + + var final = await WatchWhileTheWorkerRuns(factory, tamper, seen, plans); + + Assert.Equal(NestJobState.Succeeded, final.State); + Assert.True(tamper.LastEventIds.Count >= 2, "The stream should have been opened again."); + Assert.Null(tamper.LastEventIds[0]); + Assert.Contains(tamper.LastEventIds.Skip(1), id => id is not null); + Assert.Equal(NestJobState.Succeeded, seen.Items[^1].State); + } + + [Fact] + public async Task TheWatchPollsAServerWithoutTheStream() + { + using var factory = new ServerFactory(); + var tamper = new StreamTamper { Hide = true }; + var seen = new Sink(); + var plans = new Sink(); + + var final = await WatchWhileTheWorkerRuns(factory, tamper, seen, plans); + + Assert.Equal(NestJobState.Succeeded, final.State); + Assert.Single(tamper.LastEventIds); + Assert.Equal(NestJobState.Succeeded, seen.Items[^1].State); + } + + [Fact] + public async Task AnEnginePlanReachesTheDesktopAsTheSheetsItDraws() + { + using var factory = new ServerFactory(); + var desktop = Client(factory); + var request = Request(); + var job = await desktop.SubmitAsync(Describe(), NestJobPackage.Write(request)); + var plans = new Sink(); + var watching = new NestJobWatch(desktop) { Plan = plans }.RunAsync(job); + + // The engine's plans, as the worker's recording engine passes them on. + var reporter = new NestJobReporter(); + var engine = new RecordingNestingEngine(NestingEngineRegistry.Create(request.EngineName)) { Progress = reporter }; + var worker = Client(factory); + await worker.ClaimAsync("w1"); + using var stop = new CancellationTokenSource(); + var reporting = reporter.RunAsync(worker, job.Id, "w1", TimeSpan.FromMilliseconds(20), NullLogger.Instance, stop.Token); + var local = NestPipeline.Run(engine, request.EngineName, request); + var placed = local.Plates.Sum(p => p.Quantity * p.Parts.Count); + + // The engine's last plan is its answer: drawn here, it holds every part of the result. + var preview = new RemoteNestPlanPreview(request); + using (var timeout = new CancellationTokenSource(Wait)) + { + while (!plans.Items.ToList().Any(plan => preview.Sheets(plan)?.Sum(s => s.Quantity * s.Parts.Count) == placed)) + await Task.Delay(20, timeout.Token); + } + stop.Cancel(); + Assert.Equal(NestJobWorker.StopReason.None, await reporting); + await worker.CompleteAsync(job.Id, "w1", engine.Transcript.ToJson()); + Assert.Equal(NestJobState.Succeeded, (await watching.WaitAsync(Wait)).State); + } + + [Fact] + public async Task AWorkerSeesACancelRequestWithinOneReportInterval() + { + using var factory = new ServerFactory(); + var jobs = Client(factory); + var job = await jobs.SubmitAsync(Describe(), new byte[] { 1 }); + await jobs.ClaimAsync("w1"); + var reporter = new NestJobReporter(); + using var stop = new CancellationTokenSource(Wait); + var interval = TimeSpan.FromMilliseconds(100); + var reporting = reporter.RunAsync(jobs, job.Id, "w1", interval, NullLogger.Instance, stop.Token); + + reporter.Report(new NestJobProgress(NestJobStage.EvaluatingCandidate, "s", 0, 0, 0)); + using (var timeout = new CancellationTokenSource(Wait)) + { + while (!(await jobs.GetAsync(job.Id))!.Progress.Contains("evaluatingCandidate")) + await Task.Delay(50, timeout.Token); + } + Assert.False(reporting.IsCompleted); + + var asked = DateTime.UtcNow; + await jobs.CancelAsync(job.Id); + Assert.Equal(NestJobWorker.StopReason.CancelRequested, await reporting.WaitAsync(Wait)); + Assert.True(DateTime.UtcNow - asked < TimeSpan.FromSeconds(5)); + } +} diff --git a/OpenNest.Server.Tests/NestMaterialGradeTests.cs b/OpenNest.Server.Tests/NestMaterialGradeTests.cs index b441f370..14ade467 100644 --- a/OpenNest.Server.Tests/NestMaterialGradeTests.cs +++ b/OpenNest.Server.Tests/NestMaterialGradeTests.cs @@ -75,7 +75,7 @@ public sealed class NestMaterialGradeTests Assert.Equal("Stainless", record.Material); Assert.Equal("", record.MaterialGrade); Assert.Equal("", Assert.Single(upgraded.History(id, 0, 10)!.Items).MaterialGrade); - Assert.Equal(15L, Scalar(factory.DatabasePath, "PRAGMA user_version")); + Assert.Equal(16L, Scalar(factory.DatabasePath, "PRAGMA user_version")); } private static NestRecord Record(string name, string material, string grade) => new() diff --git a/OpenNest.Server.Tests/NestStockCodesTests.cs b/OpenNest.Server.Tests/NestStockCodesTests.cs index aa80b641..1e0a031f 100644 --- a/OpenNest.Server.Tests/NestStockCodesTests.cs +++ b/OpenNest.Server.Tests/NestStockCodesTests.cs @@ -119,7 +119,7 @@ public sealed class NestStockCodesTests database.SetDeleted(deleted, false, record.Revision); Assert.Equal(["SHEET-1", "SHEET-2"], database.StockCodesInUse(null).Select(u => u.ItemCode)); } - Assert.Equal(15L, Scalar(factory.DatabasePath, "PRAGMA user_version")); + Assert.Equal(16L, Scalar(factory.DatabasePath, "PRAGMA user_version")); } private static Nest Nest(string name, NestStatus status, params string[][] plateCodes) diff --git a/OpenNest.Server.Tests/NestUnitsTests.cs b/OpenNest.Server.Tests/NestUnitsTests.cs index 5c057aec..ac9d7829 100644 --- a/OpenNest.Server.Tests/NestUnitsTests.cs +++ b/OpenNest.Server.Tests/NestUnitsTests.cs @@ -77,7 +77,7 @@ public sealed class NestUnitsTests Assert.Equal([Units.Millimeters, Units.Millimeters], upgraded.History(metric, 0, 10)!.Items.Select(r => r.Units)); Assert.Equal(Units.Inches, upgraded.Get(inch)!.Units); Assert.Equal(Units.Inches, upgraded.Get(unreadable)!.Units); - Assert.Equal(15L, Scalar(factory.DatabasePath, "PRAGMA user_version")); + Assert.Equal(16L, Scalar(factory.DatabasePath, "PRAGMA user_version")); } private static NestRecord Record(string name, Units units) => new() diff --git a/OpenNest.Server.Tests/SetReleaseDrawingTests.cs b/OpenNest.Server.Tests/SetReleaseDrawingTests.cs index 09ce9fa8..3b58ca2b 100644 --- a/OpenNest.Server.Tests/SetReleaseDrawingTests.cs +++ b/OpenNest.Server.Tests/SetReleaseDrawingTests.cs @@ -152,7 +152,7 @@ public sealed class SetReleaseDrawingTests using var upgraded = new NestDatabase(factory.DatabasePath, pooling: false); - Assert.Equal(15L, Scalar(factory.DatabasePath, "PRAGMA user_version")); + Assert.Equal(16L, Scalar(factory.DatabasePath, "PRAGMA user_version")); var kept = upgraded.GetRelease(releaseId)!; Assert.Empty(kept.Drawings); Assert.Equal(((Guid?)kit.Id, drawing, 2), (kept.Nests[0].Items.Single().SetId, kept.Nests[0].Items.Single().DrawingId, kept.Nests[0].Items.Single().Quantity)); diff --git a/OpenNest.Server.Tests/SetReleaseTests.cs b/OpenNest.Server.Tests/SetReleaseTests.cs index ea9c5e1a..de73ff70 100644 --- a/OpenNest.Server.Tests/SetReleaseTests.cs +++ b/OpenNest.Server.Tests/SetReleaseTests.cs @@ -295,7 +295,7 @@ public sealed class SetReleaseTests using var upgraded = new NestDatabase(factory.DatabasePath, pooling: false); - Assert.Equal(15L, Scalar(factory.DatabasePath, "PRAGMA user_version")); + Assert.Equal(16L, Scalar(factory.DatabasePath, "PRAGMA user_version")); Assert.Equal(0L, Scalar(factory.DatabasePath, "SELECT COUNT(*) FROM sqlite_master WHERE name LIKE 'set_release%' OR name LIKE 'ix_set_release%'")); var release = upgraded.GetRelease(releaseId)!; Assert.Equal(("Legacy notes", "Legacy operator", false), (release.Notes, release.ReleasedBy, release.IsUndone)); diff --git a/OpenNest.Server.Tests/SharedSettingsTests.cs b/OpenNest.Server.Tests/SharedSettingsTests.cs index 8d606a30..2170342c 100644 --- a/OpenNest.Server.Tests/SharedSettingsTests.cs +++ b/OpenNest.Server.Tests/SharedSettingsTests.cs @@ -68,7 +68,7 @@ public sealed class SharedSettingsTests using var upgraded = new NestDatabase(factory.DatabasePath, pooling: false); - Assert.Equal(15L, Scalar(factory.DatabasePath, "PRAGMA user_version")); + Assert.Equal(16L, Scalar(factory.DatabasePath, "PRAGMA user_version")); Assert.Empty(upgraded.ListSharedSettings()); } diff --git a/OpenNest.Server.Worker/NestJobReporter.cs b/OpenNest.Server.Worker/NestJobReporter.cs new file mode 100644 index 00000000..4ef4c50f --- /dev/null +++ b/OpenNest.Server.Worker/NestJobReporter.cs @@ -0,0 +1,93 @@ +using OpenNest.Data; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.Jobs.Remote; + +namespace OpenNest.Server.Worker; + +/// +/// Collects a running job's engine progress and stores it on the nest server at most once per +/// interval: only the latest stage and the latest plan are sent, so a chatty engine costs one +/// small write and one plan write per interval at most. Each round, a report (or, with nothing +/// new to send, a read of the job) also tells the worker promptly that someone asked to stop. +/// +public sealed class NestJobReporter : IProgress +{ + private readonly object _sync = new(); + private RemoteNestProgress? _stage; + private RemoteNestPlan? _plan; + + public void Report(NestJobProgress value) + { + if (value is null) + return; + // Copied here, on the engine's thread, so later changes to its objects cannot leak in; + // serialized later, off that thread. + if (value.Stage == NestJobStage.PlanImproved) + { + if (value.Plan is null) + return; + var plan = RemoteNestPlan.From(value.Plan); + lock (_sync) + _plan = plan; + return; + } + var stage = RemoteNestProgress.From(value); + lock (_sync) + _stage = stage; + } + + /// + /// Sends reports every until is + /// cancelled. Returns why the job must stop (a cancel request, or the worker lost it), + /// or when cancelled first. + /// + public async Task RunAsync(RemoteNestJobs jobs, Guid id, string workerId, TimeSpan interval, + ILogger logger, CancellationToken token) + { + while (true) + { + try { await Task.Delay(interval, token); } + catch (OperationCanceledException) { return NestJobWorker.StopReason.None; } + + RemoteNestProgress? stage; + RemoteNestPlan? plan; + lock (_sync) + { + (stage, plan) = (_stage, _plan); + (_stage, _plan) = (null, null); + } + try + { + var beats = new List(); + if (plan is not null) + beats.Add(await jobs.ReportPlanAsync(id, workerId, plan.ToJson(), token)); + if (stage is not null) + beats.Add(await jobs.ReportProgressAsync(id, workerId, stage.ToJson(), token)); + if (beats.Count == 0) + { + // Nothing new: read the job instead, which costs the server no write. + var job = await jobs.GetAsync(id, token); + beats.Add(job is { State: NestJobState.Running } ? new NestJobHeartbeat { CancelRequested = job.CancelRequested } : null); + } + if (beats.Any(b => b is null)) + return NestJobWorker.StopReason.LeaseLost; + if (beats.Any(b => b!.CancelRequested)) + return NestJobWorker.StopReason.CancelRequested; + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + return NestJobWorker.StopReason.None; + } + catch (Exception ex) when (ex is IOException or HttpRequestException or TaskCanceledException) + { + // Keep solving; the next round sends whatever is latest by then. + lock (_sync) + { + _stage ??= stage; + _plan ??= plan; + } + logger.LogWarning("Progress for nest job {Id} not stored: {Message}", id, ex.Message); + } + } + } +} diff --git a/OpenNest.Server.Worker/NestJobWorker.cs b/OpenNest.Server.Worker/NestJobWorker.cs index c86ba6e2..c40d31f0 100644 --- a/OpenNest.Server.Worker/NestJobWorker.cs +++ b/OpenNest.Server.Worker/NestJobWorker.cs @@ -9,19 +9,23 @@ namespace OpenNest.Server.Worker; /// Solves the nest server's queued jobs one at a time. Each job is read from its package and /// run through with the named built-in engine wrapped in a /// , with no time limit; the recorded engine answers are -/// the result the desktop replays. A heartbeat keeps the job's lease and carries cancel requests. +/// the result the desktop replays. A heartbeat keeps the job's lease; the engine's progress and +/// best plan so far are stored on the server as it runs (), and a +/// cancel request is seen within one report interval. /// public sealed class NestJobWorker { private readonly RemoteNestJobs _jobs; private readonly ILogger _logger; private readonly TimeSpan _heartbeat; + private readonly TimeSpan _reportInterval; - public NestJobWorker(RemoteNestJobs jobs, ILogger logger, TimeSpan? heartbeat = null) + public NestJobWorker(RemoteNestJobs jobs, ILogger logger, TimeSpan? heartbeat = null, TimeSpan? reportInterval = null) { _jobs = jobs; _logger = logger; _heartbeat = heartbeat ?? NestJobRules.HeartbeatInterval; + _reportInterval = reportInterval ?? NestJobRules.ProgressInterval; } public string WorkerId { get; } = $"{Environment.MachineName}-{Guid.NewGuid():N}"; @@ -41,7 +45,15 @@ public sealed class NestJobWorker using var solve = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); var stop = StopReason.None; using var beating = new CancellationTokenSource(); + void Stop(StopReason reason) + { + if (stop == StopReason.None) + stop = reason; + solve.Cancel(); + } var heartbeat = HeartbeatAsync(job.Id, solve, reason => stop = reason, beating.Token); + var reporter = new NestJobReporter(); + var reporting = ReportAsync(job.Id, reporter, Stop, beating.Token); try { NestPipelineRequest request; @@ -61,7 +73,7 @@ public sealed class NestJobWorker return true; } - var recorder = new RecordingNestingEngine(NestingEngineRegistry.Create(request.EngineName)); + var recorder = new RecordingNestingEngine(NestingEngineRegistry.Create(request.EngineName)) { Progress = reporter }; await Task.Factory.StartNew(() => NestPipeline.Run(recorder, request.EngineName, request, progress: null, solve.Token), solve.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); if (await _jobs.CompleteAsync(job.Id, WorkerId, recorder.Transcript.ToJson(), CancellationToken.None)) @@ -96,10 +108,18 @@ public sealed class NestJobWorker { beating.Cancel(); await heartbeat; + await reporting; } return true; } + private async Task ReportAsync(Guid id, NestJobReporter reporter, Action stopped, CancellationToken token) + { + var reason = await reporter.RunAsync(_jobs, id, WorkerId, _reportInterval, _logger, token); + if (reason != StopReason.None) + stopped(reason); + } + private async Task HeartbeatAsync(Guid id, CancellationTokenSource solve, Action stopped, CancellationToken token) { while (!token.IsCancellationRequested) @@ -141,7 +161,7 @@ public sealed class NestJobWorker } } - private enum StopReason + public enum StopReason { None, CancelRequested, diff --git a/OpenNest.Server/NestDatabase.Jobs.cs b/OpenNest.Server/NestDatabase.Jobs.cs index 8f992f15..dae4dd1e 100644 --- a/OpenNest.Server/NestDatabase.Jobs.cs +++ b/OpenNest.Server/NestDatabase.Jobs.cs @@ -37,8 +37,46 @@ public sealed partial class NestDatabase PRAGMA user_version=15; """; + // v16: live progress. Revision counts the changes a watcher shows; progress and plan are + // the worker's latest reports, opaque here like packages and results. Columns already + // present (a database set back to an older version) are kept. + private static void AddJobProgress(SqliteCommand command) + { + foreach (var (name, definition) in new[] + { + ("revision", "INTEGER NOT NULL DEFAULT 1"), + ("planRevision", "INTEGER NOT NULL DEFAULT 0"), + ("progress", "TEXT NOT NULL DEFAULT ''"), + ("plan", "TEXT"), + }) + { + command.CommandText = $"SELECT COUNT(*) FROM pragma_table_info('nest_jobs') WHERE name='{name}'"; + if ((long)command.ExecuteScalar()! == 0) + { + command.CommandText = $"ALTER TABLE nest_jobs ADD COLUMN {name} {definition}"; + command.ExecuteNonQuery(); + } + } + command.CommandText = "PRAGMA user_version=16"; + command.ExecuteNonQuery(); + } + + // Every write that ends or restarts an attempt drops its progress and plan. + private const string ClearProgress = "progress='', plan=NULL, planRevision=0"; + + private TaskCompletionSource _jobsChanged = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// + /// Completes at the next change to any job in this process (event streams wait on it). Read + /// it before reading the job, so a change between the two is not missed. + /// + public Task JobsChanged => Volatile.Read(ref _jobsChanged).Task; + + private void PulseJobs() => + Interlocked.Exchange(ref _jobsChanged, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).TrySetResult(); + private const string JobColumns = - "id, title, engineName, submittedBy, state, cancelRequested, submittedAt, startedAt, finishedAt, attempts, error, packageSize, seq"; + "id, title, engineName, submittedBy, state, cancelRequested, submittedAt, startedAt, finishedAt, attempts, error, packageSize, seq, revision, planRevision, progress"; public NestJobRecord InsertJob(Guid id, NestJobSubmission submission, byte[] package, DateTimeOffset now) { @@ -59,6 +97,7 @@ public sealed partial class NestDatabase command.Parameters.AddWithValue("$size", package.LongLength); command.Parameters.AddWithValue("$package", package); command.ExecuteNonQuery(); + PulseJobs(); return GetJob(id)!; } } @@ -123,12 +162,15 @@ public sealed partial class NestDatabase state = CASE state WHEN 'Queued' THEN 'Cancelled' ELSE state END, finishedAt = CASE state WHEN 'Queued' THEN $now ELSE finishedAt END, package = CASE state WHEN 'Queued' THEN zeroblob(0) ELSE package END, - cancelRequested = CASE state WHEN 'Running' THEN 1 ELSE cancelRequested END - WHERE id=$id + cancelRequested = CASE state WHEN 'Running' THEN 1 ELSE cancelRequested END, + progress = CASE state WHEN 'Queued' THEN '' ELSE progress END, + revision = revision + 1 + WHERE id=$id AND (state='Queued' OR (state='Running' AND cancelRequested=0)) """; command.Parameters.AddWithValue("$id", id.ToString()); command.Parameters.AddWithValue("$now", Stamp(now)); - command.ExecuteNonQuery(); + if (command.ExecuteNonQuery() > 0) + PulseJobs(); return GetJob(id); } } @@ -144,7 +186,8 @@ public sealed partial class NestDatabase lock (_sync) { using var transaction = _connection.BeginTransaction(); - SettleJobLeases(transaction, now); + if (SettleJobLeases(transaction, now)) + PulseJobs(); using var running = _connection.CreateCommand(); running.Transaction = transaction; @@ -168,7 +211,7 @@ public sealed partial class NestDatabase claim.Transaction = transaction; claim.CommandText = """ UPDATE nest_jobs SET state='Running', workerId=$worker, leaseUntil=$lease, - startedAt=$now, attempts=attempts+1 + startedAt=$now, attempts=attempts+1, revision=revision+1 WHERE id=$id """; claim.Parameters.AddWithValue("$id", id); @@ -177,6 +220,7 @@ public sealed partial class NestDatabase claim.Parameters.AddWithValue("$now", Stamp(now)); claim.ExecuteNonQuery(); transaction.Commit(); + PulseJobs(); return GetJob(Guid.Parse(id)); } } @@ -199,6 +243,58 @@ public sealed partial class NestDatabase } } + /// + /// Stores the worker's latest progress report and renews the lease, like a heartbeat. Null + /// when no longer holds the job. + /// + public NestJobHeartbeat? ReportJobProgress(Guid id, string workerId, string progress, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(progress); + return Report(id, workerId, now, "progress=$value, revision=revision+1", progress); + } + + /// Stores the best plan so far, as does a report. + public NestJobHeartbeat? ReportJobPlan(Guid id, string workerId, string plan, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(plan); + // Right-hand sides read the old row, so planRevision is the new revision. + return Report(id, workerId, now, "plan=$value, planRevision=revision+1, revision=revision+1", plan); + } + + private NestJobHeartbeat? Report(Guid id, string workerId, DateTimeOffset now, string set, string value) + { + lock (_sync) + { + using var command = _connection.CreateCommand(); + command.CommandText = $""" + UPDATE nest_jobs SET {set}, leaseUntil=$lease + WHERE id=$id AND state='Running' AND workerId=$worker + RETURNING cancelRequested + """; + command.Parameters.AddWithValue("$id", id.ToString()); + command.Parameters.AddWithValue("$worker", workerId); + command.Parameters.AddWithValue("$lease", Stamp(now + NestJobRules.Lease)); + command.Parameters.AddWithValue("$value", value); + if (command.ExecuteScalar() is not long cancel) + return null; + PulseJobs(); + return new NestJobHeartbeat { CancelRequested = cancel != 0 }; + } + } + + /// A running job's best plan so far and the revision it was stored at; null when it has none. + public (string Plan, long Revision)? GetJobPlan(Guid id) + { + lock (_sync) + { + using var command = _connection.CreateCommand(); + command.CommandText = "SELECT plan, planRevision FROM nest_jobs WHERE id=$id AND plan IS NOT NULL"; + command.Parameters.AddWithValue("$id", id.ToString()); + using var reader = command.ExecuteReader(); + return reader.Read() ? (reader.GetString(0), reader.GetInt64(1)) : null; + } + } + /// /// Stores the worker's result. A job someone cancelled meanwhile ends Cancelled and the /// result is dropped. False when no longer holds the job. @@ -229,20 +325,20 @@ public sealed partial class NestDatabase lock (_sync) { using var command = _connection.CreateCommand(); - command.CommandText = """ + command.CommandText = $""" UPDATE nest_jobs SET state = CASE cancelRequested WHEN 1 THEN 'Cancelled' ELSE 'Queued' END, finishedAt = CASE cancelRequested WHEN 1 THEN $now ELSE NULL END, package = CASE cancelRequested WHEN 1 THEN zeroblob(0) ELSE package END, startedAt = CASE cancelRequested WHEN 1 THEN startedAt ELSE NULL END, attempts = CASE cancelRequested WHEN 1 THEN attempts ELSE MAX(attempts - 1, 0) END, - workerId = NULL, leaseUntil = NULL + workerId = NULL, leaseUntil = NULL, revision = revision + 1, {ClearProgress} WHERE id=$id AND state='Running' AND workerId=$worker """; command.Parameters.AddWithValue("$id", id.ToString()); command.Parameters.AddWithValue("$worker", workerId); command.Parameters.AddWithValue("$now", Stamp(now)); - return command.ExecuteNonQuery() == 1; + return Changed(command.ExecuteNonQuery() == 1); } } @@ -252,7 +348,8 @@ public sealed partial class NestDatabase { using var command = _connection.CreateCommand(); command.CommandText = $""" - UPDATE nest_jobs SET {set}, finishedAt=$now, workerId=NULL, leaseUntil=NULL, package=zeroblob(0) + UPDATE nest_jobs SET {set}, finishedAt=$now, workerId=NULL, leaseUntil=NULL, package=zeroblob(0), + plan=NULL, revision=revision+1 WHERE id=$id AND state='Running' AND workerId=$worker """; command.Parameters.AddWithValue("$id", id.ToString()); @@ -260,17 +357,24 @@ public sealed partial class NestDatabase command.Parameters.AddWithValue("$now", Stamp(now)); foreach (var (name, value) in values) command.Parameters.AddWithValue(name, value); - return command.ExecuteNonQuery() == 1; + return Changed(command.ExecuteNonQuery() == 1); } } + private bool Changed(bool changed) + { + if (changed) + PulseJobs(); + return changed; + } + // A lapsed lease means the worker stopped: a cancel request ends the job, otherwise it goes // back to the queue until it has used its attempts. - private void SettleJobLeases(SqliteTransaction transaction, DateTimeOffset now) + private bool SettleJobLeases(SqliteTransaction transaction, DateTimeOffset now) { using var command = _connection.CreateCommand(); command.Transaction = transaction; - command.CommandText = """ + command.CommandText = $""" UPDATE nest_jobs SET state = CASE WHEN cancelRequested=1 THEN 'Cancelled' WHEN attempts >= $max THEN 'Failed' ELSE 'Queued' END, @@ -280,14 +384,14 @@ public sealed partial class NestDatabase finishedAt = CASE WHEN cancelRequested=1 OR attempts >= $max THEN $now ELSE NULL END, package = CASE WHEN cancelRequested=1 OR attempts >= $max THEN zeroblob(0) ELSE package END, startedAt = CASE WHEN cancelRequested=1 OR attempts >= $max THEN startedAt ELSE NULL END, - workerId = NULL, leaseUntil = NULL + workerId = NULL, leaseUntil = NULL, revision = revision + 1, {ClearProgress} WHERE state='Running' AND leaseUntil < $now; DELETE FROM nest_jobs WHERE finishedAt IS NOT NULL AND finishedAt < $expired; """; command.Parameters.AddWithValue("$max", NestJobRules.MaxAttempts); command.Parameters.AddWithValue("$now", Stamp(now)); command.Parameters.AddWithValue("$expired", Stamp(now - NestJobRules.Retention)); - command.ExecuteNonQuery(); + return command.ExecuteNonQuery() > 0; } private static NestJobRecord ReadJob(SqliteDataReader reader) => new() @@ -304,6 +408,9 @@ public sealed partial class NestDatabase Attempts = reader.GetInt32(9), Error = reader.GetString(10), PackageSize = reader.GetInt64(11), + Revision = reader.GetInt64(13), + PlanRevision = reader.GetInt64(14), + Progress = reader.GetString(15), }; private static string Truncate(string? text) diff --git a/OpenNest.Server/NestDatabase.cs b/OpenNest.Server/NestDatabase.cs index 81a1c542..af02d6c5 100644 --- a/OpenNest.Server/NestDatabase.cs +++ b/OpenNest.Server/NestDatabase.cs @@ -344,7 +344,7 @@ public sealed partial class NestDatabase : IDisposable command.Transaction = transaction; command.CommandText = "PRAGMA user_version"; var version = (long)command.ExecuteScalar()!; - if (version > 15) throw new InvalidOperationException("Database schema is newer than this server."); + if (version > 16) throw new InvalidOperationException("Database schema is newer than this server."); if (version == 0) { command.CommandText = """ @@ -445,6 +445,8 @@ public sealed partial class NestDatabase : IDisposable command.CommandText = NestJobSchema; command.ExecuteNonQuery(); } + if (version < 16) + AddJobProgress(command); transaction.Commit(); } } diff --git a/OpenNest.Server/NestJobRoutes.cs b/OpenNest.Server/NestJobRoutes.cs index 1c533740..24e8a1ed 100644 --- a/OpenNest.Server/NestJobRoutes.cs +++ b/OpenNest.Server/NestJobRoutes.cs @@ -1,6 +1,8 @@ +using System.Globalization; using System.Text; using System.Text.Json; using Microsoft.AspNetCore.Http.Features; +using Microsoft.Extensions.Options; using OpenNest.Data; namespace OpenNest.Server; @@ -9,13 +11,17 @@ namespace OpenNest.Server; /// /api/nest-jobs: the server nesting queue. Desktops submit a package, poll its state, /// read the result and cancel; the worker (OpenNest.Server.Worker) claims a job, reads /// its package, heartbeats and reports. The server never opens a package or result: the worker -/// solves the job and the desktop validates the result against its own drawings. +/// solves the job and the desktop validates the result against its own drawings. Progress +/// and plans the worker stores reach desktops through each job's event stream. /// See docs/server-nesting.md. /// internal static class NestJobRoutes { private static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web); + /// How often an idle event stream sends a keep-alive comment; tests shorten it. + internal static TimeSpan KeepAlive { get; set; } = NestJobRules.StreamKeepAlive; + public static void MapNestJobs(this IEndpointRouteBuilder app) { app.MapPost("/api/nest-jobs", async (HttpContext http, NestDatabase db, TimeProvider clock) => @@ -68,6 +74,18 @@ internal static class NestJobRoutes : Results.NotFound(); }); + app.MapGet("/api/nest-jobs/{id:guid}/plan", (Guid id, HttpResponse response, NestDatabase db) => + { + if (db.GetJobPlan(id) is { } plan) + { + response.Headers[RemoteNestJobs.PlanRevisionHeader] = plan.Revision.ToString(CultureInfo.InvariantCulture); + return Results.Text(plan.Plan, "application/json", Encoding.UTF8); + } + return db.GetJob(id) is null ? Results.NotFound() : Results.NoContent(); + }); + + app.MapGet("/api/nest-jobs/{id:guid}/events", StreamEvents); + app.MapPost("/api/nest-jobs/{id:guid}/cancel", (Guid id, NestDatabase db, TimeProvider clock) => db.CancelJob(id, clock.GetUtcNow()) is { } job ? Results.Ok(job) : Results.NotFound()); @@ -97,25 +115,36 @@ internal static class NestJobRoutes { if (string.IsNullOrWhiteSpace(workerId)) return Results.BadRequest("workerId is required."); - if (http.Features.Get() is { IsReadOnly: false } limit) - limit.MaxRequestBodySize = NestJobRules.MaxResultBytes + 1; - if (!http.Request.HasJsonContentType()) - return Results.BadRequest("Expected an application/json result."); - using var body = new MemoryStream(); - var chunk = new byte[81920]; - int read; - while ((read = await http.Request.Body.ReadAsync(chunk, http.RequestAborted)) > 0) - { - if (body.Length + read > NestJobRules.MaxResultBytes) - return Results.BadRequest("The nest result is too large."); - body.Write(chunk, 0, read); - } - var result = Encoding.UTF8.GetString(body.GetBuffer(), 0, (int)body.Length); - return db.CompleteJob(id, workerId, result, clock.GetUtcNow()) + var (result, error) = await ReadJsonBody(http, NestJobRules.MaxResultBytes, "nest result"); + if (error is not null) return error; + return db.CompleteJob(id, workerId, result!, clock.GetUtcNow()) ? Results.Ok(db.GetJob(id)) : Results.Conflict("This worker no longer holds the job."); }); + // Progress and plans renew the lease like a heartbeat and answer as one. + app.MapPut("/api/nest-jobs/{id:guid}/progress", async (Guid id, string? workerId, HttpContext http, NestDatabase db, TimeProvider clock) => + { + if (string.IsNullOrWhiteSpace(workerId)) + return Results.BadRequest("workerId is required."); + var (progress, error) = await ReadJsonBody(http, NestJobRules.MaxProgressBytes, "progress report"); + if (error is not null) return error; + return db.ReportJobProgress(id, workerId, progress!, clock.GetUtcNow()) is { } beat + ? Results.Ok(beat) + : Results.Conflict("This worker no longer holds the job."); + }); + + app.MapPut("/api/nest-jobs/{id:guid}/plan", async (Guid id, string? workerId, HttpContext http, NestDatabase db, TimeProvider clock) => + { + if (string.IsNullOrWhiteSpace(workerId)) + return Results.BadRequest("workerId is required."); + var (plan, error) = await ReadJsonBody(http, NestJobRules.MaxPlanBytes, "nest plan"); + if (error is not null) return error; + return db.ReportJobPlan(id, workerId, plan!, clock.GetUtcNow()) is { } beat + ? Results.Ok(beat) + : Results.Conflict("This worker no longer holds the job."); + }); + app.MapPost("/api/nest-jobs/{id:guid}/fail", async (Guid id, HttpRequest request, NestDatabase db, TimeProvider clock) => { var (message, error) = await ReadWorkerMessage(request); @@ -144,6 +173,102 @@ internal static class NestJobRoutes }); } + /// + /// text/event-stream of one job until it is final. Each change sends event: job + /// (the record, id its revision), preceded by event: plan (id the plan's + /// revision) when a newer best plan was stored. A reconnect's Last-Event-ID skips what + /// it already has; a final job is always sent, then the stream ends. event: gone ends + /// it when the job is removed. Idle streams send a comment every . + /// + private static async Task StreamEvents(Guid id, HttpContext http, NestDatabase db, IOptions json) + { + var response = http.Response; + if (db.GetJob(id) is null) + { + response.StatusCode = StatusCodes.Status404NotFound; + return; + } + var seen = long.TryParse(http.Request.Headers["Last-Event-ID"].FirstOrDefault(), NumberStyles.None, + CultureInfo.InvariantCulture, out var last) ? last : 0; + var sentPlan = seen; + var sentQueue = -1; + + http.Features.Get()?.DisableBuffering(); + response.ContentType = "text/event-stream"; + response.Headers.CacheControl = "no-cache"; + response.Headers["X-Accel-Buffering"] = "no"; + var token = http.RequestAborted; + try + { + await response.Body.FlushAsync(token); + while (true) + { + var changed = db.JobsChanged; + var job = db.GetJob(id); + if (job is null) + { + await WriteEvent(response, "gone", null, "{}", token); + return; + } + if (job.PlanRevision > sentPlan && db.GetJobPlan(id) is { } plan && plan.Revision > sentPlan) + { + await WriteEvent(response, "plan", plan.Revision, plan.Plan, token); + sentPlan = plan.Revision; + } + if (job.Revision > seen || job.QueuePosition != sentQueue && sentQueue >= 0 || job.IsFinished) + { + await WriteEvent(response, "job", job.Revision, JsonSerializer.Serialize(job, json.Value.SerializerOptions), token); + seen = job.Revision; + } + sentQueue = job.QueuePosition; + if (job.IsFinished) + return; + + // Changes in this process wake the stream at once; the keep-alive also re-reads. + if (await Task.WhenAny(changed, Task.Delay(KeepAlive, token)) != changed) + { + await response.WriteAsync(": keep-alive\n\n", token); + await response.Body.FlushAsync(token); + } + } + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + // The desktop went away. + } + } + + private static async Task WriteEvent(HttpResponse response, string type, long? id, string data, CancellationToken token) + { + var text = new StringBuilder(); + text.Append("event: ").Append(type).Append('\n'); + if (id is { } value) + text.Append("id: ").Append(value.ToString(CultureInfo.InvariantCulture)).Append('\n'); + foreach (var line in data.Split('\n')) + text.Append("data: ").Append(line.TrimEnd('\r')).Append('\n'); + text.Append('\n'); + await response.WriteAsync(text.ToString(), token); + await response.Body.FlushAsync(token); + } + + private static async Task<(string? Json, IResult? Error)> ReadJsonBody(HttpContext http, long maxBytes, string what) + { + if (http.Features.Get() is { IsReadOnly: false } limit) + limit.MaxRequestBodySize = maxBytes + 1; + if (!http.Request.HasJsonContentType()) + return (null, Results.BadRequest($"Expected an application/json {what}.")); + using var body = new MemoryStream(); + var chunk = new byte[81920]; + int read; + while ((read = await http.Request.Body.ReadAsync(chunk, http.RequestAborted)) > 0) + { + if (body.Length + read > maxBytes) + return (null, Results.BadRequest($"The {what} is too large.")); + body.Write(chunk, 0, read); + } + return (Encoding.UTF8.GetString(body.GetBuffer(), 0, (int)body.Length), null); + } + private static async Task<(NestJobWorkerMessage? Message, IResult? Error)> ReadWorkerMessage(HttpRequest request) { var (json, error) = await DrawingSetRoutes.ReadJson(request, "worker message"); diff --git a/OpenNest.WinForms.Tests/Forms/ServerAutoNestTests.cs b/OpenNest.WinForms.Tests/Forms/ServerAutoNestTests.cs new file mode 100644 index 00000000..1bd067e8 --- /dev/null +++ b/OpenNest.WinForms.Tests/Forms/ServerAutoNestTests.cs @@ -0,0 +1,119 @@ +using System.Windows.Forms; +using OpenNest.CNC; +using OpenNest.Data; +using OpenNest.Engine; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.Jobs.Remote; +using OpenNest.Forms; +using OpenNest.Forms.Commands; +using OpenNest.Geometry; + +namespace OpenNest.WinForms.Tests.Forms; + +/// +/// A server Auto Nest's progress window: the streamed stage text and the worker's best plan so +/// far in the same strip a local run fills, and the notice shown when a job ends while +/// OpenNest is not in front. +/// +public class ServerAutoNestTests +{ + private sealed class Collect : IProgress + { + public readonly List Reports = new(); + + public void Report(NestJobProgress value) + { + lock (Reports) + Reports.Add(value); + } + } + + private static NestPipelineRequest Request() + { + var program = new Program(); + program.MoveTo(0, 0); + program.LineTo(10, 0); + program.LineTo(10, 20); + program.LineTo(0, 20); + program.LineTo(0, 0); + var template = new Plate(48, 96) { EdgeSpacing = new Spacing(0.25, 0.25, 0.25, 0.25), PartSpacing = 0.25 }; + return new NestPipelineRequest("Rectangles", + new[] { new NestItem { Drawing = new Drawing("bracket", program), Quantity = 9 } }, + NestStockBuilder.FromTemplate(template, null), + new NestJobOptions(maxPlates: 5)); + } + + [Fact] + public void TheProgressWindowShowsTheStreamedStageAndPlan() + { + var request = Request(); + var tap = new Collect(); + NestPipeline.Run(new RecordingNestingEngine(NestingEngineRegistry.Create(request.EngineName)) { Progress = tap }, + request.EngineName, request); + var plan = tap.Reports.Last(r => r.Stage == NestJobStage.PlanImproved).Plan; + var job = new NestJobRecord + { + Id = Guid.NewGuid(), + EngineName = "Rectangles", + State = NestJobState.Running, + Revision = 3, + Progress = RemoteNestProgress.From(new NestJobProgress(NestJobStage.EvaluatingCandidate, "s0", 1, 1, 9)).ToJson(), + }; + + StaTestThread.Run(() => + { + SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext()); + using var cts = new CancellationTokenSource(); + using var form = new NestProgressForm(cts, showPlateRow: false) { AllowAccept = false, HoldOpenUntilCompleted = true }; + form.ShowPlanStrip(new ColorScheme()); + _ = form.Handle; + var view = new ServerAutoNest.LiveView(form, request, cts.Token); + var description = form.Controls.Find("descriptionValue", true).Single(); + + view.ShowJob(job); + Assert.Equal("On the nest server: Rectangles: evaluating plate 2 on stock s0", description.Text); + + view.ShowProblem("Waiting for the nest server: connection refused"); + Assert.StartsWith("Waiting for the nest server", description.Text); + view.ShowProblem(""); + Assert.StartsWith("On the nest server", description.Text); + + view.ShowPlan(RemoteNestPlan.From(plan).ToJson()); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (!view.Drawn.IsCompleted && DateTime.UtcNow < deadline) + Application.DoEvents(); + Assert.True(view.Drawn.IsCompleted); + var strip = Descendants(form).OfType().Single(); + Assert.Equal(9, strip.PartCount); + + // Updates posted after the run ended change nothing. + view.Stop(); + view.ShowJob(new NestJobRecord { State = NestJobState.Queued }); + Assert.StartsWith("On the nest server", description.Text); + }, TimeSpan.FromSeconds(30), "The STA test did not complete."); + } + + [Fact] + public void TheNoticeShowsOnlyWhileOpenNestIsAwayAndGoesOnceItIsBack() + { + StaTestThread.Run(() => + { + using var main = new Form { ShowInTaskbar = false, WindowState = FormWindowState.Minimized }; + _ = main.Handle; + // Minimized counts as away even when one of OpenNest's windows is active. + Assert.True(ServerNestNotice.IsAway(main)); + + using var notice = ServerNestNotice.ShowIfAway(main, "Server nest finished", "N26-0042 is ready to review."); + Assert.NotNull(notice); + Assert.True(notice!.IsShown); + + // Clicking it restores the main window and removes the icon. + notice.BringForward(); + Assert.Equal(FormWindowState.Normal, main.WindowState); + Assert.False(notice.IsShown); + }, TimeSpan.FromSeconds(15), "The STA test did not complete."); + } + + private static IEnumerable Descendants(Control parent) => + parent.Controls.Cast().SelectMany(c => Descendants(c).Prepend(c)); +} diff --git a/OpenNest/Forms/Commands/ServerAutoNest.cs b/OpenNest/Forms/Commands/ServerAutoNest.cs index 7c439bf6..1d655a6d 100644 --- a/OpenNest/Forms/Commands/ServerAutoNest.cs +++ b/OpenNest/Forms/Commands/ServerAutoNest.cs @@ -14,18 +14,19 @@ namespace OpenNest.Forms.Commands { /// /// Auto Nest solved by the nest server's worker (Database mode): the job is sent as a - /// package, its state polled behind the same owned modal progress a local run uses, and the - /// server's engine answers replayed here (), so validation, - /// the review and Keep are exactly a local run's. Stop cancels the server job and discards - /// the proposal. When the server cannot take the job, the user may nest on this PC instead. + /// package and followed through its event stream (polling when the stream drops) behind the + /// same owned modal progress a local run uses, with the worker's best plan so far drawn in + /// the same strip. The server's engine answers are then replayed here + /// (), so validation, the review and Keep are exactly a + /// local run's. Stop cancels the server job and discards the proposal. A job that ends while + /// OpenNest is not in front shows a notification (). When the + /// server cannot take the job, the user may nest on this PC instead. /// See docs/server-nesting.md. /// internal static class ServerAutoNest { private const string Caption = "Auto Nest"; - private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(2); - internal static async Task SolveAsync(IWin32Window owner, EditNestForm target, NestPipelineRequest request, CancellationTokenSource cts) { @@ -59,55 +60,49 @@ namespace OpenNest.Forms.Commands AllowAccept = false, HoldOpenUntilCompleted = true, }; - var wait = WaitAsync(jobs, job, submission, progressForm, cts); + progressForm.ShowPlanStrip(target.PlateView.ColorScheme); + var wait = WaitAsync(owner, jobs, job, submission, progressForm, cts); if (!wait.IsCompleted) progressForm.ShowDialog(owner); return await wait; } - private static async Task WaitAsync(RemoteNestJobs jobs, NestJobRecord job, + private static async Task WaitAsync(IWin32Window owner, RemoteNestJobs jobs, NestJobRecord job, RemoteNestSubmission submission, NestProgressForm progressForm, CancellationTokenSource cts) { - string problem = null; + var view = new LiveView(progressForm, submission.Request, cts.Token); + var watch = new NestJobWatch(jobs) + { + Job = new Progress(view.ShowJob), + Plan = new Progress(view.ShowPlan), + Problem = new Progress(view.ShowProblem), + }; try { - while (true) + job = await watch.RunAsync(job, cts.Token); + cts.Token.ThrowIfCancellationRequested(); + switch (job.State) { - cts.Token.ThrowIfCancellationRequested(); - Show(progressForm, problem ?? Describe(job)); - switch (job.State) - { - case NestJobState.Succeeded: - Show(progressForm, "Checking the server's nest on this PC"); - var transcript = NestSolveTranscript.FromJson(await jobs.GetResultAsync(job.Id, cts.Token)); - return await Task.Run(() => submission.Complete(transcript, cts.Token), cts.Token); - case NestJobState.Failed: - throw new InvalidOperationException($"The nest server could not nest this job: {job.Error}"); - case NestJobState.Cancelled: - // Stopped from elsewhere: nothing to keep, as after Stop here. - cts.Cancel(); - cts.Token.ThrowIfCancellationRequested(); - break; - } - - await Task.Delay(PollInterval, cts.Token); - try - { - job = await jobs.GetAsync(job.Id, cts.Token) - ?? throw new InvalidOperationException("The nest server no longer has this job."); - problem = null; - } - catch (Exception ex) when (!cts.IsCancellationRequested - && ex is IOException or HttpRequestException or TaskCanceledException) - { - // The job keeps running on the server; keep asking. - problem = $"Waiting for the nest server: {ex.Message}"; - } + case NestJobState.Succeeded: + ServerNestNotice.ShowIfAway(owner, "Server nest finished", + $"{Title(job)} is ready to review. Click to open OpenNest."); + view.Show("Checking the server's nest on this PC"); + var transcript = NestSolveTranscript.FromJson(await jobs.GetResultAsync(job.Id, cts.Token)); + return await Task.Run(() => submission.Complete(transcript, cts.Token), cts.Token); + case NestJobState.Failed: + ServerNestNotice.ShowIfAway(owner, "Server nest failed", + $"The nest server could not nest {Title(job)}. Click to open OpenNest."); + throw new InvalidOperationException($"The nest server could not nest this job: {job.Error}"); + default: + // Stopped from elsewhere: nothing to keep, as after Stop here. + cts.Cancel(); + throw new OperationCanceledException(cts.Token); } } catch (OperationCanceledException) when (cts.IsCancellationRequested) { - // Best effort: a job left running finishes on the server and is never kept. + // Best effort: the worker sees the request within one report interval. A job + // left running finishes on the server and is never kept. try { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); @@ -118,25 +113,117 @@ namespace OpenNest.Forms.Commands } finally { + view.Stop(); progressForm.ShowCompleted(); progressForm.Close(); } } + private static string Title(NestJobRecord job) => + string.IsNullOrWhiteSpace(job.Title) ? "Your nest" : job.Title; + private static string Describe(NestJobRecord job) => job.State switch { NestJobState.Queued when job.QueuePosition > 0 => $"Queued on the nest server, {job.QueuePosition} {(job.QueuePosition == 1 ? "job" : "jobs")} ahead", NestJobState.Queued => "Queued on the nest server", NestJobState.Running when job.CancelRequested => "Stopping on the nest server", + NestJobState.Running when RemoteNestProgress.FromJson(job.Progress) is { } progress => + $"On the nest server: {JobEngineNest.Describe(job.EngineName, progress.ToProgress())}", NestJobState.Running => "Nesting on the nest server", _ => job.State.ToString(), }; - private static void Show(NestProgressForm form, string text) + /// + /// What the progress window shows of a server job, on the UI thread: its state or the + /// worker's stage (or why updates are late), and its best plan so far in the strip. + /// Plans are drawn off the UI thread, newest only: a plan that arrives while one is + /// drawn replaces any still waiting. + /// + internal sealed class LiveView { - if (!form.IsDisposed) - form.UpdateProgress(new NestProgress { Description = text }); + private readonly NestProgressForm form; + private readonly NestPipelineRequest request; + private readonly CancellationToken token; + private RemoteNestPlanPreview preview; + private NestJobRecord job; + private string problem = ""; + private string waitingPlan; + private bool drawing; + private bool stopped; + + public LiveView(NestProgressForm form, NestPipelineRequest request, CancellationToken token) + { + this.form = form; + this.request = request; + this.token = token; + } + + /// Completes when no plan is being drawn; tests wait on it. + internal Task Drawn { get; private set; } = Task.CompletedTask; + + public void ShowJob(NestJobRecord value) + { + job = value; + Refresh(); + } + + public void ShowProblem(string value) + { + problem = value ?? ""; + Refresh(); + } + + public void ShowPlan(string json) + { + if (stopped) + return; + waitingPlan = json; + if (!drawing) + Drawn = DrawAsync(); + } + + public void Show(string text) + { + if (!form.IsDisposed) + form.UpdateProgress(new NestProgress { Phase = NestPhase.Custom, Description = text }); + } + + /// Late updates (posted before the run ended) are ignored. + public void Stop() => stopped = true; + + private void Refresh() + { + if (!stopped && job != null) + Show(problem.Length > 0 ? problem : Describe(job)); + } + + private async Task DrawAsync() + { + drawing = true; + try + { + while (waitingPlan != null && !stopped) + { + var json = waitingPlan; + waitingPlan = null; + var sheets = await Task.Run(() => + { + preview ??= new RemoteNestPlanPreview(request, token); + return preview.Sheets(json, token); + }, token); + if (sheets != null && !stopped && !form.IsDisposed) + form.UpdatePlan(sheets); + } + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + } + finally + { + drawing = false; + } + } } } } diff --git a/OpenNest/Forms/ServerNestNotice.cs b/OpenNest/Forms/ServerNestNotice.cs new file mode 100644 index 00000000..e009eb6d --- /dev/null +++ b/OpenNest/Forms/ServerNestNotice.cs @@ -0,0 +1,80 @@ +using System; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; + +namespace OpenNest.Forms +{ + /// + /// Tells the user a server nest ended while OpenNest was not in front: a notification-area + /// balloon, which Windows 10 and 11 show as a notification. A real toast would need an + /// AppUserModelID registered with a Start menu shortcut, which the Velopack install does not + /// promise. Clicking the balloon (or the icon) brings OpenNest forward with its topmost + /// window, which is the review once the result has been checked. The icon goes away once + /// OpenNest is in front again, however the user got there. + /// + internal sealed class ServerNestNotice : IDisposable + { + private readonly Form window; + private readonly NotifyIcon icon; + private readonly Timer returned; + private bool disposed; + + private ServerNestNotice(Form window, string title, string text) + { + this.window = window; + icon = new NotifyIcon + { + Icon = window.Icon ?? SystemIcons.Application, + Text = "OpenNest", + Visible = true, + }; + icon.BalloonTipClicked += (s, e) => BringForward(); + icon.MouseClick += (s, e) => BringForward(); + icon.ShowBalloonTip(15000, title, text, ToolTipIcon.Info); + returned = new Timer { Interval = 1000 }; + returned.Tick += (s, e) => + { + if (!IsAway(window)) + Dispose(); + }; + returned.Start(); + } + + /// The notice, or null when OpenNest is in front (the user sees the result anyway). + public static ServerNestNotice ShowIfAway(IWin32Window owner, string title, string text) + { + var window = (owner as Control)?.FindForm() ?? Application.OpenForms.Cast
().FirstOrDefault(); + return window == null || window.IsDisposed || !IsAway(window) ? null : new ServerNestNotice(window, title, text); + } + + /// No OpenNest window is active, or the main window is minimized. + internal static bool IsAway(Form window) => + Form.ActiveForm == null || window.WindowState == FormWindowState.Minimized; + + internal bool IsShown => !disposed && icon.Visible; + + internal void BringForward() + { + if (!window.IsDisposed) + { + if (window.WindowState == FormWindowState.Minimized) + window.WindowState = FormWindowState.Normal; + // An owned modal (the progress, validation report or review) is what needs the user. + var top = Application.OpenForms.Cast().LastOrDefault(f => f.Visible && f.Modal && !f.IsDisposed) ?? window; + top.Activate(); + } + Dispose(); + } + + public void Dispose() + { + if (disposed) + return; + disposed = true; + returned.Dispose(); + icon.Visible = false; + icon.Dispose(); + } + } +} diff --git a/docs/automatic-nesting.md b/docs/automatic-nesting.md index 37b55d82..b3b7b982 100644 --- a/docs/automatic-nesting.md +++ b/docs/automatic-nesting.md @@ -52,7 +52,8 @@ Unplaced demand is never dropped silently. `NestPipelineResult.Unplaced` lists e An incomplete but valid proposal is keepable like any other; keeping it is still an explicit action. Desktop Auto Nest lists each unplaced drawing, count and reason in its review before committing (the drawing list keeps showing remaining quantities); Console `--autonest` writes `Unplaced:` lines to standard error; MCP `autonest_plate` adds `Unplaced:` lines and `autonest_job` names the reasons when it refuses an incomplete proposal; the API returns `NestResponse.Unplaced` by request part ID. This check does not replace pre-post CNC verification. In Database mode, **Nest on the server** sends the job to the nest server's worker instead; -the review and Keep are unchanged. See [server nesting](server-nesting.md). +the progress window shows the worker's best plan so far, and the review and Keep are +unchanged. See [server nesting](server-nesting.md). The selected engine is saved in `%APPDATA%\OpenNest\engine-selection.json`. Selection is restored after plug-ins load. A saved name from an earlier release diff --git a/docs/server-nesting.md b/docs/server-nesting.md index a540cbd2..597cec86 100644 --- a/docs/server-nesting.md +++ b/docs/server-nesting.md @@ -16,16 +16,29 @@ With the box ticked, `ServerAutoNest`: 1. Snapshots the request (`RemoteNestSubmission`) and writes its package (`NestJobPackage`). 2. Submits it. If the server cannot take it (offline, too old, refused), the user may nest on this PC instead; declining discards the run. -3. Polls every two seconds behind the same owned modal progress window a local run uses, - showing the queue position or that the job is running. Transient poll failures only - show a waiting message; the job keeps running on the server. A live plan strip is not - shown yet. +3. Follows the job (`NestJobWatch`) behind the same owned modal progress window a local run + uses: the queue position, then the worker's stage ("On the nest server: …"), and the + worker's **Best plan so far** in the same sheet strip a local run fills + (`RemoteNestPlanPreview`, below). Updates come from the job's event stream; when it drops, + the client polls once and reconnects with the last event id, and a server without the + stream is polled every two seconds throughout. Connection trouble only shows a waiting + message; the job keeps running on the server. 4. On success, replays the result here (below) and continues with the usual validation report, review, Keep or Discard and commit. A failed job shows its error. Stop (or closing the progress window) cancels the server job, best effort, and discards the -proposal, exactly like stopping a local run. The input drawings stay locked by the modal -progress for the whole wait. +proposal, exactly like stopping a local run; the worker stops within one report interval +(two seconds) plus however long the engine takes to notice its cancellation token. The input +drawings stay locked by the modal progress for the whole wait. + +**Finish notice.** When the job ends (succeeded or failed) while no OpenNest window is active +or the main window is minimized, `ServerNestNotice` shows a notification-area balloon, which +Windows 10 and 11 display as a notification. Clicking it (or the tray icon) restores OpenNest +and activates its topmost window: the check of the result, then the review. The icon goes +away once OpenNest is in front again, however the user returns. A real toast would need an +AppUserModelID registered on a Start menu shortcut, which the Velopack install (see +[desktop auto-update](auto-update.md)) does not promise, so no packaging change is needed. +Nothing is kept without the review's explicit **Keep**. ## What travels @@ -47,6 +60,15 @@ in order, as what was asked (part and stock ids with quantities) and the raw `Ne returned. Poses keep their IEEE values, nonfinite ones included. No bound plates or validation travel back. +**Live progress** travels separately while the job runs, both as versioned JSON the server +never opens: `RemoteNestProgress` (the stage of the solve in progress: `NestJobStage`, stock, +plate index and committed counts) and `RemoteNestPlan` (the engine's best plan so far, as the +raw placements of `NestJobStage.PlanImproved`). The desktop rebuilds the request's job from +its own drawings (the same part ids the worker solved) and draws the plan on detached +drawings, exactly as a local run's `PlanSheets`; a bundled cutout trial's frame proxies are +bundled once on the desktop the first time a plan names one. Like a local plan it is +unvalidated and never kept. + ## Replay on the desktop `RemoteNestSubmission.Complete` first checks that each item's drawing still has the geometry @@ -73,10 +95,14 @@ nor `OpenNest.IO`. | `POST /api/nest-jobs` | desktop | multipart `metadata` (`NestJobSubmission`) and `file` (package, at most 256 MB); returns the queued job | | `GET /api/nest-jobs/{id}` | desktop | state, attempts, error, queue position | | `GET /api/nest-jobs/{id}/result` | desktop | the transcript; 409 until the job succeeded | +| `GET /api/nest-jobs/{id}/events` | desktop | Server-Sent Events of the job until it is final (below) | +| `GET /api/nest-jobs/{id}/plan` | desktop | the best plan so far, revision in `X-Plan-Revision`; 204 when there is none (the polling fallback) | | `POST /api/nest-jobs/{id}/cancel` | desktop | queued: cancelled at once; running: flagged for the worker | | `POST /api/nest-jobs/claim` | worker | the oldest queued job on a fresh lease, or 204 | | `GET /api/nest-jobs/{id}/package` | worker | the package while queued or running | | `POST /api/nest-jobs/{id}/heartbeat` | worker | renews the lease and reports a cancel request; 409 once the worker no longer holds it | +| `PUT /api/nest-jobs/{id}/progress?workerId=` | worker | stores the latest `RemoteNestProgress` (at most 64 KB); answers like a heartbeat | +| `PUT /api/nest-jobs/{id}/plan?workerId=` | worker | stores the latest `RemoteNestPlan` (at most 16 MB); answers like a heartbeat | | `PUT /api/nest-jobs/{id}/result?workerId=` | worker | stores the transcript (at most 64 MB); a job cancelled meanwhile ends Cancelled | | `POST /api/nest-jobs/{id}/fail` | worker | ends the job Failed with a reason | | `POST /api/nest-jobs/{id}/cancelled` | worker | confirms a requested stop | @@ -86,6 +112,47 @@ States: `Queued`, `Running`, then one of `Succeeded`, `Failed` and `Cancelled`. runs at a time: a claim returns nothing while any job is running, so another worker container never takes a second job. Claims are serialized by the database's monitor and transaction. +## Progress and the event stream + +The worker is a separate process that never opens the SQLite file (it may run on another +host, and the server's file may sit on NFS, where SQLite locking is unreliable), so progress +takes the route everything else from the worker takes: HTTP to the server, which stores it in +the job's row. The server is the one writer; nothing else had to change to carry it across +processes. + +**Worker.** `RecordingNestingEngine.Progress` taps each engine solve's own progress, before +the pipeline would turn plans into sheets (the worker draws nothing). `NestJobReporter` keeps +only the latest stage and the latest plan and, every `NestJobRules.ProgressInterval` (two +seconds), stores whichever changed: at most one small write and one plan write per interval, +however chatty the engine. A bundled cutout trial reports no commits, as in a local run. +Reports renew the lease and answer with the cancel flag; a round with nothing new reads the +job instead, which costs the server no write. Either way a cancel request reaches the worker +within one interval. The heartbeat still runs every 20 seconds. + +**Server.** Schema version 16 adds to `nest_jobs`: `revision` (bumped by every change a +watcher shows: submit, claim, cancel request, progress, plan, finish, release, lapse; +heartbeats leave it alone), `progress`, `plan` and `planRevision` (the revision the plan was +stored at). A finished job keeps its last progress but drops its plan; a job given back or +lapsed drops both, so the next attempt starts clean. Every job write also completes +`NestDatabase.JobsChanged`, an in-process signal, so streams wake at once without polling the +database; each stream also re-reads at every keep-alive. + +**Stream.** `GET /api/nest-jobs/{id}/events` (`text/event-stream`, 404 for an unknown job) sends: + +- `event: plan`, `id:` the plan's revision, `data:` the `RemoteNestPlan`, whenever a newer + plan was stored, always before the job event that names it; +- `event: job`, `id:` the job's revision, `data:` the job record (with `progress`, + `revision` and `planRevision`), on every change and when the queue position moves; +- `: keep-alive` comments every 15 seconds while nothing changes; +- `event: gone` if the job is removed meanwhile. + +The stream ends after the job event that is final. A reconnect sends `Last-Event-ID`: the +server sends only a newer plan and a newer job, except that a final job is always sent before +the stream ends. Ids never go backwards on one stream. SSE rather than SignalR: one-way +updates over plain HTTP need no hub, client library or sticky connection, and degrade to the +polling endpoints the server already had. The client treats 45 seconds without a line as a +dropped stream. + **Crash recovery.** A running job holds a two-minute lease (`NestJobRules.Lease`), which the worker renews every 20 seconds. Each claim first settles lapsed leases: a job someone asked to cancel ends Cancelled; otherwise it goes back to the front of the queue, or fails after three @@ -121,6 +188,16 @@ make a job slower. Leave enough CPU and memory for the server itself. `OpenNest.Engine.Tests` `RemoteNestReplayTests`: replay equals the local proposal (including the cutout trial plus ordinary solve), edited drawings and different jobs refuse, and stock -and nonfinite poses survive the wire. `OpenNest.Server.Tests` `NestJobQueueTests` (states, -single running job, concurrent claims, cancellation, lease lapse, retry limit, release, -retention, restart) and `NestJobApiTests` (HTTP plus a real worker run end to end). +and nonfinite poses survive the wire. `RemoteNestProgressTests`: a wire plan draws as the +local `PlanSheets`, including a cutout trial's proxies. `OpenNest.Server.Tests` +`NestJobQueueTests` (states, single running job, concurrent claims, cancellation, lease +lapse, retry limit, release, retention, restart), `NestJobApiTests` (HTTP plus a real worker +run end to end) and `NestJobEventsTests` (stream order ending at the final state, +`Last-Event-ID` reconnects, the watch reconnecting a dropped stream and polling a server +without one, an engine plan reaching the desktop, a cancel seen within one report interval). +`OpenNest.WinForms.Tests` `ServerAutoNestTests`: the progress window's stage text and plan +strip, and the finish notice. + +A live check against the container: submit a job, then +`curl -N http://:8090/api/nest-jobs//events` shows `job` and `plan` events until +the final job event.