V16 / 6df58cd3ed86
MessageBridgeClient.cs
Lilith/Core/Messaging/MessageBridgeClient.cs
Unchanged from the preceding versionCS
using System.Net.Http.Headers;
using System.Net.Http.Json;
namespace Lilith.Core.Messaging;
public static class MessageBridgeClient
{
public static bool Configured => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LILITH_MESSAGES_API_TOKEN"));
public static async Task<string> RequestAsync(string action, object payload, CancellationToken ct = default)
{
if (action is not ("channels" or "inbox" or "status" or "proposal" or "claim" or "prepare" or "send" or "reject")) throw new ArgumentException("Unknown messaging action.");
string token = Environment.GetEnvironmentVariable("LILITH_MESSAGES_API_TOKEN") ?? "";
if (token.Length is < 32 or > 256 || token.Any(char.IsControl)) throw new InvalidOperationException("Messaging bridge is not configured.");
int port = int.TryParse(Environment.GetEnvironmentVariable("LILITH_MESSAGES_PORT"), out int p) ? p : 5184;
if (port is < 1024 or > 65535) throw new InvalidOperationException("Invalid bridge port.");
using var handler = new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false, UseCookies = false };
using var http = new HttpClient(handler) { BaseAddress = new($"http://127.0.0.1:{port}/"), Timeout = TimeSpan.FromSeconds(10), MaxResponseContentBufferSize = 256000 };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
using var response = await http.PostAsJsonAsync("api/v1/messages/" + action, payload, ct);
if (!response.IsSuccessStatusCode) throw new IOException("Messaging bridge request failed (HTTP " + (int)response.StatusCode + "). No delivery is claimed.");
return await response.Content.ReadAsStringAsync(ct);
}
}