using System.Diagnostics; using System.Net; using System.Security.Cryptography; using System.Text.Json.Nodes; using Google.Protobuf; using Grpc.Core; using Grpc.Net.Client; using Strata.Node.V1; namespace Strata.Desktop; internal static partial class CoreClient { private static readonly SemaphoreSlim Gate = new(1); private static GrpcChannel? channel; private static Strata.Node.V1.Node.NodeClient? client; private static Process? ownedAgent; private static string credential = ""; private static Metadata Headers() => new() { { "authorization", "Bearer " + credential } }; private static async Task Connect(CancellationToken cancellationToken) { await Gate.WaitAsync(cancellationToken); try { if (client != null && (ownedAgent == null || !ownedAgent.HasExited)) return client; CloseTransport(); var endpoint = selectedLocal ? null : Environment.GetEnvironmentVariable("STRATA_NODE_ENDPOINT"); if (selectedRemote is { } remote) endpoint = await BootstrapRemote(remote, cancellationToken); else if (endpoint == null) { var executable = CoreExecutable(); credential = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); ownedAgent = new Process { StartInfo = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, CreateNoWindow = true }}; foreach (var arg in new[] { "node", "--listen", "127.0.0.1:0", "--token-env", "STRATA_BOOTSTRAP_TOKEN", "--stdio-lifetime" }) ownedAgent.StartInfo.ArgumentList.Add(arg); ownedAgent.StartInfo.Environment["STRATA_BOOTSTRAP_TOKEN"] = credential; ownedAgent.Start(); ownedAgent.StartInfo.Environment.Remove("STRATA_BOOTSTRAP_TOKEN"); // No remote stderr or credential data is surfaced; drain with no accumulation. _ = Drain(ownedAgent.StandardError); var line = await ReadLineBounded(ownedAgent.StandardOutput, cancellationToken); var descriptor = JsonNode.Parse(line) as JsonObject; if (descriptor?["schema_version"]?.GetValue() != 1) throw new InvalidOperationException("Несумісний bootstrap node."); endpoint = descriptor["endpoint"]?.GetValue(); _ = Drain(ownedAgent.StandardOutput); } else credential = Environment.GetEnvironmentVariable("STRATA_NODE_TOKEN") ?? throw new InvalidOperationException("Потрібен STRATA_NODE_TOKEN для налаштованого node."); if (credential.Length < 32 || credential.Length > 4096 || credential.Any(c => c < 33 || c > 126)) throw new InvalidOperationException("Некоректний credential node."); if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || uri.Scheme != "http" || !IPAddress.TryParse(uri.Host.Trim('[', ']'), out var ip) || !IPAddress.IsLoopback(ip) || uri.AbsolutePath != "/" || uri.UserInfo.Length != 0 || uri.Query.Length != 0 || uri.Fragment.Length != 0) throw new InvalidOperationException("Node має бути loopback або локальним SSH-тунелем."); channel = GrpcChannel.ForAddress(uri, new GrpcChannelOptions { MaxReceiveMessageSize = 2 * 1024 * 1024 + 1024, MaxSendMessageSize = 2 * 1024 * 1024 + 1024, HttpHandler = new SocketsHttpHandler { UseProxy = false, AllowAutoRedirect = false } }); var connected = new Strata.Node.V1.Node.NodeClient(channel); var hello = await connected.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: cancellationToken); if (hello.ProtocolVersion != 1 || !hello.Capabilities.Contains("hardware.v1") || !hello.Capabilities.Contains("plan.v1")) throw new InvalidOperationException("Node не підтримує потрібний контракт."); client = connected; return connected; } catch { CloseTransport(); throw; } finally { Gate.Release(); } } internal sealed record ConnectionState(string Phase, string? Epoch = null, ulong Sequence = 0, uint ActiveResponses = 0); public static async Task Observe(Action publish, CancellationToken token) { var delay = 200; Snapshot? last = null; while (!token.IsCancellationRequested) { try { publish(new("connecting")); using var startup = CancellationTokenSource.CreateLinkedTokenSource(token); startup.CancelAfter(TimeSpan.FromSeconds(15)); var c = await Connect(startup.Token); var hello = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: token); ValidateSnapshot(hello, last); using var call = c.Watch(new Cursor { AgentEpoch = hello.AgentEpoch, Sequence = hello.Sequence }, Headers(), cancellationToken: token); var pending = call.ResponseStream.MoveNext(token); var initial = true; while (!token.IsCancellationRequested) { Snapshot next; using var tick = CancellationTokenSource.CreateLinkedTokenSource(token); var timer = Task.Delay(TimeSpan.FromSeconds(5), tick.Token); if (await Task.WhenAny(pending, timer) == pending) { tick.Cancel(); if (!await pending) throw new RpcException(new Status(StatusCode.Unavailable, "Node subscription ended")); next = call.ResponseStream.Current; // Heartbeat may have overtaken an already buffered state event. if (last != null && next.AgentEpoch == last.AgentEpoch && next.Sequence < last.Sequence) { pending = call.ResponseStream.MoveNext(token); continue; } pending = call.ResponseStream.MoveNext(token); } else { token.ThrowIfCancellationRequested(); if (initial) throw new RpcException(new Status(StatusCode.DeadlineExceeded, "Node snapshot timeout")); next = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: token); } ValidateSnapshot(next, last); if (!initial && last != null && next.AgentEpoch != last.AgentEpoch) throw new RpcException(new Status(StatusCode.Unavailable, "Node epoch changed")); last = next; initial = false; delay = 200; publish(new("ready", next.AgentEpoch, next.Sequence, next.ActiveResponses)); } } catch (OperationCanceledException) when (token.IsCancellationRequested) { break; } catch (RpcException) when (token.IsCancellationRequested) { break; } catch (RpcException e) when (e.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied) { publish(new("auth_error")); return; } catch (RpcException e) when (e.StatusCode is StatusCode.FailedPrecondition or StatusCode.Unimplemented or StatusCode.InvalidArgument) { publish(new("protocol_error")); return; } catch (InvalidOperationException) { publish(new("configuration_error")); return; } catch (Exception e) when (e is RpcException or IOException or OperationCanceledException) { publish(new("disconnected")); } try { await Task.Delay(Math.Min(10000, delay + Random.Shared.Next(0, 101)), token); } catch (OperationCanceledException) { break; } delay = Math.Min(10000, delay * 2); } } private static void ValidateSnapshot(Snapshot next, Snapshot? previous) { if (next.ProtocolVersion != 1 || !next.FullSnapshot || next.AgentEpoch.Length is 0 or > 128 || next.Sequence == 0 || next.Capabilities.Count > 64 || next.Capabilities.Any(c => c.Length > 128) || (previous != null && previous.AgentEpoch == next.AgentEpoch && previous.Sequence > next.Sequence)) throw new RpcException(new Status(StatusCode.FailedPrecondition, "Invalid node snapshot")); } public static async Task Run(CancellationToken cancellationToken, params string[] args) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(TimeSpan.FromSeconds(15)); var c = await Connect(timeout.Token); JsonDocument result; if (args is ["hardware"]) result = await c.HardwareAsync(new Empty(), Headers(), deadline: DateTime.UtcNow.AddSeconds(10), cancellationToken: timeout.Token); else if (args is ["plan", var path]) { await using var file = File.OpenRead(path); using var data = new MemoryStream(); var buffer = new byte[8192]; int count; while ((count = await file.ReadAsync(buffer, timeout.Token)) > 0) { if (data.Length + count > 1024 * 1024) throw new InvalidOperationException("Профіль перевищує 1 MiB."); data.Write(buffer, 0, count); } result = await c.PlanAsync(new JsonDocument { Json = ByteString.CopyFrom(data.ToArray()) }, Headers(), deadline: DateTime.UtcNow.AddSeconds(10), cancellationToken: timeout.Token); } else throw new InvalidOperationException("Непідтриманий виклик core."); var value = JsonNode.Parse(result.Json.Span) as JsonObject ?? throw new InvalidOperationException("Некоректний документ node."); if (value["schema_version"]?.GetValue() != 1) throw new InvalidOperationException("Несумісна версія документа node."); return value; } private static async Task ReadLineBounded(StreamReader reader, CancellationToken token) { var text = new System.Text.StringBuilder(); var buffer = new char[1]; while (await reader.ReadAsync(buffer.AsMemory(), token) > 0) { if (buffer[0] == '\n') return text.ToString(); if (text.Length >= 4096) throw new InvalidOperationException("Node bootstrap завеликий."); text.Append(buffer[0]); } throw new InvalidOperationException("Node не запустився."); } private static async Task Drain(StreamReader reader) { try { var buffer = new char[4096]; while (await reader.ReadAsync(buffer) > 0) {} } catch (ObjectDisposedException) {} catch (IOException) {} } public static void Close() { CloseTransport(); selectedRemote = null; selectedLocal = false; } private static void CloseTransport() { client = null; channel?.Dispose(); channel = null; credential = ""; if (ownedAgent is { } process) { ownedAgent = null; try { process.StandardInput.Close(); if (!process.WaitForExit(1500)) process.Kill(entireProcessTree: true); } catch (InvalidOperationException) {} finally { process.Dispose(); } } } public static async Task ReconnectSelfCheck(bool requireNewEpoch = true) { if (Environment.GetEnvironmentVariable("STRATA_NODE_ENDPOINT") == null) throw new InvalidOperationException("Reconnect check requires an isolated external test node."); using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(25)); string? firstEpoch = null; bool disconnected = false; bool recovered = false; await Observe(state => { Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(state)); if (state.Phase == "ready") { firstEpoch ??= state.Epoch; if (disconnected && (requireNewEpoch ? state.Epoch != firstEpoch : state.Epoch == firstEpoch)) {recovered = true; timeout.Cancel();} } if (state.Phase == "disconnected") disconnected = true; }, timeout.Token); if (!recovered) throw new InvalidOperationException("No observed recovery to the expected epoch."); Console.WriteLine(requireNewEpoch ? "PASS: C# observer recovered after isolated node restart; no inference replay." : "PASS: C# observer recovered after owned SSH transport loss; node epoch unchanged."); } public static async Task SelfCheck() { var h = await Run(CancellationToken.None, "hardware"); if (h["memory"] is not JsonObject || h["accelerators"] is not JsonArray) throw new InvalidOperationException("Missing hardware contract fields."); var p = await Run(CancellationToken.None, "plan", Path.Combine(AppContext.BaseDirectory, "example-requirements.json")); if (p["evidence"]?.GetValue() != "estimated" || p["candidates"] is not JsonArray { Count: > 0 }) throw new InvalidOperationException("Missing planning contract fields."); var c = await Connect(CancellationToken.None); using var watch = c.Watch(new Cursor(), Headers(), deadline: DateTime.UtcNow.AddSeconds(5)); if (!await watch.ResponseStream.MoveNext(CancellationToken.None) || !watch.ResponseStream.Current.FullSnapshot) throw new InvalidOperationException("Missing node snapshot."); Console.WriteLine("PASS: C# → gRPC/HTTP2 → Rust node: authenticated handshake, hardware, plan, snapshot; no inference."); } }