using Grpc.Core; using Strata.Node.V1; namespace Strata.Desktop; internal static partial class CoreClient { public static IWorkerRpc WorkerRpc() => new WorkerRpcClient(); private sealed class WorkerRpcClient : IWorkerRpc { public async Task Read(CancellationToken token) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); timeout.CancelAfter(TimeSpan.FromSeconds(10)); var c = await Connect(timeout.Token); var hello = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: timeout.Token); ValidateSnapshot(hello, null); if (!hello.Capabilities.Contains("worker.lifecycle.v1")) return new(hello.AgentEpoch, null); var state = await c.WorkerStatusAsync(new Empty(), Headers(), deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: timeout.Token); var after = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: timeout.Token); ValidateSnapshot(after, hello); if (after.AgentEpoch != hello.AgentEpoch) throw new RpcException(new Status(StatusCode.Unavailable, "Node changed")); if (state.ProfileId.Length > 128 || state.Model.Length > 256 || state.Reason.Length > 256 || state.Phase is not ("stopped" or "starting" or "ready" or "draining" or "failed")) throw new InvalidOperationException("Invalid worker state"); return new(hello.AgentEpoch, state, hello.Capabilities.Contains("worker.journal.v1")); } public async Task Submit(WorkerCommand command, CancellationToken token) { var c = await Connect(token); return await c.ControlWorkerAsync(command, Headers(), deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: token); } public async Task Lookup(string id, CancellationToken token) { var c = await Connect(token); return await c.OperationStatusAsync(new OperationQuery { OperationId = id }, Headers(), deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: token); } } }