Files
leleka/desktop/CoreClient.cs
T

145 lines
8.6 KiB
C#

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 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<Strata.Node.V1.Node.NodeClient> Connect(CancellationToken cancellationToken)
{
await Gate.WaitAsync(cancellationToken);
try
{
if (client != null && (ownedAgent == null || !ownedAgent.HasExited)) return client;
Close();
var endpoint = Environment.GetEnvironmentVariable("STRATA_NODE_ENDPOINT");
if (endpoint == null)
{
var executable = Environment.GetEnvironmentVariable("STRATA_DESKTOP_CORE")
?? Path.Combine(AppContext.BaseDirectory, OperatingSystem.IsWindows() ? "strata-desktop.exe" : "strata-desktop");
if (!Path.IsPathFullyQualified(executable) || !File.Exists(executable))
throw new InvalidOperationException("Rust core не знайдено. Зберіть desktop-core або вкажіть абсолютний STRATA_DESKTOP_CORE.");
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<int>() != 1)
throw new InvalidOperationException("Несумісний bootstrap node.");
endpoint = descriptor["endpoint"]?.GetValue<string>();
_ = 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 { Close(); throw; }
finally { Gate.Release(); }
}
public static async Task<JsonObject> 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<int>() != 1) throw new InvalidOperationException("Несумісна версія документа node.");
return value;
}
private static async Task<string> 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()
{
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 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<string>() != "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.");
}
}