|
| 1 | +using System.Diagnostics; |
| 2 | +using System.Text; |
| 3 | +using System.Text.Json; |
| 4 | + |
| 5 | +namespace RustSharp.ProcWireCandidate; |
| 6 | + |
| 7 | +/// <summary>Stateless JSON contract checks only; no transport, host, filesystem capability or macro execution.</summary> |
| 8 | +public static class Contract |
| 9 | +{ |
| 10 | + public const string Protocol = "rustsharp.proc-wire.candidate.v1"; |
| 11 | + public const int MaximumFrameBytes = 65_536; |
| 12 | + public const int MaximumTokens = 256; |
| 13 | + public const int MaximumSpans = 256; |
| 14 | + public const int MaximumDocuments = 8; |
| 15 | + public const int MaximumDiagnostics = 16; |
| 16 | + public const int MaximumTokenBytes = 256; |
| 17 | + public const int MaximumDiagnosticBytes = 2_048; |
| 18 | + public const int MaximumDelimiterDepth = 16; |
| 19 | + public const int MaximumJsonDepth = 12; |
| 20 | + public const int MaximumOperations = 8_192; |
| 21 | + public const int TimeoutMilliseconds = 1_000; |
| 22 | + private static readonly string[] Capabilities = ["token-tree-v1", "span-v1", "diagnostics-v1", "cancellation-v1"]; |
| 23 | + |
| 24 | + public static Result Validate(string json, CancellationToken cancellationToken = default) |
| 25 | + { |
| 26 | + ArgumentNullException.ThrowIfNull(json); cancellationToken.ThrowIfCancellationRequested(); |
| 27 | + if (json.Length > MaximumFrameBytes || Encoding.UTF8.GetByteCount(json) > MaximumFrameBytes) return Invalid("RSPROC1090", "Frame byte budget exceeded."); |
| 28 | + var validator = new Validator(Stopwatch.StartNew(), cancellationToken); |
| 29 | + try |
| 30 | + { |
| 31 | + using JsonDocument document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = MaximumJsonDepth }); |
| 32 | + JsonElement root = document.RootElement; validator.Tree(root, 0); |
| 33 | + validator.Properties(root, ["protocolVersion", "requestId", "direction", "kind", "capabilities", "documents", "spans", "tokens", "diagnostics"]); |
| 34 | + if (validator.Text(root, "protocolVersion", 64) != Protocol) return Invalid("RSPROC1002", "Unsupported exact wire version."); |
| 35 | + _ = validator.Text(root, "requestId", 64); |
| 36 | + string direction = validator.Text(root, "direction", 32), kind = validator.Text(root, "kind", 32); |
| 37 | + string expectedDirection = kind switch |
| 38 | + { |
| 39 | + "hello" or "expand" or "cancel" => "compiler-to-host", |
| 40 | + "ready" or "expanded" or "diagnostic" or "error" or "cancelled" => "host-to-compiler", |
| 41 | + _ => throw new FormatException("Unsupported envelope kind."), |
| 42 | + }; |
| 43 | + validator.Require(direction == expectedDirection, "Envelope direction/kind mismatch."); |
| 44 | + JsonElement capabilities = validator.Array(root, "capabilities", 4); |
| 45 | + var seenCapabilities = new HashSet<string>(StringComparer.Ordinal); |
| 46 | + foreach (JsonElement value in capabilities.EnumerateArray()) |
| 47 | + { |
| 48 | + validator.Step(); string capability = value.GetString() ?? throw new FormatException("Null capability."); |
| 49 | + if (!Capabilities.Contains(capability, StringComparer.Ordinal)) return Invalid("RSPROC1001", "Unsupported capability: " + capability); |
| 50 | + validator.Require(seenCapabilities.Add(capability), "Duplicate capability."); |
| 51 | + } |
| 52 | + bool handshake = kind is "hello" or "ready"; |
| 53 | + validator.Require(handshake ? seenCapabilities.SetEquals(Capabilities) : seenCapabilities.Count == 0, "Capabilities are exact at handshake and empty in later envelopes."); |
| 54 | + var documents = new Dictionary<string, int>(StringComparer.Ordinal); |
| 55 | + JsonElement sourceDocuments = validator.Array(root, "documents", MaximumDocuments); |
| 56 | + foreach (JsonElement value in sourceDocuments.EnumerateArray()) |
| 57 | + { |
| 58 | + validator.Step(); validator.Properties(value, ["id", "utf16Length"]); |
| 59 | + string id = validator.Text(value, "id", 64); int length = value.GetProperty("utf16Length").GetInt32(); |
| 60 | + validator.Require(length is >= 0 and <= MaximumFrameBytes && documents.TryAdd(id, length), "Invalid or duplicate source document."); |
| 61 | + } |
| 62 | + JsonElement spans = validator.Array(root, "spans", MaximumSpans); |
| 63 | + foreach (JsonElement value in spans.EnumerateArray()) |
| 64 | + { |
| 65 | + validator.Step(); validator.Properties(value, ["documentId", "start", "length"]); |
| 66 | + string id = validator.Text(value, "documentId", 64); int start = value.GetProperty("start").GetInt32(), length = value.GetProperty("length").GetInt32(); |
| 67 | + validator.Require(documents.TryGetValue(id, out int size) && start >= 0 && length >= 0 && start <= size - length, "Span outside its declared UTF16 document bounds."); |
| 68 | + } |
| 69 | + JsonElement tokens = validator.Array(root, "tokens", MaximumTokens); |
| 70 | + var delimiters = new Stack<char>(); |
| 71 | + foreach (JsonElement token in tokens.EnumerateArray()) |
| 72 | + { |
| 73 | + validator.Step(); validator.Properties(token, ["kind", "text", "spanIndex"]); |
| 74 | + string tokenKind = validator.Text(token, "kind", 32), text = validator.Text(token, "text", MaximumTokenBytes); |
| 75 | + validator.Require(tokenKind is "identifier" or "literal" or "punctuation" or "open" or "close", "Unknown token kind."); |
| 76 | + int spanIndex = token.GetProperty("spanIndex").GetInt32(); validator.Require(spanIndex >= 0 && spanIndex < spans.GetArrayLength(), "Token span index is invalid."); |
| 77 | + if (tokenKind == "open") |
| 78 | + { |
| 79 | + validator.Require(text.Length == 1 && text[0] is '(' or '[' or '{' && delimiters.Count < MaximumDelimiterDepth, "Open delimiter/depth limit is invalid."); |
| 80 | + delimiters.Push(text[0]); |
| 81 | + } |
| 82 | + else if (tokenKind == "close") |
| 83 | + { |
| 84 | + validator.Require(text.Length == 1 && text[0] is ')' or ']' or '}' && delimiters.Count > 0, "Unmatched close delimiter."); |
| 85 | + char open = delimiters.Pop(); validator.Require((open, text[0]) is ('(', ')') or ('[', ']') or ('{', '}'), "Delimiter kind mismatch."); |
| 86 | + } |
| 87 | + } |
| 88 | + validator.Require(delimiters.Count == 0, "Unclosed delimiter tree."); |
| 89 | + JsonElement diagnostics = validator.Array(root, "diagnostics", MaximumDiagnostics); |
| 90 | + foreach (JsonElement diagnostic in diagnostics.EnumerateArray()) |
| 91 | + { |
| 92 | + validator.Step(); validator.Properties(diagnostic, ["severity", "code", "message", "spanIndex"]); |
| 93 | + string severity = validator.Text(diagnostic, "severity", 32); validator.Require(severity is "error" or "warning" or "note", "Unknown diagnostic severity."); |
| 94 | + _ = validator.Text(diagnostic, "code", 64); _ = validator.Text(diagnostic, "message", MaximumDiagnosticBytes); |
| 95 | + int index = diagnostic.GetProperty("spanIndex").GetInt32(); validator.Require(index == -1 || index >= 0 && index < spans.GetArrayLength(), "Invalid diagnostic span index."); |
| 96 | + if (kind == "error") validator.Require(severity == "error", "Error envelope requires error diagnostics."); |
| 97 | + } |
| 98 | + bool expansion = kind is "expand" or "expanded", diagnosticEnvelope = kind is "diagnostic" or "error"; |
| 99 | + validator.Require(expansion ? tokens.GetArrayLength() > 0 && documents.Count > 0 && spans.GetArrayLength() > 0 : tokens.GetArrayLength() == 0, "Token payload is inappropriate for envelope kind."); |
| 100 | + validator.Require(diagnosticEnvelope ? diagnostics.GetArrayLength() > 0 : diagnostics.GetArrayLength() == 0, "Diagnostic payload is inappropriate for envelope kind."); |
| 101 | + if (handshake || kind is "cancel" or "cancelled") validator.Require(documents.Count == 0 && spans.GetArrayLength() == 0, "Control envelope cannot carry source payload."); |
| 102 | + validator.Step(); return new(true, string.Empty, string.Empty, kind, tokens.GetArrayLength(), spans.GetArrayLength()); |
| 103 | + } |
| 104 | + catch (Exception exception) when (exception is JsonException or InvalidOperationException or FormatException or KeyNotFoundException or OverflowException or TimeoutException) |
| 105 | + { return Invalid("RSPROC1090", exception.Message); } |
| 106 | + } |
| 107 | + private static Result Invalid(string code, string message) => new(false, code, message, string.Empty, 0, 0); |
| 108 | + private sealed class Validator(Stopwatch clock, CancellationToken cancellationToken) |
| 109 | + { |
| 110 | + private int _operations; |
| 111 | + internal void Step() { cancellationToken.ThrowIfCancellationRequested(); if (++_operations > MaximumOperations || clock.ElapsedMilliseconds >= TimeoutMilliseconds) throw new TimeoutException("Wire validation operation/deadline budget exceeded."); } |
| 112 | + internal void Require(bool condition, string message) { Step(); if (!condition) throw new FormatException(message); } |
| 113 | + internal string Text(JsonElement value, string name, int maximumBytes) { Step(); string? text = value.GetProperty(name).GetString(); Require(!string.IsNullOrWhiteSpace(text) && Encoding.UTF8.GetByteCount(text) <= maximumBytes, "Missing, empty or oversized text: " + name); return text!; } |
| 114 | + internal JsonElement Array(JsonElement value, string name, int maximum) { Step(); JsonElement array = value.GetProperty(name); Require(array.ValueKind == JsonValueKind.Array && array.GetArrayLength() <= maximum, "Array type/count limit: " + name); return array; } |
| 115 | + internal void Properties(JsonElement value, string[] names) |
| 116 | + { |
| 117 | + Step(); var actual = new HashSet<string>(StringComparer.Ordinal); |
| 118 | + foreach (JsonProperty property in value.EnumerateObject()) { Step(); Require(actual.Add(property.Name), "Duplicate JSON property."); } |
| 119 | + Require(actual.SetEquals(names), "Missing or unexpected JSON property."); |
| 120 | + } |
| 121 | + internal void Tree(JsonElement value, int depth) |
| 122 | + { |
| 123 | + Step(); Require(depth <= MaximumJsonDepth, "JSON nesting depth exceeded."); |
| 124 | + if (value.ValueKind == JsonValueKind.Object) |
| 125 | + { |
| 126 | + var names = new HashSet<string>(StringComparer.Ordinal); |
| 127 | + foreach (JsonProperty property in value.EnumerateObject()) { Step(); Require(names.Add(property.Name), "Duplicate JSON property."); Tree(property.Value, depth + 1); } |
| 128 | + } |
| 129 | + else if (value.ValueKind == JsonValueKind.Array) |
| 130 | + { |
| 131 | + Require(value.GetArrayLength() <= MaximumTokens, "Generic array item budget exceeded."); |
| 132 | + foreach (JsonElement item in value.EnumerateArray()) Tree(item, depth + 1); |
| 133 | + } |
| 134 | + } |
| 135 | + } |
| 136 | +} |
| 137 | +public sealed record Result(bool IsSuccessful, string DiagnosticCode, string Message, string Kind, int TokenCount, int SpanCount) |
| 138 | +{ public bool FormalAcceptanceAllowed { get; } public int MacroCodeExecutions { get; } } |
0 commit comments