Files
leleka/desktop/WorkerController.cs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

105 lines
5.9 KiB
C#

using Grpc.Core;
using Strata.Node.V1;
namespace Strata.Desktop;
internal sealed record WorkerReading(string Epoch, WorkerState? Worker, bool Durable = false);
internal interface IWorkerRpc
{
Task<WorkerReading> Read(CancellationToken token);
Task<WorkerOperation> Submit(WorkerCommand command, CancellationToken token);
Task<WorkerOperation> Lookup(string id, CancellationToken token);
}
internal sealed record WorkerView(string Phase, string Model = "", string Detail = "", bool CanStart = false,
bool CanStop = false, string OperationId = "", uint Pid = 0);
// One outstanding command, never automatically resubmitted. Polling is read-only.
internal sealed class WorkerController(IWorkerRpc rpc)
{
private readonly SemaphoreSlim gate = new(1);
private WorkerCommand? pending;
private bool uncertain;
public WorkerView View { get; private set; } = new("connecting");
private static bool Startable(WorkerState w) => w.Reason != "reconciliation_required" && w.Pid == 0 && w.Phase is "stopped" or "failed";
private static bool Stoppable(WorkerState w) => w.Reason != "reconciliation_required" && w.Pid != 0 && w.Phase is "ready" or "failed";
private void Show(WorkerState w, string detail = "")
{
View = new(w.Phase, w.Model, detail.Length > 0 ? detail : w.Reason,
pending == null && Startable(w), pending == null && Stoppable(w), pending?.OperationId ?? "", w.Pid);
}
public async Task Refresh(CancellationToken token)
{
await gate.WaitAsync(token);
try { await RefreshLocked(token); }
catch (Exception e) when (e is RpcException or IOException or InvalidOperationException or OperationCanceledException)
{ Offline(e); }
finally { gate.Release(); }
}
private async Task RefreshLocked(CancellationToken token)
{
var reading = await rpc.Read(token);
if (pending != null && reading.Epoch != pending.ExpectedEpoch && !reading.Durable) uncertain = true;
if (reading.Worker == null) {
View = new("unmanaged", Detail: pending == null ? "" : "Операцію неможливо звірити: вузол змінився.", OperationId: pending?.OperationId ?? "");
return;
}
if (pending == null) { Show(reading.Worker); return; }
if (uncertain) { Show(reading.Worker, "Вузол або журнал змінився. Потрібна ручна звірка операції; повторного запуску немає."); return; }
WorkerOperation op;
try { op = await rpc.Lookup(pending.OperationId, token); }
catch (RpcException e) when (e.StatusCode == StatusCode.NotFound) {
uncertain = true; Show(reading.Worker, "Результат операції невідомий. Команду не повторено."); return;
}
Validate(op, pending.OperationId);
if (op.Status == "indeterminate") { uncertain = true; Show(reading.Worker, "Операцію перервано рестартом. Потрібна звірка; команду не повторено."); return; }
// Recheck epoch and phase after lookup: a replacement may have occurred between RPCs.
var after = await rpc.Read(token);
if (after.Epoch != reading.Epoch || after.Worker == null || (after.Epoch != pending.ExpectedEpoch && !after.Durable)) {
uncertain = true; View = new("reconcile", Detail: "Вузол змінився. Команду не повторено.", OperationId: pending.OperationId); return;
}
if (op.Status is "succeeded" or "failed") {
pending = null;
Show(after.Worker, op.Status == "succeeded" ? "Операцію завершено." : "Операція не виконана: " + op.Reason);
}
else Show(after.Worker, "Операція виконується…");
}
public async Task Command(bool start, CancellationToken token)
{
await gate.WaitAsync(token);
try {
if (pending != null) return;
var reading = await rpc.Read(token);
var w = reading.Worker;
if (w == null || !(start ? Startable(w) : Stoppable(w))) {
if (w != null) Show(w, "Стан змінився; команду не надіслано.");
return;
}
pending = new WorkerCommand {
OperationId = Guid.NewGuid().ToString(), ExpectedEpoch = reading.Epoch,
Action = start ? WorkerCommand.Types.Action.Start : WorkerCommand.Types.Action.Stop,
DrainTimeoutMs = start ? 0u : 30000u
};
uncertain = false; Show(w, "Надсилання команди…");
// Keep pending even if acknowledgement is lost. Only Lookup follows.
var result = await rpc.Submit(pending.Clone(), token);
Validate(result, pending.OperationId);
await RefreshLocked(token);
}
catch (Exception e) when (e is RpcException or IOException or InvalidOperationException or OperationCanceledException)
{ Offline(e); }
finally { gate.Release(); }
}
private void Offline(Exception e)
{
var phase = e is RpcException r && r.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied
? "auth_error" : "disconnected";
View = new(phase, Detail: pending == null ? "Оновлюю зв’язок…" : "Очікую результат попередньої операції; команда не повторюється.",
OperationId: pending?.OperationId ?? "");
}
private static void Validate(WorkerOperation op, string id)
{
if (op.OperationId != id || op.Status is not ("accepted" or "running" or "succeeded" or "failed" or "indeterminate") || op.Reason.Length > 256)
throw new InvalidOperationException("Invalid operation state");
}
}