From fbd7883a95a0e2f82684b3d07420c14e8aa581da Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 11 Nov 2026 02:10:15 -0500 Subject: [PATCH 01/14] feat: serve the FDC3 DesktopAgent to native apps over gRPC on a named pipe New Bermuda.Fdc3.Grpc project: a Kestrel named-pipe (current-user-only) gRPC service mirroring IFdc3Commands. Each Subscribe(app_id) stream is one app instance (app id validated against the AppDirectory) and is disposed when the stream or pipe ends; Fdc3Errors strings are the gRPC status detail. Started/stopped by App.xaml.cs (FDC3_GRPC_ENABLED, FDC3_GRPC_PIPE). Adds a reference .NET pipe client, integration tests over a real pipe and a docs/fdc3.md section. Co-Authored-By: Claude Sonnet 5.5 --- Bermuda.slnx | 2 + Directory.Packages.props | 4 + docs/fdc3.md | 13 + .../Bermuda.Fdc3.Grpc.Tests.csproj | 26 ++ src/Bermuda.Fdc3.Grpc.Tests/Fdc3PipeClient.cs | 118 +++++++++ .../PipeIntegrationTests.cs | 250 ++++++++++++++++++ .../Bermuda.Fdc3.Grpc.csproj | 25 ++ src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs | 206 +++++++++++++++ src/Bermuda.Fdc3.Grpc/Fdc3ErrorInterceptor.cs | 52 ++++ src/Bermuda.Fdc3.Grpc/Fdc3GrpcHost.cs | 77 ++++++ src/Bermuda.Fdc3.Grpc/Mapping.cs | 193 ++++++++++++++ src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto | 235 ++++++++++++++++ src/Bermuda/App.xaml.cs | 28 ++ src/Bermuda/Bermuda.csproj | 1 + src/Bermuda/appsettings.json | 3 +- 15 files changed, 1232 insertions(+), 1 deletion(-) create mode 100644 src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj create mode 100644 src/Bermuda.Fdc3.Grpc.Tests/Fdc3PipeClient.cs create mode 100644 src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs create mode 100644 src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj create mode 100644 src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs create mode 100644 src/Bermuda.Fdc3.Grpc/Fdc3ErrorInterceptor.cs create mode 100644 src/Bermuda.Fdc3.Grpc/Fdc3GrpcHost.cs create mode 100644 src/Bermuda.Fdc3.Grpc/Mapping.cs create mode 100644 src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto diff --git a/Bermuda.slnx b/Bermuda.slnx index 45011e6..d7cf417 100644 --- a/Bermuda.slnx +++ b/Bermuda.slnx @@ -3,6 +3,8 @@ + + diff --git a/Directory.Packages.props b/Directory.Packages.props index f858674..0888671 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -27,6 +27,10 @@ + + + + diff --git a/docs/fdc3.md b/docs/fdc3.md index c778857..b721231 100644 --- a/docs/fdc3.md +++ b/docs/fdc3.md @@ -138,6 +138,18 @@ Rejections are `Error`s whose `message` is the standard FDC3 error string; over - Selecting an incident broadcasts `{ type: "bermuda.incident", id: { incidentId }, name: }`. Selection that *arrives* over FDC3 (a broadcast on the joined channel, or the `ViewIncident` intent) selects the incident but does not re-broadcast, so linked windows cannot echo. - Incidents unknown to the receiving window are ignored. +## 7a. Native apps over gRPC (named pipe) + +Native side apps join the same in-process agent as the web windows, so they share channels and intents with them. `Bermuda.Fdc3.Grpc` hosts a gRPC service (Kestrel named-pipe transport, HTTP/2 without TLS) that mirrors `IFdc3Commands`; the contract is `src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto`. + +- **Pipe**: `\\.\pipe\bermuda-fdc3-` by default (pipe names are machine-wide, so the user name keeps users apart). Override with `FDC3_GRPC_PIPE`; disable with `FDC3_GRPC_ENABLED=false` (both in `appsettings.json` or the environment). The pipe is current-user-only. +- **Connect**: call `Subscribe(app_id)`. `app_id` MUST be in the App Directory, else the call fails with `AppNotFound`. The first stream message is `connected { instance_id }`; context, intent and API-event deliveries follow (`ContextEvent`, `IntentEvent`, `ApiEvent`, mirroring `Fdc3*Event`). +- **Calls**: every other RPC carries the `x-fdc3-instance` header (the `instance_id`) and must use the same pipe connection as the stream, else `AccessDenied`. +- **Lifetime**: the stream is the app instance. When it ends (cancelled, process exit, pipe closed) the instance is disconnected like a closed window. +- **Contexts** are JSON text (`*_json` fields). **Errors** are gRPC errors whose status *detail* is the `Fdc3Errors` string (`NoChannelFound`, `MalformedContext`, …); the code is a coarse mapping (e.g. `NotFound`, `InvalidArgument`, `PermissionDenied`). +- **Client**: any gRPC stack that can dial a named pipe. `src/Bermuda.Fdc3.Grpc.Tests/Fdc3PipeClient.cs` is a ~100-line .NET reference (`SocketsHttpHandler.ConnectCallback` returning a `NamedPipeClientStream`). +- Limitations: native apps are not launched by the agent (`open`/intents can target them only while connected), and web windows are still the only apps with launch URLs. + ## 8. Known limitations - **No origin check.** Any page loaded in a host window gets `window.fdc3` and can issue `fdc3.*` commands as that window's app identity (and, as before this feature, can use the host's other bridges). Fine while the host only loads trusted app URLs; restrict by origin before navigating to untrusted content. @@ -155,6 +167,7 @@ Rejections are `Error`s whose `message` is the standard FDC3 error string; over | `open` and metadata (4.5) | `DesktopAgentTests`: open with context, unknown app, `getInfo`; `ReviewRegressionTests`: contextless `open` waits for connect, times out | | Wire contract (5) | `IpcDispatchTests`: command naming, every command discovered, payload binding, `InvalidArguments`, unwrapped errors | | `window.fdc3` (4.2, frontend) | `hostDesktopAgent.test.ts` (listener routing, results, validation, `getResult` caching), `preload.test.ts` | +| gRPC pipe (7a) | `Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests`: unknown app rejected, instance lifetime, channel broadcast web↔pipe and pipe↔pipe, intent round trip both directions, error details, instance-header/connection binding | | End to end, live app | `e2e/fdc3.spec.ts`: `getInfo`, two linked windows sharing selection and an intent to a specific instance, and a plain-HTML app receiving `open` with a context (proves the preload) | Run: `dotnet test`, `pnpm test`, and `pnpm e2e` (needs the app: `aspire run`). diff --git a/src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj b/src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj new file mode 100644 index 0000000..0482983 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + + diff --git a/src/Bermuda.Fdc3.Grpc.Tests/Fdc3PipeClient.cs b/src/Bermuda.Fdc3.Grpc.Tests/Fdc3PipeClient.cs new file mode 100644 index 0000000..15588e5 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc.Tests/Fdc3PipeClient.cs @@ -0,0 +1,118 @@ +using System.IO.Pipes; +using System.Net.Http; +using System.Threading.Channels; +using Bermuda.Fdc3.Grpc.Proto; +using Grpc.Core; +using Grpc.Net.Client; + +namespace Bermuda.Fdc3.Grpc.Tests; + +/// +/// A minimal native FDC3 app: connects to Bermuda's named pipe, subscribes as +/// appId and exposes the generated client plus the agent's pushed +/// events. This is the pattern a real side app follows (see docs/fdc3.md). +/// +public sealed class Fdc3PipeClient : IAsyncDisposable +{ + private readonly GrpcChannel _channel; + private readonly CancellationTokenSource _lifetime = new(); + private readonly Channel _events = Channel.CreateUnbounded(); + private readonly Task _pump; + private int _disposed; + + private Fdc3PipeClient(GrpcChannel channel, Fdc3Agent.Fdc3AgentClient rpc, string instanceId, string appId, + AsyncServerStreamingCall stream) + { + _channel = channel; + Rpc = rpc; + InstanceId = instanceId; + AppId = appId; + Headers = new Metadata { { Fdc3Headers.Instance, instanceId } }; + _pump = Pump(stream); + } + + public Fdc3Agent.Fdc3AgentClient Rpc { get; } + public string InstanceId { get; } + public string AppId { get; } + + /// Pass as headers: to every call other than Subscribe. + public Metadata Headers { get; } + + /// Throws (detail = FDC3 error string) if the agent rejects the app id. + public static async Task ConnectAsync(string pipeName, string appId, CancellationToken cancellationToken = default) + { + var handler = new SocketsHttpHandler + { + ConnectCallback = async (_, token) => + { + var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + try + { + await pipe.ConnectAsync(token); + return pipe; + } + catch + { + await pipe.DisposeAsync(); + throw; + } + }, + }; + var channel = GrpcChannel.ForAddress("http://pipe.invalid", new GrpcChannelOptions { HttpHandler = handler }); + try + { + var rpc = new Fdc3Agent.Fdc3AgentClient(channel); + var stream = rpc.Subscribe(new SubscribeRequest { AppId = appId }, cancellationToken: cancellationToken); + if (!await stream.ResponseStream.MoveNext(cancellationToken) || stream.ResponseStream.Current.Connected is not { } connected) + throw new InvalidOperationException("The agent closed the stream before connecting."); + return new Fdc3PipeClient(channel, rpc, connected.InstanceId, connected.AppId, stream); + } + catch + { + channel.Dispose(); + throw; + } + } + + private async Task Pump(AsyncServerStreamingCall stream) + { + try + { + while (await stream.ResponseStream.MoveNext(_lifetime.Token)) + _events.Writer.TryWrite(stream.ResponseStream.Current); + _events.Writer.TryComplete(); + } + catch (Exception ex) + { + _events.Writer.TryComplete(ex); + } + finally + { + stream.Dispose(); + } + } + + /// The next event the agent pushed; throws if none arrives. + public async Task NextEventAsync(TimeSpan? timeout = null) + { + using var cts = new CancellationTokenSource(timeout ?? TimeSpan.FromSeconds(5)); + try + { + return await _events.Reader.ReadAsync(cts.Token); + } + catch (OperationCanceledException) + { + throw new TimeoutException("No FDC3 event arrived."); + } + } + + /// Ends the Subscribe stream, which disconnects the instance. + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) == 1) return; + await _lifetime.CancelAsync(); + try { await _pump; } catch { /* the stream was cancelled */ } + _channel.Dispose(); + _lifetime.Dispose(); + } +} diff --git a/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs b/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs new file mode 100644 index 0000000..0ee2dbe --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs @@ -0,0 +1,250 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using Bermuda.Fdc3.Grpc.Proto; +using Bermuda.IpcContract; +using Google.Protobuf.WellKnownTypes; +using Grpc.Core; + +namespace Bermuda.Fdc3.Grpc.Tests; + +/// Real named pipe, real Kestrel, real gRPC: native clients next to an in-process (web-window-style) connection. +public sealed class PipeIntegrationTests : IAsyncLifetime +{ + private const string AppD = """ + { + "applications": [ + { "appId": "native-app", "title": "Native" }, + { + "appId": "incidents", + "title": "Incidents", + "interop": { "intents": { "listensFor": { + "ViewIncident": { "contexts": ["bermuda.incident"], "resultType": "fdc3.contact" } + } } } + }, + { + "appId": "web-app", + "title": "Web", + "interop": { "intents": { "listensFor": { + "ViewMap": { "contexts": ["bermuda.incident"] } + } } } + } + ] + } + """; + + private const string Incident = """{ "type": "bermuda.incident", "id": { "incidentId": "7" } }"""; + + private readonly DesktopAgent _agent = new(AppDirectory.Parse(AppD), launchTimeout: TimeSpan.FromSeconds(2)); + private readonly string _pipe = "bermuda-fdc3-test-" + Guid.NewGuid().ToString("N"); + private readonly List _clients = []; + private Fdc3GrpcHost _host = null!; + + public async Task InitializeAsync() => _host = await Fdc3GrpcHost.StartAsync(_agent, _pipe); + + public async Task DisposeAsync() + { + foreach (var client in _clients) await client.DisposeAsync(); + await _host.DisposeAsync(); + } + + private async Task ConnectAsync(string appId) + { + var client = await Fdc3PipeClient.ConnectAsync(_pipe, appId); + _clients.Add(client); + return client; + } + + private static JsonElement Json(string json) => JsonSerializer.Deserialize(json); + + [Fact] + public async Task Rejects_an_app_id_that_is_not_in_the_app_directory() + { + var ex = await Assert.ThrowsAsync(() => Fdc3PipeClient.ConnectAsync(_pipe, "nobody")); + + Assert.Equal(StatusCode.NotFound, ex.StatusCode); + Assert.Equal(Fdc3Errors.AppNotFound, ex.Status.Detail); + } + + [Fact] + public async Task Connecting_registers_an_instance_that_is_removed_when_the_client_goes_away() + { + var client = await ConnectAsync("native-app"); + using var observer = _agent.Connect("web-app", new RecordingSink()); + + var instances = observer.FindInstances(new Fdc3AppIdentifier("native-app")); + Assert.Equal(client.InstanceId, Assert.Single(instances).InstanceId); + + var info = await client.Rpc.GetInfoAsync(new Empty(), client.Headers); + Assert.Equal("2.2", info.Fdc3Version); + Assert.Equal("native-app", info.AppMetadata.AppId); + Assert.Equal(client.InstanceId, info.AppMetadata.InstanceId); + + await client.DisposeAsync(); + await EventuallyAsync(() => observer.FindInstances(new Fdc3AppIdentifier("native-app")).Length == 0); + } + + [Fact] + public async Task Channel_broadcast_flows_between_a_pipe_client_and_an_in_process_connection() + { + var native = await ConnectAsync("native-app"); + var webSink = new RecordingSink(); + using var web = _agent.Connect("web-app", webSink); + + await native.Rpc.JoinUserChannelAsync(new ChannelIdRequest { ChannelId = "fdc3.channel.1" }, native.Headers); + await native.Rpc.AddContextListenerAsync( + new AddContextListenerRequest { ListenerId = "n1", ContextType = "bermuda.incident" }, native.Headers); + web.JoinUserChannel(new Fdc3ChannelIdRequest("fdc3.channel.1")); + web.AddContextListener(new Fdc3AddContextListenerRequest("w1", null, "bermuda.incident")); + + // web -> pipe + web.Broadcast(new Fdc3BroadcastRequest(null, Json(Incident))); + var received = (await native.NextEventAsync()).Context; + Assert.Equal("n1", received.ListenerId); + Assert.Equal("bermuda.incident", Json(received.ContextJson).GetProperty("type").GetString()); + Assert.Equal("web-app", received.Source.AppId); + + // pipe -> web + await native.Rpc.BroadcastAsync(new BroadcastRequest { ContextJson = """{ "type": "bermuda.incident", "id": { "incidentId": "9" } }""" }, native.Headers); + var delivered = await webSink.NextAsync(); + Assert.Equal("w1", delivered.ListenerId); + Assert.Equal("9", delivered.Context.GetProperty("id").GetProperty("incidentId").GetString()); + Assert.Equal("native-app", delivered.Source!.AppId); + + // a late joiner on the channel sees the current context + var current = await native.Rpc.GetCurrentContextAsync( + new GetCurrentContextRequest { ChannelId = "fdc3.channel.1" }, native.Headers); + Assert.Contains("\"9\"", current.ContextJson); + } + + [Fact] + public async Task Two_pipe_clients_share_a_channel() + { + var a = await ConnectAsync("native-app"); + var b = await ConnectAsync("native-app"); + foreach (var c in new[] { a, b }) + { + await c.Rpc.JoinUserChannelAsync(new ChannelIdRequest { ChannelId = "fdc3.channel.2" }, c.Headers); + await c.Rpc.AddContextListenerAsync(new AddContextListenerRequest { ListenerId = "l" }, c.Headers); + } + + await a.Rpc.BroadcastAsync(new BroadcastRequest { ContextJson = Incident }, a.Headers); + + Assert.Equal("l", (await b.NextEventAsync()).Context.ListenerId); + } + + [Fact] + public async Task Intent_round_trip_from_an_in_process_raiser_to_a_pipe_handler() + { + var native = await ConnectAsync("incidents"); + using var web = _agent.Connect("web-app", new RecordingSink()); + await native.Rpc.AddIntentListenerAsync( + new AddIntentListenerRequest { ListenerId = "i1", Intent = "ViewIncident" }, native.Headers); + + var resolution = await web.RaiseIntentAsync(new Fdc3RaiseIntentRequest("ViewIncident", Json(Incident), null)); + Assert.Equal("incidents", resolution.Source.AppId); + + var e = (await native.NextEventAsync()).Intent; + Assert.Equal("i1", e.ListenerId); + Assert.Equal("ViewIncident", e.Intent); + Assert.Equal("web-app", e.Source.AppId); + Assert.Equal(resolution.ResultId, e.ResultId); + + await native.Rpc.SendIntentResultAsync(new SendIntentResultRequest + { + ResultId = e.ResultId, + ContextJson = """{ "type": "fdc3.contact", "name": "Ann" }""", + }, native.Headers); + + var result = await web.GetIntentResultAsync(new Fdc3ResultIdRequest(resolution.ResultId)); + Assert.Equal("Ann", result.Context!.Value.GetProperty("name").GetString()); + } + + [Fact] + public async Task Intent_round_trip_from_a_pipe_raiser_to_an_in_process_handler() + { + var native = await ConnectAsync("native-app"); + var webSink = new RecordingSink(); + using var web = _agent.Connect("web-app", webSink); + web.AddIntentListener(new Fdc3AddIntentListenerRequest("h1", "ViewMap")); + + var resolution = await native.Rpc.RaiseIntentAsync( + new RaiseIntentRequest { Intent = "ViewMap", ContextJson = Incident }, native.Headers); + Assert.Equal("ViewMap", resolution.Intent); + + var delivered = await webSink.NextAsync(); + Assert.Equal("native-app", delivered.Source!.AppId); + web.SendIntentResult(new Fdc3SendIntentResultRequest( + delivered.ResultId, Json("""{ "type": "fdc3.contact", "name": "Bo" }"""), null, null)); + + var result = await native.Rpc.GetIntentResultAsync(new ResultIdRequest { ResultId = resolution.ResultId }, native.Headers); + Assert.Equal("Bo", Json(result.ContextJson).GetProperty("name").GetString()); + } + + [Fact] + public async Task Errors_carry_the_fdc3_error_string_as_the_status_detail() + { + var native = await ConnectAsync("native-app"); + + var unknownChannel = await Assert.ThrowsAsync(async () => + await native.Rpc.JoinUserChannelAsync(new ChannelIdRequest { ChannelId = "nope" }, native.Headers)); + Assert.Equal(Fdc3Errors.NoChannelFound, unknownChannel.Status.Detail); + + var noTarget = await Assert.ThrowsAsync(async () => + await native.Rpc.RaiseIntentAsync(new RaiseIntentRequest { Intent = "Nothing", ContextJson = Incident }, native.Headers)); + Assert.Equal(Fdc3Errors.NoAppsFound, noTarget.Status.Detail); + + var malformed = await Assert.ThrowsAsync(async () => + await native.Rpc.BroadcastAsync(new BroadcastRequest { ContextJson = "{ not json" }, native.Headers)); + Assert.Equal(Fdc3Errors.MalformedContext, malformed.Status.Detail); + Assert.Equal(StatusCode.InvalidArgument, malformed.StatusCode); + } + + [Fact] + public async Task Calls_without_a_valid_instance_header_are_denied() + { + var native = await ConnectAsync("native-app"); + + var missing = await Assert.ThrowsAsync(async () => await native.Rpc.GetInfoAsync(new Empty())); + Assert.Equal(Fdc3Errors.AccessDenied, missing.Status.Detail); + + var wrong = await Assert.ThrowsAsync(async () => + await native.Rpc.GetInfoAsync(new Empty(), new Metadata { { Fdc3Headers.Instance, "someone-else" } })); + Assert.Equal(StatusCode.PermissionDenied, wrong.StatusCode); + } + + [Fact] + public async Task An_instance_id_does_not_work_from_another_pipe_connection() + { + var native = await ConnectAsync("native-app"); + var other = await ConnectAsync("native-app"); + + var ex = await Assert.ThrowsAsync(async () => + await other.Rpc.GetInfoAsync(new Empty(), native.Headers)); + + Assert.Equal(Fdc3Errors.AccessDenied, ex.Status.Detail); + } + + private static async Task EventuallyAsync(Func condition) + { + var deadline = DateTime.UtcNow.AddSeconds(5); + while (!condition()) + { + if (DateTime.UtcNow > deadline) throw new TimeoutException("Condition not met."); + await Task.Delay(25); + } + } + + private sealed class RecordingSink : IFdc3AppSink + { + private readonly BlockingCollection _messages = []; + + public void Post(object message) => _messages.Add(message); + + public Task NextAsync() => Task.Run(() => + { + if (!_messages.TryTake(out var message, TimeSpan.FromSeconds(5))) + throw new TimeoutException("No message arrived."); + return Assert.IsType(message); + }); + } +} diff --git a/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj b/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj new file mode 100644 index 0000000..8364d88 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + enable + enable + Bermuda.Fdc3.Grpc + Bermuda.Fdc3.Grpc + + + + + + + + + + + + + + + + + diff --git a/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs b/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs new file mode 100644 index 0000000..39582eb --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs @@ -0,0 +1,206 @@ +using System.Collections.Concurrent; +using System.Threading.Channels; +using Bermuda.Fdc3.Grpc.Proto; +using Google.Protobuf.WellKnownTypes; +using Grpc.Core; + +namespace Bermuda.Fdc3.Grpc; + +/// Request header carrying the instance id from the Connected event. +public static class Fdc3Headers +{ + public const string Instance = "x-fdc3-instance"; +} + +/// Instances currently subscribed through gRPC, and the pipe connection each belongs to. +internal sealed class Fdc3ConnectionRegistry +{ + private readonly ConcurrentDictionary _live = new(); + + public void Add(Fdc3Connection connection, string transportConnectionId) => + _live[connection.InstanceId] = (connection, transportConnectionId); + + public void Remove(string instanceId) => _live.TryRemove(instanceId, out _); + + public int Count => _live.Count; + + /// The caller's connection; only valid on the pipe connection it subscribed on. + public Fdc3Connection Resolve(ServerCallContext context) + { + var instance = context.RequestHeaders.GetValue(Fdc3Headers.Instance); + var transportId = context.GetHttpContext().Connection.Id; + if (instance is null || !_live.TryGetValue(instance, out var entry) || entry.TransportConnectionId != transportId) + throw new Fdc3Exception(Fdc3Errors.AccessDenied); + return entry.Connection; + } +} + +/// Queues the agent's deliveries for the Subscribe stream. +internal sealed class ChannelSink : IFdc3AppSink +{ + private readonly Channel _events = Channel.CreateUnbounded( + new UnboundedChannelOptions { SingleReader = true }); + + public ChannelReader Reader => _events.Reader; + + public void Post(object message) + { + if (Mapping.ToProtoEvent(message) is { } e) _events.Writer.TryWrite(e); + } + + public void Complete() => _events.Writer.TryComplete(); +} + +/// +/// The gRPC face of . A Subscribe stream is +/// one app instance; its other RPCs are served by that instance's +/// . s become gRPC +/// errors in . +/// +internal sealed class Fdc3AgentService(DesktopAgent agent, Fdc3ConnectionRegistry registry) : Fdc3Agent.Fdc3AgentBase +{ + private static readonly Empty Done = new(); + + public override async Task Subscribe(SubscribeRequest request, IServerStreamWriter responseStream, ServerCallContext context) + { + if (string.IsNullOrWhiteSpace(request.AppId)) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + if (agent.Directory.Find(request.AppId) is not { } app) throw new Fdc3Exception(Fdc3Errors.AppNotFound); + + var sink = new ChannelSink(); + // The directory's casing wins, so instances of one app always share an AppId. + using var connection = agent.Connect(app.AppId, sink); + registry.Add(connection, context.GetHttpContext().Connection.Id); + try + { + await responseStream.WriteAsync(new AgentEvent + { + Connected = new Connected { InstanceId = connection.InstanceId, AppId = app.AppId }, + }); + await foreach (var e in sink.Reader.ReadAllAsync(context.CancellationToken)) + await responseStream.WriteAsync(e); + } + catch (OperationCanceledException) + { + // Client went away (or the host is stopping): fall through to disconnect. + } + finally + { + registry.Remove(connection.InstanceId); + sink.Complete(); + } + } + + private Fdc3Connection Caller(ServerCallContext context) => registry.Resolve(context); + + public override Task GetInfo(Empty request, ServerCallContext context) => + Task.FromResult(Mapping.ToProto(Caller(context).GetInfo())); + + public override Task GetAppMetadata(AppIdentifier request, ServerCallContext context) => + Task.FromResult(Mapping.ToProto(Caller(context).GetAppMetadata(Mapping.ToContract(request)))); + + public override Task FindInstances(AppIdentifier request, ServerCallContext context) + { + var result = new AppIdentifiers(); + result.Apps.AddRange(Caller(context).FindInstances(Mapping.ToContract(request)).Select(Mapping.ToProto)); + return Task.FromResult(result); + } + + public override async Task Open(OpenRequest request, ServerCallContext context) => + Mapping.ToProto(await Caller(context).OpenAsync(Mapping.ToContract(request))); + + public override Task GetUserChannels(Empty request, ServerCallContext context) + { + var result = new ChannelInfos(); + result.Channels.AddRange(Caller(context).GetUserChannels().Select(Mapping.ToProto)); + return Task.FromResult(result); + } + + public override Task JoinUserChannel(ChannelIdRequest request, ServerCallContext context) + { + Caller(context).JoinUserChannel(Mapping.ToContract(request)); + return Task.FromResult(Done); + } + + public override Task LeaveCurrentChannel(Empty request, ServerCallContext context) + { + Caller(context).LeaveCurrentChannel(); + return Task.FromResult(Done); + } + + public override Task GetCurrentChannel(Empty request, ServerCallContext context) + { + var result = new CurrentChannel(); + if (Caller(context).GetCurrentChannel() is { } channel) result.Channel = Mapping.ToProto(channel); + return Task.FromResult(result); + } + + public override Task GetOrCreateChannel(ChannelIdRequest request, ServerCallContext context) => + Task.FromResult(Mapping.ToProto(Caller(context).GetOrCreateChannel(Mapping.ToContract(request)))); + + public override Task CreatePrivateChannel(Empty request, ServerCallContext context) => + Task.FromResult(Mapping.ToProto(Caller(context).CreatePrivateChannel())); + + public override Task DisconnectPrivateChannel(ChannelIdRequest request, ServerCallContext context) + { + Caller(context).DisconnectPrivateChannel(Mapping.ToContract(request)); + return Task.FromResult(Done); + } + + public override Task Broadcast(BroadcastRequest request, ServerCallContext context) + { + Caller(context).Broadcast(Mapping.ToContract(request)); + return Task.FromResult(Done); + } + + public override Task GetCurrentContext(GetCurrentContextRequest request, ServerCallContext context) => + Task.FromResult(Mapping.ToCurrentContext(Caller(context).GetCurrentContext(Mapping.ToContract(request)))); + + public override Task AddContextListener(AddContextListenerRequest request, ServerCallContext context) + { + Caller(context).AddContextListener(Mapping.ToContract(request)); + return Task.FromResult(Done); + } + + public override Task AddIntentListener(AddIntentListenerRequest request, ServerCallContext context) + { + Caller(context).AddIntentListener(Mapping.ToContract(request)); + return Task.FromResult(Done); + } + + public override Task AddEventListener(AddEventListenerRequest request, ServerCallContext context) + { + Caller(context).AddEventListener(Mapping.ToContract(request)); + return Task.FromResult(Done); + } + + public override Task Unsubscribe(ListenerIdRequest request, ServerCallContext context) + { + Caller(context).Unsubscribe(Mapping.ToContract(request)); + return Task.FromResult(Done); + } + + public override Task FindIntent(FindIntentRequest request, ServerCallContext context) => + Task.FromResult(Mapping.ToProto(Caller(context).FindIntent(Mapping.ToContract(request)))); + + public override Task FindIntentsByContext(FindIntentsByContextRequest request, ServerCallContext context) + { + var result = new AppIntents(); + result.AppIntents_.AddRange(Caller(context).FindIntentsByContext(Mapping.ToContract(request)).Select(Mapping.ToProto)); + return Task.FromResult(result); + } + + public override async Task RaiseIntent(RaiseIntentRequest request, ServerCallContext context) => + Mapping.ToProto(await Caller(context).RaiseIntentAsync(Mapping.ToContract(request))); + + public override async Task RaiseIntentForContext(RaiseIntentForContextRequest request, ServerCallContext context) => + Mapping.ToProto(await Caller(context).RaiseIntentForContextAsync(Mapping.ToContract(request))); + + public override async Task GetIntentResult(ResultIdRequest request, ServerCallContext context) => + Mapping.ToProto(await Caller(context).GetIntentResultAsync(Mapping.ToContract(request))); + + public override Task SendIntentResult(SendIntentResultRequest request, ServerCallContext context) + { + Caller(context).SendIntentResult(Mapping.ToContract(request)); + return Task.FromResult(Done); + } +} diff --git a/src/Bermuda.Fdc3.Grpc/Fdc3ErrorInterceptor.cs b/src/Bermuda.Fdc3.Grpc/Fdc3ErrorInterceptor.cs new file mode 100644 index 0000000..8573423 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Fdc3ErrorInterceptor.cs @@ -0,0 +1,52 @@ +using Grpc.Core; +using Grpc.Core.Interceptors; + +namespace Bermuda.Fdc3.Grpc; + +/// +/// Turns into an whose +/// status detail is the FDC3 error string (), so +/// native clients branch on ex.Status.Detail exactly as web apps branch +/// on error.message. +/// +internal sealed class Fdc3ErrorInterceptor : Interceptor +{ + public override async Task UnaryServerHandler( + TRequest request, ServerCallContext context, UnaryServerMethod continuation) + { + try + { + return await continuation(request, context); + } + catch (Fdc3Exception ex) + { + throw ToRpc(ex); + } + } + + public override async Task ServerStreamingServerHandler( + TRequest request, IServerStreamWriter responseStream, ServerCallContext context, + ServerStreamingServerMethod continuation) + { + try + { + await continuation(request, responseStream, context); + } + catch (Fdc3Exception ex) + { + throw ToRpc(ex); + } + } + + internal static RpcException ToRpc(Fdc3Exception ex) => new(new Status(CodeFor(ex.Message), ex.Message)); + + private static StatusCode CodeFor(string error) => error switch + { + Fdc3Errors.InvalidArguments or Fdc3Errors.MalformedContext => StatusCode.InvalidArgument, + Fdc3Errors.AccessDenied => StatusCode.PermissionDenied, + Fdc3Errors.AppNotFound or Fdc3Errors.NoAppsFound or Fdc3Errors.NoChannelFound + or Fdc3Errors.TargetAppUnavailable or Fdc3Errors.TargetInstanceUnavailable => StatusCode.NotFound, + Fdc3Errors.AppTimeout => StatusCode.DeadlineExceeded, + _ => StatusCode.FailedPrecondition, + }; +} diff --git a/src/Bermuda.Fdc3.Grpc/Fdc3GrpcHost.cs b/src/Bermuda.Fdc3.Grpc/Fdc3GrpcHost.cs new file mode 100644 index 0000000..9946daf --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Fdc3GrpcHost.cs @@ -0,0 +1,77 @@ +using System.Text.RegularExpressions; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Bermuda.Fdc3.Grpc; + +/// +/// Serves a to native apps over gRPC on a Windows +/// named pipe (Kestrel's named-pipe transport, HTTP/2 without TLS). The pipe +/// is restricted to the current user. Dispose stops the server and +/// disconnects every pipe client's instance. +/// +public sealed class Fdc3GrpcHost : IAsyncDisposable +{ + private readonly WebApplication _app; + + private Fdc3GrpcHost(WebApplication app, string pipeName) + { + _app = app; + PipeName = pipeName; + } + + public string PipeName { get; } + + /// + /// bermuda-fdc3-<user name>. Pipe names are machine-wide, so the + /// user name keeps two signed-in users from sharing (or fighting over) one. + /// + public static string DefaultPipeName { get; } = + "bermuda-fdc3-" + Regex.Replace(Environment.UserName, @"[^A-Za-z0-9_.-]", "_"); + + /// The pipe name (without \\.\pipe\); null = . + public static async Task StartAsync(DesktopAgent agent, string? pipeName = null, CancellationToken cancellationToken = default) + { + pipeName = string.IsNullOrWhiteSpace(pipeName) ? DefaultPipeName : pipeName; + + var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions + { + ContentRootPath = AppContext.BaseDirectory, + }); + // Only the pipe: ignore ASPNETCORE_URLS and friends. + builder.WebHost.UseSetting(WebHostDefaults.ServerUrlsKey, ""); + // Named pipes are Windows-only (this is a Windows desktop host); elsewhere Start fails. +#pragma warning disable CA1416 + builder.WebHost.UseNamedPipes(options => options.CurrentUserOnly = true); +#pragma warning restore CA1416 + builder.WebHost.ConfigureKestrel(kestrel => kestrel.ListenNamedPipe(pipeName, listen => + { + listen.Protocols = HttpProtocols.Http2; + })); + builder.Services.Configure(o => o.ShutdownTimeout = TimeSpan.FromSeconds(2)); + builder.Services.AddSingleton(agent); + builder.Services.AddSingleton(); + builder.Services.AddGrpc(o => o.Interceptors.Add()); + + var app = builder.Build(); + app.MapGrpcService(); + await app.StartAsync(cancellationToken); + return new Fdc3GrpcHost(app, pipeName); + } + + public async ValueTask DisposeAsync() + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + try + { + await _app.StopAsync(timeout.Token); + } + catch (OperationCanceledException) + { + } + await _app.DisposeAsync(); + } +} diff --git a/src/Bermuda.Fdc3.Grpc/Mapping.cs b/src/Bermuda.Fdc3.Grpc/Mapping.cs new file mode 100644 index 0000000..f0fb6dd --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Mapping.cs @@ -0,0 +1,193 @@ +using System.Text.Json; +using Bermuda.IpcContract; +using Proto = Bermuda.Fdc3.Grpc.Proto; + +namespace Bermuda.Fdc3.Grpc; + +/// Converts between the protobuf messages and the Fdc3Contract records. +internal static class Mapping +{ + // Contexts ------------------------------------------------------------------ + + public static JsonElement ParseContext(string? json) + { + if (string.IsNullOrWhiteSpace(json)) throw new Fdc3Exception(Fdc3Errors.MalformedContext); + try + { + return JsonSerializer.Deserialize(json); + } + catch (JsonException) + { + throw new Fdc3Exception(Fdc3Errors.MalformedContext); + } + } + + public static JsonElement? ParseOptionalContext(string? json) => + json is null ? null : ParseContext(json); + + // Requests (proto -> contract) --------------------------------------------------- + + public static Fdc3AppIdentifier ToContract(Proto.AppIdentifier? app) => + app is null ? throw new Fdc3Exception(Fdc3Errors.InvalidArguments) : new(app.AppId, app.HasInstanceId ? app.InstanceId : null); + + public static Fdc3AppIdentifier? ToContractOptional(Proto.AppIdentifier? app) => + app is null ? null : ToContract(app); + + public static Fdc3ChannelIdRequest ToContract(Proto.ChannelIdRequest r) => new(r.ChannelId); + + public static Fdc3BroadcastRequest ToContract(Proto.BroadcastRequest r) => + new(r.HasChannelId ? r.ChannelId : null, ParseContext(r.ContextJson)); + + public static Fdc3GetCurrentContextRequest ToContract(Proto.GetCurrentContextRequest r) => + new(r.ChannelId, r.HasContextType ? r.ContextType : null); + + public static Fdc3AddContextListenerRequest ToContract(Proto.AddContextListenerRequest r) => + new(r.ListenerId, r.HasChannelId ? r.ChannelId : null, r.HasContextType ? r.ContextType : null); + + public static Fdc3AddIntentListenerRequest ToContract(Proto.AddIntentListenerRequest r) => + new(r.ListenerId, r.Intent); + + public static Fdc3AddEventListenerRequest ToContract(Proto.AddEventListenerRequest r) => + new(r.ListenerId, r.HasEventType ? r.EventType : null, r.HasChannelId ? r.ChannelId : null); + + public static Fdc3ListenerIdRequest ToContract(Proto.ListenerIdRequest r) => new(r.ListenerId); + + public static Fdc3FindIntentRequest ToContract(Proto.FindIntentRequest r) => + new(r.Intent, ParseOptionalContext(r.HasContextJson ? r.ContextJson : null), r.HasResultType ? r.ResultType : null); + + public static Fdc3FindIntentsByContextRequest ToContract(Proto.FindIntentsByContextRequest r) => + new(ParseContext(r.ContextJson), r.HasResultType ? r.ResultType : null); + + public static Fdc3OpenRequest ToContract(Proto.OpenRequest r) => + new(ToContract(r.App), ParseOptionalContext(r.HasContextJson ? r.ContextJson : null)); + + public static Fdc3RaiseIntentRequest ToContract(Proto.RaiseIntentRequest r) => + new(r.Intent, ParseContext(r.ContextJson), ToContractOptional(r.App)); + + public static Fdc3RaiseIntentForContextRequest ToContract(Proto.RaiseIntentForContextRequest r) => + new(ParseContext(r.ContextJson), ToContractOptional(r.App)); + + public static Fdc3ResultIdRequest ToContract(Proto.ResultIdRequest r) => new(r.ResultId); + + public static Fdc3SendIntentResultRequest ToContract(Proto.SendIntentResultRequest r) => + new(r.ResultId, ParseOptionalContext(r.HasContextJson ? r.ContextJson : null), r.HasChannelId ? r.ChannelId : null, r.HasError ? r.Error : null); + + // Responses (contract -> proto) ------------------------------------------------- + + public static Proto.AppIdentifier ToProto(Fdc3AppIdentifier a) + { + var app = new Proto.AppIdentifier { AppId = a.AppId }; + if (a.InstanceId is not null) app.InstanceId = a.InstanceId; + return app; + } + + public static Proto.ChannelInfo ToProto(Fdc3ChannelInfo c) + { + var info = new Proto.ChannelInfo { Id = c.Id, Type = c.Type }; + if (c.DisplayMetadata is { } d) + { + var display = new Proto.DisplayMetadata(); + if (d.Name is not null) display.Name = d.Name; + if (d.Color is not null) display.Color = d.Color; + if (d.Glyph is not null) display.Glyph = d.Glyph; + info.DisplayMetadata = display; + } + return info; + } + + public static Proto.AppMetadata ToProto(Fdc3AppMetadata a) + { + var app = new Proto.AppMetadata { AppId = a.AppId }; + if (a.InstanceId is not null) app.InstanceId = a.InstanceId; + if (a.Name is not null) app.Name = a.Name; + if (a.Version is not null) app.Version = a.Version; + if (a.Title is not null) app.Title = a.Title; + if (a.Tooltip is not null) app.Tooltip = a.Tooltip; + if (a.Description is not null) app.Description = a.Description; + if (a.ResultType is not null) app.ResultType = a.ResultType; + return app; + } + + public static Proto.AppIntent ToProto(Fdc3AppIntent a) + { + var metadata = new Proto.IntentMetadata { Name = a.Intent.Name }; + if (a.Intent.DisplayName is not null) metadata.DisplayName = a.Intent.DisplayName; + var intent = new Proto.AppIntent { Intent = metadata }; + intent.Apps.AddRange(a.Apps.Select(ToProto)); + return intent; + } + + public static Proto.ImplementationMetadata ToProto(Fdc3ImplementationMetadata m) + { + var info = new Proto.ImplementationMetadata + { + Fdc3Version = m.Fdc3Version, + Provider = m.Provider, + OptionalFeatures = new Proto.OptionalFeatures + { + OriginatingAppMetadata = m.OptionalFeatures.OriginatingAppMetadata, + UserChannelMembershipApis = m.OptionalFeatures.UserChannelMembershipAPIs, + DesktopAgentBridging = m.OptionalFeatures.DesktopAgentBridging, + }, + AppMetadata = ToProto(m.AppMetadata), + }; + if (m.ProviderVersion is not null) info.ProviderVersion = m.ProviderVersion; + return info; + } + + public static Proto.IntentResolutionInfo ToProto(Fdc3IntentResolutionInfo r) => + new() { Source = ToProto(r.Source), Intent = r.Intent, ResultId = r.ResultId }; + + public static Proto.IntentResultInfo ToProto(Fdc3IntentResultInfo r) + { + var result = new Proto.IntentResultInfo(); + if (r.Context is { } context) result.ContextJson = context.GetRawText(); + if (r.Channel is { } channel) result.Channel = ToProto(channel); + return result; + } + + public static Proto.CurrentContext ToCurrentContext(JsonElement? context) + { + var result = new Proto.CurrentContext(); + if (context is { } value) result.ContextJson = value.GetRawText(); + return result; + } + + // Events (contract -> proto) -------------------------------------------------- + + /// Maps what the agent posts to a sink; null for a message type this transport doesn't know. + public static Proto.AgentEvent? ToProtoEvent(object message) => message switch + { + Fdc3ContextEvent e => new Proto.AgentEvent { Context = ContextEvent(e) }, + Fdc3IntentEvent e => new Proto.AgentEvent { Intent = IntentEvent(e) }, + Fdc3ApiEvent e => new Proto.AgentEvent { Api = ApiEvent(e) }, + _ => null, + }; + + private static Proto.ContextEvent ContextEvent(Fdc3ContextEvent e) + { + var result = new Proto.ContextEvent { ListenerId = e.ListenerId, ContextJson = e.Context.GetRawText() }; + if (e.Source is not null) result.Source = ToProto(e.Source); + return result; + } + + private static Proto.IntentEvent IntentEvent(Fdc3IntentEvent e) + { + var result = new Proto.IntentEvent + { + ListenerId = e.ListenerId, + Intent = e.Intent, + ContextJson = e.Context.GetRawText(), + ResultId = e.ResultId, + }; + if (e.Source is not null) result.Source = ToProto(e.Source); + return result; + } + + private static Proto.ApiEvent ApiEvent(Fdc3ApiEvent e) + { + var result = new Proto.ApiEvent { ListenerId = e.ListenerId, EventType = e.EventType }; + if (e.Details is not null) result.DetailsJson = JsonSerializer.Serialize(e.Details, JsonSerializerOptions.Web); + return result; + } +} diff --git a/src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto b/src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto new file mode 100644 index 0000000..2961f9d --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto @@ -0,0 +1,235 @@ +syntax = "proto3"; + +package bermuda.fdc3.v1; + +import "google/protobuf/empty.proto"; + +option csharp_namespace = "Bermuda.Fdc3.Grpc.Proto"; + +// gRPC mirror of IFdc3Commands (src/Bermuda.IpcContract/Fdc3Contract.cs). +// +// Connection model: one pipe client opens Subscribe(app_id). The first message +// on that stream is `connected` (carrying the new instance_id); the agent's +// context/intent/event deliveries follow. Every other RPC must carry the +// instance_id in the `x-fdc3-instance` request header and travel on the same +// pipe connection. The instance leaves the agent when the Subscribe stream +// ends (cancelled, or the pipe closes). +// +// FDC3 contexts are open-ended JSON objects, carried as JSON text in +// *_json fields. Failures are gRPC errors whose status *detail* is the +// standard FDC3 error string (Fdc3Errors, e.g. "NoChannelFound"). + +service Fdc3Agent { + rpc Subscribe(SubscribeRequest) returns (stream AgentEvent); + + rpc GetInfo(google.protobuf.Empty) returns (ImplementationMetadata); + rpc GetAppMetadata(AppIdentifier) returns (AppMetadata); + rpc FindInstances(AppIdentifier) returns (AppIdentifiers); + rpc Open(OpenRequest) returns (AppIdentifier); + + rpc GetUserChannels(google.protobuf.Empty) returns (ChannelInfos); + rpc JoinUserChannel(ChannelIdRequest) returns (google.protobuf.Empty); + rpc LeaveCurrentChannel(google.protobuf.Empty) returns (google.protobuf.Empty); + rpc GetCurrentChannel(google.protobuf.Empty) returns (CurrentChannel); + rpc GetOrCreateChannel(ChannelIdRequest) returns (ChannelInfo); + rpc CreatePrivateChannel(google.protobuf.Empty) returns (ChannelInfo); + rpc DisconnectPrivateChannel(ChannelIdRequest) returns (google.protobuf.Empty); + + rpc Broadcast(BroadcastRequest) returns (google.protobuf.Empty); + rpc GetCurrentContext(GetCurrentContextRequest) returns (CurrentContext); + rpc AddContextListener(AddContextListenerRequest) returns (google.protobuf.Empty); + rpc AddIntentListener(AddIntentListenerRequest) returns (google.protobuf.Empty); + rpc AddEventListener(AddEventListenerRequest) returns (google.protobuf.Empty); + rpc Unsubscribe(ListenerIdRequest) returns (google.protobuf.Empty); + + rpc FindIntent(FindIntentRequest) returns (AppIntent); + rpc FindIntentsByContext(FindIntentsByContextRequest) returns (AppIntents); + rpc RaiseIntent(RaiseIntentRequest) returns (IntentResolutionInfo); + rpc RaiseIntentForContext(RaiseIntentForContextRequest) returns (IntentResolutionInfo); + rpc GetIntentResult(ResultIdRequest) returns (IntentResultInfo); + rpc SendIntentResult(SendIntentResultRequest) returns (google.protobuf.Empty); +} + +// Shapes --------------------------------------------------------------------- + +message AppIdentifier { + string app_id = 1; + optional string instance_id = 2; +} +message AppIdentifiers { repeated AppIdentifier apps = 1; } + +message DisplayMetadata { + optional string name = 1; + optional string color = 2; + optional string glyph = 3; +} + +// type is 'user' | 'app' | 'private'. +message ChannelInfo { + string id = 1; + string type = 2; + optional DisplayMetadata display_metadata = 3; +} +message ChannelInfos { repeated ChannelInfo channels = 1; } +message CurrentChannel { optional ChannelInfo channel = 1; } +message CurrentContext { optional string context_json = 1; } + +message IntentMetadata { + string name = 1; + optional string display_name = 2; +} + +message AppMetadata { + string app_id = 1; + optional string instance_id = 2; + optional string name = 3; + optional string version = 4; + optional string title = 5; + optional string tooltip = 6; + optional string description = 7; + optional string result_type = 8; +} + +message AppIntent { + IntentMetadata intent = 1; + repeated AppMetadata apps = 2; +} +message AppIntents { repeated AppIntent app_intents = 1; } + +message OptionalFeatures { + bool originating_app_metadata = 1; + bool user_channel_membership_apis = 2; + bool desktop_agent_bridging = 3; +} + +message ImplementationMetadata { + string fdc3_version = 1; + string provider = 2; + optional string provider_version = 3; + OptionalFeatures optional_features = 4; + AppMetadata app_metadata = 5; +} + +message IntentResolutionInfo { + AppIdentifier source = 1; + string intent = 2; + string result_id = 3; +} + +// A handler's result: a context, a channel, or neither (void). +message IntentResultInfo { + optional string context_json = 1; + optional ChannelInfo channel = 2; +} + +// Requests ------------------------------------------------------------------- + +message SubscribeRequest { string app_id = 1; } + +message ChannelIdRequest { string channel_id = 1; } + +// channel_id unset = the caller's current user channel. +message BroadcastRequest { + optional string channel_id = 1; + string context_json = 2; +} + +message GetCurrentContextRequest { + string channel_id = 1; + optional string context_type = 2; +} + +// channel_id unset = follow whichever user channel the caller is joined to. +message AddContextListenerRequest { + string listener_id = 1; + optional string channel_id = 2; + optional string context_type = 3; +} + +message AddIntentListenerRequest { + string listener_id = 1; + string intent = 2; +} + +// channel_id unset = desktop-agent events; event_type unset = all types. +message AddEventListenerRequest { + string listener_id = 1; + optional string event_type = 2; + optional string channel_id = 3; +} + +message ListenerIdRequest { string listener_id = 1; } + +message FindIntentRequest { + string intent = 1; + optional string context_json = 2; + optional string result_type = 3; +} + +message FindIntentsByContextRequest { + string context_json = 1; + optional string result_type = 2; +} + +message OpenRequest { + AppIdentifier app = 1; + optional string context_json = 2; +} + +message RaiseIntentRequest { + string intent = 1; + string context_json = 2; + optional AppIdentifier app = 3; +} + +message RaiseIntentForContextRequest { + string context_json = 1; + optional AppIdentifier app = 2; +} + +message ResultIdRequest { string result_id = 1; } + +// At most one of context_json/channel_id (neither = void); error set instead if the handler threw. +message SendIntentResultRequest { + string result_id = 1; + optional string context_json = 2; + optional string channel_id = 3; + optional string error = 4; +} + +// Agent -> app events (Subscribe stream) --------------------------------------- + +message AgentEvent { + oneof event { + Connected connected = 1; + ContextEvent context = 2; + IntentEvent intent = 3; + ApiEvent api = 4; + } +} + +// First message of every Subscribe stream. +message Connected { + string instance_id = 1; + string app_id = 2; +} + +message ContextEvent { + string listener_id = 1; + string context_json = 2; + optional AppIdentifier source = 3; +} + +message IntentEvent { + string listener_id = 1; + string intent = 2; + string context_json = 3; + optional AppIdentifier source = 4; + string result_id = 5; +} + +message ApiEvent { + string listener_id = 1; + string event_type = 2; + optional string details_json = 3; +} diff --git a/src/Bermuda/App.xaml.cs b/src/Bermuda/App.xaml.cs index 8d32507..a3cffed 100644 --- a/src/Bermuda/App.xaml.cs +++ b/src/Bermuda/App.xaml.cs @@ -1,6 +1,7 @@ using System.IO; using System.Windows; using Bermuda.Fdc3; +using Bermuda.Fdc3.Grpc; using Microsoft.Extensions.Configuration; namespace Bermuda; @@ -25,12 +26,39 @@ protected override void OnStartup(StartupEventArgs e) var fdc3 = new DesktopAgent(directory, launcher); launcher.Agent = fdc3; + StartGrpcHost(config, fdc3); + var window = new MainWindow(config, fdc3, MainAppId); window.Show(); } + /// + /// Lets native apps join the agent over gRPC on a named pipe. Config: + /// FDC3_GRPC_ENABLED (default true) and FDC3_GRPC_PIPE (default per-user, + /// see ). A failure to listen + /// (e.g. the pipe name is taken) must not stop the app. + /// + private void StartGrpcHost(IConfiguration config, DesktopAgent agent) + { + if (bool.TryParse(config["FDC3_GRPC_ENABLED"], out var enabled) && !enabled) return; + try + { + _grpcHost = Task.Run(() => Fdc3GrpcHost.StartAsync(agent, config["FDC3_GRPC_PIPE"])).GetAwaiter().GetResult(); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"FDC3 gRPC pipe host failed to start: {ex}"); + } + } + + private Fdc3GrpcHost? _grpcHost; + protected override void OnExit(ExitEventArgs e) { + if (_grpcHost is { } grpcHost) + { + Task.Run(() => grpcHost.DisposeAsync().AsTask()).Wait(TimeSpan.FromSeconds(6)); + } NotificationService.Clear(); base.OnExit(e); } diff --git a/src/Bermuda/Bermuda.csproj b/src/Bermuda/Bermuda.csproj index 79f0b00..999092f 100644 --- a/src/Bermuda/Bermuda.csproj +++ b/src/Bermuda/Bermuda.csproj @@ -109,6 +109,7 @@ + + + Exe + net10.0 + enable + enable + + + + + + + diff --git a/src/Bermuda.Fdc3.Grpc.Generator/Program.cs b/src/Bermuda.Fdc3.Grpc.Generator/Program.cs new file mode 100644 index 0000000..74b8d02 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc.Generator/Program.cs @@ -0,0 +1,386 @@ +using System.Reflection; +using System.Text; +using System.Text.Json; +using Bermuda.IpcContract; + +// Usage: Bermuda.Fdc3.Grpc.Generator +// +// Contract -> gRPC rules +// record Fdc3Foo(...) -> message Foo (fields numbered in constructor order, so only ever append) +// string / bool -> string / bool; a nullable string becomes `optional` +// JsonElement -> string _json (JSON text); nullable -> `optional` +// object? (event details) -> optional string _json (serialised with the web options) +// record -> message reference; Foo[] -> repeated +// method M(Req) -> Resp -> rpc M(Req) returns (Resp); no parameter / void -> google.protobuf.Empty; +// array / nullable results are wrapped in Response { items | result } +// [IpcType] Fdc3*Event records -> alternatives of AgentEvent's oneof +var outDir = args.Length > 0 ? args[0] : throw new ArgumentException("Pass the output directory."); +Directory.CreateDirectory(outDir); + +var model = new ContractModel(typeof(IFdc3Commands)); +Write("fdc3.proto", new ProtoWriter(model).Generate()); +Write("Fdc3Generated.g.cs", new CSharpWriter(model).Generate()); +return 0; + +void Write(string name, string content) +{ + var path = Path.Combine(outDir, name); + content = content.Replace("\r\n", "\n"); + // Don't touch an unchanged file, so incremental builds stay incremental. + if (!File.Exists(path) || File.ReadAllText(path) != content) File.WriteAllText(path, content); +} + +enum Kind { String, Bool, Json, Object, Message } + +sealed record Field(string ClrName, string ProtoName, string CsName, Kind Kind, bool IsArray, bool Optional, Type? MessageType) +{ + public bool IsScalarOptional => Optional && Kind is Kind.String or Kind.Json or Kind.Object; +} + +sealed record Message(Type Type, string Name, List Fields, ConstructorInfo Constructor); + +sealed record Method(MethodInfo Info, string RpcName, Type? Param, Type? Result, bool ResultIsArray, bool ResultNullable, bool IsAsync, bool IsVoid) +{ + public bool NeedsWrapper => !IsVoid && (ResultIsArray || ResultNullable); + public string WrapperName => RpcName + "Response"; +} + +sealed class ContractModel +{ + private readonly NullabilityInfoContext _nullability = new(); + + public List Messages { get; } = []; + public List Methods { get; } = []; + public List Events { get; } = []; + + public ContractModel(Type commands) + { + foreach (var info in commands.GetMethods()) + { + var parameters = info.GetParameters(); + if (parameters.Length > 1) throw new NotSupportedException($"{info.Name}: at most one parameter."); + + var returnType = info.ReturnType; + var isAsync = false; + if (returnType == typeof(Task)) { returnType = typeof(void); isAsync = true; } + else if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>)) + { + returnType = returnType.GetGenericArguments()[0]; + isAsync = true; + } + + var isVoid = returnType == typeof(void); + var isArray = returnType.IsArray; + var nullable = !isVoid && (Nullable.GetUnderlyingType(returnType) is not null + || (!isAsync && !returnType.IsValueType && _nullability.Create(info.ReturnParameter).ReadState == NullabilityState.Nullable)); + var element = isVoid ? null : isArray ? returnType.GetElementType()! : Nullable.GetUnderlyingType(returnType) ?? returnType; + + if (parameters.Length == 1) Visit(parameters[0].ParameterType); + if (element is not null && element != typeof(JsonElement)) Visit(element); + + var rpcName = info.Name.EndsWith("Async", StringComparison.Ordinal) ? info.Name[..^5] : info.Name; + Methods.Add(new Method(info, rpcName, parameters.Length == 1 ? parameters[0].ParameterType : null, + element, isArray, nullable, isAsync, isVoid)); + } + + foreach (var type in commands.Assembly.GetTypes() + .Where(t => t.GetCustomAttribute() is not null && t.Name.StartsWith("Fdc3", StringComparison.Ordinal) && t.Name.EndsWith("Event", StringComparison.Ordinal)) + .OrderBy(t => t.Name, StringComparer.Ordinal)) + { + Visit(type); + Events.Add(Messages.Single(m => m.Type == type)); + } + } + + public static string MessageName(Type type) => type.Name.StartsWith("Fdc3", StringComparison.Ordinal) ? type.Name[4..] : type.Name; + + public Message Of(Type type) => Messages.Single(m => m.Type == type); + + private void Visit(Type type) + { + if (Messages.Any(m => m.Type == type)) return; + if (type.Assembly != typeof(IFdc3Commands).Assembly || type.IsPrimitive || type == typeof(string)) + throw new NotSupportedException($"{type}: only contract records can be messages."); + + var ctor = type.GetConstructors().Single(); + var message = new Message(type, MessageName(type), [], ctor); + Messages.Add(message); + + foreach (var p in ctor.GetParameters()) + { + var isArray = p.ParameterType.IsArray; + var t = isArray ? p.ParameterType.GetElementType()! : p.ParameterType; + var underlying = Nullable.GetUnderlyingType(t); + var optional = underlying is not null || (!t.IsValueType && _nullability.Create(p).ReadState == NullabilityState.Nullable); + t = underlying ?? t; + + var snake = Naming.Snake(p.Name!); + if (t == typeof(string)) message.Fields.Add(new(p.Name!, snake, Naming.Pascal(snake), Kind.String, isArray, optional, null)); + else if (t == typeof(bool)) message.Fields.Add(new(p.Name!, snake, Naming.Pascal(snake), Kind.Bool, isArray, false, null)); + else if (t == typeof(JsonElement)) message.Fields.Add(new(p.Name!, snake + "_json", Naming.Pascal(snake + "_json"), Kind.Json, isArray, optional, null)); + else if (t == typeof(object)) message.Fields.Add(new(p.Name!, snake + "_json", Naming.Pascal(snake + "_json"), Kind.Object, isArray, optional, null)); + else + { + Visit(t); + message.Fields.Add(new(p.Name!, snake, Naming.Pascal(snake), Kind.Message, isArray, optional, t)); + } + } + } +} + +static class Naming +{ + /// PascalCase -> snake_case the way protoc round-trips it ("APIs" -> "ap_is"). + public static string Snake(string name) + { + var sb = new StringBuilder(); + for (var i = 0; i < name.Length; i++) + { + var c = name[i]; + if (char.IsUpper(c)) + { + var prevLowerOrDigit = i > 0 && (char.IsLower(name[i - 1]) || char.IsDigit(name[i - 1])); + var acronymEnd = i > 0 && char.IsUpper(name[i - 1]) && i + 1 < name.Length && char.IsLower(name[i + 1]); + if (prevLowerOrDigit || acronymEnd) sb.Append('_'); + sb.Append(char.ToLowerInvariant(c)); + } + else sb.Append(c); + } + return sb.ToString(); + } + + /// protoc's C# property name for a proto field. + public static string Pascal(string snake) => + string.Concat(snake.Split('_', StringSplitOptions.RemoveEmptyEntries).Select(s => char.ToUpperInvariant(s[0]) + s[1..])); +} + +sealed class ProtoWriter(ContractModel model) +{ + private readonly StringBuilder _sb = new(); + + public string Generate() + { + Line("// "); + Line("// Generated by Bermuda.Fdc3.Grpc.Generator from IFdc3Commands (src/Bermuda.IpcContract/Fdc3Contract.cs)."); + Line("// Do not edit: change the contract and rebuild Bermuda.Fdc3.Grpc."); + Line("// "); + Line("syntax = \"proto3\";"); + Line(); + Line("package bermuda.fdc3.v1;"); + Line(); + Line("import \"google/protobuf/empty.proto\";"); + Line(); + Line("option csharp_namespace = \"Bermuda.Fdc3.Grpc.Proto\";"); + Line(); + Line("// Connection model: one pipe client opens Subscribe(app_id). The first message on that stream is"); + Line("// `connected` (carrying the new instance_id); the agent's deliveries follow. Every other RPC must carry"); + Line("// the instance_id in the `x-fdc3-instance` request header and use the same pipe connection. The instance"); + Line("// leaves the agent when the Subscribe stream ends. Contexts are JSON text (*_json fields); failures are"); + Line("// gRPC errors whose status detail is the FDC3 error string (Fdc3Errors)."); + Line("service Fdc3Agent {"); + Line(" rpc Subscribe(SubscribeRequest) returns (stream AgentEvent);"); + Line(); + foreach (var m in model.Methods) + Line($" rpc {m.RpcName}({RequestType(m)}) returns ({ResponseType(m)});"); + Line("}"); + Line(); + + foreach (var message in model.Messages) WriteMessage(message); + + foreach (var m in model.Methods.Where(m => m.NeedsWrapper)) + { + Line($"message {m.WrapperName} {{"); + if (m.ResultIsArray) Line($" repeated {ElementType(m)} items = 1;"); + else if (m.Result == typeof(JsonElement)) Line(" optional string result_json = 1;"); + else Line($" {ElementType(m)} result = 1;"); + Line("}"); + Line(); + } + + Line("message SubscribeRequest { string app_id = 1; }"); + Line(); + Line("// First message of every Subscribe stream."); + Line("message Connected {"); + Line(" string instance_id = 1;"); + Line(" string app_id = 2;"); + Line("}"); + Line(); + Line("message AgentEvent {"); + Line(" oneof event {"); + Line(" Connected connected = 1;"); + var number = 2; + foreach (var e in model.Events) + Line($" {e.Name} {EventField(e)} = {number++};"); + Line(" }"); + Line("}"); + return _sb.ToString(); + } + + public static string EventField(Message e) => Naming.Snake(e.Name.EndsWith("Event", StringComparison.Ordinal) ? e.Name[..^5] : e.Name); + + public static string RequestType(Method m) => m.Param is null ? "google.protobuf.Empty" : ContractModel.MessageName(m.Param); + + public static string ResponseType(Method m) => + m.IsVoid ? "google.protobuf.Empty" : m.NeedsWrapper ? m.WrapperName : ContractModel.MessageName(m.Result!); + + private static string ElementType(Method m) => m.Result == typeof(JsonElement) ? "string" : ContractModel.MessageName(m.Result!); + + private void WriteMessage(Message message) + { + Line($"message {message.Name} {{"); + var number = 1; + foreach (var f in message.Fields) + { + var type = f.Kind switch + { + Kind.String or Kind.Json or Kind.Object => "string", + Kind.Bool => "bool", + _ => ContractModel.MessageName(f.MessageType!), + }; + var prefix = f.IsArray ? "repeated " : f.IsScalarOptional ? "optional " : ""; + Line($" {prefix}{type} {f.ProtoName} = {number++};"); + } + Line("}"); + Line(); + } + + private void Line(string text = "") => _sb.Append(text).Append('\n'); +} + +sealed class CSharpWriter(ContractModel model) +{ + private readonly StringBuilder _sb = new(); + private int _indent; + + public string Generate() + { + L("// "); + L("// Generated by Bermuda.Fdc3.Grpc.Generator from IFdc3Commands. Do not edit."); + L("// "); + L("#nullable enable"); + L("using System.Text.Json;"); + L("using Bermuda.IpcContract;"); + L("using Google.Protobuf.WellKnownTypes;"); + L("using Grpc.Core;"); + L("using Proto = Bermuda.Fdc3.Grpc.Proto;"); + L(); + L("namespace Bermuda.Fdc3.Grpc;"); + L(); + L("internal static class GeneratedMapping"); + Open(); + foreach (var message in model.Messages) + { + if (!model.Events.Contains(message)) WriteToContract(message); + WriteToProto(message); + } + + L("/// Maps what the agent posts to a sink; null for a message type this transport doesn't know."); + L("public static Proto.AgentEvent? ToProtoEvent(object message) => message switch"); + Open(); + foreach (var e in model.Events) + L($"{e.Type.Name} e => new Proto.AgentEvent {{ {Naming.Pascal(ProtoWriter.EventField(e))} = ToProto(e) }},"); + L("_ => null,"); + Close(";"); + Close(); + L(); + + L("internal sealed partial class Fdc3AgentService"); + Open(); + foreach (var m in model.Methods) WriteRpc(m); + Close(); + return _sb.ToString(); + } + + private void WriteToContract(Message message) + { + var type = message.Type.Name; + L($"public static {type} ToContract(Proto.{message.Name}? p)"); + Open(); + L("if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments);"); + L($"return new {type}("); + _indent++; + var args = message.Constructor.GetParameters().Select((_, i) => ToContractArg(message.Fields[i])).ToList(); + for (var i = 0; i < args.Count; i++) L(args[i] + (i < args.Count - 1 ? "," : ");")); + _indent--; + Close(); + L(); + } + + private static string ToContractArg(Field f) + { + var p = "p." + f.CsName; + var has = "p.Has" + f.CsName; + if (f.IsArray) return $"{p}.Select(ToContract).ToArray()"; + return f.Kind switch + { + Kind.String => f.Optional ? $"{has} ? {p} : null" : p, + Kind.Bool => p, + Kind.Json => f.Optional ? $"{has} ? Mapping.ParseContext({p}) : null" : $"Mapping.ParseContext({p})", + Kind.Object => throw new NotSupportedException("object fields only flow agent -> app."), + _ => f.Optional ? $"{p} is null ? null : ToContract({p})" : $"ToContract({p})", + }; + } + + private void WriteToProto(Message message) + { + L($"public static Proto.{message.Name} ToProto({message.Type.Name} r)"); + Open(); + L($"var m = new Proto.{message.Name}();"); + foreach (var f in message.Fields) + { + var r = "r." + f.ClrName[..1].ToUpperInvariant() + f.ClrName[1..]; + var m = "m." + f.CsName; + if (f.IsArray) { L($"{m}.AddRange({r}.Select(ToProto));"); continue; } + var value = f.Kind switch + { + Kind.String or Kind.Bool => r, + Kind.Json => $"{r}{(f.Optional ? ".Value" : "")}.GetRawText()", + Kind.Object => $"JsonSerializer.Serialize({r}, JsonSerializerOptions.Web)", + _ => $"ToProto({r}{(f.MessageType!.IsValueType ? "" : "")})", + }; + L(f.Optional ? $"if ({r} is not null) {m} = {value};" : $"{m} = {value};"); + } + L("return m;"); + Close(); + L(); + } + + private void WriteRpc(Method m) + { + var req = ProtoWriter.RequestType(m).Replace("google.protobuf.Empty", "Empty"); + var resp = ProtoWriter.ResponseType(m).Replace("google.protobuf.Empty", "Empty"); + var respType = resp == "Empty" ? "Empty" : "Proto." + resp; + var reqType = req == "Empty" ? "Empty" : "Proto." + req; + var call = $"Caller(context).{m.Info.Name}({(m.Param is null ? "" : "GeneratedMapping.ToContract(request)")})"; + + L($"public override {(m.IsAsync ? "async " : "")}Task<{respType}> {m.RpcName}({reqType} request, ServerCallContext context)"); + Open(); + if (m.IsVoid) + { + L(m.IsAsync ? $"await {call};" : $"{call};"); + L(m.IsAsync ? "return new Empty();" : "return Task.FromResult(new Empty());"); + Close(); + L(); + return; + } + + L($"var result = {(m.IsAsync ? "await " : "")}{call};"); + var ret = new StringBuilder(); + if (!m.NeedsWrapper) ret.Append("GeneratedMapping.ToProto(result)"); + if (m.NeedsWrapper) + { + L($"var response = new Proto.{m.WrapperName}();"); + if (m.ResultIsArray) L("response.Items.AddRange(result.Select(GeneratedMapping.ToProto));"); + else if (m.Result == typeof(JsonElement)) L("if (result is { } value) response.ResultJson = value.GetRawText();"); + else L("if (result is not null) response.Result = GeneratedMapping.ToProto(result);"); + ret.Append("response"); + } + L(m.IsAsync ? $"return {ret};" : $"return Task.FromResult({ret});"); + Close(); + L(); + } + + private void Open() { L("{"); _indent++; } + private void Close(string suffix = "") { _indent--; L("}" + suffix); } + private void L(string text = "") => _sb.Append(text.Length == 0 ? "" : new string(' ', _indent * 4) + text).Append('\n'); +} diff --git a/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs b/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs index 0ee2dbe..ffb6325 100644 --- a/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs +++ b/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs @@ -113,7 +113,7 @@ await native.Rpc.AddContextListenerAsync( // a late joiner on the channel sees the current context var current = await native.Rpc.GetCurrentContextAsync( new GetCurrentContextRequest { ChannelId = "fdc3.channel.1" }, native.Headers); - Assert.Contains("\"9\"", current.ContextJson); + Assert.Contains("\"9\"", current.ResultJson); } [Fact] diff --git a/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj b/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj index 8364d88..40999aa 100644 --- a/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj +++ b/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj @@ -15,9 +15,26 @@ - + + + + + + + + + + diff --git a/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs b/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs index 39582eb..20424ff 100644 --- a/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs +++ b/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs @@ -45,7 +45,7 @@ internal sealed class ChannelSink : IFdc3AppSink public void Post(object message) { - if (Mapping.ToProtoEvent(message) is { } e) _events.Writer.TryWrite(e); + if (GeneratedMapping.ToProtoEvent(message) is { } e) _events.Writer.TryWrite(e); } public void Complete() => _events.Writer.TryComplete(); @@ -53,11 +53,11 @@ public void Post(object message) /// /// The gRPC face of . A Subscribe stream is -/// one app instance; its other RPCs are served by that instance's +/// one app instance; its other RPCs (generated, see Generated/Fdc3Generated.g.cs) are served by that instance's /// . s become gRPC /// errors in . /// -internal sealed class Fdc3AgentService(DesktopAgent agent, Fdc3ConnectionRegistry registry) : Fdc3Agent.Fdc3AgentBase +internal sealed partial class Fdc3AgentService(DesktopAgent agent, Fdc3ConnectionRegistry registry) : Fdc3Agent.Fdc3AgentBase { private static readonly Empty Done = new(); @@ -91,116 +91,4 @@ await responseStream.WriteAsync(new AgentEvent } private Fdc3Connection Caller(ServerCallContext context) => registry.Resolve(context); - - public override Task GetInfo(Empty request, ServerCallContext context) => - Task.FromResult(Mapping.ToProto(Caller(context).GetInfo())); - - public override Task GetAppMetadata(AppIdentifier request, ServerCallContext context) => - Task.FromResult(Mapping.ToProto(Caller(context).GetAppMetadata(Mapping.ToContract(request)))); - - public override Task FindInstances(AppIdentifier request, ServerCallContext context) - { - var result = new AppIdentifiers(); - result.Apps.AddRange(Caller(context).FindInstances(Mapping.ToContract(request)).Select(Mapping.ToProto)); - return Task.FromResult(result); - } - - public override async Task Open(OpenRequest request, ServerCallContext context) => - Mapping.ToProto(await Caller(context).OpenAsync(Mapping.ToContract(request))); - - public override Task GetUserChannels(Empty request, ServerCallContext context) - { - var result = new ChannelInfos(); - result.Channels.AddRange(Caller(context).GetUserChannels().Select(Mapping.ToProto)); - return Task.FromResult(result); - } - - public override Task JoinUserChannel(ChannelIdRequest request, ServerCallContext context) - { - Caller(context).JoinUserChannel(Mapping.ToContract(request)); - return Task.FromResult(Done); - } - - public override Task LeaveCurrentChannel(Empty request, ServerCallContext context) - { - Caller(context).LeaveCurrentChannel(); - return Task.FromResult(Done); - } - - public override Task GetCurrentChannel(Empty request, ServerCallContext context) - { - var result = new CurrentChannel(); - if (Caller(context).GetCurrentChannel() is { } channel) result.Channel = Mapping.ToProto(channel); - return Task.FromResult(result); - } - - public override Task GetOrCreateChannel(ChannelIdRequest request, ServerCallContext context) => - Task.FromResult(Mapping.ToProto(Caller(context).GetOrCreateChannel(Mapping.ToContract(request)))); - - public override Task CreatePrivateChannel(Empty request, ServerCallContext context) => - Task.FromResult(Mapping.ToProto(Caller(context).CreatePrivateChannel())); - - public override Task DisconnectPrivateChannel(ChannelIdRequest request, ServerCallContext context) - { - Caller(context).DisconnectPrivateChannel(Mapping.ToContract(request)); - return Task.FromResult(Done); - } - - public override Task Broadcast(BroadcastRequest request, ServerCallContext context) - { - Caller(context).Broadcast(Mapping.ToContract(request)); - return Task.FromResult(Done); - } - - public override Task GetCurrentContext(GetCurrentContextRequest request, ServerCallContext context) => - Task.FromResult(Mapping.ToCurrentContext(Caller(context).GetCurrentContext(Mapping.ToContract(request)))); - - public override Task AddContextListener(AddContextListenerRequest request, ServerCallContext context) - { - Caller(context).AddContextListener(Mapping.ToContract(request)); - return Task.FromResult(Done); - } - - public override Task AddIntentListener(AddIntentListenerRequest request, ServerCallContext context) - { - Caller(context).AddIntentListener(Mapping.ToContract(request)); - return Task.FromResult(Done); - } - - public override Task AddEventListener(AddEventListenerRequest request, ServerCallContext context) - { - Caller(context).AddEventListener(Mapping.ToContract(request)); - return Task.FromResult(Done); - } - - public override Task Unsubscribe(ListenerIdRequest request, ServerCallContext context) - { - Caller(context).Unsubscribe(Mapping.ToContract(request)); - return Task.FromResult(Done); - } - - public override Task FindIntent(FindIntentRequest request, ServerCallContext context) => - Task.FromResult(Mapping.ToProto(Caller(context).FindIntent(Mapping.ToContract(request)))); - - public override Task FindIntentsByContext(FindIntentsByContextRequest request, ServerCallContext context) - { - var result = new AppIntents(); - result.AppIntents_.AddRange(Caller(context).FindIntentsByContext(Mapping.ToContract(request)).Select(Mapping.ToProto)); - return Task.FromResult(result); - } - - public override async Task RaiseIntent(RaiseIntentRequest request, ServerCallContext context) => - Mapping.ToProto(await Caller(context).RaiseIntentAsync(Mapping.ToContract(request))); - - public override async Task RaiseIntentForContext(RaiseIntentForContextRequest request, ServerCallContext context) => - Mapping.ToProto(await Caller(context).RaiseIntentForContextAsync(Mapping.ToContract(request))); - - public override async Task GetIntentResult(ResultIdRequest request, ServerCallContext context) => - Mapping.ToProto(await Caller(context).GetIntentResultAsync(Mapping.ToContract(request))); - - public override Task SendIntentResult(SendIntentResultRequest request, ServerCallContext context) - { - Caller(context).SendIntentResult(Mapping.ToContract(request)); - return Task.FromResult(Done); - } } diff --git a/src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs b/src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs new file mode 100644 index 0000000..a990423 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs @@ -0,0 +1,620 @@ +// +// Generated by Bermuda.Fdc3.Grpc.Generator from IFdc3Commands. Do not edit. +// +#nullable enable +using System.Text.Json; +using Bermuda.IpcContract; +using Google.Protobuf.WellKnownTypes; +using Grpc.Core; +using Proto = Bermuda.Fdc3.Grpc.Proto; + +namespace Bermuda.Fdc3.Grpc; + +internal static class GeneratedMapping +{ + public static Fdc3ImplementationMetadata ToContract(Proto.ImplementationMetadata? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3ImplementationMetadata( + p.Fdc3Version, + p.Provider, + p.HasProviderVersion ? p.ProviderVersion : null, + ToContract(p.OptionalFeatures), + ToContract(p.AppMetadata)); + } + + public static Proto.ImplementationMetadata ToProto(Fdc3ImplementationMetadata r) + { + var m = new Proto.ImplementationMetadata(); + m.Fdc3Version = r.Fdc3Version; + m.Provider = r.Provider; + if (r.ProviderVersion is not null) m.ProviderVersion = r.ProviderVersion; + m.OptionalFeatures = ToProto(r.OptionalFeatures); + m.AppMetadata = ToProto(r.AppMetadata); + return m; + } + + public static Fdc3OptionalFeatures ToContract(Proto.OptionalFeatures? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3OptionalFeatures( + p.OriginatingAppMetadata, + p.UserChannelMembershipApIs, + p.DesktopAgentBridging); + } + + public static Proto.OptionalFeatures ToProto(Fdc3OptionalFeatures r) + { + var m = new Proto.OptionalFeatures(); + m.OriginatingAppMetadata = r.OriginatingAppMetadata; + m.UserChannelMembershipApIs = r.UserChannelMembershipAPIs; + m.DesktopAgentBridging = r.DesktopAgentBridging; + return m; + } + + public static Fdc3AppMetadata ToContract(Proto.AppMetadata? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3AppMetadata( + p.AppId, + p.HasInstanceId ? p.InstanceId : null, + p.HasName ? p.Name : null, + p.HasVersion ? p.Version : null, + p.HasTitle ? p.Title : null, + p.HasTooltip ? p.Tooltip : null, + p.HasDescription ? p.Description : null, + p.HasResultType ? p.ResultType : null); + } + + public static Proto.AppMetadata ToProto(Fdc3AppMetadata r) + { + var m = new Proto.AppMetadata(); + m.AppId = r.AppId; + if (r.InstanceId is not null) m.InstanceId = r.InstanceId; + if (r.Name is not null) m.Name = r.Name; + if (r.Version is not null) m.Version = r.Version; + if (r.Title is not null) m.Title = r.Title; + if (r.Tooltip is not null) m.Tooltip = r.Tooltip; + if (r.Description is not null) m.Description = r.Description; + if (r.ResultType is not null) m.ResultType = r.ResultType; + return m; + } + + public static Fdc3AppIdentifier ToContract(Proto.AppIdentifier? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3AppIdentifier( + p.AppId, + p.HasInstanceId ? p.InstanceId : null); + } + + public static Proto.AppIdentifier ToProto(Fdc3AppIdentifier r) + { + var m = new Proto.AppIdentifier(); + m.AppId = r.AppId; + if (r.InstanceId is not null) m.InstanceId = r.InstanceId; + return m; + } + + public static Fdc3OpenRequest ToContract(Proto.OpenRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3OpenRequest( + ToContract(p.App), + p.HasContextJson ? Mapping.ParseContext(p.ContextJson) : null); + } + + public static Proto.OpenRequest ToProto(Fdc3OpenRequest r) + { + var m = new Proto.OpenRequest(); + m.App = ToProto(r.App); + if (r.Context is not null) m.ContextJson = r.Context.Value.GetRawText(); + return m; + } + + public static Fdc3ChannelInfo ToContract(Proto.ChannelInfo? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3ChannelInfo( + p.Id, + p.Type, + p.DisplayMetadata is null ? null : ToContract(p.DisplayMetadata)); + } + + public static Proto.ChannelInfo ToProto(Fdc3ChannelInfo r) + { + var m = new Proto.ChannelInfo(); + m.Id = r.Id; + m.Type = r.Type; + if (r.DisplayMetadata is not null) m.DisplayMetadata = ToProto(r.DisplayMetadata); + return m; + } + + public static Fdc3DisplayMetadata ToContract(Proto.DisplayMetadata? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3DisplayMetadata( + p.HasName ? p.Name : null, + p.HasColor ? p.Color : null, + p.HasGlyph ? p.Glyph : null); + } + + public static Proto.DisplayMetadata ToProto(Fdc3DisplayMetadata r) + { + var m = new Proto.DisplayMetadata(); + if (r.Name is not null) m.Name = r.Name; + if (r.Color is not null) m.Color = r.Color; + if (r.Glyph is not null) m.Glyph = r.Glyph; + return m; + } + + public static Fdc3ChannelIdRequest ToContract(Proto.ChannelIdRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3ChannelIdRequest( + p.ChannelId); + } + + public static Proto.ChannelIdRequest ToProto(Fdc3ChannelIdRequest r) + { + var m = new Proto.ChannelIdRequest(); + m.ChannelId = r.ChannelId; + return m; + } + + public static Fdc3BroadcastRequest ToContract(Proto.BroadcastRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3BroadcastRequest( + p.HasChannelId ? p.ChannelId : null, + Mapping.ParseContext(p.ContextJson)); + } + + public static Proto.BroadcastRequest ToProto(Fdc3BroadcastRequest r) + { + var m = new Proto.BroadcastRequest(); + if (r.ChannelId is not null) m.ChannelId = r.ChannelId; + m.ContextJson = r.Context.GetRawText(); + return m; + } + + public static Fdc3GetCurrentContextRequest ToContract(Proto.GetCurrentContextRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3GetCurrentContextRequest( + p.ChannelId, + p.HasContextType ? p.ContextType : null); + } + + public static Proto.GetCurrentContextRequest ToProto(Fdc3GetCurrentContextRequest r) + { + var m = new Proto.GetCurrentContextRequest(); + m.ChannelId = r.ChannelId; + if (r.ContextType is not null) m.ContextType = r.ContextType; + return m; + } + + public static Fdc3AddContextListenerRequest ToContract(Proto.AddContextListenerRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3AddContextListenerRequest( + p.ListenerId, + p.HasChannelId ? p.ChannelId : null, + p.HasContextType ? p.ContextType : null); + } + + public static Proto.AddContextListenerRequest ToProto(Fdc3AddContextListenerRequest r) + { + var m = new Proto.AddContextListenerRequest(); + m.ListenerId = r.ListenerId; + if (r.ChannelId is not null) m.ChannelId = r.ChannelId; + if (r.ContextType is not null) m.ContextType = r.ContextType; + return m; + } + + public static Fdc3AddIntentListenerRequest ToContract(Proto.AddIntentListenerRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3AddIntentListenerRequest( + p.ListenerId, + p.Intent); + } + + public static Proto.AddIntentListenerRequest ToProto(Fdc3AddIntentListenerRequest r) + { + var m = new Proto.AddIntentListenerRequest(); + m.ListenerId = r.ListenerId; + m.Intent = r.Intent; + return m; + } + + public static Fdc3AddEventListenerRequest ToContract(Proto.AddEventListenerRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3AddEventListenerRequest( + p.ListenerId, + p.HasEventType ? p.EventType : null, + p.HasChannelId ? p.ChannelId : null); + } + + public static Proto.AddEventListenerRequest ToProto(Fdc3AddEventListenerRequest r) + { + var m = new Proto.AddEventListenerRequest(); + m.ListenerId = r.ListenerId; + if (r.EventType is not null) m.EventType = r.EventType; + if (r.ChannelId is not null) m.ChannelId = r.ChannelId; + return m; + } + + public static Fdc3ListenerIdRequest ToContract(Proto.ListenerIdRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3ListenerIdRequest( + p.ListenerId); + } + + public static Proto.ListenerIdRequest ToProto(Fdc3ListenerIdRequest r) + { + var m = new Proto.ListenerIdRequest(); + m.ListenerId = r.ListenerId; + return m; + } + + public static Fdc3FindIntentRequest ToContract(Proto.FindIntentRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3FindIntentRequest( + p.Intent, + p.HasContextJson ? Mapping.ParseContext(p.ContextJson) : null, + p.HasResultType ? p.ResultType : null); + } + + public static Proto.FindIntentRequest ToProto(Fdc3FindIntentRequest r) + { + var m = new Proto.FindIntentRequest(); + m.Intent = r.Intent; + if (r.Context is not null) m.ContextJson = r.Context.Value.GetRawText(); + if (r.ResultType is not null) m.ResultType = r.ResultType; + return m; + } + + public static Fdc3AppIntent ToContract(Proto.AppIntent? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3AppIntent( + ToContract(p.Intent), + p.Apps.Select(ToContract).ToArray()); + } + + public static Proto.AppIntent ToProto(Fdc3AppIntent r) + { + var m = new Proto.AppIntent(); + m.Intent = ToProto(r.Intent); + m.Apps.AddRange(r.Apps.Select(ToProto)); + return m; + } + + public static Fdc3IntentMetadata ToContract(Proto.IntentMetadata? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3IntentMetadata( + p.Name, + p.HasDisplayName ? p.DisplayName : null); + } + + public static Proto.IntentMetadata ToProto(Fdc3IntentMetadata r) + { + var m = new Proto.IntentMetadata(); + m.Name = r.Name; + if (r.DisplayName is not null) m.DisplayName = r.DisplayName; + return m; + } + + public static Fdc3FindIntentsByContextRequest ToContract(Proto.FindIntentsByContextRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3FindIntentsByContextRequest( + Mapping.ParseContext(p.ContextJson), + p.HasResultType ? p.ResultType : null); + } + + public static Proto.FindIntentsByContextRequest ToProto(Fdc3FindIntentsByContextRequest r) + { + var m = new Proto.FindIntentsByContextRequest(); + m.ContextJson = r.Context.GetRawText(); + if (r.ResultType is not null) m.ResultType = r.ResultType; + return m; + } + + public static Fdc3RaiseIntentRequest ToContract(Proto.RaiseIntentRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3RaiseIntentRequest( + p.Intent, + Mapping.ParseContext(p.ContextJson), + p.App is null ? null : ToContract(p.App)); + } + + public static Proto.RaiseIntentRequest ToProto(Fdc3RaiseIntentRequest r) + { + var m = new Proto.RaiseIntentRequest(); + m.Intent = r.Intent; + m.ContextJson = r.Context.GetRawText(); + if (r.App is not null) m.App = ToProto(r.App); + return m; + } + + public static Fdc3IntentResolutionInfo ToContract(Proto.IntentResolutionInfo? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3IntentResolutionInfo( + ToContract(p.Source), + p.Intent, + p.ResultId); + } + + public static Proto.IntentResolutionInfo ToProto(Fdc3IntentResolutionInfo r) + { + var m = new Proto.IntentResolutionInfo(); + m.Source = ToProto(r.Source); + m.Intent = r.Intent; + m.ResultId = r.ResultId; + return m; + } + + public static Fdc3RaiseIntentForContextRequest ToContract(Proto.RaiseIntentForContextRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3RaiseIntentForContextRequest( + Mapping.ParseContext(p.ContextJson), + p.App is null ? null : ToContract(p.App)); + } + + public static Proto.RaiseIntentForContextRequest ToProto(Fdc3RaiseIntentForContextRequest r) + { + var m = new Proto.RaiseIntentForContextRequest(); + m.ContextJson = r.Context.GetRawText(); + if (r.App is not null) m.App = ToProto(r.App); + return m; + } + + public static Fdc3ResultIdRequest ToContract(Proto.ResultIdRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3ResultIdRequest( + p.ResultId); + } + + public static Proto.ResultIdRequest ToProto(Fdc3ResultIdRequest r) + { + var m = new Proto.ResultIdRequest(); + m.ResultId = r.ResultId; + return m; + } + + public static Fdc3IntentResultInfo ToContract(Proto.IntentResultInfo? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3IntentResultInfo( + p.HasContextJson ? Mapping.ParseContext(p.ContextJson) : null, + p.Channel is null ? null : ToContract(p.Channel)); + } + + public static Proto.IntentResultInfo ToProto(Fdc3IntentResultInfo r) + { + var m = new Proto.IntentResultInfo(); + if (r.Context is not null) m.ContextJson = r.Context.Value.GetRawText(); + if (r.Channel is not null) m.Channel = ToProto(r.Channel); + return m; + } + + public static Fdc3SendIntentResultRequest ToContract(Proto.SendIntentResultRequest? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3SendIntentResultRequest( + p.ResultId, + p.HasContextJson ? Mapping.ParseContext(p.ContextJson) : null, + p.HasChannelId ? p.ChannelId : null, + p.HasError ? p.Error : null); + } + + public static Proto.SendIntentResultRequest ToProto(Fdc3SendIntentResultRequest r) + { + var m = new Proto.SendIntentResultRequest(); + m.ResultId = r.ResultId; + if (r.Context is not null) m.ContextJson = r.Context.Value.GetRawText(); + if (r.ChannelId is not null) m.ChannelId = r.ChannelId; + if (r.Error is not null) m.Error = r.Error; + return m; + } + + public static Proto.ApiEvent ToProto(Fdc3ApiEvent r) + { + var m = new Proto.ApiEvent(); + m.ListenerId = r.ListenerId; + m.EventType = r.EventType; + if (r.Details is not null) m.DetailsJson = JsonSerializer.Serialize(r.Details, JsonSerializerOptions.Web); + return m; + } + + public static Proto.ContextEvent ToProto(Fdc3ContextEvent r) + { + var m = new Proto.ContextEvent(); + m.ListenerId = r.ListenerId; + m.ContextJson = r.Context.GetRawText(); + if (r.Source is not null) m.Source = ToProto(r.Source); + return m; + } + + public static Proto.IntentEvent ToProto(Fdc3IntentEvent r) + { + var m = new Proto.IntentEvent(); + m.ListenerId = r.ListenerId; + m.Intent = r.Intent; + m.ContextJson = r.Context.GetRawText(); + if (r.Source is not null) m.Source = ToProto(r.Source); + m.ResultId = r.ResultId; + return m; + } + + /// Maps what the agent posts to a sink; null for a message type this transport doesn't know. + public static Proto.AgentEvent? ToProtoEvent(object message) => message switch + { + Fdc3ApiEvent e => new Proto.AgentEvent { Api = ToProto(e) }, + Fdc3ContextEvent e => new Proto.AgentEvent { Context = ToProto(e) }, + Fdc3IntentEvent e => new Proto.AgentEvent { Intent = ToProto(e) }, + _ => null, + }; +} + +internal sealed partial class Fdc3AgentService +{ + public override Task GetInfo(Empty request, ServerCallContext context) + { + var result = Caller(context).GetInfo(); + return Task.FromResult(GeneratedMapping.ToProto(result)); + } + + public override Task GetAppMetadata(Proto.AppIdentifier request, ServerCallContext context) + { + var result = Caller(context).GetAppMetadata(GeneratedMapping.ToContract(request)); + return Task.FromResult(GeneratedMapping.ToProto(result)); + } + + public override Task FindInstances(Proto.AppIdentifier request, ServerCallContext context) + { + var result = Caller(context).FindInstances(GeneratedMapping.ToContract(request)); + var response = new Proto.FindInstancesResponse(); + response.Items.AddRange(result.Select(GeneratedMapping.ToProto)); + return Task.FromResult(response); + } + + public override async Task Open(Proto.OpenRequest request, ServerCallContext context) + { + var result = await Caller(context).OpenAsync(GeneratedMapping.ToContract(request)); + return GeneratedMapping.ToProto(result); + } + + public override Task GetUserChannels(Empty request, ServerCallContext context) + { + var result = Caller(context).GetUserChannels(); + var response = new Proto.GetUserChannelsResponse(); + response.Items.AddRange(result.Select(GeneratedMapping.ToProto)); + return Task.FromResult(response); + } + + public override Task JoinUserChannel(Proto.ChannelIdRequest request, ServerCallContext context) + { + Caller(context).JoinUserChannel(GeneratedMapping.ToContract(request)); + return Task.FromResult(new Empty()); + } + + public override Task LeaveCurrentChannel(Empty request, ServerCallContext context) + { + Caller(context).LeaveCurrentChannel(); + return Task.FromResult(new Empty()); + } + + public override Task GetCurrentChannel(Empty request, ServerCallContext context) + { + var result = Caller(context).GetCurrentChannel(); + var response = new Proto.GetCurrentChannelResponse(); + if (result is not null) response.Result = GeneratedMapping.ToProto(result); + return Task.FromResult(response); + } + + public override Task GetOrCreateChannel(Proto.ChannelIdRequest request, ServerCallContext context) + { + var result = Caller(context).GetOrCreateChannel(GeneratedMapping.ToContract(request)); + return Task.FromResult(GeneratedMapping.ToProto(result)); + } + + public override Task CreatePrivateChannel(Empty request, ServerCallContext context) + { + var result = Caller(context).CreatePrivateChannel(); + return Task.FromResult(GeneratedMapping.ToProto(result)); + } + + public override Task DisconnectPrivateChannel(Proto.ChannelIdRequest request, ServerCallContext context) + { + Caller(context).DisconnectPrivateChannel(GeneratedMapping.ToContract(request)); + return Task.FromResult(new Empty()); + } + + public override Task Broadcast(Proto.BroadcastRequest request, ServerCallContext context) + { + Caller(context).Broadcast(GeneratedMapping.ToContract(request)); + return Task.FromResult(new Empty()); + } + + public override Task GetCurrentContext(Proto.GetCurrentContextRequest request, ServerCallContext context) + { + var result = Caller(context).GetCurrentContext(GeneratedMapping.ToContract(request)); + var response = new Proto.GetCurrentContextResponse(); + if (result is { } value) response.ResultJson = value.GetRawText(); + return Task.FromResult(response); + } + + public override Task AddContextListener(Proto.AddContextListenerRequest request, ServerCallContext context) + { + Caller(context).AddContextListener(GeneratedMapping.ToContract(request)); + return Task.FromResult(new Empty()); + } + + public override Task AddIntentListener(Proto.AddIntentListenerRequest request, ServerCallContext context) + { + Caller(context).AddIntentListener(GeneratedMapping.ToContract(request)); + return Task.FromResult(new Empty()); + } + + public override Task AddEventListener(Proto.AddEventListenerRequest request, ServerCallContext context) + { + Caller(context).AddEventListener(GeneratedMapping.ToContract(request)); + return Task.FromResult(new Empty()); + } + + public override Task Unsubscribe(Proto.ListenerIdRequest request, ServerCallContext context) + { + Caller(context).Unsubscribe(GeneratedMapping.ToContract(request)); + return Task.FromResult(new Empty()); + } + + public override Task FindIntent(Proto.FindIntentRequest request, ServerCallContext context) + { + var result = Caller(context).FindIntent(GeneratedMapping.ToContract(request)); + return Task.FromResult(GeneratedMapping.ToProto(result)); + } + + public override Task FindIntentsByContext(Proto.FindIntentsByContextRequest request, ServerCallContext context) + { + var result = Caller(context).FindIntentsByContext(GeneratedMapping.ToContract(request)); + var response = new Proto.FindIntentsByContextResponse(); + response.Items.AddRange(result.Select(GeneratedMapping.ToProto)); + return Task.FromResult(response); + } + + public override async Task RaiseIntent(Proto.RaiseIntentRequest request, ServerCallContext context) + { + var result = await Caller(context).RaiseIntentAsync(GeneratedMapping.ToContract(request)); + return GeneratedMapping.ToProto(result); + } + + public override async Task RaiseIntentForContext(Proto.RaiseIntentForContextRequest request, ServerCallContext context) + { + var result = await Caller(context).RaiseIntentForContextAsync(GeneratedMapping.ToContract(request)); + return GeneratedMapping.ToProto(result); + } + + public override async Task GetIntentResult(Proto.ResultIdRequest request, ServerCallContext context) + { + var result = await Caller(context).GetIntentResultAsync(GeneratedMapping.ToContract(request)); + return GeneratedMapping.ToProto(result); + } + + public override Task SendIntentResult(Proto.SendIntentResultRequest request, ServerCallContext context) + { + Caller(context).SendIntentResult(GeneratedMapping.ToContract(request)); + return Task.FromResult(new Empty()); + } + +} diff --git a/src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto b/src/Bermuda.Fdc3.Grpc/Generated/fdc3.proto similarity index 65% rename from src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto rename to src/Bermuda.Fdc3.Grpc/Generated/fdc3.proto index 2961f9d..a68cf4a 100644 --- a/src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto +++ b/src/Bermuda.Fdc3.Grpc/Generated/fdc3.proto @@ -1,3 +1,7 @@ +// +// Generated by Bermuda.Fdc3.Grpc.Generator from IFdc3Commands (src/Bermuda.IpcContract/Fdc3Contract.cs). +// Do not edit: change the contract and rebuild Bermuda.Fdc3.Grpc. +// syntax = "proto3"; package bermuda.fdc3.v1; @@ -6,77 +10,51 @@ import "google/protobuf/empty.proto"; option csharp_namespace = "Bermuda.Fdc3.Grpc.Proto"; -// gRPC mirror of IFdc3Commands (src/Bermuda.IpcContract/Fdc3Contract.cs). -// -// Connection model: one pipe client opens Subscribe(app_id). The first message -// on that stream is `connected` (carrying the new instance_id); the agent's -// context/intent/event deliveries follow. Every other RPC must carry the -// instance_id in the `x-fdc3-instance` request header and travel on the same -// pipe connection. The instance leaves the agent when the Subscribe stream -// ends (cancelled, or the pipe closes). -// -// FDC3 contexts are open-ended JSON objects, carried as JSON text in -// *_json fields. Failures are gRPC errors whose status *detail* is the -// standard FDC3 error string (Fdc3Errors, e.g. "NoChannelFound"). - +// Connection model: one pipe client opens Subscribe(app_id). The first message on that stream is +// `connected` (carrying the new instance_id); the agent's deliveries follow. Every other RPC must carry +// the instance_id in the `x-fdc3-instance` request header and use the same pipe connection. The instance +// leaves the agent when the Subscribe stream ends. Contexts are JSON text (*_json fields); failures are +// gRPC errors whose status detail is the FDC3 error string (Fdc3Errors). service Fdc3Agent { rpc Subscribe(SubscribeRequest) returns (stream AgentEvent); rpc GetInfo(google.protobuf.Empty) returns (ImplementationMetadata); rpc GetAppMetadata(AppIdentifier) returns (AppMetadata); - rpc FindInstances(AppIdentifier) returns (AppIdentifiers); + rpc FindInstances(AppIdentifier) returns (FindInstancesResponse); rpc Open(OpenRequest) returns (AppIdentifier); - - rpc GetUserChannels(google.protobuf.Empty) returns (ChannelInfos); + rpc GetUserChannels(google.protobuf.Empty) returns (GetUserChannelsResponse); rpc JoinUserChannel(ChannelIdRequest) returns (google.protobuf.Empty); rpc LeaveCurrentChannel(google.protobuf.Empty) returns (google.protobuf.Empty); - rpc GetCurrentChannel(google.protobuf.Empty) returns (CurrentChannel); + rpc GetCurrentChannel(google.protobuf.Empty) returns (GetCurrentChannelResponse); rpc GetOrCreateChannel(ChannelIdRequest) returns (ChannelInfo); rpc CreatePrivateChannel(google.protobuf.Empty) returns (ChannelInfo); rpc DisconnectPrivateChannel(ChannelIdRequest) returns (google.protobuf.Empty); - rpc Broadcast(BroadcastRequest) returns (google.protobuf.Empty); - rpc GetCurrentContext(GetCurrentContextRequest) returns (CurrentContext); + rpc GetCurrentContext(GetCurrentContextRequest) returns (GetCurrentContextResponse); rpc AddContextListener(AddContextListenerRequest) returns (google.protobuf.Empty); rpc AddIntentListener(AddIntentListenerRequest) returns (google.protobuf.Empty); rpc AddEventListener(AddEventListenerRequest) returns (google.protobuf.Empty); rpc Unsubscribe(ListenerIdRequest) returns (google.protobuf.Empty); - rpc FindIntent(FindIntentRequest) returns (AppIntent); - rpc FindIntentsByContext(FindIntentsByContextRequest) returns (AppIntents); + rpc FindIntentsByContext(FindIntentsByContextRequest) returns (FindIntentsByContextResponse); rpc RaiseIntent(RaiseIntentRequest) returns (IntentResolutionInfo); rpc RaiseIntentForContext(RaiseIntentForContextRequest) returns (IntentResolutionInfo); rpc GetIntentResult(ResultIdRequest) returns (IntentResultInfo); rpc SendIntentResult(SendIntentResultRequest) returns (google.protobuf.Empty); } -// Shapes --------------------------------------------------------------------- - -message AppIdentifier { - string app_id = 1; - optional string instance_id = 2; -} -message AppIdentifiers { repeated AppIdentifier apps = 1; } - -message DisplayMetadata { - optional string name = 1; - optional string color = 2; - optional string glyph = 3; -} - -// type is 'user' | 'app' | 'private'. -message ChannelInfo { - string id = 1; - string type = 2; - optional DisplayMetadata display_metadata = 3; +message ImplementationMetadata { + string fdc3_version = 1; + string provider = 2; + optional string provider_version = 3; + OptionalFeatures optional_features = 4; + AppMetadata app_metadata = 5; } -message ChannelInfos { repeated ChannelInfo channels = 1; } -message CurrentChannel { optional ChannelInfo channel = 1; } -message CurrentContext { optional string context_json = 1; } -message IntentMetadata { - string name = 1; - optional string display_name = 2; +message OptionalFeatures { + bool originating_app_metadata = 1; + bool user_channel_membership_ap_is = 2; + bool desktop_agent_bridging = 3; } message AppMetadata { @@ -90,45 +68,32 @@ message AppMetadata { optional string result_type = 8; } -message AppIntent { - IntentMetadata intent = 1; - repeated AppMetadata apps = 2; +message AppIdentifier { + string app_id = 1; + optional string instance_id = 2; } -message AppIntents { repeated AppIntent app_intents = 1; } -message OptionalFeatures { - bool originating_app_metadata = 1; - bool user_channel_membership_apis = 2; - bool desktop_agent_bridging = 3; +message OpenRequest { + AppIdentifier app = 1; + optional string context_json = 2; } -message ImplementationMetadata { - string fdc3_version = 1; - string provider = 2; - optional string provider_version = 3; - OptionalFeatures optional_features = 4; - AppMetadata app_metadata = 5; +message ChannelInfo { + string id = 1; + string type = 2; + DisplayMetadata display_metadata = 3; } -message IntentResolutionInfo { - AppIdentifier source = 1; - string intent = 2; - string result_id = 3; +message DisplayMetadata { + optional string name = 1; + optional string color = 2; + optional string glyph = 3; } -// A handler's result: a context, a channel, or neither (void). -message IntentResultInfo { - optional string context_json = 1; - optional ChannelInfo channel = 2; +message ChannelIdRequest { + string channel_id = 1; } -// Requests ------------------------------------------------------------------- - -message SubscribeRequest { string app_id = 1; } - -message ChannelIdRequest { string channel_id = 1; } - -// channel_id unset = the caller's current user channel. message BroadcastRequest { optional string channel_id = 1; string context_json = 2; @@ -139,7 +104,6 @@ message GetCurrentContextRequest { optional string context_type = 2; } -// channel_id unset = follow whichever user channel the caller is joined to. message AddContextListenerRequest { string listener_id = 1; optional string channel_id = 2; @@ -151,14 +115,15 @@ message AddIntentListenerRequest { string intent = 2; } -// channel_id unset = desktop-agent events; event_type unset = all types. message AddEventListenerRequest { string listener_id = 1; optional string event_type = 2; optional string channel_id = 3; } -message ListenerIdRequest { string listener_id = 1; } +message ListenerIdRequest { + string listener_id = 1; +} message FindIntentRequest { string intent = 1; @@ -166,30 +131,47 @@ message FindIntentRequest { optional string result_type = 3; } +message AppIntent { + IntentMetadata intent = 1; + repeated AppMetadata apps = 2; +} + +message IntentMetadata { + string name = 1; + optional string display_name = 2; +} + message FindIntentsByContextRequest { string context_json = 1; optional string result_type = 2; } -message OpenRequest { - AppIdentifier app = 1; - optional string context_json = 2; -} - message RaiseIntentRequest { string intent = 1; string context_json = 2; - optional AppIdentifier app = 3; + AppIdentifier app = 3; +} + +message IntentResolutionInfo { + AppIdentifier source = 1; + string intent = 2; + string result_id = 3; } message RaiseIntentForContextRequest { string context_json = 1; - optional AppIdentifier app = 2; + AppIdentifier app = 2; } -message ResultIdRequest { string result_id = 1; } +message ResultIdRequest { + string result_id = 1; +} + +message IntentResultInfo { + optional string context_json = 1; + ChannelInfo channel = 2; +} -// At most one of context_json/channel_id (neither = void); error set instead if the handler threw. message SendIntentResultRequest { string result_id = 1; optional string context_json = 2; @@ -197,39 +179,59 @@ message SendIntentResultRequest { optional string error = 4; } -// Agent -> app events (Subscribe stream) --------------------------------------- - -message AgentEvent { - oneof event { - Connected connected = 1; - ContextEvent context = 2; - IntentEvent intent = 3; - ApiEvent api = 4; - } -} - -// First message of every Subscribe stream. -message Connected { - string instance_id = 1; - string app_id = 2; +message ApiEvent { + string listener_id = 1; + string event_type = 2; + optional string details_json = 3; } message ContextEvent { string listener_id = 1; string context_json = 2; - optional AppIdentifier source = 3; + AppIdentifier source = 3; } message IntentEvent { string listener_id = 1; string intent = 2; string context_json = 3; - optional AppIdentifier source = 4; + AppIdentifier source = 4; string result_id = 5; } -message ApiEvent { - string listener_id = 1; - string event_type = 2; - optional string details_json = 3; +message FindInstancesResponse { + repeated AppIdentifier items = 1; +} + +message GetUserChannelsResponse { + repeated ChannelInfo items = 1; +} + +message GetCurrentChannelResponse { + ChannelInfo result = 1; +} + +message GetCurrentContextResponse { + optional string result_json = 1; +} + +message FindIntentsByContextResponse { + repeated AppIntent items = 1; +} + +message SubscribeRequest { string app_id = 1; } + +// First message of every Subscribe stream. +message Connected { + string instance_id = 1; + string app_id = 2; +} + +message AgentEvent { + oneof event { + Connected connected = 1; + ApiEvent api = 2; + ContextEvent context = 3; + IntentEvent intent = 4; + } } diff --git a/src/Bermuda.Fdc3.Grpc/Mapping.cs b/src/Bermuda.Fdc3.Grpc/Mapping.cs index f0fb6dd..571a404 100644 --- a/src/Bermuda.Fdc3.Grpc/Mapping.cs +++ b/src/Bermuda.Fdc3.Grpc/Mapping.cs @@ -1,14 +1,14 @@ using System.Text.Json; -using Bermuda.IpcContract; -using Proto = Bermuda.Fdc3.Grpc.Proto; namespace Bermuda.Fdc3.Grpc; -/// Converts between the protobuf messages and the Fdc3Contract records. +/// +/// The hand-written part of the proto <-> contract mapping: how a JSON +/// text field becomes a context. Everything else is in +/// Generated/Fdc3Generated.g.cs (see Bermuda.Fdc3.Grpc.Generator). +/// internal static class Mapping { - // Contexts ------------------------------------------------------------------ - public static JsonElement ParseContext(string? json) { if (string.IsNullOrWhiteSpace(json)) throw new Fdc3Exception(Fdc3Errors.MalformedContext); @@ -21,173 +21,4 @@ public static JsonElement ParseContext(string? json) throw new Fdc3Exception(Fdc3Errors.MalformedContext); } } - - public static JsonElement? ParseOptionalContext(string? json) => - json is null ? null : ParseContext(json); - - // Requests (proto -> contract) --------------------------------------------------- - - public static Fdc3AppIdentifier ToContract(Proto.AppIdentifier? app) => - app is null ? throw new Fdc3Exception(Fdc3Errors.InvalidArguments) : new(app.AppId, app.HasInstanceId ? app.InstanceId : null); - - public static Fdc3AppIdentifier? ToContractOptional(Proto.AppIdentifier? app) => - app is null ? null : ToContract(app); - - public static Fdc3ChannelIdRequest ToContract(Proto.ChannelIdRequest r) => new(r.ChannelId); - - public static Fdc3BroadcastRequest ToContract(Proto.BroadcastRequest r) => - new(r.HasChannelId ? r.ChannelId : null, ParseContext(r.ContextJson)); - - public static Fdc3GetCurrentContextRequest ToContract(Proto.GetCurrentContextRequest r) => - new(r.ChannelId, r.HasContextType ? r.ContextType : null); - - public static Fdc3AddContextListenerRequest ToContract(Proto.AddContextListenerRequest r) => - new(r.ListenerId, r.HasChannelId ? r.ChannelId : null, r.HasContextType ? r.ContextType : null); - - public static Fdc3AddIntentListenerRequest ToContract(Proto.AddIntentListenerRequest r) => - new(r.ListenerId, r.Intent); - - public static Fdc3AddEventListenerRequest ToContract(Proto.AddEventListenerRequest r) => - new(r.ListenerId, r.HasEventType ? r.EventType : null, r.HasChannelId ? r.ChannelId : null); - - public static Fdc3ListenerIdRequest ToContract(Proto.ListenerIdRequest r) => new(r.ListenerId); - - public static Fdc3FindIntentRequest ToContract(Proto.FindIntentRequest r) => - new(r.Intent, ParseOptionalContext(r.HasContextJson ? r.ContextJson : null), r.HasResultType ? r.ResultType : null); - - public static Fdc3FindIntentsByContextRequest ToContract(Proto.FindIntentsByContextRequest r) => - new(ParseContext(r.ContextJson), r.HasResultType ? r.ResultType : null); - - public static Fdc3OpenRequest ToContract(Proto.OpenRequest r) => - new(ToContract(r.App), ParseOptionalContext(r.HasContextJson ? r.ContextJson : null)); - - public static Fdc3RaiseIntentRequest ToContract(Proto.RaiseIntentRequest r) => - new(r.Intent, ParseContext(r.ContextJson), ToContractOptional(r.App)); - - public static Fdc3RaiseIntentForContextRequest ToContract(Proto.RaiseIntentForContextRequest r) => - new(ParseContext(r.ContextJson), ToContractOptional(r.App)); - - public static Fdc3ResultIdRequest ToContract(Proto.ResultIdRequest r) => new(r.ResultId); - - public static Fdc3SendIntentResultRequest ToContract(Proto.SendIntentResultRequest r) => - new(r.ResultId, ParseOptionalContext(r.HasContextJson ? r.ContextJson : null), r.HasChannelId ? r.ChannelId : null, r.HasError ? r.Error : null); - - // Responses (contract -> proto) ------------------------------------------------- - - public static Proto.AppIdentifier ToProto(Fdc3AppIdentifier a) - { - var app = new Proto.AppIdentifier { AppId = a.AppId }; - if (a.InstanceId is not null) app.InstanceId = a.InstanceId; - return app; - } - - public static Proto.ChannelInfo ToProto(Fdc3ChannelInfo c) - { - var info = new Proto.ChannelInfo { Id = c.Id, Type = c.Type }; - if (c.DisplayMetadata is { } d) - { - var display = new Proto.DisplayMetadata(); - if (d.Name is not null) display.Name = d.Name; - if (d.Color is not null) display.Color = d.Color; - if (d.Glyph is not null) display.Glyph = d.Glyph; - info.DisplayMetadata = display; - } - return info; - } - - public static Proto.AppMetadata ToProto(Fdc3AppMetadata a) - { - var app = new Proto.AppMetadata { AppId = a.AppId }; - if (a.InstanceId is not null) app.InstanceId = a.InstanceId; - if (a.Name is not null) app.Name = a.Name; - if (a.Version is not null) app.Version = a.Version; - if (a.Title is not null) app.Title = a.Title; - if (a.Tooltip is not null) app.Tooltip = a.Tooltip; - if (a.Description is not null) app.Description = a.Description; - if (a.ResultType is not null) app.ResultType = a.ResultType; - return app; - } - - public static Proto.AppIntent ToProto(Fdc3AppIntent a) - { - var metadata = new Proto.IntentMetadata { Name = a.Intent.Name }; - if (a.Intent.DisplayName is not null) metadata.DisplayName = a.Intent.DisplayName; - var intent = new Proto.AppIntent { Intent = metadata }; - intent.Apps.AddRange(a.Apps.Select(ToProto)); - return intent; - } - - public static Proto.ImplementationMetadata ToProto(Fdc3ImplementationMetadata m) - { - var info = new Proto.ImplementationMetadata - { - Fdc3Version = m.Fdc3Version, - Provider = m.Provider, - OptionalFeatures = new Proto.OptionalFeatures - { - OriginatingAppMetadata = m.OptionalFeatures.OriginatingAppMetadata, - UserChannelMembershipApis = m.OptionalFeatures.UserChannelMembershipAPIs, - DesktopAgentBridging = m.OptionalFeatures.DesktopAgentBridging, - }, - AppMetadata = ToProto(m.AppMetadata), - }; - if (m.ProviderVersion is not null) info.ProviderVersion = m.ProviderVersion; - return info; - } - - public static Proto.IntentResolutionInfo ToProto(Fdc3IntentResolutionInfo r) => - new() { Source = ToProto(r.Source), Intent = r.Intent, ResultId = r.ResultId }; - - public static Proto.IntentResultInfo ToProto(Fdc3IntentResultInfo r) - { - var result = new Proto.IntentResultInfo(); - if (r.Context is { } context) result.ContextJson = context.GetRawText(); - if (r.Channel is { } channel) result.Channel = ToProto(channel); - return result; - } - - public static Proto.CurrentContext ToCurrentContext(JsonElement? context) - { - var result = new Proto.CurrentContext(); - if (context is { } value) result.ContextJson = value.GetRawText(); - return result; - } - - // Events (contract -> proto) -------------------------------------------------- - - /// Maps what the agent posts to a sink; null for a message type this transport doesn't know. - public static Proto.AgentEvent? ToProtoEvent(object message) => message switch - { - Fdc3ContextEvent e => new Proto.AgentEvent { Context = ContextEvent(e) }, - Fdc3IntentEvent e => new Proto.AgentEvent { Intent = IntentEvent(e) }, - Fdc3ApiEvent e => new Proto.AgentEvent { Api = ApiEvent(e) }, - _ => null, - }; - - private static Proto.ContextEvent ContextEvent(Fdc3ContextEvent e) - { - var result = new Proto.ContextEvent { ListenerId = e.ListenerId, ContextJson = e.Context.GetRawText() }; - if (e.Source is not null) result.Source = ToProto(e.Source); - return result; - } - - private static Proto.IntentEvent IntentEvent(Fdc3IntentEvent e) - { - var result = new Proto.IntentEvent - { - ListenerId = e.ListenerId, - Intent = e.Intent, - ContextJson = e.Context.GetRawText(), - ResultId = e.ResultId, - }; - if (e.Source is not null) result.Source = ToProto(e.Source); - return result; - } - - private static Proto.ApiEvent ApiEvent(Fdc3ApiEvent e) - { - var result = new Proto.ApiEvent { ListenerId = e.ListenerId, EventType = e.EventType }; - if (e.Details is not null) result.DetailsJson = JsonSerializer.Serialize(e.Details, JsonSerializerOptions.Web); - return result; - } } From 409e82873da4d2419fa2562fd1c42dc7e8ad15b2 Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 11 Nov 2026 02:36:09 -0500 Subject: [PATCH 03/14] feat: add a native FDC3 side app, run by Aspire, with e2e Bermuda.NativeApp connects to the host's gRPC pipe as native-incidents (registered in fdc3-appd.json), joins a channel and acks incidents it receives, as a broadcast or as a ViewIncident intent result. The AppHost starts it after the host. Fdc3PipeClient moves into Bermuda.Fdc3.Grpc so native .NET apps can reuse it. Playwright e2e covers web->native and native->web over the channel, the intent round trip and findIntent. Co-Authored-By: Claude Sonnet 5.5 --- Bermuda.slnx | 1 + Directory.Packages.props | 2 +- src/Bermuda.AppHost/AppHost.cs | 7 +- src/Bermuda.AppHost/Bermuda.AppHost.csproj | 1 + .../Bermuda.Fdc3.Grpc.Tests.csproj | 1 - .../Bermuda.Fdc3.Grpc.csproj | 1 + .../Fdc3PipeClient.cs | 13 +-- .../Bermuda.NativeApp.csproj | 19 ++++ src/Bermuda.NativeApp/Program.cs | 78 +++++++++++++++ src/Bermuda.Web/e2e/native-app.spec.ts | 96 +++++++++++++++++++ src/Bermuda/fdc3-appd.json | 22 +++++ 11 files changed, 232 insertions(+), 9 deletions(-) rename src/{Bermuda.Fdc3.Grpc.Tests => Bermuda.Fdc3.Grpc}/Fdc3PipeClient.cs (88%) create mode 100644 src/Bermuda.NativeApp/Bermuda.NativeApp.csproj create mode 100644 src/Bermuda.NativeApp/Program.cs create mode 100644 src/Bermuda.Web/e2e/native-app.spec.ts diff --git a/Bermuda.slnx b/Bermuda.slnx index c297bb7..e15caf2 100644 --- a/Bermuda.slnx +++ b/Bermuda.slnx @@ -7,6 +7,7 @@ + diff --git a/Directory.Packages.props b/Directory.Packages.props index 0888671..4d13a29 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -27,7 +27,7 @@ - + diff --git a/src/Bermuda.AppHost/AppHost.cs b/src/Bermuda.AppHost/AppHost.cs index f25c98f..ce3d386 100644 --- a/src/Bermuda.AppHost/AppHost.cs +++ b/src/Bermuda.AppHost/AppHost.cs @@ -11,11 +11,16 @@ .WithEnvironment("RELAY_SCHEMA_URL", api.GetEndpoint("http")) .WaitFor(api); -builder.AddProject("host") +var host = builder.AddProject("host") .WithEnvironment("WEB_URL", web.GetEndpoint("http")) .WithEnvironment("CDP_PORT", "9222") .WaitFor(web) .WaitFor(api); +// A native FDC3 side app: joins the host's agent over the gRPC named pipe +// (both use the default per-user pipe name; it reconnects until the pipe is up). +builder.AddProject("native-app") + .WaitFor(host); + builder.Build().Run(); diff --git a/src/Bermuda.AppHost/Bermuda.AppHost.csproj b/src/Bermuda.AppHost/Bermuda.AppHost.csproj index 1bedc53..a3300af 100644 --- a/src/Bermuda.AppHost/Bermuda.AppHost.csproj +++ b/src/Bermuda.AppHost/Bermuda.AppHost.csproj @@ -11,6 +11,7 @@ + diff --git a/src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj b/src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj index 0482983..b31e311 100644 --- a/src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj +++ b/src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj @@ -12,7 +12,6 @@ - diff --git a/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj b/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj index 40999aa..3fc49aa 100644 --- a/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj +++ b/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj @@ -11,6 +11,7 @@ + diff --git a/src/Bermuda.Fdc3.Grpc.Tests/Fdc3PipeClient.cs b/src/Bermuda.Fdc3.Grpc/Fdc3PipeClient.cs similarity index 88% rename from src/Bermuda.Fdc3.Grpc.Tests/Fdc3PipeClient.cs rename to src/Bermuda.Fdc3.Grpc/Fdc3PipeClient.cs index 15588e5..8973dba 100644 --- a/src/Bermuda.Fdc3.Grpc.Tests/Fdc3PipeClient.cs +++ b/src/Bermuda.Fdc3.Grpc/Fdc3PipeClient.cs @@ -5,7 +5,7 @@ using Grpc.Core; using Grpc.Net.Client; -namespace Bermuda.Fdc3.Grpc.Tests; +namespace Bermuda.Fdc3.Grpc; /// /// A minimal native FDC3 app: connects to Bermuda's named pipe, subscribes as @@ -39,13 +39,13 @@ private Fdc3PipeClient(GrpcChannel channel, Fdc3Agent.Fdc3AgentClient rpc, strin public Metadata Headers { get; } /// Throws (detail = FDC3 error string) if the agent rejects the app id. - public static async Task ConnectAsync(string pipeName, string appId, CancellationToken cancellationToken = default) + public static async Task ConnectAsync(string? pipeName, string appId, CancellationToken cancellationToken = default) { var handler = new SocketsHttpHandler { ConnectCallback = async (_, token) => { - var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + var pipe = new NamedPipeClientStream(".", pipeName ?? Fdc3GrpcHost.DefaultPipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); try { await pipe.ConnectAsync(token); @@ -93,14 +93,15 @@ private async Task Pump(AsyncServerStreamingCall stream) } /// The next event the agent pushed; throws if none arrives. - public async Task NextEventAsync(TimeSpan? timeout = null) + public async Task NextEventAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default) { - using var cts = new CancellationTokenSource(timeout ?? TimeSpan.FromSeconds(5)); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(timeout ?? TimeSpan.FromSeconds(5)); try { return await _events.Reader.ReadAsync(cts.Token); } - catch (OperationCanceledException) + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { throw new TimeoutException("No FDC3 event arrived."); } diff --git a/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj b/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj new file mode 100644 index 0000000..297b304 --- /dev/null +++ b/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj @@ -0,0 +1,19 @@ + + + + + Exe + net10.0 + enable + enable + + + + + + + diff --git a/src/Bermuda.NativeApp/Program.cs b/src/Bermuda.NativeApp/Program.cs new file mode 100644 index 0000000..58e6b7d --- /dev/null +++ b/src/Bermuda.NativeApp/Program.cs @@ -0,0 +1,78 @@ +using System.Text.Json; +using Bermuda.Fdc3.Grpc; +using Bermuda.Fdc3.Grpc.Proto; +using Google.Protobuf.WellKnownTypes; +using Grpc.Core; + +// Native FDC3 side app for Bermuda. +// +// * joins user channel NATIVE_CHANNEL (default fdc3.channel.1) +// * listens for `bermuda.incident` contexts there and answers each by +// broadcasting `bermuda.native.ack` carrying the incident it saw +// * handles the `ViewIncident` intent and returns the same ack as its result +// +// Config (environment): FDC3_GRPC_PIPE (default: Bermuda's per-user pipe), NATIVE_CHANNEL. +// It reconnects whenever the host goes away, so start order doesn't matter. + +const string AppId = "native-incidents"; +const string AckType = "bermuda.native.ack"; + +var pipe = Environment.GetEnvironmentVariable("FDC3_GRPC_PIPE"); +var channel = Environment.GetEnvironmentVariable("NATIVE_CHANNEL") is { Length: > 0 } c ? c : "fdc3.channel.1"; + +using var shutdown = new CancellationTokenSource(); +Console.CancelKeyPress += (_, e) => { e.Cancel = true; shutdown.Cancel(); }; + +while (!shutdown.IsCancellationRequested) +{ + try + { + await using var client = await Fdc3PipeClient.ConnectAsync(pipe, AppId, shutdown.Token); + Console.WriteLine($"[{AppId}] connected as {client.InstanceId}"); + await RunAsync(client, shutdown.Token); + } + catch (OperationCanceledException) when (shutdown.IsCancellationRequested) + { + } + catch (Exception ex) when (ex is RpcException or IOException or TimeoutException or InvalidOperationException) + { + Console.WriteLine($"[{AppId}] {ex.GetType().Name}: {ex.Message}"); + } + + try { await Task.Delay(TimeSpan.FromSeconds(1), shutdown.Token); } + catch (OperationCanceledException) { } +} + +async Task RunAsync(Fdc3PipeClient client, CancellationToken cancellationToken) +{ + await client.Rpc.JoinUserChannelAsync(new ChannelIdRequest { ChannelId = channel }, client.Headers, cancellationToken: cancellationToken); + await client.Rpc.AddContextListenerAsync( + new AddContextListenerRequest { ListenerId = "incidents", ContextType = "bermuda.incident" }, + client.Headers, cancellationToken: cancellationToken); + await client.Rpc.AddIntentListenerAsync( + new AddIntentListenerRequest { ListenerId = "view", Intent = "ViewIncident" }, + client.Headers, cancellationToken: cancellationToken); + + while (!cancellationToken.IsCancellationRequested) + { + var e = await client.NextEventAsync(Timeout.InfiniteTimeSpan, cancellationToken); + switch (e.EventCase) + { + case AgentEvent.EventOneofCase.Context: + Console.WriteLine($"[{AppId}] context from {e.Context.Source?.AppId}: {e.Context.ContextJson}"); + await client.Rpc.BroadcastAsync(new BroadcastRequest { ContextJson = Ack(e.Context.ContextJson) }, + client.Headers, cancellationToken: cancellationToken); + break; + + case AgentEvent.EventOneofCase.Intent: + Console.WriteLine($"[{AppId}] {e.Intent.Intent} from {e.Intent.Source?.AppId}: {e.Intent.ContextJson}"); + await client.Rpc.SendIntentResultAsync( + new SendIntentResultRequest { ResultId = e.Intent.ResultId, ContextJson = Ack(e.Intent.ContextJson) }, + client.Headers, cancellationToken: cancellationToken); + break; + } + } +} + +static string Ack(string contextJson) => + JsonSerializer.Serialize(new { type = AckType, of = JsonSerializer.Deserialize(contextJson) }); diff --git a/src/Bermuda.Web/e2e/native-app.spec.ts b/src/Bermuda.Web/e2e/native-app.spec.ts new file mode 100644 index 0000000..35a4307 --- /dev/null +++ b/src/Bermuda.Web/e2e/native-app.spec.ts @@ -0,0 +1,96 @@ +import type { Page } from '@playwright/test' +import type { DesktopAgent, Listener } from '@finos/fdc3-standard' +import type { Context } from '../src/fdc3' +import { test, expect } from './fixtures' + +// Exercises the native side app (src/Bermuda.NativeApp), which Aspire starts +// next to the host. It connects to the host's gRPC named pipe as +// "native-incidents", joins fdc3.channel.1 and answers every +// bermuda.incident context / ViewIncident intent with a bermuda.native.ack +// that carries the incident it saw. So a round trip here proves both +// directions: web -> native (the incident arrives) and native -> web (the ack). + +const NATIVE = 'native-incidents' +const channelButtons = (page: Page) => page.locator('fieldset[aria-label="FDC3 channel"] button') + +const incident = (id: string) => ({ type: 'bermuda.incident', id: { incidentId: id } }) as Context + +type Ack = { type: string; of: { id: { incidentId: string } } } + +test.describe('FDC3 native side app (gRPC named pipe)', () => { + test.beforeEach(async ({ page }) => { + // Aspire starts the native app after the host, so give it time to connect. + await expect + .poll( + () => page.evaluate(async (appId) => (await (window.fdc3 as DesktopAgent).findInstances({ appId })).length, NATIVE), + { timeout: 60_000, message: 'native app never connected to the host agent' }, + ) + .toBe(1) + }) + + test('is in the app directory and reports its metadata', async ({ page }) => { + const metadata = await page.evaluate(async (appId) => { + const [instance] = await (window.fdc3 as DesktopAgent).findInstances({ appId }) + return (window.fdc3 as DesktopAgent).getAppMetadata(instance) + }, NATIVE) + expect(metadata).toMatchObject({ appId: NATIVE, title: 'Native Incidents' }) + expect(metadata.instanceId).toBeTruthy() + }) + + test('a web broadcast reaches the native app, which answers on the channel', async ({ page }) => { + const first = channelButtons(page).first() + await first.click() + await expect(first).toHaveAttribute('aria-pressed', 'true') + + try { + await page.evaluate(async () => { + const w = window as unknown as { acks: { ack: unknown; source?: string }[]; ackListener: Listener } + w.acks = [] + w.ackListener = await (window.fdc3 as DesktopAgent).addContextListener('bermuda.native.ack', (ack, metadata) => { + w.acks.push({ ack, source: (metadata?.source as { appId?: string } | undefined)?.appId }) + }) + }) + + await page.evaluate((ctx) => (window.fdc3 as DesktopAgent).broadcast(ctx), incident('native-1')) + + // The listener may first be replayed an older ack the channel still holds + // (no source); the one for this broadcast is the one to look for. + const ackFor = () => + page.evaluate( + () => + (window as unknown as { acks: { ack: Ack; source?: string }[] }).acks.find( + (a) => a.ack.of?.id?.incidentId === 'native-1', + ), + ) + await expect.poll(ackFor).toBeDefined() + const received = (await ackFor())! + expect(received.source).toBe(NATIVE) + expect(received.ack.type).toBe('bermuda.native.ack') + } finally { + await page.evaluate(() => (window as unknown as { ackListener?: Listener }).ackListener?.unsubscribe()) + await first.click() // leave the channel again + await expect(first).toHaveAttribute('aria-pressed', 'false') + } + }) + + test('an intent raised at the native app returns its result', async ({ page }) => { + const result = await page.evaluate( + async ([ctx, appId]) => { + const agent = window.fdc3 as DesktopAgent + const [instance] = await agent.findInstances({ appId }) + const resolution = await agent.raiseIntent('ViewIncident', ctx as Context, instance) + return { source: resolution.source, intent: resolution.intent, result: await resolution.getResult() } + }, + [incident('native-2'), NATIVE] as const, + ) + + expect(result.source.appId).toBe(NATIVE) + expect(result.intent).toBe('ViewIncident') + expect(result.result).toMatchObject({ type: 'bermuda.native.ack', of: { id: { incidentId: 'native-2' } } }) + }) + + test('findIntent lists the native app next to the web app', async ({ page }) => { + const apps = await page.evaluate(async () => (await (window.fdc3 as DesktopAgent).findIntent('ViewIncident')).apps.map((a) => a.appId)) + expect(apps).toEqual(expect.arrayContaining([NATIVE, 'bermuda-incidents'])) + }) +}) diff --git a/src/Bermuda/fdc3-appd.json b/src/Bermuda/fdc3-appd.json index fcfc2bc..24206da 100644 --- a/src/Bermuda/fdc3-appd.json +++ b/src/Bermuda/fdc3-appd.json @@ -1,5 +1,27 @@ { "applications": [ + { + "appId": "native-incidents", + "name": "native-incidents", + "title": "Native Incidents", + "description": "Sample native side app (Bermuda.NativeApp) connected over gRPC on a named pipe. Acknowledges incidents it receives.", + "type": "native", + "interop": { + "intents": { + "listensFor": { + "ViewIncident": { + "displayName": "View Incident (native)", + "contexts": ["bermuda.incident"], + "resultType": "bermuda.native.ack" + } + } + }, + "userChannels": { + "broadcasts": ["bermuda.native.ack"], + "listensFor": ["bermuda.incident"] + } + } + }, { "appId": "fdc3-probe", "name": "fdc3-probe", From fc1908e975e96579b27318804b833816d7cb54fc Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 11 Nov 2026 02:38:14 -0500 Subject: [PATCH 04/14] refactor: make fdc3.proto the source of truth for the gRPC surface The proto is now hand-written (Protos/fdc3.proto) and built by Grpc.Tools. The generator reads protoc's descriptor set, fails the build if the C# contract disagrees with it, and writes the mapping/service glue from it. Co-Authored-By: Claude Sonnet 5.5 --- Directory.Packages.props | 1 + docs/fdc3.md | 6 +- .../Bermuda.Fdc3.Grpc.Generator.csproj | 11 +- src/Bermuda.Fdc3.Grpc.Generator/Program.cs | 221 ++++++++++-------- .../Bermuda.Fdc3.Grpc.csproj | 21 +- .../{Generated => Protos}/fdc3.proto | 17 +- 6 files changed, 165 insertions(+), 112 deletions(-) rename src/Bermuda.Fdc3.Grpc/{Generated => Protos}/fdc3.proto (85%) diff --git a/Directory.Packages.props b/Directory.Packages.props index 4d13a29..05cd5a4 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -29,6 +29,7 @@ + diff --git a/docs/fdc3.md b/docs/fdc3.md index c7a21c3..e8ded5c 100644 --- a/docs/fdc3.md +++ b/docs/fdc3.md @@ -140,16 +140,16 @@ Rejections are `Error`s whose `message` is the standard FDC3 error string; over ## 7a. Native apps over gRPC (named pipe) -Native side apps join the same in-process agent as the web windows, so they share channels and intents with them. `Bermuda.Fdc3.Grpc` hosts a gRPC service (Kestrel named-pipe transport, HTTP/2 without TLS) that mirrors `IFdc3Commands`; the contract is `src/Bermuda.Fdc3.Grpc/Generated/fdc3.proto`. +Native side apps join the same in-process agent as the web windows, so they share channels and intents with them. `Bermuda.Fdc3.Grpc` hosts a gRPC service (Kestrel named-pipe transport, HTTP/2 without TLS) that mirrors `IFdc3Commands`; the contract is `src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto`. -**Generated, not hand-written.** `Bermuda.Fdc3.Grpc.Generator` reads `IFdc3Commands` and the records it uses by reflection and writes `Generated/fdc3.proto` (consumed by Grpc.Tools) and `Generated/Fdc3Generated.g.cs` (proto↔contract mapping and one service override per command). Building `Bermuda.Fdc3.Grpc` re-runs it whenever `Fdc3Contract.cs` or the generator changes; the outputs are checked in, like `ipc.d.ts`. Adding a command, a field or a record to the contract therefore updates the gRPC side with no further edits. Field numbers follow constructor order, so only append fields. Hand-written: the `Subscribe` stream and caller lookup (`Fdc3AgentService.cs`) and the JSON helper (`Mapping.cs`). +**The proto is the source of truth** for the gRPC surface. Grpc.Tools builds the messages and the `Fdc3Agent` service base from it. After protoc runs, `Bermuda.Fdc3.Grpc.Generator` reads protoc's descriptor set and checks it against `IFdc3Commands` and the records it uses. Any difference (a missing or extra rpc, message or field, or a type, `optional` or `repeated` mismatch) **fails the build** and lists the differences. When they agree, it writes `Generated/Fdc3Generated.g.cs` (checked in, refreshed by the build): the proto↔contract mapping and one service override per rpc. So changing the gRPC surface means editing the proto and updating `Fdc3Contract.cs` to match. The mapping conventions are at the top of the proto. Hand-written: the `Subscribe` stream and caller lookup (`Fdc3AgentService.cs`) and the JSON helper (`Mapping.cs`). - **Pipe**: `\\.\pipe\bermuda-fdc3-` by default (pipe names are machine-wide, so the user name keeps users apart). Override with `FDC3_GRPC_PIPE`; disable with `FDC3_GRPC_ENABLED=false` (both in `appsettings.json` or the environment). The pipe is current-user-only. - **Connect**: call `Subscribe(app_id)`. `app_id` MUST be in the App Directory, else the call fails with `AppNotFound`. The first stream message is `connected { instance_id }`; context, intent and API-event deliveries follow (`ContextEvent`, `IntentEvent`, `ApiEvent`, mirroring `Fdc3*Event`). - **Calls**: every other RPC carries the `x-fdc3-instance` header (the `instance_id`) and must use the same pipe connection as the stream, else `AccessDenied`. - **Lifetime**: the stream is the app instance. When it ends (cancelled, process exit, pipe closed) the instance is disconnected like a closed window. - **Contexts** are JSON text (`*_json` fields). **Errors** are gRPC errors whose status *detail* is the `Fdc3Errors` string (`NoChannelFound`, `MalformedContext`, …); the code is a coarse mapping (e.g. `NotFound`, `InvalidArgument`, `PermissionDenied`). -- **Client**: any gRPC stack that can dial a named pipe. `src/Bermuda.Fdc3.Grpc.Tests/Fdc3PipeClient.cs` is a ~100-line .NET reference (`SocketsHttpHandler.ConnectCallback` returning a `NamedPipeClientStream`). +- **Client**: any gRPC stack that can dial a named pipe. `Fdc3PipeClient` (in `Bermuda.Fdc3.Grpc`; used by the sample `src/Bermuda.NativeApp`) is a ~100-line .NET reference (`SocketsHttpHandler.ConnectCallback` returning a `NamedPipeClientStream`). - Limitations: native apps are not launched by the agent (`open`/intents can target them only while connected), and web windows are still the only apps with launch URLs. ## 8. Known limitations diff --git a/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj b/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj index 08f2def..97aecc9 100644 --- a/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj +++ b/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj @@ -1,10 +1,9 @@ Exe @@ -13,6 +12,10 @@ enable + + + + diff --git a/src/Bermuda.Fdc3.Grpc.Generator/Program.cs b/src/Bermuda.Fdc3.Grpc.Generator/Program.cs index 74b8d02..6af8430 100644 --- a/src/Bermuda.Fdc3.Grpc.Generator/Program.cs +++ b/src/Bermuda.Fdc3.Grpc.Generator/Program.cs @@ -2,23 +2,31 @@ using System.Text; using System.Text.Json; using Bermuda.IpcContract; +using Google.Protobuf; +using Google.Protobuf.Reflection; -// Usage: Bermuda.Fdc3.Grpc.Generator +// Usage: Bermuda.Fdc3.Grpc.Generator // -// Contract -> gRPC rules -// record Fdc3Foo(...) -> message Foo (fields numbered in constructor order, so only ever append) -// string / bool -> string / bool; a nullable string becomes `optional` -// JsonElement -> string _json (JSON text); nullable -> `optional` -// object? (event details) -> optional string _json (serialised with the web options) -// record -> message reference; Foo[] -> repeated -// method M(Req) -> Resp -> rpc M(Req) returns (Resp); no parameter / void -> google.protobuf.Empty; -// array / nullable results are wrapped in Response { items | result } -// [IpcType] Fdc3*Event records -> alternatives of AgentEvent's oneof -var outDir = args.Length > 0 ? args[0] : throw new ArgumentException("Pass the output directory."); +// fdc3.proto is the source of truth. This tool reads protoc's descriptor set of it, checks that the C# +// contract (IFdc3Commands and the records it uses) still matches it, and writes the glue that turns each +// gRPC call into a call on Fdc3Connection. Any mismatch fails the build with the list of differences. +// The rules it enforces are documented at the top of Protos/fdc3.proto. +if (args.Length != 2) throw new ArgumentException("Usage: "); +var descriptorPath = args[0]; +var outDir = args[1]; Directory.CreateDirectory(outDir); +var set = FileDescriptorSet.Parser.ParseFrom(File.ReadAllBytes(descriptorPath)); +var file = set.File.Single(f => f.Name.EndsWith("fdc3.proto", StringComparison.Ordinal)); var model = new ContractModel(typeof(IFdc3Commands)); -Write("fdc3.proto", new ProtoWriter(model).Generate()); +var errors = ProtoCheck.Run(model, file); +if (errors.Count > 0) +{ + Console.Error.WriteLine("fdc3.proto and the C# contract (Fdc3Contract.cs) disagree:"); + foreach (var error in errors) Console.Error.WriteLine(" - " + error); + return 1; +} + Write("Fdc3Generated.g.cs", new CSharpWriter(model).Generate()); return 0; @@ -154,97 +162,128 @@ public static string Pascal(string snake) => string.Concat(snake.Split('_', StringSplitOptions.RemoveEmptyEntries).Select(s => char.ToUpperInvariant(s[0]) + s[1..])); } -sealed class ProtoWriter(ContractModel model) +static class Expect { - private readonly StringBuilder _sb = new(); - - public string Generate() - { - Line("// "); - Line("// Generated by Bermuda.Fdc3.Grpc.Generator from IFdc3Commands (src/Bermuda.IpcContract/Fdc3Contract.cs)."); - Line("// Do not edit: change the contract and rebuild Bermuda.Fdc3.Grpc."); - Line("// "); - Line("syntax = \"proto3\";"); - Line(); - Line("package bermuda.fdc3.v1;"); - Line(); - Line("import \"google/protobuf/empty.proto\";"); - Line(); - Line("option csharp_namespace = \"Bermuda.Fdc3.Grpc.Proto\";"); - Line(); - Line("// Connection model: one pipe client opens Subscribe(app_id). The first message on that stream is"); - Line("// `connected` (carrying the new instance_id); the agent's deliveries follow. Every other RPC must carry"); - Line("// the instance_id in the `x-fdc3-instance` request header and use the same pipe connection. The instance"); - Line("// leaves the agent when the Subscribe stream ends. Contexts are JSON text (*_json fields); failures are"); - Line("// gRPC errors whose status detail is the FDC3 error string (Fdc3Errors)."); - Line("service Fdc3Agent {"); - Line(" rpc Subscribe(SubscribeRequest) returns (stream AgentEvent);"); - Line(); - foreach (var m in model.Methods) - Line($" rpc {m.RpcName}({RequestType(m)}) returns ({ResponseType(m)});"); - Line("}"); - Line(); - - foreach (var message in model.Messages) WriteMessage(message); - - foreach (var m in model.Methods.Where(m => m.NeedsWrapper)) - { - Line($"message {m.WrapperName} {{"); - if (m.ResultIsArray) Line($" repeated {ElementType(m)} items = 1;"); - else if (m.Result == typeof(JsonElement)) Line(" optional string result_json = 1;"); - else Line($" {ElementType(m)} result = 1;"); - Line("}"); - Line(); - } - - Line("message SubscribeRequest { string app_id = 1; }"); - Line(); - Line("// First message of every Subscribe stream."); - Line("message Connected {"); - Line(" string instance_id = 1;"); - Line(" string app_id = 2;"); - Line("}"); - Line(); - Line("message AgentEvent {"); - Line(" oneof event {"); - Line(" Connected connected = 1;"); - var number = 2; - foreach (var e in model.Events) - Line($" {e.Name} {EventField(e)} = {number++};"); - Line(" }"); - Line("}"); - return _sb.ToString(); - } - public static string EventField(Message e) => Naming.Snake(e.Name.EndsWith("Event", StringComparison.Ordinal) ? e.Name[..^5] : e.Name); public static string RequestType(Method m) => m.Param is null ? "google.protobuf.Empty" : ContractModel.MessageName(m.Param); public static string ResponseType(Method m) => m.IsVoid ? "google.protobuf.Empty" : m.NeedsWrapper ? m.WrapperName : ContractModel.MessageName(m.Result!); +} - private static string ElementType(Method m) => m.Result == typeof(JsonElement) ? "string" : ContractModel.MessageName(m.Result!); - - private void WriteMessage(Message message) +/// Checks the contract against the .proto: every difference is an error. +static class ProtoCheck +{ + public static List Run(ContractModel model, FileDescriptorProto file) { - Line($"message {message.Name} {{"); - var number = 1; - foreach (var f in message.Fields) + var errors = new List(); + var pkg = file.Package; + string Full(string name) => name.Contains('.') ? "." + name : "." + pkg + "." + name; + string Qualified(string name) => name == "google.protobuf.Empty" ? ".google.protobuf.Empty" : Full(name); + + var messages = file.MessageType.ToDictionary(m => m.Name); + var used = new HashSet { "SubscribeRequest", "Connected", "AgentEvent" }; + + // Service + var service = file.Service.SingleOrDefault(s => s.Name == "Fdc3Agent"); + if (service is null) { errors.Add("service Fdc3Agent is missing."); return errors; } + var rpcs = service.Method.Where(m => m.Name != "Subscribe").ToDictionary(m => m.Name); + if (!service.Method.Any(m => m.Name == "Subscribe" && m.ServerStreaming && m.InputType == Full("SubscribeRequest") && m.OutputType == Full("AgentEvent"))) + errors.Add("rpc Subscribe(SubscribeRequest) returns (stream AgentEvent) is required."); + + foreach (var method in model.Methods) + { + if (!rpcs.Remove(method.RpcName, out var rpc)) + { + errors.Add($"IFdc3Commands.{method.Info.Name} has no rpc {method.RpcName} in the proto."); + continue; + } + if (rpc.ClientStreaming || rpc.ServerStreaming) errors.Add($"rpc {rpc.Name} must be unary."); + if (rpc.InputType != Qualified(Expect.RequestType(method))) + errors.Add($"rpc {rpc.Name} takes {rpc.InputType.TrimStart('.')}; the contract expects {Expect.RequestType(method)}."); + if (rpc.OutputType != Qualified(Expect.ResponseType(method))) + errors.Add($"rpc {rpc.Name} returns {rpc.OutputType.TrimStart('.')}; the contract expects {Expect.ResponseType(method)}."); + + if (method.NeedsWrapper) + { + used.Add(method.WrapperName); + if (!messages.TryGetValue(method.WrapperName, out var wrapper)) { errors.Add($"message {method.WrapperName} is missing."); continue; } + var elementType = method.Result == typeof(JsonElement) ? null : Full(ContractModel.MessageName(method.Result!)); + if (method.ResultIsArray) + ExpectFields(errors, wrapper, ("items", FieldDescriptorProto.Types.Type.Message, elementType, true, false)); + else if (method.Result == typeof(JsonElement)) + ExpectFields(errors, wrapper, ("result_json", FieldDescriptorProto.Types.Type.String, null, false, true)); + else + ExpectFields(errors, wrapper, ("result", FieldDescriptorProto.Types.Type.Message, elementType, false, false)); + } + } + foreach (var extra in rpcs.Keys) errors.Add($"rpc {extra} has no matching method on IFdc3Commands."); + + // Messages + foreach (var message in model.Messages) { - var type = f.Kind switch + used.Add(message.Name); + if (!messages.TryGetValue(message.Name, out var proto)) { errors.Add($"message {message.Name} is missing (contract record {message.Type.Name})."); continue; } + var expected = message.Fields.Select(f => ( + f.ProtoName, + f.Kind switch + { + Kind.Bool => FieldDescriptorProto.Types.Type.Bool, + Kind.Message => FieldDescriptorProto.Types.Type.Message, + _ => FieldDescriptorProto.Types.Type.String, + }, + f.Kind == Kind.Message ? Full(ContractModel.MessageName(f.MessageType!)) : null, + f.IsArray, + f.IsScalarOptional)).ToArray(); + ExpectFields(errors, proto, expected); + } + + // Events + if (!messages.TryGetValue("AgentEvent", out var agentEvent)) errors.Add("message AgentEvent is missing."); + else + { + var expected = new List<(string, FieldDescriptorProto.Types.Type, string?, bool, bool)> { - Kind.String or Kind.Json or Kind.Object => "string", - Kind.Bool => "bool", - _ => ContractModel.MessageName(f.MessageType!), + ("connected", FieldDescriptorProto.Types.Type.Message, Full("Connected"), false, false), }; - var prefix = f.IsArray ? "repeated " : f.IsScalarOptional ? "optional " : ""; - Line($" {prefix}{type} {f.ProtoName} = {number++};"); + expected.AddRange(model.Events.Select(e => (Expect.EventField(e), FieldDescriptorProto.Types.Type.Message, (string?)Full(e.Name), false, false))); + ExpectFields(errors, agentEvent, expected.ToArray()); + if (agentEvent.OneofDecl.Count != 1 || agentEvent.Field.Any(f => !f.HasOneofIndex)) + errors.Add("message AgentEvent: all fields must be alternatives of a single oneof."); + } + + foreach (var name in messages.Keys.Where(n => !used.Contains(n))) + errors.Add($"message {name} is not used by any rpc, record or event; remove it or add it to the contract."); + return errors; + } + + private static void ExpectFields( + List errors, + DescriptorProto message, + params (string Name, FieldDescriptorProto.Types.Type Type, string? TypeName, bool Repeated, bool Optional)[] expected) + { + var actual = message.Field.ToDictionary(f => f.Name); + foreach (var e in expected) + { + if (!actual.Remove(e.Name, out var f)) + { + errors.Add($"message {message.Name}: field {e.Name} is in the contract but not in the proto."); + continue; + } + if (f.Type != e.Type || (e.TypeName is not null && f.TypeName != e.TypeName)) + errors.Add($"message {message.Name}.{e.Name}: proto has {Describe(f)}; the contract expects {(e.TypeName?.TrimStart('.') ?? e.Type.ToString().ToLowerInvariant())}."); + if ((f.Label == FieldDescriptorProto.Types.Label.Repeated) != e.Repeated) + errors.Add($"message {message.Name}.{e.Name}: {(e.Repeated ? "must be" : "must not be")} repeated (the contract {(e.Repeated ? "has an array" : "has a single value")})."); + if (e.Type != FieldDescriptorProto.Types.Type.Message && !e.Repeated && f.Proto3Optional != e.Optional) + errors.Add($"message {message.Name}.{e.Name}: {(e.Optional ? "must be" : "must not be")} `optional` (the contract value {(e.Optional ? "is" : "is not")} nullable)."); } - Line("}"); - Line(); + foreach (var extra in actual.Keys) + errors.Add($"message {message.Name}: field {extra} is in the proto but not in the contract record."); } - private void Line(string text = "") => _sb.Append(text).Append('\n'); + private static string Describe(FieldDescriptorProto f) => + f.Type == FieldDescriptorProto.Types.Type.Message ? f.TypeName.TrimStart('.') : f.Type.ToString().ToLowerInvariant(); } sealed class CSharpWriter(ContractModel model) @@ -278,7 +317,7 @@ public string Generate() L("public static Proto.AgentEvent? ToProtoEvent(object message) => message switch"); Open(); foreach (var e in model.Events) - L($"{e.Type.Name} e => new Proto.AgentEvent {{ {Naming.Pascal(ProtoWriter.EventField(e))} = ToProto(e) }},"); + L($"{e.Type.Name} e => new Proto.AgentEvent {{ {Naming.Pascal(Expect.EventField(e))} = ToProto(e) }},"); L("_ => null,"); Close(";"); Close(); @@ -347,8 +386,8 @@ private void WriteToProto(Message message) private void WriteRpc(Method m) { - var req = ProtoWriter.RequestType(m).Replace("google.protobuf.Empty", "Empty"); - var resp = ProtoWriter.ResponseType(m).Replace("google.protobuf.Empty", "Empty"); + var req = Expect.RequestType(m).Replace("google.protobuf.Empty", "Empty"); + var resp = Expect.ResponseType(m).Replace("google.protobuf.Empty", "Empty"); var respType = resp == "Empty" ? "Empty" : "Proto." + resp; var reqType = req == "Empty" ? "Empty" : "Proto." + req; var call = $"Caller(context).{m.Info.Name}({(m.Param is null ? "" : "GeneratedMapping.ToContract(request)")})"; diff --git a/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj b/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj index 3fc49aa..845ad76 100644 --- a/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj +++ b/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj @@ -16,24 +16,25 @@ - + + - - + + diff --git a/src/Bermuda.Fdc3.Grpc/Generated/fdc3.proto b/src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto similarity index 85% rename from src/Bermuda.Fdc3.Grpc/Generated/fdc3.proto rename to src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto index a68cf4a..3b4d666 100644 --- a/src/Bermuda.Fdc3.Grpc/Generated/fdc3.proto +++ b/src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto @@ -1,7 +1,16 @@ -// -// Generated by Bermuda.Fdc3.Grpc.Generator from IFdc3Commands (src/Bermuda.IpcContract/Fdc3Contract.cs). -// Do not edit: change the contract and rebuild Bermuda.Fdc3.Grpc. -// +// The gRPC contract for Bermuda's FDC3 desktop agent, and its source of truth: Grpc.Tools builds the C# +// messages and the Fdc3Agent service base from this file, and Bermuda.Fdc3.Grpc.Generator derives the +// proto <-> IFdc3Commands glue from it (Generated/Fdc3Generated.g.cs). The build FAILS if the C# contract +// (src/Bermuda.IpcContract/Fdc3Contract.cs) no longer matches this file, so a change here means updating +// the contract too (and vice versa). Never renumber or reuse field numbers. +// +// Conventions the generator relies on: +// message Foo <-> record Fdc3Foo; field snake_case names <-> constructor parameters +// string xxx_json <-> JsonElement / object? xxx (JSON text); proto3 `optional` <-> nullable +// repeated Foo <-> Foo[] +// rpc M(Req) returns (R) <-> M(Req) / MAsync(Req); google.protobuf.Empty <-> no parameter / void +// MResponse { items | result | result_json } wraps a result that is an array / nullable +// AgentEvent oneof <-> the [IpcType] Fdc3*Event records (plus the transport-only `connected`) syntax = "proto3"; package bermuda.fdc3.v1; From a0764f12b0690a46c42db7df4b054a069b4d9b46 Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 11 Nov 2026 02:55:21 -0500 Subject: [PATCH 05/14] refactor: generate the C# FDC3 contract and gRPC glue from fdc3.proto fdc3.proto (new Bermuda.Fdc3.Proto project) is now the single source of truth. Its build runs Bermuda.Fdc3.Grpc.Generator on protoc's descriptor set to write the Fdc3* records and IFdc3Commands (Bermuda.IpcContract/ Generated) and the gRPC glue (Bermuda.Fdc3.Grpc/Generated). The pipe client moves into the proto project so native apps need no ASP.NET Core. API event details are JSON; AgentEvent's oneof is `kind`. Co-Authored-By: Claude Sonnet 5.5 --- Bermuda.slnx | 1 + Directory.Packages.props | 2 + .../Bermuda.Fdc3.Grpc.Generator.csproj | 9 +- src/Bermuda.Fdc3.Grpc.Generator/Program.cs | 587 ++++++++++-------- .../Bermuda.Fdc3.Grpc.csproj | 30 +- src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs | 6 - src/Bermuda.Fdc3.Grpc/Fdc3GrpcHost.cs | 11 +- .../Generated/Fdc3Generated.g.cs | 279 +++++---- .../Bermuda.Fdc3.Proto.csproj | 41 ++ .../Fdc3PipeClient.cs | 19 +- .../Protos/fdc3.proto | 232 ++++--- src/Bermuda.Fdc3/DesktopAgent.cs | 10 +- .../Bermuda.IpcContract.csproj | 8 + src/Bermuda.IpcContract/Fdc3Contract.cs | 176 ------ .../Generated/Fdc3Contract.g.cs | 155 +++++ src/Bermuda.NativeApp/Program.cs | 6 +- src/Bermuda.Web/src/fdc3/hostDesktopAgent.ts | 2 +- .../src/ipc/__generated__/ipc.d.ts | 2 +- src/Bermuda/App.xaml.cs | 2 +- 19 files changed, 846 insertions(+), 732 deletions(-) create mode 100644 src/Bermuda.Fdc3.Proto/Bermuda.Fdc3.Proto.csproj rename src/{Bermuda.Fdc3.Grpc => Bermuda.Fdc3.Proto}/Fdc3PipeClient.cs (84%) rename src/{Bermuda.Fdc3.Grpc => Bermuda.Fdc3.Proto}/Protos/fdc3.proto (51%) delete mode 100644 src/Bermuda.IpcContract/Fdc3Contract.cs create mode 100644 src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs diff --git a/Bermuda.slnx b/Bermuda.slnx index e15caf2..eedad4a 100644 --- a/Bermuda.slnx +++ b/Bermuda.slnx @@ -6,6 +6,7 @@ + diff --git a/Directory.Packages.props b/Directory.Packages.props index 05cd5a4..e27c7b4 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -30,6 +30,8 @@ + + diff --git a/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj b/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj index 97aecc9..03c1da8 100644 --- a/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj +++ b/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj @@ -1,9 +1,8 @@ Exe @@ -16,8 +15,4 @@ - - - - diff --git a/src/Bermuda.Fdc3.Grpc.Generator/Program.cs b/src/Bermuda.Fdc3.Grpc.Generator/Program.cs index 6af8430..bab602c 100644 --- a/src/Bermuda.Fdc3.Grpc.Generator/Program.cs +++ b/src/Bermuda.Fdc3.Grpc.Generator/Program.cs @@ -1,303 +1,344 @@ -using System.Reflection; using System.Text; -using System.Text.Json; -using Bermuda.IpcContract; using Google.Protobuf; using Google.Protobuf.Reflection; -// Usage: Bermuda.Fdc3.Grpc.Generator +// Usage: Bermuda.Fdc3.Grpc.Generator // -// fdc3.proto is the source of truth. This tool reads protoc's descriptor set of it, checks that the C# -// contract (IFdc3Commands and the records it uses) still matches it, and writes the glue that turns each -// gRPC call into a call on Fdc3Connection. Any mismatch fails the build with the list of differences. -// The rules it enforces are documented at the top of Protos/fdc3.proto. -if (args.Length != 2) throw new ArgumentException("Usage: "); -var descriptorPath = args[0]; -var outDir = args[1]; -Directory.CreateDirectory(outDir); - -var set = FileDescriptorSet.Parser.ParseFrom(File.ReadAllBytes(descriptorPath)); +// Protos/fdc3.proto is the source of truth for Bermuda's FDC3 contract (the conventions are documented at the +// top of that file). This tool reads protoc's descriptor set of it (with source info, for the doc comments) and +// writes: +// * the C# contract the in-process agent and the web bridge use: Fdc3* records and IFdc3Commands; +// * the glue that serves it over gRPC: proto <-> record mapping and one service override per rpc. +// A proto that breaks the conventions fails the build with the list of problems. +if (args.Length != 3) throw new ArgumentException("Usage: "); + +// The `async` method option (field 50001 of google.protobuf.MethodOptions) is defined in fdc3.proto itself. +var asyncOption = new Extension(50001, FieldCodec.ForBool(50001u << 3)); +var set = FileDescriptorSet.Parser + .WithExtensionRegistry(new ExtensionRegistry { asyncOption }) + .ParseFrom(File.ReadAllBytes(args[0])); var file = set.File.Single(f => f.Name.EndsWith("fdc3.proto", StringComparison.Ordinal)); -var model = new ContractModel(typeof(IFdc3Commands)); -var errors = ProtoCheck.Run(model, file); + +var (model, errors) = ProtoModel.Build(file, asyncOption); if (errors.Count > 0) { - Console.Error.WriteLine("fdc3.proto and the C# contract (Fdc3Contract.cs) disagree:"); + Console.Error.WriteLine("fdc3.proto breaks the generator's conventions:"); foreach (var error in errors) Console.Error.WriteLine(" - " + error); return 1; } -Write("Fdc3Generated.g.cs", new CSharpWriter(model).Generate()); +Write(args[1], new ContractWriter(model).Generate()); +Write(args[2], new GlueWriter(model).Generate()); return 0; -void Write(string name, string content) +static void Write(string path, string content) { - var path = Path.Combine(outDir, name); + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!); content = content.Replace("\r\n", "\n"); // Don't touch an unchanged file, so incremental builds stay incremental. - if (!File.Exists(path) || File.ReadAllText(path) != content) File.WriteAllText(path, content); + if (!File.Exists(path) || File.ReadAllText(path).Replace("\r\n", "\n") != content) File.WriteAllText(path, content); } -enum Kind { String, Bool, Json, Object, Message } +enum Kind { String, Bool, Json, Message } -sealed record Field(string ClrName, string ProtoName, string CsName, Kind Kind, bool IsArray, bool Optional, Type? MessageType) +/// Property name on the protoc-generated class. +/// Property name on the contract record (and so the web JSON name). +sealed record Field(string ProtoName, string ProtoCs, string Prop, Kind Kind, bool Repeated, bool Optional, string? Message) { - public bool IsScalarOptional => Optional && Kind is Kind.String or Kind.Json or Kind.Object; + public bool Nullable => Optional && !Repeated; } -sealed record Message(Type Type, string Name, List Fields, ConstructorInfo Constructor); +sealed record Msg(string Name, string Record, List Fields, string? Doc); -sealed record Method(MethodInfo Info, string RpcName, Type? Param, Type? Result, bool ResultIsArray, bool ResultNullable, bool IsAsync, bool IsVoid) -{ - public bool NeedsWrapper => !IsVoid && (ResultIsArray || ResultNullable); - public string WrapperName => RpcName + "Response"; -} +enum Shape { Void, Direct, Array, Nullable, NullableJson } -sealed class ContractModel +/// Request message, null for google.protobuf.Empty. +/// Result message (null for void / JSON); says how the contract returns it. +sealed record Rpc(string Name, string? Request, string? Result, Shape Shape, bool Async, string? Wrapper, string? Doc); + +/// AgentEvent oneof field, which is also the web message type suffix ("fdc3.<field>"). +sealed record Ev(Msg Message, string Field, string ProtoCs); + +sealed class ProtoModel { - private readonly NullabilityInfoContext _nullability = new(); + private static readonly HashSet Transport = ["SubscribeRequest", "Connected", "AgentEvent"]; - public List Messages { get; } = []; - public List Methods { get; } = []; - public List Events { get; } = []; + public List Messages { get; } = []; + public List Rpcs { get; } = []; + public List Events { get; } = []; - public ContractModel(Type commands) + public static (ProtoModel Model, List Errors) Build(FileDescriptorProto file, Extension asyncOption) { - foreach (var info in commands.GetMethods()) - { - var parameters = info.GetParameters(); - if (parameters.Length > 1) throw new NotSupportedException($"{info.Name}: at most one parameter."); + var model = new ProtoModel(); + var errors = new List(); + var prefix = "." + file.Package + "."; + string? Local(string typeName) => typeName.StartsWith(prefix, StringComparison.Ordinal) ? typeName[prefix.Length..] : null; - var returnType = info.ReturnType; - var isAsync = false; - if (returnType == typeof(Task)) { returnType = typeof(void); isAsync = true; } - else if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>)) - { - returnType = returnType.GetGenericArguments()[0]; - isAsync = true; - } + var docs = file.SourceCodeInfo?.Location + .Where(l => l.LeadingComments.Length > 0) + .ToDictionary(l => string.Join(',', l.Path), l => Clean(l.LeadingComments)) ?? []; + string? DocOf(params int[] path) => docs.GetValueOrDefault(string.Join(',', path)); - var isVoid = returnType == typeof(void); - var isArray = returnType.IsArray; - var nullable = !isVoid && (Nullable.GetUnderlyingType(returnType) is not null - || (!isAsync && !returnType.IsValueType && _nullability.Create(info.ReturnParameter).ReadState == NullabilityState.Nullable)); - var element = isVoid ? null : isArray ? returnType.GetElementType()! : Nullable.GetUnderlyingType(returnType) ?? returnType; + var service = file.Service.SingleOrDefault(s => s.Name == "Fdc3Agent"); + if (service is null) { errors.Add("service Fdc3Agent is missing."); return (model, errors); } + var serviceIndex = file.Service.IndexOf(service); - if (parameters.Length == 1) Visit(parameters[0].ParameterType); - if (element is not null && element != typeof(JsonElement)) Visit(element); + // Wrapper messages are named after the rpc whose result they carry. + var wrapperNames = service.Method.Select(m => m.Name + "Response").ToHashSet(); + var byName = file.MessageType.ToDictionary(m => m.Name); - var rpcName = info.Name.EndsWith("Async", StringComparison.Ordinal) ? info.Name[..^5] : info.Name; - Methods.Add(new Method(info, rpcName, parameters.Length == 1 ? parameters[0].ParameterType : null, - element, isArray, nullable, isAsync, isVoid)); - } + if (!service.Method.Any(m => m.Name == "Subscribe" && m.ServerStreaming && m.InputType == prefix + "SubscribeRequest" && m.OutputType == prefix + "AgentEvent")) + errors.Add("rpc Subscribe(SubscribeRequest) returns (stream AgentEvent) is required."); - foreach (var type in commands.Assembly.GetTypes() - .Where(t => t.GetCustomAttribute() is not null && t.Name.StartsWith("Fdc3", StringComparison.Ordinal) && t.Name.EndsWith("Event", StringComparison.Ordinal)) - .OrderBy(t => t.Name, StringComparer.Ordinal)) + // Events: AgentEvent's oneof alternatives other than `connected`. + var events = new List<(string Field, string Message)>(); + if (!byName.TryGetValue("AgentEvent", out var agentEvent)) errors.Add("message AgentEvent is missing."); + else { - Visit(type); - Events.Add(Messages.Single(m => m.Type == type)); + if (agentEvent.OneofDecl.Count != 1 || agentEvent.Field.Any(f => !f.HasOneofIndex)) + errors.Add("message AgentEvent must contain exactly one oneof holding all its fields."); + foreach (var f in agentEvent.Field.Where(f => f.Name != "connected")) + { + var type = f.Type == FieldDescriptorProto.Types.Type.Message ? Local(f.TypeName) : null; + if (type is null || !type.EndsWith("Event", StringComparison.Ordinal)) + errors.Add($"AgentEvent.{f.Name} must be a message whose name ends in Event."); + else events.Add((f.Name, type)); + } } - } - public static string MessageName(Type type) => type.Name.StartsWith("Fdc3", StringComparison.Ordinal) ? type.Name[4..] : type.Name; + // Messages + for (var i = 0; i < file.MessageType.Count; i++) + { + var m = file.MessageType[i]; + if (Transport.Contains(m.Name) || wrapperNames.Contains(m.Name)) continue; + var fields = new List(); + foreach (var f in m.Field) + { + var repeated = f.Label == FieldDescriptorProto.Types.Label.Repeated; + var optional = f.Proto3Optional; + string? message = null; + Kind kind; + switch (f.Type) + { + case FieldDescriptorProto.Types.Type.String when f.Name.EndsWith("_json", StringComparison.Ordinal): + kind = Kind.Json; + break; + case FieldDescriptorProto.Types.Type.String: + kind = Kind.String; + break; + case FieldDescriptorProto.Types.Type.Bool: + kind = Kind.Bool; + break; + case FieldDescriptorProto.Types.Type.Message when Local(f.TypeName) is { } local: + kind = Kind.Message; + message = local; + break; + default: + errors.Add($"{m.Name}.{f.Name}: unsupported type {f.Type} (use string, bool, a message of this package, or repeated message)."); + continue; + } + if (repeated && kind != Kind.Message) errors.Add($"{m.Name}.{f.Name}: only message fields can be repeated."); + if (repeated && optional) errors.Add($"{m.Name}.{f.Name}: a repeated field cannot be optional."); + if (kind is Kind.Bool && optional) errors.Add($"{m.Name}.{f.Name}: optional bool is not supported."); + + var json = string.IsNullOrEmpty(f.JsonName) ? Naming.Camel(f.Name) : f.JsonName; + if (kind == Kind.Json && json.EndsWith("Json", StringComparison.Ordinal)) json = json[..^4]; + fields.Add(new Field(f.Name, Naming.Pascal(f.Name), char.ToUpperInvariant(json[0]) + json[1..], kind, repeated, optional, message)); + } + model.Messages.Add(new Msg(m.Name, "Fdc3" + m.Name, fields, DocOf(4, i))); + } - public Message Of(Type type) => Messages.Single(m => m.Type == type); + var messages = model.Messages.ToDictionary(m => m.Name); + foreach (var (field, message) in events) + { + if (!messages.TryGetValue(message, out var msg)) { errors.Add($"event message {message} is missing."); continue; } + model.Events.Add(new Ev(msg, field, Naming.Pascal(field))); + } - private void Visit(Type type) - { - if (Messages.Any(m => m.Type == type)) return; - if (type.Assembly != typeof(IFdc3Commands).Assembly || type.IsPrimitive || type == typeof(string)) - throw new NotSupportedException($"{type}: only contract records can be messages."); + // Rpcs + for (var i = 0; i < service.Method.Count; i++) + { + var rpc = service.Method[i]; + if (rpc.Name == "Subscribe") continue; + if (rpc.ClientStreaming || rpc.ServerStreaming) errors.Add($"rpc {rpc.Name} must be unary."); - var ctor = type.GetConstructors().Single(); - var message = new Message(type, MessageName(type), [], ctor); - Messages.Add(message); + var request = rpc.InputType == ".google.protobuf.Empty" ? null : Local(rpc.InputType); + if (rpc.InputType != ".google.protobuf.Empty" && (request is null || !messages.ContainsKey(request))) + errors.Add($"rpc {rpc.Name}: request type {rpc.InputType} must be google.protobuf.Empty or a message of this package."); - foreach (var p in ctor.GetParameters()) - { - var isArray = p.ParameterType.IsArray; - var t = isArray ? p.ParameterType.GetElementType()! : p.ParameterType; - var underlying = Nullable.GetUnderlyingType(t); - var optional = underlying is not null || (!t.IsValueType && _nullability.Create(p).ReadState == NullabilityState.Nullable); - t = underlying ?? t; - - var snake = Naming.Snake(p.Name!); - if (t == typeof(string)) message.Fields.Add(new(p.Name!, snake, Naming.Pascal(snake), Kind.String, isArray, optional, null)); - else if (t == typeof(bool)) message.Fields.Add(new(p.Name!, snake, Naming.Pascal(snake), Kind.Bool, isArray, false, null)); - else if (t == typeof(JsonElement)) message.Fields.Add(new(p.Name!, snake + "_json", Naming.Pascal(snake + "_json"), Kind.Json, isArray, optional, null)); - else if (t == typeof(object)) message.Fields.Add(new(p.Name!, snake + "_json", Naming.Pascal(snake + "_json"), Kind.Object, isArray, optional, null)); + var isAsync = rpc.Options is not null && rpc.Options.HasExtension(asyncOption) && rpc.Options.GetExtension(asyncOption); + string? result = null; + string? wrapper = null; + Shape shape; + if (rpc.OutputType == ".google.protobuf.Empty") shape = Shape.Void; + else if (Local(rpc.OutputType) is { } output && output == rpc.Name + "Response" && byName.TryGetValue(output, out var w)) + { + wrapper = output; + var f = w.Field.Count == 1 ? w.Field[0] : null; + if (f is { Name: "items", Type: FieldDescriptorProto.Types.Type.Message } && f.Label == FieldDescriptorProto.Types.Label.Repeated && Local(f.TypeName) is { } item) + (shape, result) = (Shape.Array, item); + else if (f is { Name: "result", Type: FieldDescriptorProto.Types.Type.Message, Proto3Optional: true } && Local(f.TypeName) is { } single) + (shape, result) = (Shape.Nullable, single); + else if (f is { Name: "result_json", Type: FieldDescriptorProto.Types.Type.String, Proto3Optional: true }) + shape = Shape.NullableJson; + else + { + errors.Add($"{output} must have exactly one field: `repeated Message items`, `optional Message result` or `optional string result_json`."); + shape = Shape.Direct; + } + } + else if (Local(rpc.OutputType) is { } direct && messages.ContainsKey(direct)) (shape, result) = (Shape.Direct, direct); else { - Visit(t); - message.Fields.Add(new(p.Name!, snake, Naming.Pascal(snake), Kind.Message, isArray, optional, t)); + errors.Add($"rpc {rpc.Name}: response type {rpc.OutputType} must be google.protobuf.Empty or a message of this package."); + shape = Shape.Void; } + model.Rpcs.Add(new Rpc(rpc.Name, request, result, shape, isAsync, wrapper, DocOf(6, serviceIndex, 2, i))); } - } -} -static class Naming -{ - /// PascalCase -> snake_case the way protoc round-trips it ("APIs" -> "ap_is"). - public static string Snake(string name) - { - var sb = new StringBuilder(); - for (var i = 0; i < name.Length; i++) + // Every contract message must be reachable from an rpc or an event; otherwise it is dead weight. + var used = new HashSet(); + void Use(string? name) { - var c = name[i]; - if (char.IsUpper(c)) - { - var prevLowerOrDigit = i > 0 && (char.IsLower(name[i - 1]) || char.IsDigit(name[i - 1])); - var acronymEnd = i > 0 && char.IsUpper(name[i - 1]) && i + 1 < name.Length && char.IsLower(name[i + 1]); - if (prevLowerOrDigit || acronymEnd) sb.Append('_'); - sb.Append(char.ToLowerInvariant(c)); - } - else sb.Append(c); + if (name is null || !used.Add(name) || !messages.TryGetValue(name, out var msg)) return; + foreach (var f in msg.Fields) Use(f.Message); } - return sb.ToString(); + foreach (var r in model.Rpcs) { Use(r.Request); Use(r.Result); } + foreach (var e in model.Events) Use(e.Message.Name); + foreach (var m in model.Messages.Where(m => !used.Contains(m.Name))) + errors.Add($"message {m.Name} is not used by any rpc or event; remove it."); + foreach (var w in wrapperNames.Where(byName.ContainsKey).Where(n => model.Rpcs.All(r => r.Wrapper != n))) + errors.Add($"message {w} looks like a wrapper but rpc {w[..^8]} does not return it."); + + return (model, errors); } - /// protoc's C# property name for a proto field. + private static string Clean(string comment) => + string.Join("\n", comment.TrimEnd().Split('\n').Select(l => l.StartsWith(' ') ? l[1..] : l)); +} + +static class Naming +{ + /// protoc's C# property name for a proto field: "app_id" -> "AppId". public static string Pascal(string snake) => string.Concat(snake.Split('_', StringSplitOptions.RemoveEmptyEntries).Select(s => char.ToUpperInvariant(s[0]) + s[1..])); + + /// protoc's default json_name: "app_id" -> "appId". + public static string Camel(string snake) + { + var pascal = Pascal(snake); + return char.ToLowerInvariant(pascal[0]) + pascal[1..]; + } } -static class Expect +abstract class CodeWriter { - public static string EventField(Message e) => Naming.Snake(e.Name.EndsWith("Event", StringComparison.Ordinal) ? e.Name[..^5] : e.Name); + private readonly StringBuilder _sb = new(); + private int _indent; - public static string RequestType(Method m) => m.Param is null ? "google.protobuf.Empty" : ContractModel.MessageName(m.Param); + protected void L(string text = "") => _sb.Append(text.Length == 0 ? "" : new string(' ', _indent * 4) + text).Append('\n'); + protected void Open() { L("{"); _indent++; } + protected void Close(string suffix = "") { _indent--; L("}" + suffix); } + protected string Result => _sb.ToString(); - public static string ResponseType(Method m) => - m.IsVoid ? "google.protobuf.Empty" : m.NeedsWrapper ? m.WrapperName : ContractModel.MessageName(m.Result!); + protected void Doc(string? comment) + { + if (string.IsNullOrWhiteSpace(comment)) return; + L("/// "); + foreach (var line in comment.Split('\n')) + L(("/// " + line.Replace("&", "&").Replace("<", "<").Replace(">", ">")).TrimEnd()); + L("/// "); + } } -/// Checks the contract against the .proto: every difference is an error. -static class ProtoCheck +/// Fdc3* records and IFdc3Commands: what DesktopAgent, Fdc3Connection and the web bridge are written against. +sealed class ContractWriter(ProtoModel model) : CodeWriter { - public static List Run(ContractModel model, FileDescriptorProto file) + public string Generate() { - var errors = new List(); - var pkg = file.Package; - string Full(string name) => name.Contains('.') ? "." + name : "." + pkg + "." + name; - string Qualified(string name) => name == "google.protobuf.Empty" ? ".google.protobuf.Empty" : Full(name); - - var messages = file.MessageType.ToDictionary(m => m.Name); - var used = new HashSet { "SubscribeRequest", "Connected", "AgentEvent" }; - - // Service - var service = file.Service.SingleOrDefault(s => s.Name == "Fdc3Agent"); - if (service is null) { errors.Add("service Fdc3Agent is missing."); return errors; } - var rpcs = service.Method.Where(m => m.Name != "Subscribe").ToDictionary(m => m.Name); - if (!service.Method.Any(m => m.Name == "Subscribe" && m.ServerStreaming && m.InputType == Full("SubscribeRequest") && m.OutputType == Full("AgentEvent"))) - errors.Add("rpc Subscribe(SubscribeRequest) returns (stream AgentEvent) is required."); + L("// "); + L("// Generated by Bermuda.Fdc3.Grpc.Generator from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto. Do not edit:"); + L("// change the proto and rebuild Bermuda.Fdc3.Proto."); + L("// "); + L("#nullable enable"); + L("using System.Text.Json;"); + L(); + L("namespace Bermuda.IpcContract;"); + L(); - foreach (var method in model.Methods) + foreach (var m in model.Messages) { - if (!rpcs.Remove(method.RpcName, out var rpc)) + var ev = model.Events.FirstOrDefault(e => e.Message == m); + Doc(m.Doc); + if (ev is not null) L("[IpcType]"); + L($"public sealed record {m.Record}({Parameters(m)}){(ev is null ? ";" : "")}"); + if (ev is not null) { - errors.Add($"IFdc3Commands.{method.Info.Name} has no rpc {method.RpcName} in the proto."); - continue; + Open(); + L($"public string Type => \"fdc3.{ev.Field}\";"); + Close(); } - if (rpc.ClientStreaming || rpc.ServerStreaming) errors.Add($"rpc {rpc.Name} must be unary."); - if (rpc.InputType != Qualified(Expect.RequestType(method))) - errors.Add($"rpc {rpc.Name} takes {rpc.InputType.TrimStart('.')}; the contract expects {Expect.RequestType(method)}."); - if (rpc.OutputType != Qualified(Expect.ResponseType(method))) - errors.Add($"rpc {rpc.Name} returns {rpc.OutputType.TrimStart('.')}; the contract expects {Expect.ResponseType(method)}."); - - if (method.NeedsWrapper) - { - used.Add(method.WrapperName); - if (!messages.TryGetValue(method.WrapperName, out var wrapper)) { errors.Add($"message {method.WrapperName} is missing."); continue; } - var elementType = method.Result == typeof(JsonElement) ? null : Full(ContractModel.MessageName(method.Result!)); - if (method.ResultIsArray) - ExpectFields(errors, wrapper, ("items", FieldDescriptorProto.Types.Type.Message, elementType, true, false)); - else if (method.Result == typeof(JsonElement)) - ExpectFields(errors, wrapper, ("result_json", FieldDescriptorProto.Types.Type.String, null, false, true)); - else - ExpectFields(errors, wrapper, ("result", FieldDescriptorProto.Types.Type.Message, elementType, false, false)); - } - } - foreach (var extra in rpcs.Keys) errors.Add($"rpc {extra} has no matching method on IFdc3Commands."); - - // Messages - foreach (var message in model.Messages) - { - used.Add(message.Name); - if (!messages.TryGetValue(message.Name, out var proto)) { errors.Add($"message {message.Name} is missing (contract record {message.Type.Name})."); continue; } - var expected = message.Fields.Select(f => ( - f.ProtoName, - f.Kind switch - { - Kind.Bool => FieldDescriptorProto.Types.Type.Bool, - Kind.Message => FieldDescriptorProto.Types.Type.Message, - _ => FieldDescriptorProto.Types.Type.String, - }, - f.Kind == Kind.Message ? Full(ContractModel.MessageName(f.MessageType!)) : null, - f.IsArray, - f.IsScalarOptional)).ToArray(); - ExpectFields(errors, proto, expected); + L(); } - // Events - if (!messages.TryGetValue("AgentEvent", out var agentEvent)) errors.Add("message AgentEvent is missing."); - else + L("/// "); + L("/// The fdc3.* commands: one per FDC3 DesktopAgent / Channel / PrivateChannel / IntentResolution call,"); + L("/// plus SendIntentResult, which reports an intent handler's outcome back. Implemented per app instance"); + L("/// by Bermuda.Fdc3.Fdc3Connection. Methods throw Fdc3Exception, whose message is the"); + L("/// standard FDC3 error string."); + L("/// "); + L("[IpcCommands(\"fdc3\")]"); + L("public interface IFdc3Commands"); + Open(); + foreach (var rpc in model.Rpcs) { - var expected = new List<(string, FieldDescriptorProto.Types.Type, string?, bool, bool)> + Doc(rpc.Doc); + var returns = rpc.Shape switch { - ("connected", FieldDescriptorProto.Types.Type.Message, Full("Connected"), false, false), + Shape.Void => rpc.Async ? "Task" : "void", + _ => rpc.Async ? $"Task<{ReturnType(rpc)}>" : ReturnType(rpc), }; - expected.AddRange(model.Events.Select(e => (Expect.EventField(e), FieldDescriptorProto.Types.Type.Message, (string?)Full(e.Name), false, false))); - ExpectFields(errors, agentEvent, expected.ToArray()); - if (agentEvent.OneofDecl.Count != 1 || agentEvent.Field.Any(f => !f.HasOneofIndex)) - errors.Add("message AgentEvent: all fields must be alternatives of a single oneof."); + var parameter = rpc.Request is null ? "" : $"Fdc3{rpc.Request} request"; + L($"{returns} {rpc.Name}{(rpc.Async ? "Async" : "")}({parameter});"); } - - foreach (var name in messages.Keys.Where(n => !used.Contains(n))) - errors.Add($"message {name} is not used by any rpc, record or event; remove it or add it to the contract."); - return errors; + Close(); + return Result; } - private static void ExpectFields( - List errors, - DescriptorProto message, - params (string Name, FieldDescriptorProto.Types.Type Type, string? TypeName, bool Repeated, bool Optional)[] expected) + private static string ReturnType(Rpc rpc) => rpc.Shape switch { - var actual = message.Field.ToDictionary(f => f.Name); - foreach (var e in expected) - { - if (!actual.Remove(e.Name, out var f)) - { - errors.Add($"message {message.Name}: field {e.Name} is in the contract but not in the proto."); - continue; - } - if (f.Type != e.Type || (e.TypeName is not null && f.TypeName != e.TypeName)) - errors.Add($"message {message.Name}.{e.Name}: proto has {Describe(f)}; the contract expects {(e.TypeName?.TrimStart('.') ?? e.Type.ToString().ToLowerInvariant())}."); - if ((f.Label == FieldDescriptorProto.Types.Label.Repeated) != e.Repeated) - errors.Add($"message {message.Name}.{e.Name}: {(e.Repeated ? "must be" : "must not be")} repeated (the contract {(e.Repeated ? "has an array" : "has a single value")})."); - if (e.Type != FieldDescriptorProto.Types.Type.Message && !e.Repeated && f.Proto3Optional != e.Optional) - errors.Add($"message {message.Name}.{e.Name}: {(e.Optional ? "must be" : "must not be")} `optional` (the contract value {(e.Optional ? "is" : "is not")} nullable)."); - } - foreach (var extra in actual.Keys) - errors.Add($"message {message.Name}: field {extra} is in the proto but not in the contract record."); + Shape.Array => $"Fdc3{rpc.Result}[]", + Shape.Nullable => $"Fdc3{rpc.Result}?", + Shape.NullableJson => "JsonElement?", + _ => $"Fdc3{rpc.Result}", + }; + + private static string Parameters(Msg m) + { + var parts = m.Fields.Select(f => (Type: TypeOf(f), f.Prop, f.Nullable)).ToList(); + var firstDefault = parts.Count; + while (firstDefault > 0 && parts[firstDefault - 1].Nullable) firstDefault--; + return string.Join(", ", parts.Select((p, i) => $"{p.Type} {p.Prop}{(i >= firstDefault ? " = null" : "")}")); } - private static string Describe(FieldDescriptorProto f) => - f.Type == FieldDescriptorProto.Types.Type.Message ? f.TypeName.TrimStart('.') : f.Type.ToString().ToLowerInvariant(); + private static string TypeOf(Field f) => f.Kind switch + { + Kind.String => f.Nullable ? "string?" : "string", + Kind.Bool => "bool", + Kind.Json => f.Nullable ? "JsonElement?" : "JsonElement", + _ => "Fdc3" + f.Message + (f.Repeated ? "[]" : f.Nullable ? "?" : ""), + }; } -sealed class CSharpWriter(ContractModel model) +/// The gRPC side: proto message <-> record mapping, and the service overrides that call Fdc3Connection. +sealed class GlueWriter(ProtoModel model) : CodeWriter { - private readonly StringBuilder _sb = new(); - private int _indent; - public string Generate() { L("// "); - L("// Generated by Bermuda.Fdc3.Grpc.Generator from IFdc3Commands. Do not edit."); + L("// Generated by Bermuda.Fdc3.Grpc.Generator from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto. Do not edit."); L("// "); L("#nullable enable"); - L("using System.Text.Json;"); L("using Bermuda.IpcContract;"); L("using Google.Protobuf.WellKnownTypes;"); L("using Grpc.Core;"); @@ -307,17 +348,17 @@ public string Generate() L(); L("internal static class GeneratedMapping"); Open(); - foreach (var message in model.Messages) + foreach (var m in model.Messages) { - if (!model.Events.Contains(message)) WriteToContract(message); - WriteToProto(message); + if (model.Events.All(e => e.Message != m)) WriteToContract(m); + WriteToProto(m); } L("/// Maps what the agent posts to a sink; null for a message type this transport doesn't know."); L("public static Proto.AgentEvent? ToProtoEvent(object message) => message switch"); Open(); foreach (var e in model.Events) - L($"{e.Type.Name} e => new Proto.AgentEvent {{ {Naming.Pascal(Expect.EventField(e))} = ToProto(e) }},"); + L($"{e.Message.Record} e => new Proto.AgentEvent {{ {e.ProtoCs} = ToProto(e) }},"); L("_ => null,"); Close(";"); Close(); @@ -325,101 +366,103 @@ public string Generate() L("internal sealed partial class Fdc3AgentService"); Open(); - foreach (var m in model.Methods) WriteRpc(m); + foreach (var rpc in model.Rpcs) WriteRpc(rpc); Close(); - return _sb.ToString(); + return Result; } - private void WriteToContract(Message message) + private void WriteToContract(Msg m) { - var type = message.Type.Name; - L($"public static {type} ToContract(Proto.{message.Name}? p)"); + L($"public static {m.Record} ToContract(Proto.{m.Name}? p)"); Open(); L("if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments);"); - L($"return new {type}("); - _indent++; - var args = message.Constructor.GetParameters().Select((_, i) => ToContractArg(message.Fields[i])).ToList(); - for (var i = 0; i < args.Count; i++) L(args[i] + (i < args.Count - 1 ? "," : ");")); - _indent--; + L($"return new {m.Record}("); + for (var i = 0; i < m.Fields.Count; i++) + L(" " + ToContractArg(m.Fields[i]) + (i < m.Fields.Count - 1 ? "," : ");")); Close(); L(); } private static string ToContractArg(Field f) { - var p = "p." + f.CsName; - var has = "p.Has" + f.CsName; - if (f.IsArray) return $"{p}.Select(ToContract).ToArray()"; + var p = "p." + f.ProtoCs; + var has = "p.Has" + f.ProtoCs; + if (f.Repeated) return $"{p}.Select(ToContract).ToArray()"; return f.Kind switch { Kind.String => f.Optional ? $"{has} ? {p} : null" : p, Kind.Bool => p, Kind.Json => f.Optional ? $"{has} ? Mapping.ParseContext({p}) : null" : $"Mapping.ParseContext({p})", - Kind.Object => throw new NotSupportedException("object fields only flow agent -> app."), _ => f.Optional ? $"{p} is null ? null : ToContract({p})" : $"ToContract({p})", }; } - private void WriteToProto(Message message) + private void WriteToProto(Msg m) { - L($"public static Proto.{message.Name} ToProto({message.Type.Name} r)"); + L($"public static Proto.{m.Name} ToProto({m.Record} r)"); Open(); - L($"var m = new Proto.{message.Name}();"); - foreach (var f in message.Fields) + L($"var m = new Proto.{m.Name}();"); + foreach (var f in m.Fields) { - var r = "r." + f.ClrName[..1].ToUpperInvariant() + f.ClrName[1..]; - var m = "m." + f.CsName; - if (f.IsArray) { L($"{m}.AddRange({r}.Select(ToProto));"); continue; } - var value = f.Kind switch + var r = "r." + f.Prop; + var target = "m." + f.ProtoCs; + if (f.Repeated) { L($"{target}.AddRange({r}.Select(ToProto));"); continue; } + switch (f.Kind) { - Kind.String or Kind.Bool => r, - Kind.Json => $"{r}{(f.Optional ? ".Value" : "")}.GetRawText()", - Kind.Object => $"JsonSerializer.Serialize({r}, JsonSerializerOptions.Web)", - _ => $"ToProto({r}{(f.MessageType!.IsValueType ? "" : "")})", - }; - L(f.Optional ? $"if ({r} is not null) {m} = {value};" : $"{m} = {value};"); + case Kind.Json when f.Optional: L($"if ({r} is {{ }} {f.ProtoCs.ToLowerInvariant()}) {target} = {f.ProtoCs.ToLowerInvariant()}.GetRawText();"); break; + case Kind.Json: L($"{target} = {r}.GetRawText();"); break; + case Kind.Message when f.Optional: L($"if ({r} is not null) {target} = ToProto({r});"); break; + case Kind.Message: L($"{target} = ToProto({r});"); break; + default: L(f.Optional ? $"if ({r} is not null) {target} = {r};" : $"{target} = {r};"); break; + } } L("return m;"); Close(); L(); } - private void WriteRpc(Method m) + private void WriteRpc(Rpc rpc) { - var req = Expect.RequestType(m).Replace("google.protobuf.Empty", "Empty"); - var resp = Expect.ResponseType(m).Replace("google.protobuf.Empty", "Empty"); - var respType = resp == "Empty" ? "Empty" : "Proto." + resp; - var reqType = req == "Empty" ? "Empty" : "Proto." + req; - var call = $"Caller(context).{m.Info.Name}({(m.Param is null ? "" : "GeneratedMapping.ToContract(request)")})"; + var requestType = rpc.Request is null ? "Empty" : "Proto." + rpc.Request; + var responseType = rpc.Shape == Shape.Void ? "Empty" : "Proto." + (rpc.Wrapper ?? rpc.Result); + var call = $"Caller(context).{rpc.Name}{(rpc.Async ? "Async" : "")}({(rpc.Request is null ? "" : "GeneratedMapping.ToContract(request)")})"; - L($"public override {(m.IsAsync ? "async " : "")}Task<{respType}> {m.RpcName}({reqType} request, ServerCallContext context)"); + L($"public override {(rpc.Async ? "async " : "")}Task<{responseType}> {rpc.Name}({requestType} request, ServerCallContext context)"); Open(); - if (m.IsVoid) + if (rpc.Shape == Shape.Void) { - L(m.IsAsync ? $"await {call};" : $"{call};"); - L(m.IsAsync ? "return new Empty();" : "return Task.FromResult(new Empty());"); + L(rpc.Async ? $"await {call};" : $"{call};"); + L(rpc.Async ? "return new Empty();" : "return Task.FromResult(new Empty());"); Close(); L(); return; } - L($"var result = {(m.IsAsync ? "await " : "")}{call};"); - var ret = new StringBuilder(); - if (!m.NeedsWrapper) ret.Append("GeneratedMapping.ToProto(result)"); - if (m.NeedsWrapper) + L($"var result = {(rpc.Async ? "await " : "")}{call};"); + string response; + switch (rpc.Shape) { - L($"var response = new Proto.{m.WrapperName}();"); - if (m.ResultIsArray) L("response.Items.AddRange(result.Select(GeneratedMapping.ToProto));"); - else if (m.Result == typeof(JsonElement)) L("if (result is { } value) response.ResultJson = value.GetRawText();"); - else L("if (result is not null) response.Result = GeneratedMapping.ToProto(result);"); - ret.Append("response"); + case Shape.Direct: + response = "GeneratedMapping.ToProto(result)"; + break; + case Shape.Array: + L($"var response = new Proto.{rpc.Wrapper}();"); + L("response.Items.AddRange(result.Select(GeneratedMapping.ToProto));"); + response = "response"; + break; + case Shape.Nullable: + L($"var response = new Proto.{rpc.Wrapper}();"); + L("if (result is not null) response.Result = GeneratedMapping.ToProto(result);"); + response = "response"; + break; + default: + L($"var response = new Proto.{rpc.Wrapper}();"); + L("if (result is { } value) response.ResultJson = value.GetRawText();"); + response = "response"; + break; } - L(m.IsAsync ? $"return {ret};" : $"return Task.FromResult({ret});"); + L(rpc.Async ? $"return {response};" : $"return Task.FromResult({response});"); Close(); L(); } - - private void Open() { L("{"); _indent++; } - private void Close(string suffix = "") { _indent--; L("}" + suffix); } - private void L(string text = "") => _sb.Append(text.Length == 0 ? "" : new string(' ', _indent * 4) + text).Append('\n'); } diff --git a/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj b/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj index 845ad76..5b30e7b 100644 --- a/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj +++ b/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj @@ -1,5 +1,11 @@ + net10.0 enable @@ -15,29 +21,7 @@ - - - - - - - - - - - - - - - + diff --git a/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs b/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs index 20424ff..e0c6317 100644 --- a/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs +++ b/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs @@ -6,12 +6,6 @@ namespace Bermuda.Fdc3.Grpc; -/// Request header carrying the instance id from the Connected event. -public static class Fdc3Headers -{ - public const string Instance = "x-fdc3-instance"; -} - /// Instances currently subscribed through gRPC, and the pipe connection each belongs to. internal sealed class Fdc3ConnectionRegistry { diff --git a/src/Bermuda.Fdc3.Grpc/Fdc3GrpcHost.cs b/src/Bermuda.Fdc3.Grpc/Fdc3GrpcHost.cs index 9946daf..e2a6d51 100644 --- a/src/Bermuda.Fdc3.Grpc/Fdc3GrpcHost.cs +++ b/src/Bermuda.Fdc3.Grpc/Fdc3GrpcHost.cs @@ -25,17 +25,10 @@ private Fdc3GrpcHost(WebApplication app, string pipeName) public string PipeName { get; } - /// - /// bermuda-fdc3-<user name>. Pipe names are machine-wide, so the - /// user name keeps two signed-in users from sharing (or fighting over) one. - /// - public static string DefaultPipeName { get; } = - "bermuda-fdc3-" + Regex.Replace(Environment.UserName, @"[^A-Za-z0-9_.-]", "_"); - - /// The pipe name (without \\.\pipe\); null = . + /// The pipe name (without \\.\pipe\); null = . public static async Task StartAsync(DesktopAgent agent, string? pipeName = null, CancellationToken cancellationToken = default) { - pipeName = string.IsNullOrWhiteSpace(pipeName) ? DefaultPipeName : pipeName; + pipeName = string.IsNullOrWhiteSpace(pipeName) ? Fdc3Pipe.DefaultName : pipeName; var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { diff --git a/src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs b/src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs index a990423..1c78fd5 100644 --- a/src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs +++ b/src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs @@ -1,8 +1,7 @@ // -// Generated by Bermuda.Fdc3.Grpc.Generator from IFdc3Commands. Do not edit. +// Generated by Bermuda.Fdc3.Grpc.Generator from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto. Do not edit. // #nullable enable -using System.Text.Json; using Bermuda.IpcContract; using Google.Protobuf.WellKnownTypes; using Grpc.Core; @@ -12,43 +11,71 @@ namespace Bermuda.Fdc3.Grpc; internal static class GeneratedMapping { - public static Fdc3ImplementationMetadata ToContract(Proto.ImplementationMetadata? p) + public static Fdc3AppIdentifier ToContract(Proto.AppIdentifier? p) { if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); - return new Fdc3ImplementationMetadata( - p.Fdc3Version, - p.Provider, - p.HasProviderVersion ? p.ProviderVersion : null, - ToContract(p.OptionalFeatures), - ToContract(p.AppMetadata)); + return new Fdc3AppIdentifier( + p.AppId, + p.HasInstanceId ? p.InstanceId : null); } - public static Proto.ImplementationMetadata ToProto(Fdc3ImplementationMetadata r) + public static Proto.AppIdentifier ToProto(Fdc3AppIdentifier r) { - var m = new Proto.ImplementationMetadata(); - m.Fdc3Version = r.Fdc3Version; - m.Provider = r.Provider; - if (r.ProviderVersion is not null) m.ProviderVersion = r.ProviderVersion; - m.OptionalFeatures = ToProto(r.OptionalFeatures); - m.AppMetadata = ToProto(r.AppMetadata); + var m = new Proto.AppIdentifier(); + m.AppId = r.AppId; + if (r.InstanceId is not null) m.InstanceId = r.InstanceId; return m; } - public static Fdc3OptionalFeatures ToContract(Proto.OptionalFeatures? p) + public static Fdc3DisplayMetadata ToContract(Proto.DisplayMetadata? p) { if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); - return new Fdc3OptionalFeatures( - p.OriginatingAppMetadata, - p.UserChannelMembershipApIs, - p.DesktopAgentBridging); + return new Fdc3DisplayMetadata( + p.HasName ? p.Name : null, + p.HasColor ? p.Color : null, + p.HasGlyph ? p.Glyph : null); } - public static Proto.OptionalFeatures ToProto(Fdc3OptionalFeatures r) + public static Proto.DisplayMetadata ToProto(Fdc3DisplayMetadata r) { - var m = new Proto.OptionalFeatures(); - m.OriginatingAppMetadata = r.OriginatingAppMetadata; - m.UserChannelMembershipApIs = r.UserChannelMembershipAPIs; - m.DesktopAgentBridging = r.DesktopAgentBridging; + var m = new Proto.DisplayMetadata(); + if (r.Name is not null) m.Name = r.Name; + if (r.Color is not null) m.Color = r.Color; + if (r.Glyph is not null) m.Glyph = r.Glyph; + return m; + } + + public static Fdc3ChannelInfo ToContract(Proto.ChannelInfo? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3ChannelInfo( + p.Id, + p.Type, + p.DisplayMetadata is null ? null : ToContract(p.DisplayMetadata)); + } + + public static Proto.ChannelInfo ToProto(Fdc3ChannelInfo r) + { + var m = new Proto.ChannelInfo(); + m.Id = r.Id; + m.Type = r.Type; + if (r.DisplayMetadata is not null) m.DisplayMetadata = ToProto(r.DisplayMetadata); + return m; + } + + public static Fdc3IntentMetadata ToContract(Proto.IntentMetadata? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3IntentMetadata( + p.Name, + p.HasDisplayName ? p.DisplayName : null); + } + + public static Proto.IntentMetadata ToProto(Fdc3IntentMetadata r) + { + var m = new Proto.IntentMetadata(); + m.Name = r.Name; + if (r.DisplayName is not null) m.DisplayName = r.DisplayName; return m; } @@ -80,71 +107,93 @@ public static Proto.AppMetadata ToProto(Fdc3AppMetadata r) return m; } - public static Fdc3AppIdentifier ToContract(Proto.AppIdentifier? p) + public static Fdc3AppIntent ToContract(Proto.AppIntent? p) { if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); - return new Fdc3AppIdentifier( - p.AppId, - p.HasInstanceId ? p.InstanceId : null); + return new Fdc3AppIntent( + ToContract(p.Intent), + p.Apps.Select(ToContract).ToArray()); } - public static Proto.AppIdentifier ToProto(Fdc3AppIdentifier r) + public static Proto.AppIntent ToProto(Fdc3AppIntent r) { - var m = new Proto.AppIdentifier(); - m.AppId = r.AppId; - if (r.InstanceId is not null) m.InstanceId = r.InstanceId; + var m = new Proto.AppIntent(); + m.Intent = ToProto(r.Intent); + m.Apps.AddRange(r.Apps.Select(ToProto)); return m; } - public static Fdc3OpenRequest ToContract(Proto.OpenRequest? p) + public static Fdc3OptionalFeatures ToContract(Proto.OptionalFeatures? p) { if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); - return new Fdc3OpenRequest( - ToContract(p.App), - p.HasContextJson ? Mapping.ParseContext(p.ContextJson) : null); + return new Fdc3OptionalFeatures( + p.OriginatingAppMetadata, + p.UserChannelMembershipApis, + p.DesktopAgentBridging); } - public static Proto.OpenRequest ToProto(Fdc3OpenRequest r) + public static Proto.OptionalFeatures ToProto(Fdc3OptionalFeatures r) { - var m = new Proto.OpenRequest(); - m.App = ToProto(r.App); - if (r.Context is not null) m.ContextJson = r.Context.Value.GetRawText(); + var m = new Proto.OptionalFeatures(); + m.OriginatingAppMetadata = r.OriginatingAppMetadata; + m.UserChannelMembershipApis = r.UserChannelMembershipAPIs; + m.DesktopAgentBridging = r.DesktopAgentBridging; return m; } - public static Fdc3ChannelInfo ToContract(Proto.ChannelInfo? p) + public static Fdc3ImplementationMetadata ToContract(Proto.ImplementationMetadata? p) { if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); - return new Fdc3ChannelInfo( - p.Id, - p.Type, - p.DisplayMetadata is null ? null : ToContract(p.DisplayMetadata)); + return new Fdc3ImplementationMetadata( + p.Fdc3Version, + p.Provider, + p.HasProviderVersion ? p.ProviderVersion : null, + ToContract(p.OptionalFeatures), + ToContract(p.AppMetadata)); } - public static Proto.ChannelInfo ToProto(Fdc3ChannelInfo r) + public static Proto.ImplementationMetadata ToProto(Fdc3ImplementationMetadata r) { - var m = new Proto.ChannelInfo(); - m.Id = r.Id; - m.Type = r.Type; - if (r.DisplayMetadata is not null) m.DisplayMetadata = ToProto(r.DisplayMetadata); + var m = new Proto.ImplementationMetadata(); + m.Fdc3Version = r.Fdc3Version; + m.Provider = r.Provider; + if (r.ProviderVersion is not null) m.ProviderVersion = r.ProviderVersion; + m.OptionalFeatures = ToProto(r.OptionalFeatures); + m.AppMetadata = ToProto(r.AppMetadata); return m; } - public static Fdc3DisplayMetadata ToContract(Proto.DisplayMetadata? p) + public static Fdc3IntentResolutionInfo ToContract(Proto.IntentResolutionInfo? p) { if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); - return new Fdc3DisplayMetadata( - p.HasName ? p.Name : null, - p.HasColor ? p.Color : null, - p.HasGlyph ? p.Glyph : null); + return new Fdc3IntentResolutionInfo( + ToContract(p.Source), + p.Intent, + p.ResultId); } - public static Proto.DisplayMetadata ToProto(Fdc3DisplayMetadata r) + public static Proto.IntentResolutionInfo ToProto(Fdc3IntentResolutionInfo r) { - var m = new Proto.DisplayMetadata(); - if (r.Name is not null) m.Name = r.Name; - if (r.Color is not null) m.Color = r.Color; - if (r.Glyph is not null) m.Glyph = r.Glyph; + var m = new Proto.IntentResolutionInfo(); + m.Source = ToProto(r.Source); + m.Intent = r.Intent; + m.ResultId = r.ResultId; + return m; + } + + public static Fdc3IntentResultInfo ToContract(Proto.IntentResultInfo? p) + { + if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); + return new Fdc3IntentResultInfo( + p.HasContextJson ? Mapping.ParseContext(p.ContextJson) : null, + p.Channel is null ? null : ToContract(p.Channel)); + } + + public static Proto.IntentResultInfo ToProto(Fdc3IntentResultInfo r) + { + var m = new Proto.IntentResultInfo(); + if (r.Context is { } contextjson) m.ContextJson = contextjson.GetRawText(); + if (r.Channel is not null) m.Channel = ToProto(r.Channel); return m; } @@ -273,43 +322,11 @@ public static Proto.FindIntentRequest ToProto(Fdc3FindIntentRequest r) { var m = new Proto.FindIntentRequest(); m.Intent = r.Intent; - if (r.Context is not null) m.ContextJson = r.Context.Value.GetRawText(); + if (r.Context is { } contextjson) m.ContextJson = contextjson.GetRawText(); if (r.ResultType is not null) m.ResultType = r.ResultType; return m; } - public static Fdc3AppIntent ToContract(Proto.AppIntent? p) - { - if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); - return new Fdc3AppIntent( - ToContract(p.Intent), - p.Apps.Select(ToContract).ToArray()); - } - - public static Proto.AppIntent ToProto(Fdc3AppIntent r) - { - var m = new Proto.AppIntent(); - m.Intent = ToProto(r.Intent); - m.Apps.AddRange(r.Apps.Select(ToProto)); - return m; - } - - public static Fdc3IntentMetadata ToContract(Proto.IntentMetadata? p) - { - if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); - return new Fdc3IntentMetadata( - p.Name, - p.HasDisplayName ? p.DisplayName : null); - } - - public static Proto.IntentMetadata ToProto(Fdc3IntentMetadata r) - { - var m = new Proto.IntentMetadata(); - m.Name = r.Name; - if (r.DisplayName is not null) m.DisplayName = r.DisplayName; - return m; - } - public static Fdc3FindIntentsByContextRequest ToContract(Proto.FindIntentsByContextRequest? p) { if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); @@ -326,39 +343,37 @@ public static Proto.FindIntentsByContextRequest ToProto(Fdc3FindIntentsByContext return m; } - public static Fdc3RaiseIntentRequest ToContract(Proto.RaiseIntentRequest? p) + public static Fdc3OpenRequest ToContract(Proto.OpenRequest? p) { if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); - return new Fdc3RaiseIntentRequest( - p.Intent, - Mapping.ParseContext(p.ContextJson), - p.App is null ? null : ToContract(p.App)); + return new Fdc3OpenRequest( + ToContract(p.App), + p.HasContextJson ? Mapping.ParseContext(p.ContextJson) : null); } - public static Proto.RaiseIntentRequest ToProto(Fdc3RaiseIntentRequest r) + public static Proto.OpenRequest ToProto(Fdc3OpenRequest r) { - var m = new Proto.RaiseIntentRequest(); - m.Intent = r.Intent; - m.ContextJson = r.Context.GetRawText(); - if (r.App is not null) m.App = ToProto(r.App); + var m = new Proto.OpenRequest(); + m.App = ToProto(r.App); + if (r.Context is { } contextjson) m.ContextJson = contextjson.GetRawText(); return m; } - public static Fdc3IntentResolutionInfo ToContract(Proto.IntentResolutionInfo? p) + public static Fdc3RaiseIntentRequest ToContract(Proto.RaiseIntentRequest? p) { if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); - return new Fdc3IntentResolutionInfo( - ToContract(p.Source), + return new Fdc3RaiseIntentRequest( p.Intent, - p.ResultId); + Mapping.ParseContext(p.ContextJson), + p.App is null ? null : ToContract(p.App)); } - public static Proto.IntentResolutionInfo ToProto(Fdc3IntentResolutionInfo r) + public static Proto.RaiseIntentRequest ToProto(Fdc3RaiseIntentRequest r) { - var m = new Proto.IntentResolutionInfo(); - m.Source = ToProto(r.Source); + var m = new Proto.RaiseIntentRequest(); m.Intent = r.Intent; - m.ResultId = r.ResultId; + m.ContextJson = r.Context.GetRawText(); + if (r.App is not null) m.App = ToProto(r.App); return m; } @@ -392,22 +407,6 @@ public static Proto.ResultIdRequest ToProto(Fdc3ResultIdRequest r) return m; } - public static Fdc3IntentResultInfo ToContract(Proto.IntentResultInfo? p) - { - if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); - return new Fdc3IntentResultInfo( - p.HasContextJson ? Mapping.ParseContext(p.ContextJson) : null, - p.Channel is null ? null : ToContract(p.Channel)); - } - - public static Proto.IntentResultInfo ToProto(Fdc3IntentResultInfo r) - { - var m = new Proto.IntentResultInfo(); - if (r.Context is not null) m.ContextJson = r.Context.Value.GetRawText(); - if (r.Channel is not null) m.Channel = ToProto(r.Channel); - return m; - } - public static Fdc3SendIntentResultRequest ToContract(Proto.SendIntentResultRequest? p) { if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); @@ -422,21 +421,12 @@ public static Proto.SendIntentResultRequest ToProto(Fdc3SendIntentResultRequest { var m = new Proto.SendIntentResultRequest(); m.ResultId = r.ResultId; - if (r.Context is not null) m.ContextJson = r.Context.Value.GetRawText(); + if (r.Context is { } contextjson) m.ContextJson = contextjson.GetRawText(); if (r.ChannelId is not null) m.ChannelId = r.ChannelId; if (r.Error is not null) m.Error = r.Error; return m; } - public static Proto.ApiEvent ToProto(Fdc3ApiEvent r) - { - var m = new Proto.ApiEvent(); - m.ListenerId = r.ListenerId; - m.EventType = r.EventType; - if (r.Details is not null) m.DetailsJson = JsonSerializer.Serialize(r.Details, JsonSerializerOptions.Web); - return m; - } - public static Proto.ContextEvent ToProto(Fdc3ContextEvent r) { var m = new Proto.ContextEvent(); @@ -457,10 +447,19 @@ public static Proto.IntentEvent ToProto(Fdc3IntentEvent r) return m; } + public static Proto.ApiEvent ToProto(Fdc3ApiEvent r) + { + var m = new Proto.ApiEvent(); + m.ListenerId = r.ListenerId; + m.EventType = r.EventType; + if (r.Details is { } detailsjson) m.DetailsJson = detailsjson.GetRawText(); + return m; + } + /// Maps what the agent posts to a sink; null for a message type this transport doesn't know. public static Proto.AgentEvent? ToProtoEvent(object message) => message switch { - Fdc3ApiEvent e => new Proto.AgentEvent { Api = ToProto(e) }, + Fdc3ApiEvent e => new Proto.AgentEvent { Event = ToProto(e) }, Fdc3ContextEvent e => new Proto.AgentEvent { Context = ToProto(e) }, Fdc3IntentEvent e => new Proto.AgentEvent { Intent = ToProto(e) }, _ => null, diff --git a/src/Bermuda.Fdc3.Proto/Bermuda.Fdc3.Proto.csproj b/src/Bermuda.Fdc3.Proto/Bermuda.Fdc3.Proto.csproj new file mode 100644 index 0000000..e76fa72 --- /dev/null +++ b/src/Bermuda.Fdc3.Proto/Bermuda.Fdc3.Proto.csproj @@ -0,0 +1,41 @@ + + + + + net10.0 + enable + enable + Bermuda.Fdc3.Proto + Bermuda.Fdc3.Grpc.Proto + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Bermuda.Fdc3.Grpc/Fdc3PipeClient.cs b/src/Bermuda.Fdc3.Proto/Fdc3PipeClient.cs similarity index 84% rename from src/Bermuda.Fdc3.Grpc/Fdc3PipeClient.cs rename to src/Bermuda.Fdc3.Proto/Fdc3PipeClient.cs index 8973dba..735cbb4 100644 --- a/src/Bermuda.Fdc3.Grpc/Fdc3PipeClient.cs +++ b/src/Bermuda.Fdc3.Proto/Fdc3PipeClient.cs @@ -7,6 +7,23 @@ namespace Bermuda.Fdc3.Grpc; +/// Request header carrying the instance id from the Connected event. +public static class Fdc3Headers +{ + public const string Instance = "x-fdc3-instance"; +} + +/// Where Bermuda's FDC3 pipe lives. +public static class Fdc3Pipe +{ + /// + /// bermuda-fdc3-<user name>. Pipe names are machine-wide, so the user name keeps two + /// signed-in users from sharing (or fighting over) one. Host and clients compute it the same way. + /// + public static string DefaultName { get; } = + "bermuda-fdc3-" + System.Text.RegularExpressions.Regex.Replace(Environment.UserName, @"[^A-Za-z0-9_.-]", "_"); +} + /// /// A minimal native FDC3 app: connects to Bermuda's named pipe, subscribes as /// appId and exposes the generated client plus the agent's pushed @@ -45,7 +62,7 @@ public static async Task ConnectAsync(string? pipeName, string a { ConnectCallback = async (_, token) => { - var pipe = new NamedPipeClientStream(".", pipeName ?? Fdc3GrpcHost.DefaultPipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + var pipe = new NamedPipeClientStream(".", pipeName ?? Fdc3Pipe.DefaultName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); try { await pipe.ConnectAsync(token); diff --git a/src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto b/src/Bermuda.Fdc3.Proto/Protos/fdc3.proto similarity index 51% rename from src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto rename to src/Bermuda.Fdc3.Proto/Protos/fdc3.proto index 3b4d666..f6389c3 100644 --- a/src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto +++ b/src/Bermuda.Fdc3.Proto/Protos/fdc3.proto @@ -1,36 +1,57 @@ -// The gRPC contract for Bermuda's FDC3 desktop agent, and its source of truth: Grpc.Tools builds the C# -// messages and the Fdc3Agent service base from this file, and Bermuda.Fdc3.Grpc.Generator derives the -// proto <-> IFdc3Commands glue from it (Generated/Fdc3Generated.g.cs). The build FAILS if the C# contract -// (src/Bermuda.IpcContract/Fdc3Contract.cs) no longer matches this file, so a change here means updating -// the contract too (and vice versa). Never renumber or reuse field numbers. +// Bermuda's FDC3 2.2 Desktop Agent contract. THIS FILE IS THE SOURCE OF TRUTH for it. // -// Conventions the generator relies on: -// message Foo <-> record Fdc3Foo; field snake_case names <-> constructor parameters -// string xxx_json <-> JsonElement / object? xxx (JSON text); proto3 `optional` <-> nullable -// repeated Foo <-> Foo[] -// rpc M(Req) returns (R) <-> M(Req) / MAsync(Req); google.protobuf.Empty <-> no parameter / void -// MResponse { items | result | result_json } wraps a result that is an array / nullable -// AgentEvent oneof <-> the [IpcType] Fdc3*Event records (plus the transport-only `connected`) +// From it the build produces (Bermuda.Fdc3.Proto): +// * the gRPC messages and Fdc3Agent service (Grpc.Tools), used by native apps over the named pipe; +// * src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs: the C# records and IFdc3Commands that the +// in-process DesktopAgent implements and the web bridge dispatches ([IpcCommands]/[IpcType], from +// which the TypeScript types are generated); +// * src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs: the glue between the two. +// The generated C# is checked in. Edit this file, rebuild, commit the regenerated files. +// +// Shapes mirror the FDC3 API types (AppIdentifier, AppMetadata, AppIntent, ...) closely enough that the +// frontend shim passes them through with at most a light wrap. FDC3 contexts are open-ended JSON objects +// whose only required field is `type`, so they travel as JSON text. +// +// Conventions the generator relies on (it fails the build on anything else): +// message Foo -> record Fdc3Foo; fields keep their order, which is also the constructor order +// string / bool -> string / bool; proto3 `optional` -> nullable (also for message fields) +// string xxx_json -> JsonElement xxx (JSON text on the wire); optional -> JsonElement? +// repeated Foo -> Foo[] +// json_name -> the C# property / web JSON name, when it is not the camel-cased field name +// rpc M(Req) returns (Resp) -> M(Req request) on IFdc3Commands (MAsync returning Task when `async`); +// google.protobuf.Empty -> no parameter / void +// message MResponse -> M's result when it is an array (`repeated items`), nullable (`result`) or +// a nullable context (`optional string result_json`) +// AgentEvent oneof -> the [IpcType] event records; the field name is the web message type +// ("fdc3."); `connected` exists only on the gRPC stream +// Never renumber or reuse a field number. syntax = "proto3"; package bermuda.fdc3.v1; +import "google/protobuf/descriptor.proto"; import "google/protobuf/empty.proto"; option csharp_namespace = "Bermuda.Fdc3.Grpc.Proto"; -// Connection model: one pipe client opens Subscribe(app_id). The first message on that stream is +extend google.protobuf.MethodOptions { + // The command waits for another app (launch, handler result), so the C# method is `Task`-returning. + bool async = 50001; +} + +// Connection model (gRPC): one pipe client opens Subscribe(app_id). The first message on that stream is // `connected` (carrying the new instance_id); the agent's deliveries follow. Every other RPC must carry // the instance_id in the `x-fdc3-instance` request header and use the same pipe connection. The instance -// leaves the agent when the Subscribe stream ends. Contexts are JSON text (*_json fields); failures are -// gRPC errors whose status detail is the FDC3 error string (Fdc3Errors). +// leaves the agent when the Subscribe stream ends. Failures are gRPC errors whose status detail is the +// FDC3 error string (Fdc3Errors). service Fdc3Agent { rpc Subscribe(SubscribeRequest) returns (stream AgentEvent); rpc GetInfo(google.protobuf.Empty) returns (ImplementationMetadata); rpc GetAppMetadata(AppIdentifier) returns (AppMetadata); rpc FindInstances(AppIdentifier) returns (FindInstancesResponse); - rpc Open(OpenRequest) returns (AppIdentifier); + rpc Open(OpenRequest) returns (AppIdentifier) { option (async) = true; } + rpc GetUserChannels(google.protobuf.Empty) returns (GetUserChannelsResponse); rpc JoinUserChannel(ChannelIdRequest) returns (google.protobuf.Empty); rpc LeaveCurrentChannel(google.protobuf.Empty) returns (google.protobuf.Empty); @@ -38,32 +59,49 @@ service Fdc3Agent { rpc GetOrCreateChannel(ChannelIdRequest) returns (ChannelInfo); rpc CreatePrivateChannel(google.protobuf.Empty) returns (ChannelInfo); rpc DisconnectPrivateChannel(ChannelIdRequest) returns (google.protobuf.Empty); + + // FDC3 broadcast() and channel.broadcast(). rpc Broadcast(BroadcastRequest) returns (google.protobuf.Empty); rpc GetCurrentContext(GetCurrentContextRequest) returns (GetCurrentContextResponse); rpc AddContextListener(AddContextListenerRequest) returns (google.protobuf.Empty); rpc AddIntentListener(AddIntentListenerRequest) returns (google.protobuf.Empty); rpc AddEventListener(AddEventListenerRequest) returns (google.protobuf.Empty); + // Listener.unsubscribe(), for every kind of listener. rpc Unsubscribe(ListenerIdRequest) returns (google.protobuf.Empty); + rpc FindIntent(FindIntentRequest) returns (AppIntent); rpc FindIntentsByContext(FindIntentsByContextRequest) returns (FindIntentsByContextResponse); - rpc RaiseIntent(RaiseIntentRequest) returns (IntentResolutionInfo); - rpc RaiseIntentForContext(RaiseIntentForContextRequest) returns (IntentResolutionInfo); - rpc GetIntentResult(ResultIdRequest) returns (IntentResultInfo); + rpc RaiseIntent(RaiseIntentRequest) returns (IntentResolutionInfo) { option (async) = true; } + rpc RaiseIntentForContext(RaiseIntentForContextRequest) returns (IntentResolutionInfo) { option (async) = true; } + // IntentResolution.getResult(). + rpc GetIntentResult(ResultIdRequest) returns (IntentResultInfo) { option (async) = true; } + // Reports an intent handler's result back to the raiser. rpc SendIntentResult(SendIntentResultRequest) returns (google.protobuf.Empty); } -message ImplementationMetadata { - string fdc3_version = 1; - string provider = 2; - optional string provider_version = 3; - OptionalFeatures optional_features = 4; - AppMetadata app_metadata = 5; +// Shapes --------------------------------------------------------------------- + +message AppIdentifier { + string app_id = 1; + optional string instance_id = 2; } -message OptionalFeatures { - bool originating_app_metadata = 1; - bool user_channel_membership_ap_is = 2; - bool desktop_agent_bridging = 3; +message DisplayMetadata { + optional string name = 1; + optional string color = 2; + optional string glyph = 3; +} + +// A user, app or private channel. `type` is one of 'user' | 'app' | 'private'. +message ChannelInfo { + string id = 1; + string type = 2; + optional DisplayMetadata display_metadata = 3; +} + +message IntentMetadata { + string name = 1; + optional string display_name = 2; } message AppMetadata { @@ -77,32 +115,46 @@ message AppMetadata { optional string result_type = 8; } -message AppIdentifier { - string app_id = 1; - optional string instance_id = 2; +message AppIntent { + IntentMetadata intent = 1; + repeated AppMetadata apps = 2; } -message OpenRequest { - AppIdentifier app = 1; - optional string context_json = 2; +message OptionalFeatures { + bool originating_app_metadata = 1; + bool user_channel_membership_apis = 2 [json_name = "userChannelMembershipAPIs"]; + bool desktop_agent_bridging = 3; } -message ChannelInfo { - string id = 1; - string type = 2; - DisplayMetadata display_metadata = 3; +message ImplementationMetadata { + string fdc3_version = 1; + string provider = 2; + optional string provider_version = 3; + OptionalFeatures optional_features = 4; + AppMetadata app_metadata = 5; } -message DisplayMetadata { - optional string name = 1; - optional string color = 2; - optional string glyph = 3; +// What raiseIntent/raiseIntentForContext return. The frontend turns it into an FDC3 IntentResolution whose +// getResult() calls getIntentResult with `result_id`. +message IntentResolutionInfo { + AppIdentifier source = 1; + string intent = 2; + string result_id = 3; +} + +// An intent handler's result: a context, a channel, or neither (void). +message IntentResultInfo { + optional string context_json = 1; + optional ChannelInfo channel = 2; } +// Requests ------------------------------------------------------------------- + message ChannelIdRequest { string channel_id = 1; } +// `channel_id` unset = the caller's current user channel. message BroadcastRequest { optional string channel_id = 1; string context_json = 2; @@ -113,6 +165,9 @@ message GetCurrentContextRequest { optional string context_type = 2; } +// `listener_id` is chosen by the caller and echoed back in every ContextEvent for this listener. +// `channel_id` unset = follow whichever user channel the caller is joined to (fdc3.addContextListener); +// set = a specific app/private channel (channel.addContextListener). message AddContextListenerRequest { string listener_id = 1; optional string channel_id = 2; @@ -124,6 +179,8 @@ message AddIntentListenerRequest { string intent = 2; } +// `channel_id` unset = desktop-agent events ('userChannelChanged'); set = private channel events +// ('addContextListener' | 'unsubscribe' | 'disconnect'). `event_type` unset = all event types. message AddEventListenerRequest { string listener_id = 1; optional string event_type = 2; @@ -140,47 +197,33 @@ message FindIntentRequest { optional string result_type = 3; } -message AppIntent { - IntentMetadata intent = 1; - repeated AppMetadata apps = 2; -} - -message IntentMetadata { - string name = 1; - optional string display_name = 2; -} - message FindIntentsByContextRequest { string context_json = 1; optional string result_type = 2; } +message OpenRequest { + AppIdentifier app = 1; + optional string context_json = 2; +} + message RaiseIntentRequest { string intent = 1; string context_json = 2; - AppIdentifier app = 3; -} - -message IntentResolutionInfo { - AppIdentifier source = 1; - string intent = 2; - string result_id = 3; + optional AppIdentifier app = 3; } message RaiseIntentForContextRequest { string context_json = 1; - AppIdentifier app = 2; + optional AppIdentifier app = 2; } message ResultIdRequest { string result_id = 1; } -message IntentResultInfo { - optional string context_json = 1; - ChannelInfo channel = 2; -} - +// Sent by the instance that handled an intent once its handler settles. At most one of +// `context_json`/`channel_id` is set (neither = void); `error` is set instead if the handler threw/rejected. message SendIntentResultRequest { string result_id = 1; optional string context_json = 2; @@ -188,25 +231,7 @@ message SendIntentResultRequest { optional string error = 4; } -message ApiEvent { - string listener_id = 1; - string event_type = 2; - optional string details_json = 3; -} - -message ContextEvent { - string listener_id = 1; - string context_json = 2; - AppIdentifier source = 3; -} - -message IntentEvent { - string listener_id = 1; - string intent = 2; - string context_json = 3; - AppIdentifier source = 4; - string result_id = 5; -} +// Results that are lists or can be absent --------------------------------------- message FindInstancesResponse { repeated AppIdentifier items = 1; @@ -217,7 +242,7 @@ message GetUserChannelsResponse { } message GetCurrentChannelResponse { - ChannelInfo result = 1; + optional ChannelInfo result = 1; } message GetCurrentContextResponse { @@ -228,7 +253,36 @@ message FindIntentsByContextResponse { repeated AppIntent items = 1; } -message SubscribeRequest { string app_id = 1; } +// Agent -> app events ------------------------------------------------------------- + +// Delivery to a listener added with AddContextListener. +message ContextEvent { + string listener_id = 1; + string context_json = 2; + optional AppIdentifier source = 3; +} + +// Delivery to an intent listener; the handler reports back with SendIntentResult(result_id). +message IntentEvent { + string listener_id = 1; + string intent = 2; + string context_json = 3; + optional AppIdentifier source = 4; + string result_id = 5; +} + +// An FDC3 ApiEvent (`event_type` + `details`) for a listener added via AddEventListener. +message ApiEvent { + string listener_id = 1; + string event_type = 2; + optional string details_json = 3; +} + +// gRPC transport only ------------------------------------------------------------- + +message SubscribeRequest { + string app_id = 1; +} // First message of every Subscribe stream. message Connected { @@ -237,9 +291,9 @@ message Connected { } message AgentEvent { - oneof event { + oneof kind { Connected connected = 1; - ApiEvent api = 2; + ApiEvent event = 2; ContextEvent context = 3; IntentEvent intent = 4; } diff --git a/src/Bermuda.Fdc3/DesktopAgent.cs b/src/Bermuda.Fdc3/DesktopAgent.cs index 2d3c498..999a1c8 100644 --- a/src/Bermuda.Fdc3/DesktopAgent.cs +++ b/src/Bermuda.Fdc3/DesktopAgent.cs @@ -263,6 +263,10 @@ internal void LeaveCurrentChannel(AppInstance caller) outbox.Flush(); } + /// API event details are plain objects built here; events carry them as JSON. + private static JsonElement? ToJson(object? details) => + details is null ? null : JsonSerializer.SerializeToElement(details, JsonSerializerOptions.Web); + private void QueueUserChannelChanged(AppInstance caller, Outbox outbox) { var details = new Dictionary { ["currentChannelId"] = caller.CurrentUserChannelId }; @@ -270,7 +274,7 @@ private void QueueUserChannelChanged(AppInstance caller, Outbox outbox) l.InstanceId == caller.InstanceId && l.Kind == ListenerKind.Event && l.ChannelId is null && (l.EventType is null || l.EventType == "userChannelChanged"))) { - outbox.Add(caller.Sink, new Fdc3ApiEvent(listener.ListenerId, "userChannelChanged", details)); + outbox.Add(caller.Sink, new Fdc3ApiEvent(listener.ListenerId, "userChannelChanged", ToJson(details))); } } @@ -376,7 +380,7 @@ private void QueuePrivateChannelEvent(string fromInstanceId, ChannelState channe (l.EventType is null || l.EventType == eventType))) { if (_instances.TryGetValue(listener.InstanceId, out var target)) - outbox.Add(target.Sink, new Fdc3ApiEvent(listener.ListenerId, eventType, details)); + outbox.Add(target.Sink, new Fdc3ApiEvent(listener.ListenerId, eventType, ToJson(details))); } } @@ -536,7 +540,7 @@ internal void AddEventListener(AppInstance caller, Fdc3AddEventListenerRequest r l.Kind == ListenerKind.Context && l.ChannelId == channel.Id && l.InstanceId != caller.InstanceId)) { outbox.Add(caller.Sink, new Fdc3ApiEvent(request.ListenerId, "addContextListener", - new Dictionary { ["contextType"] = existing.ContextType })); + ToJson(new Dictionary { ["contextType"] = existing.ContextType }))); } } } diff --git a/src/Bermuda.IpcContract/Bermuda.IpcContract.csproj b/src/Bermuda.IpcContract/Bermuda.IpcContract.csproj index d9497f5..3868d47 100644 --- a/src/Bermuda.IpcContract/Bermuda.IpcContract.csproj +++ b/src/Bermuda.IpcContract/Bermuda.IpcContract.csproj @@ -8,4 +8,12 @@ Bermuda.IpcContract + + + + + diff --git a/src/Bermuda.IpcContract/Fdc3Contract.cs b/src/Bermuda.IpcContract/Fdc3Contract.cs deleted file mode 100644 index 4039ba8..0000000 --- a/src/Bermuda.IpcContract/Fdc3Contract.cs +++ /dev/null @@ -1,176 +0,0 @@ -using System.Text.Json; - -namespace Bermuda.IpcContract; - -// FDC3 2.2 Desktop Agent wire contract -// ==================================== -// The frontend's window.fdc3 (src/Bermuda.Web/src/fdc3/) implements the -// standard @finos/fdc3-standard DesktopAgent interface by calling the -// fdc3.* commands of IFdc3Commands (bottom of this file) over the invoke() -// channel; Bermuda.Fdc3 handles them on the host. Shapes mirror the FDC3 API types (AppIdentifier, -// AppMetadata, AppIntent, ...) closely enough that the frontend shim can pass -// them through with at most a light wrap (e.g. adding methods to a Channel). -// -// Contexts are carried as raw JsonElement (`unknown` in TS) — FDC3 contexts -// are open-ended JSON objects whose only required field is `type`. -// -// Host → web push messages (Fdc3ContextEvent etc.) carry a constant `type` -// discriminator so bridge/index.ts can tell them apart from HostResponses. - -public sealed record Fdc3AppIdentifier(string AppId, string? InstanceId = null); - -public sealed record Fdc3DisplayMetadata(string? Name, string? Color, string? Glyph); - -/// A user, app or private channel. Type is one of 'user' | 'app' | 'private'. -public sealed record Fdc3ChannelInfo(string Id, string Type, Fdc3DisplayMetadata? DisplayMetadata); - -public sealed record Fdc3IntentMetadata(string Name, string? DisplayName); - -public sealed record Fdc3AppMetadata( - string AppId, - string? InstanceId, - string? Name, - string? Version, - string? Title, - string? Tooltip, - string? Description, - string? ResultType); - -public sealed record Fdc3AppIntent(Fdc3IntentMetadata Intent, Fdc3AppMetadata[] Apps); - -public sealed record Fdc3OptionalFeatures( - bool OriginatingAppMetadata, - bool UserChannelMembershipAPIs, - bool DesktopAgentBridging); - -public sealed record Fdc3ImplementationMetadata( - string Fdc3Version, - string Provider, - string? ProviderVersion, - Fdc3OptionalFeatures OptionalFeatures, - Fdc3AppMetadata AppMetadata); - -/// -/// What raiseIntent/raiseIntentForContext return. The frontend -/// turns it into an FDC3 IntentResolution whose getResult() calls -/// fdc3.getIntentResult with ResultId. -/// -public sealed record Fdc3IntentResolutionInfo(Fdc3AppIdentifier Source, string Intent, string ResultId); - -/// An intent handler's result: a context, a channel, or neither (void). -public sealed record Fdc3IntentResultInfo(JsonElement? Context, Fdc3ChannelInfo? Channel); - -// Requests --------------------------------------------------------------- - -public sealed record Fdc3ChannelIdRequest(string ChannelId); - -/// ChannelId null = the caller's current user channel. -public sealed record Fdc3BroadcastRequest(string? ChannelId, JsonElement Context); - -public sealed record Fdc3GetCurrentContextRequest(string ChannelId, string? ContextType); - -/// -/// ListenerId is generated by the frontend and echoed back in every -/// for this listener. ChannelId null = -/// follow whichever user channel the caller is joined to (fdc3.addContextListener); -/// non-null = a specific app/private channel (channel.addContextListener). -/// -public sealed record Fdc3AddContextListenerRequest(string ListenerId, string? ChannelId, string? ContextType); - -public sealed record Fdc3AddIntentListenerRequest(string ListenerId, string Intent); - -/// -/// ChannelId null = desktop-agent events ('userChannelChanged'); -/// non-null = private channel events ('addContextListener' | 'unsubscribe' | 'disconnect'). -/// EventType null = all event types. -/// -public sealed record Fdc3AddEventListenerRequest(string ListenerId, string? EventType, string? ChannelId); - -public sealed record Fdc3ListenerIdRequest(string ListenerId); - -public sealed record Fdc3FindIntentRequest(string Intent, JsonElement? Context, string? ResultType); - -public sealed record Fdc3FindIntentsByContextRequest(JsonElement Context, string? ResultType); - -public sealed record Fdc3OpenRequest(Fdc3AppIdentifier App, JsonElement? Context); - -public sealed record Fdc3RaiseIntentRequest(string Intent, JsonElement Context, Fdc3AppIdentifier? App); - -public sealed record Fdc3RaiseIntentForContextRequest(JsonElement Context, Fdc3AppIdentifier? App); - -public sealed record Fdc3ResultIdRequest(string ResultId); - -/// -/// Sent by the instance that handled an intent once its handler settles. -/// At most one of Context/ChannelId is set (neither = void); -/// Error is set instead if the handler threw/rejected. -/// -public sealed record Fdc3SendIntentResultRequest(string ResultId, JsonElement? Context, string? ChannelId, string? Error); - -// Host → web push messages ---------------------------------------------------- - -[IpcType] -public sealed record Fdc3ContextEvent(string ListenerId, JsonElement Context, Fdc3AppIdentifier? Source) -{ - public string Type => "fdc3.context"; -} - -[IpcType] -public sealed record Fdc3IntentEvent(string ListenerId, string Intent, JsonElement Context, Fdc3AppIdentifier? Source, string ResultId) -{ - public string Type => "fdc3.intent"; -} - -/// An FDC3 ApiEvent (EventType + Details) for a listener added via addEventListener. -[IpcType] -public sealed record Fdc3ApiEvent(string ListenerId, string EventType, object? Details) -{ - public string Type => "fdc3.event"; -} - -// Commands ------------------------------------------------------------------- - -/// -/// The fdc3.* commands: one per FDC3 DesktopAgent / Channel / PrivateChannel / -/// IntentResolution call, plus , which reports an -/// intent handler's outcome back. Implemented per app instance by -/// Bermuda.Fdc3.Fdc3Connection. Methods throw Fdc3Exception, whose -/// message is the standard FDC3 error string. -/// -[IpcCommands("fdc3")] -public interface IFdc3Commands -{ - Fdc3ImplementationMetadata GetInfo(); - Fdc3AppMetadata GetAppMetadata(Fdc3AppIdentifier app); - Fdc3AppIdentifier[] FindInstances(Fdc3AppIdentifier app); - Task OpenAsync(Fdc3OpenRequest request); - - Fdc3ChannelInfo[] GetUserChannels(); - void JoinUserChannel(Fdc3ChannelIdRequest request); - void LeaveCurrentChannel(); - Fdc3ChannelInfo? GetCurrentChannel(); - Fdc3ChannelInfo GetOrCreateChannel(Fdc3ChannelIdRequest request); - Fdc3ChannelInfo CreatePrivateChannel(); - void DisconnectPrivateChannel(Fdc3ChannelIdRequest request); - - /// FDC3 broadcast() and channel.broadcast(). - void Broadcast(Fdc3BroadcastRequest request); - JsonElement? GetCurrentContext(Fdc3GetCurrentContextRequest request); - void AddContextListener(Fdc3AddContextListenerRequest request); - void AddIntentListener(Fdc3AddIntentListenerRequest request); - void AddEventListener(Fdc3AddEventListenerRequest request); - - /// Listener.unsubscribe(), for every kind of listener. - void Unsubscribe(Fdc3ListenerIdRequest request); - - Fdc3AppIntent FindIntent(Fdc3FindIntentRequest request); - Fdc3AppIntent[] FindIntentsByContext(Fdc3FindIntentsByContextRequest request); - Task RaiseIntentAsync(Fdc3RaiseIntentRequest request); - Task RaiseIntentForContextAsync(Fdc3RaiseIntentForContextRequest request); - - /// IntentResolution.getResult(). - Task GetIntentResultAsync(Fdc3ResultIdRequest request); - - /// Reports an intent handler's result back to the raiser. - void SendIntentResult(Fdc3SendIntentResultRequest request); -} diff --git a/src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs b/src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs new file mode 100644 index 0000000..f971fe7 --- /dev/null +++ b/src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs @@ -0,0 +1,155 @@ +// +// Generated by Bermuda.Fdc3.Grpc.Generator from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto. Do not edit: +// change the proto and rebuild Bermuda.Fdc3.Proto. +// +#nullable enable +using System.Text.Json; + +namespace Bermuda.IpcContract; + +public sealed record Fdc3AppIdentifier(string AppId, string? InstanceId = null); + +public sealed record Fdc3DisplayMetadata(string? Name = null, string? Color = null, string? Glyph = null); + +/// +/// A user, app or private channel. `type` is one of 'user' | 'app' | 'private'. +/// +public sealed record Fdc3ChannelInfo(string Id, string Type, Fdc3DisplayMetadata? DisplayMetadata = null); + +public sealed record Fdc3IntentMetadata(string Name, string? DisplayName = null); + +public sealed record Fdc3AppMetadata(string AppId, string? InstanceId = null, string? Name = null, string? Version = null, string? Title = null, string? Tooltip = null, string? Description = null, string? ResultType = null); + +public sealed record Fdc3AppIntent(Fdc3IntentMetadata Intent, Fdc3AppMetadata[] Apps); + +public sealed record Fdc3OptionalFeatures(bool OriginatingAppMetadata, bool UserChannelMembershipAPIs, bool DesktopAgentBridging); + +public sealed record Fdc3ImplementationMetadata(string Fdc3Version, string Provider, string? ProviderVersion, Fdc3OptionalFeatures OptionalFeatures, Fdc3AppMetadata AppMetadata); + +/// +/// What raiseIntent/raiseIntentForContext return. The frontend turns it into an FDC3 IntentResolution whose +/// getResult() calls getIntentResult with `result_id`. +/// +public sealed record Fdc3IntentResolutionInfo(Fdc3AppIdentifier Source, string Intent, string ResultId); + +/// +/// An intent handler's result: a context, a channel, or neither (void). +/// +public sealed record Fdc3IntentResultInfo(JsonElement? Context = null, Fdc3ChannelInfo? Channel = null); + +public sealed record Fdc3ChannelIdRequest(string ChannelId); + +/// +/// `channel_id` unset = the caller's current user channel. +/// +public sealed record Fdc3BroadcastRequest(string? ChannelId, JsonElement Context); + +public sealed record Fdc3GetCurrentContextRequest(string ChannelId, string? ContextType = null); + +/// +/// `listener_id` is chosen by the caller and echoed back in every ContextEvent for this listener. +/// `channel_id` unset = follow whichever user channel the caller is joined to (fdc3.addContextListener); +/// set = a specific app/private channel (channel.addContextListener). +/// +public sealed record Fdc3AddContextListenerRequest(string ListenerId, string? ChannelId = null, string? ContextType = null); + +public sealed record Fdc3AddIntentListenerRequest(string ListenerId, string Intent); + +/// +/// `channel_id` unset = desktop-agent events ('userChannelChanged'); set = private channel events +/// ('addContextListener' | 'unsubscribe' | 'disconnect'). `event_type` unset = all event types. +/// +public sealed record Fdc3AddEventListenerRequest(string ListenerId, string? EventType = null, string? ChannelId = null); + +public sealed record Fdc3ListenerIdRequest(string ListenerId); + +public sealed record Fdc3FindIntentRequest(string Intent, JsonElement? Context = null, string? ResultType = null); + +public sealed record Fdc3FindIntentsByContextRequest(JsonElement Context, string? ResultType = null); + +public sealed record Fdc3OpenRequest(Fdc3AppIdentifier App, JsonElement? Context = null); + +public sealed record Fdc3RaiseIntentRequest(string Intent, JsonElement Context, Fdc3AppIdentifier? App = null); + +public sealed record Fdc3RaiseIntentForContextRequest(JsonElement Context, Fdc3AppIdentifier? App = null); + +public sealed record Fdc3ResultIdRequest(string ResultId); + +/// +/// Sent by the instance that handled an intent once its handler settles. At most one of +/// `context_json`/`channel_id` is set (neither = void); `error` is set instead if the handler threw/rejected. +/// +public sealed record Fdc3SendIntentResultRequest(string ResultId, JsonElement? Context = null, string? ChannelId = null, string? Error = null); + +/// +/// Delivery to a listener added with AddContextListener. +/// +[IpcType] +public sealed record Fdc3ContextEvent(string ListenerId, JsonElement Context, Fdc3AppIdentifier? Source = null) +{ + public string Type => "fdc3.context"; +} + +/// +/// Delivery to an intent listener; the handler reports back with SendIntentResult(result_id). +/// +[IpcType] +public sealed record Fdc3IntentEvent(string ListenerId, string Intent, JsonElement Context, Fdc3AppIdentifier? Source, string ResultId) +{ + public string Type => "fdc3.intent"; +} + +/// +/// An FDC3 ApiEvent (`event_type` + `details`) for a listener added via AddEventListener. +/// +[IpcType] +public sealed record Fdc3ApiEvent(string ListenerId, string EventType, JsonElement? Details = null) +{ + public string Type => "fdc3.event"; +} + +/// +/// The fdc3.* commands: one per FDC3 DesktopAgent / Channel / PrivateChannel / IntentResolution call, +/// plus SendIntentResult, which reports an intent handler's outcome back. Implemented per app instance +/// by Bermuda.Fdc3.Fdc3Connection. Methods throw Fdc3Exception, whose message is the +/// standard FDC3 error string. +/// +[IpcCommands("fdc3")] +public interface IFdc3Commands +{ + Fdc3ImplementationMetadata GetInfo(); + Fdc3AppMetadata GetAppMetadata(Fdc3AppIdentifier request); + Fdc3AppIdentifier[] FindInstances(Fdc3AppIdentifier request); + Task OpenAsync(Fdc3OpenRequest request); + Fdc3ChannelInfo[] GetUserChannels(); + void JoinUserChannel(Fdc3ChannelIdRequest request); + void LeaveCurrentChannel(); + Fdc3ChannelInfo? GetCurrentChannel(); + Fdc3ChannelInfo GetOrCreateChannel(Fdc3ChannelIdRequest request); + Fdc3ChannelInfo CreatePrivateChannel(); + void DisconnectPrivateChannel(Fdc3ChannelIdRequest request); + /// + /// FDC3 broadcast() and channel.broadcast(). + /// + void Broadcast(Fdc3BroadcastRequest request); + JsonElement? GetCurrentContext(Fdc3GetCurrentContextRequest request); + void AddContextListener(Fdc3AddContextListenerRequest request); + void AddIntentListener(Fdc3AddIntentListenerRequest request); + void AddEventListener(Fdc3AddEventListenerRequest request); + /// + /// Listener.unsubscribe(), for every kind of listener. + /// + void Unsubscribe(Fdc3ListenerIdRequest request); + Fdc3AppIntent FindIntent(Fdc3FindIntentRequest request); + Fdc3AppIntent[] FindIntentsByContext(Fdc3FindIntentsByContextRequest request); + Task RaiseIntentAsync(Fdc3RaiseIntentRequest request); + Task RaiseIntentForContextAsync(Fdc3RaiseIntentForContextRequest request); + /// + /// IntentResolution.getResult(). + /// + Task GetIntentResultAsync(Fdc3ResultIdRequest request); + /// + /// Reports an intent handler's result back to the raiser. + /// + void SendIntentResult(Fdc3SendIntentResultRequest request); +} diff --git a/src/Bermuda.NativeApp/Program.cs b/src/Bermuda.NativeApp/Program.cs index 58e6b7d..c3f451e 100644 --- a/src/Bermuda.NativeApp/Program.cs +++ b/src/Bermuda.NativeApp/Program.cs @@ -56,15 +56,15 @@ await client.Rpc.AddIntentListenerAsync( while (!cancellationToken.IsCancellationRequested) { var e = await client.NextEventAsync(Timeout.InfiniteTimeSpan, cancellationToken); - switch (e.EventCase) + switch (e.KindCase) { - case AgentEvent.EventOneofCase.Context: + case AgentEvent.KindOneofCase.Context: Console.WriteLine($"[{AppId}] context from {e.Context.Source?.AppId}: {e.Context.ContextJson}"); await client.Rpc.BroadcastAsync(new BroadcastRequest { ContextJson = Ack(e.Context.ContextJson) }, client.Headers, cancellationToken: cancellationToken); break; - case AgentEvent.EventOneofCase.Intent: + case AgentEvent.KindOneofCase.Intent: Console.WriteLine($"[{AppId}] {e.Intent.Intent} from {e.Intent.Source?.AppId}: {e.Intent.ContextJson}"); await client.Rpc.SendIntentResultAsync( new SendIntentResultRequest { ResultId = e.Intent.ResultId, ContextJson = Ack(e.Intent.ContextJson) }, diff --git a/src/Bermuda.Web/src/fdc3/hostDesktopAgent.ts b/src/Bermuda.Web/src/fdc3/hostDesktopAgent.ts index c854fb1..334a338 100644 --- a/src/Bermuda.Web/src/fdc3/hostDesktopAgent.ts +++ b/src/Bermuda.Web/src/fdc3/hostDesktopAgent.ts @@ -3,7 +3,7 @@ // The Desktop Agent itself lives in the host (src/Bermuda.Fdc3/DesktopAgent.cs); // this class implements the standard @finos/fdc3-standard DesktopAgent // interface by forwarding each call as an fdc3.* invoke() command (shapes -// generated into ipc/__generated__/ipc.d.ts from src/Bermuda.IpcContract/Fdc3Contract.cs) +// generated into ipc/__generated__/ipc.d.ts from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto) // and dispatching the host's fdc3.context / fdc3.intent / fdc3.event pushes to // the handlers registered here. Errors reject with `new Error()` // (e.g. 'NoAppsFound'), as the standard specifies. diff --git a/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts b/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts index 1a29c10..b20e37f 100644 --- a/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts +++ b/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts @@ -22,7 +22,7 @@ export interface Fdc3AddIntentListenerRequest { } export interface Fdc3ApiEvent { - details: unknown | null; + details?: unknown | null; eventType: string; listenerId: string; type: string; diff --git a/src/Bermuda/App.xaml.cs b/src/Bermuda/App.xaml.cs index a3cffed..91383c4 100644 --- a/src/Bermuda/App.xaml.cs +++ b/src/Bermuda/App.xaml.cs @@ -35,7 +35,7 @@ protected override void OnStartup(StartupEventArgs e) /// /// Lets native apps join the agent over gRPC on a named pipe. Config: /// FDC3_GRPC_ENABLED (default true) and FDC3_GRPC_PIPE (default per-user, - /// see ). A failure to listen + /// see ). A failure to listen /// (e.g. the pipe name is taken) must not stop the app. /// private void StartGrpcHost(IConfiguration config, DesktopAgent agent) From 3ac3094b5a1941a5b6b41444232d09839a275568 Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 11 Nov 2026 02:55:21 -0500 Subject: [PATCH 06/14] feat: ship the native FDC3 app inside Bermuda's MSIX The native side app is a second application of the Bermuda package (own startup task, no Start entry), published into the same folder as the host, so it installs and updates with Bermuda from the same .appinstaller. CI publishes it into the release folder and fails if the committed generated FDC3 code is stale. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 11 ++++++++++ README.md | 4 +++- docs/fdc3.md | 15 ++++++++++---- .../Bermuda.NativeApp.csproj | 16 ++++++++++----- src/Bermuda/Bermuda.csproj | 7 ++++++- src/Bermuda/Package.appxmanifest | 20 +++++++++++++++++++ 6 files changed, 62 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 79f8281..a152426 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,6 +57,12 @@ jobs: if: startsWith(github.ref, 'refs/tags/v') run: dotnet publish src/Bermuda/Bermuda.csproj --configuration Release --runtime win-x64 --self-contained true --output artifacts/publish -p:PublishSingleFile=false -p:PublishReadyToRun=false + # The native side app (src/Bermuda.NativeApp) ships inside Bermuda's MSIX as a second application, + # so it is published into the same folder (shared runtime/library files are identical). + - name: Publish self-contained native app into the same folder + if: startsWith(github.ref, 'refs/tags/v') + run: dotnet publish src/Bermuda.NativeApp/Bermuda.NativeApp.csproj --configuration Release --runtime win-x64 --self-contained true --output artifacts/publish -p:PublishSingleFile=false -p:PublishReadyToRun=false + - name: Upload self-contained app if: startsWith(github.ref, 'refs/tags/v') uses: actions/upload-artifact@v4 @@ -70,6 +76,11 @@ jobs: - name: Check committed FDC3 preload is up to date run: git diff --ignore-cr-at-eol --exit-code -- src/Bermuda/Preload + # The FDC3 contract is generated from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto by the build + # (Bermuda.Fdc3.Proto); the outputs are committed, so a stale or hand-edited copy fails here. + - name: Check committed FDC3 generated code is up to date + run: git diff --ignore-cr-at-eol --exit-code -- src/Bermuda.IpcContract/Generated src/Bermuda.Fdc3.Grpc/Generated + # ─── E2E (requires a Windows desktop runner) ────────────────────────────── # # The Playwright tests connect to the live app via CDP (port 9222). diff --git a/README.md b/README.md index 69acb62..4d4f00e 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ await window.fdc3.broadcast({ type: 'bermuda.incident', id: { incidentId: '7' } const resolution = await window.fdc3.raiseIntent('ViewIncident', context) ``` -- **Where it lives** — the agent is `src/Bermuda.Fdc3/DesktopAgent.cs` (one per process, shared by all windows). `src/Bermuda.Web/src/fdc3/` implements the `@finos/fdc3-standard` `DesktopAgent` interface by calling `fdc3.*` `invoke()` commands (the `IFdc3Commands` interface in `Bermuda.IpcContract/Fdc3Contract.cs`, implemented per app instance by `Fdc3Connection`, so their TS types are generated like everything else) and dispatching the host's `fdc3.context` / `fdc3.intent` / `fdc3.event` pushes to registered handlers. +- **Where it lives** — the agent is `src/Bermuda.Fdc3/DesktopAgent.cs` (one per process, shared by all windows). `src/Bermuda.Web/src/fdc3/` implements the `@finos/fdc3-standard` `DesktopAgent` interface by calling `fdc3.*` `invoke()` commands (the `IFdc3Commands` interface, generated from `Bermuda.Fdc3.Proto/Protos/fdc3.proto` into `Bermuda.IpcContract/Generated/Fdc3Contract.g.cs`, implemented per app instance by `Fdc3Connection`, so their TS types are generated like everything else) and dispatching the host's `fdc3.context` / `fdc3.intent` / `fdc3.event` pushes to registered handlers. - **Supported** — the 8 recommended user channels, app channels, private channels (with their events), `broadcast`/`addContextListener`/`getCurrentContext`, `findIntent`/`findIntentsByContext`/`raiseIntent`/`raiseIntentForContext`/`addIntentListener` with results (context or channel), `open`, `findInstances`, `getAppMetadata`, `getInfo`, and the `userChannelChanged` event. Not yet: Desktop Agent Bridging, or the Web Connection Protocol for browser apps outside the host. - **Preload bundle** — `fdc3-preload.js` is built from `src/Bermuda.Web/src/fdc3/preload.ts` by `pnpm build:preload` (part of `pnpm build`) and committed, like `ipc.d.ts`, so the host builds without Node; CI fails if it's out of date. Re-run `pnpm build:preload` after touching anything under `src/fdc3/`. - **App Directory** — `src/Bermuda/fdc3-appd.json` uses the AppD v2 `applications` shape; relative `details.url`s resolve against `WEB_URL`. `fdc3.open` (or raising an intent at an app that isn't running) opens the app in a new host window and resolves once the app has connected (and, if you passed a context, registered a listener for it), or rejects with `AppTimeout`. Intent results the raiser never collects are dropped after 10 minutes. @@ -117,6 +117,8 @@ const resolution = await window.fdc3.raiseIntent('ViewIncident', context) # Build a self-contained MSIX installer (needs the winapp CLI: winget install Microsoft.winappcli --source winget) dotnet msbuild src/Bermuda -t:CreateMsix -p:Configuration=Release # Output: artifacts/msix/ + +# The package also contains the sample native FDC3 side app (src/Bermuda.NativeApp) as a second application. ``` ### Releases and auto-update diff --git a/docs/fdc3.md b/docs/fdc3.md index e8ded5c..a95349f 100644 --- a/docs/fdc3.md +++ b/docs/fdc3.md @@ -28,7 +28,7 @@ Make the Bermuda host an [FDC3 2.2](https://fdc3.finos.org/docs/2.2/fdc3-intro) |---|---|---| | `DesktopAgent` | `src/Bermuda.Fdc3` | All state and rules: instances, channels, listeners, intents, results, launching. One per process. | | `Fdc3Connection` | `src/Bermuda.Fdc3` | One app instance's handle on the agent; implements the command interface for that instance. `IDisposable`. | -| `IFdc3Commands` | `src/Bermuda.IpcContract/Fdc3Contract.cs` | The wire contract: one method per `fdc3.*` command. TypeScript types are generated from it into `ipc.d.ts`. | +| `IFdc3Commands` | `src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs` | The wire contract: one method per `fdc3.*` command. Generated from `src/Bermuda.Fdc3.Proto/Protos/fdc3.proto` (see 7a); TypeScript types are generated from it into `ipc.d.ts`. | | `HostBridge` | `src/Bermuda` | Dispatches an `invoke()` command to the window's connection, binding the JSON payload to the method's parameter type. | | `MainWindow` | `src/Bermuda` | One connected instance per page load; injects the preload; delivers the agent's pushes to the page. | | `WindowAppLauncher` | `src/Bermuda` | Opens App Directory apps in new host windows for `open` and for intents. | @@ -140,16 +140,23 @@ Rejections are `Error`s whose `message` is the standard FDC3 error string; over ## 7a. Native apps over gRPC (named pipe) -Native side apps join the same in-process agent as the web windows, so they share channels and intents with them. `Bermuda.Fdc3.Grpc` hosts a gRPC service (Kestrel named-pipe transport, HTTP/2 without TLS) that mirrors `IFdc3Commands`; the contract is `src/Bermuda.Fdc3.Grpc/Protos/fdc3.proto`. +Native side apps join the same in-process agent as the web windows, so they share channels and intents with them. `Bermuda.Fdc3.Grpc` hosts a gRPC service (Kestrel named-pipe transport, HTTP/2 without TLS) that serves `IFdc3Commands`. -**The proto is the source of truth** for the gRPC surface. Grpc.Tools builds the messages and the `Fdc3Agent` service base from it. After protoc runs, `Bermuda.Fdc3.Grpc.Generator` reads protoc's descriptor set and checks it against `IFdc3Commands` and the records it uses. Any difference (a missing or extra rpc, message or field, or a type, `optional` or `repeated` mismatch) **fails the build** and lists the differences. When they agree, it writes `Generated/Fdc3Generated.g.cs` (checked in, refreshed by the build): the proto↔contract mapping and one service override per rpc. So changing the gRPC surface means editing the proto and updating `Fdc3Contract.cs` to match. The mapping conventions are at the top of the proto. Hand-written: the `Subscribe` stream and caller lookup (`Fdc3AgentService.cs`) and the JSON helper (`Mapping.cs`). +**The proto is the source of truth for the whole FDC3 contract**, web and native: `src/Bermuda.Fdc3.Proto/Protos/fdc3.proto`. Building `Bermuda.Fdc3.Proto` does three things: + +1. Grpc.Tools turns it into the gRPC messages and the `Fdc3Agent` service (and client) classes. +2. `Bermuda.Fdc3.Grpc.Generator` reads protoc's descriptor set and writes `src/Bermuda.IpcContract/Generated/Fdc3Contract.g.cs`: the `Fdc3*` records and `IFdc3Commands` that `DesktopAgent`, `Fdc3Connection` and the web bridge are written against (and that `ipc.d.ts` is generated from). +3. The same tool writes `src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs`: the proto↔record mapping and one service override per rpc. + +Both generated files are checked in, like `ipc.d.ts`, and CI fails if they are stale. So adding or changing a command, field or message means editing the proto and rebuilding; nothing else is hand-synchronised. The naming and nullability conventions (and the `async` method option for commands that wait on another app) are documented at the top of the proto; a proto that breaks them fails the build with the list of problems. Hand-written: the `Subscribe` stream and caller lookup (`Fdc3AgentService.cs`), the JSON helper (`Mapping.cs`) and the host and client. - **Pipe**: `\\.\pipe\bermuda-fdc3-` by default (pipe names are machine-wide, so the user name keeps users apart). Override with `FDC3_GRPC_PIPE`; disable with `FDC3_GRPC_ENABLED=false` (both in `appsettings.json` or the environment). The pipe is current-user-only. - **Connect**: call `Subscribe(app_id)`. `app_id` MUST be in the App Directory, else the call fails with `AppNotFound`. The first stream message is `connected { instance_id }`; context, intent and API-event deliveries follow (`ContextEvent`, `IntentEvent`, `ApiEvent`, mirroring `Fdc3*Event`). - **Calls**: every other RPC carries the `x-fdc3-instance` header (the `instance_id`) and must use the same pipe connection as the stream, else `AccessDenied`. - **Lifetime**: the stream is the app instance. When it ends (cancelled, process exit, pipe closed) the instance is disconnected like a closed window. - **Contexts** are JSON text (`*_json` fields). **Errors** are gRPC errors whose status *detail* is the `Fdc3Errors` string (`NoChannelFound`, `MalformedContext`, …); the code is a coarse mapping (e.g. `NotFound`, `InvalidArgument`, `PermissionDenied`). -- **Client**: any gRPC stack that can dial a named pipe. `Fdc3PipeClient` (in `Bermuda.Fdc3.Grpc`; used by the sample `src/Bermuda.NativeApp`) is a ~100-line .NET reference (`SocketsHttpHandler.ConnectCallback` returning a `NamedPipeClientStream`). +- **Client**: any gRPC stack that can dial a named pipe. `Fdc3PipeClient` (in `Bermuda.Fdc3.Proto`, so a client does not need ASP.NET Core; used by the sample `src/Bermuda.NativeApp`) is a ~100-line .NET reference (`SocketsHttpHandler.ConnectCallback` returning a `NamedPipeClientStream`). +- **Sample app and packaging**: `src/Bermuda.NativeApp` connects as `native-incidents` (in `fdc3-appd.json`), joins a channel and acknowledges incidents; Aspire starts it next to the host in development. For installs it ships **inside Bermuda's MSIX** as a second application of that package (`Package.appxmanifest`: full trust, no Start menu entry, its own startup task), so it deploys, updates and is signed exactly like Bermuda, from the same `.appinstaller`. `CreateMsix` publishes it into the same folder as the host, and CI does the same for tagged releases. It starts at sign-in and retries until the host's pipe is up. - Limitations: native apps are not launched by the agent (`open`/intents can target them only while connected), and web windows are still the only apps with launch URLs. ## 8. Known limitations diff --git a/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj b/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj index 297b304..c364a4c 100644 --- a/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj +++ b/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj @@ -1,19 +1,25 @@ - Exe + WinExe net10.0 enable enable - + + diff --git a/src/Bermuda/Bermuda.csproj b/src/Bermuda/Bermuda.csproj index 999092f..dee0936 100644 --- a/src/Bermuda/Bermuda.csproj +++ b/src/Bermuda/Bermuda.csproj @@ -115,7 +115,7 @@ + + + + diff --git a/src/Bermuda/Package.appxmanifest b/src/Bermuda/Package.appxmanifest index 1c1d414..2df014a 100644 --- a/src/Bermuda/Package.appxmanifest +++ b/src/Bermuda/Package.appxmanifest @@ -59,6 +59,26 @@ + + + + + + + + + + From 4cb0329d980c0e2d017373018b5e7aef82938d8e Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 11 Nov 2026 03:05:26 -0500 Subject: [PATCH 07/14] feat: Bermuda starts and stops the native FDC3 side app The host launches Bermuda.NativeApp.exe from its own package on startup (NATIVE_APP_AUTOSTART=false disables it) and closes it on exit; the side app allows one copy per user. Its own startup task is removed: the host is what starts it, so it no longer needs a sign-in entry. Co-Authored-By: Claude Sonnet 5.5 --- docs/fdc3.md | 2 +- src/Bermuda.NativeApp/Program.cs | 4 ++++ src/Bermuda/App.xaml.cs | 39 ++++++++++++++++++++++++++++++++ src/Bermuda/Package.appxmanifest | 9 ++------ src/Bermuda/appsettings.json | 3 ++- 5 files changed, 48 insertions(+), 9 deletions(-) diff --git a/docs/fdc3.md b/docs/fdc3.md index a95349f..8c41f51 100644 --- a/docs/fdc3.md +++ b/docs/fdc3.md @@ -156,7 +156,7 @@ Both generated files are checked in, like `ipc.d.ts`, and CI fails if they are s - **Lifetime**: the stream is the app instance. When it ends (cancelled, process exit, pipe closed) the instance is disconnected like a closed window. - **Contexts** are JSON text (`*_json` fields). **Errors** are gRPC errors whose status *detail* is the `Fdc3Errors` string (`NoChannelFound`, `MalformedContext`, …); the code is a coarse mapping (e.g. `NotFound`, `InvalidArgument`, `PermissionDenied`). - **Client**: any gRPC stack that can dial a named pipe. `Fdc3PipeClient` (in `Bermuda.Fdc3.Proto`, so a client does not need ASP.NET Core; used by the sample `src/Bermuda.NativeApp`) is a ~100-line .NET reference (`SocketsHttpHandler.ConnectCallback` returning a `NamedPipeClientStream`). -- **Sample app and packaging**: `src/Bermuda.NativeApp` connects as `native-incidents` (in `fdc3-appd.json`), joins a channel and acknowledges incidents; Aspire starts it next to the host in development. For installs it ships **inside Bermuda's MSIX** as a second application of that package (`Package.appxmanifest`: full trust, no Start menu entry, its own startup task), so it deploys, updates and is signed exactly like Bermuda, from the same `.appinstaller`. `CreateMsix` publishes it into the same folder as the host, and CI does the same for tagged releases. It starts at sign-in and retries until the host's pipe is up. +- **Sample app and packaging**: `src/Bermuda.NativeApp` connects as `native-incidents` (in `fdc3-appd.json`), joins a channel and acknowledges incidents; Aspire starts it next to the host in development. For installs it ships **inside Bermuda's MSIX** as a second application of that package (`Package.appxmanifest`: full trust, no Start menu entry, no startup task of its own), so it deploys, updates and is signed exactly like Bermuda, from the same `.appinstaller`. `CreateMsix` publishes it into the same folder as the host, and CI does the same for tagged releases. **Bermuda starts it** when the host starts (`App.StartNativeApp`; `NATIVE_APP_AUTOSTART=false` turns that off) and closes it on exit; the app allows one copy per user, so a second start is harmless. It retries until the host's pipe is up. - Limitations: native apps are not launched by the agent (`open`/intents can target them only while connected), and web windows are still the only apps with launch URLs. ## 8. Known limitations diff --git a/src/Bermuda.NativeApp/Program.cs b/src/Bermuda.NativeApp/Program.cs index c3f451e..419f807 100644 --- a/src/Bermuda.NativeApp/Program.cs +++ b/src/Bermuda.NativeApp/Program.cs @@ -20,6 +20,10 @@ var pipe = Environment.GetEnvironmentVariable("FDC3_GRPC_PIPE"); var channel = Environment.GetEnvironmentVariable("NATIVE_CHANNEL") is { Length: > 0 } c ? c : "fdc3.channel.1"; +// One copy per user: Windows starts it at sign-in and Bermuda starts it too; a second copy just exits. +using var singleInstance = new Mutex(true, @"LocalBermuda.NativeApp." + AppId, out var first); +if (!first) return; + using var shutdown = new CancellationTokenSource(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; shutdown.Cancel(); }; diff --git a/src/Bermuda/App.xaml.cs b/src/Bermuda/App.xaml.cs index 91383c4..ce94cd1 100644 --- a/src/Bermuda/App.xaml.cs +++ b/src/Bermuda/App.xaml.cs @@ -27,6 +27,7 @@ protected override void OnStartup(StartupEventArgs e) launcher.Agent = fdc3; StartGrpcHost(config, fdc3); + if (_grpcHost is not null) StartNativeApp(config); var window = new MainWindow(config, fdc3, MainAppId); window.Show(); @@ -52,9 +53,47 @@ private void StartGrpcHost(IConfiguration config, DesktopAgent agent) } private Fdc3GrpcHost? _grpcHost; + private System.Diagnostics.Process? _nativeApp; + + /// + /// Starts the sample native FDC3 app that ships in the same package (Bermuda.NativeApp.exe next to this exe), + /// so it is running whenever Bermuda is, however Bermuda was started and whether or not Windows has run the + /// app's own startup task yet. It allows a single copy per user, so a second start is harmless. Not found + /// (development: Aspire runs it) or NATIVE_APP_AUTOSTART=false: nothing happens. + /// + private void StartNativeApp(IConfiguration config) + { + if (bool.TryParse(config["NATIVE_APP_AUTOSTART"], out var enabled) && !enabled) return; + var exe = Path.Combine(AppContext.BaseDirectory, "Bermuda.NativeApp.exe"); + if (!File.Exists(exe)) return; + try + { + _nativeApp = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(exe) + { + UseShellExecute = false, + WorkingDirectory = AppContext.BaseDirectory, + }); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Native FDC3 app failed to start: {ex}"); + } + } protected override void OnExit(ExitEventArgs e) { + // Close the side app we started. If it was already running (so our copy exited at once because it + // allows one per user), or someone else started it, that handle has exited and nothing is killed. + try + { + if (_nativeApp is { HasExited: false }) _nativeApp.Kill(); + _nativeApp?.Dispose(); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Native FDC3 app did not stop: {ex.Message}"); + } + if (_grpcHost is { } grpcHost) { Task.Run(() => grpcHost.DisposeAsync().AsTask()).Wait(TimeSpan.FromSeconds(6)); diff --git a/src/Bermuda/Package.appxmanifest b/src/Bermuda/Package.appxmanifest index 2df014a..a1fdd79 100644 --- a/src/Bermuda/Package.appxmanifest +++ b/src/Bermuda/Package.appxmanifest @@ -61,8 +61,8 @@ + updates with Bermuda. A background app with no Start menu entry and no startup task of its own: Bermuda + starts it (App.StartNativeApp) and closes it again on exit. --> @@ -73,11 +73,6 @@ Square150x150Logo="Assets\Square150x150Logo.png" Square44x44Logo="Assets\Square44x44Logo.png" AppListEntry="none" /> - - - - - diff --git a/src/Bermuda/appsettings.json b/src/Bermuda/appsettings.json index df1d817..cba3c3f 100644 --- a/src/Bermuda/appsettings.json +++ b/src/Bermuda/appsettings.json @@ -2,5 +2,6 @@ "WEB_URL": "http://localhost:5555", "CDP_PORT": 9222, "TITLE_BAR": "client", - "FDC3_GRPC_ENABLED": true + "FDC3_GRPC_ENABLED": true, + "NATIVE_APP_AUTOSTART": true } From f972b07ad70675a54d855d6fc8657c6074d6c94a Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 11 Nov 2026 13:57:28 -0500 Subject: [PATCH 08/14] fix: restore the backslash in the native app's single-instance mutex name The name had lost it (LocalBermuda...), so the copy Bermuda autostarts and the one Aspire starts both stayed up and the e2e saw two native-incidents instances. Co-Authored-By: Claude Sonnet 5.5 --- src/Bermuda.NativeApp/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Bermuda.NativeApp/Program.cs b/src/Bermuda.NativeApp/Program.cs index 419f807..8ad7439 100644 --- a/src/Bermuda.NativeApp/Program.cs +++ b/src/Bermuda.NativeApp/Program.cs @@ -21,7 +21,7 @@ var channel = Environment.GetEnvironmentVariable("NATIVE_CHANNEL") is { Length: > 0 } c ? c : "fdc3.channel.1"; // One copy per user: Windows starts it at sign-in and Bermuda starts it too; a second copy just exits. -using var singleInstance = new Mutex(true, @"LocalBermuda.NativeApp." + AppId, out var first); +using var singleInstance = new Mutex(true, @"Local\Bermuda.NativeApp." + AppId, out var first); if (!first) return; using var shutdown = new CancellationTokenSource(); From 47e1b3afe9d9777c37cfc75a049f56126e1ce296 Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 11 Nov 2026 14:04:49 -0500 Subject: [PATCH 09/14] feat: discover native side apps from the FDC3 App Directory fdc3-appd.json is now the one list of native side apps (type native, details.path, details.project). Aspire, the MSIX build (native-apps.ps1 publishes each project and adds its manifest Application), CI and the host's autostart all read it, so adding a native app is a one-line edit of that file. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 8 +-- README.md | 2 +- docs/fdc3.md | 6 ++- src/Bermuda.AppHost/AppHost.cs | 20 ++++++-- src/Bermuda.AppHost/Bermuda.AppHost.csproj | 1 - src/Bermuda.Fdc3/AppDirectory.cs | 7 ++- src/Bermuda/App.xaml.cs | 57 ++++++++++++---------- src/Bermuda/Bermuda.csproj | 39 ++++++++++++--- src/Bermuda/Package.appxmanifest | 15 +----- src/Bermuda/fdc3-appd.json | 4 ++ src/Bermuda/native-apps.ps1 | 48 ++++++++++++++++++ 11 files changed, 150 insertions(+), 57 deletions(-) create mode 100644 src/Bermuda/native-apps.ps1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a152426..49c6e3b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,11 +57,11 @@ jobs: if: startsWith(github.ref, 'refs/tags/v') run: dotnet publish src/Bermuda/Bermuda.csproj --configuration Release --runtime win-x64 --self-contained true --output artifacts/publish -p:PublishSingleFile=false -p:PublishReadyToRun=false - # The native side app (src/Bermuda.NativeApp) ships inside Bermuda's MSIX as a second application, - # so it is published into the same folder (shared runtime/library files are identical). - - name: Publish self-contained native app into the same folder + # The native side apps listed in fdc3-appd.json ship inside Bermuda's MSIX as more applications, so they + # are published into the same folder (shared runtime/library files are identical). + - name: Publish self-contained native apps into the same folder if: startsWith(github.ref, 'refs/tags/v') - run: dotnet publish src/Bermuda.NativeApp/Bermuda.NativeApp.csproj --configuration Release --runtime win-x64 --self-contained true --output artifacts/publish -p:PublishSingleFile=false -p:PublishReadyToRun=false + run: dotnet msbuild src/Bermuda/Bermuda.csproj -t:PublishNativeApps -p:Configuration=Release -p:NativeAppsPublishDir=${{ github.workspace }}/artifacts/publish/ - name: Upload self-contained app if: startsWith(github.ref, 'refs/tags/v') diff --git a/README.md b/README.md index 4d4f00e..b5b3fc0 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ const resolution = await window.fdc3.raiseIntent('ViewIncident', context) dotnet msbuild src/Bermuda -t:CreateMsix -p:Configuration=Release # Output: artifacts/msix/ -# The package also contains the sample native FDC3 side app (src/Bermuda.NativeApp) as a second application. +# The package also contains the native FDC3 side apps listed in src/Bermuda/fdc3-appd.json (type "native"). ``` ### Releases and auto-update diff --git a/docs/fdc3.md b/docs/fdc3.md index 8c41f51..67d6a89 100644 --- a/docs/fdc3.md +++ b/docs/fdc3.md @@ -156,7 +156,11 @@ Both generated files are checked in, like `ipc.d.ts`, and CI fails if they are s - **Lifetime**: the stream is the app instance. When it ends (cancelled, process exit, pipe closed) the instance is disconnected like a closed window. - **Contexts** are JSON text (`*_json` fields). **Errors** are gRPC errors whose status *detail* is the `Fdc3Errors` string (`NoChannelFound`, `MalformedContext`, …); the code is a coarse mapping (e.g. `NotFound`, `InvalidArgument`, `PermissionDenied`). - **Client**: any gRPC stack that can dial a named pipe. `Fdc3PipeClient` (in `Bermuda.Fdc3.Proto`, so a client does not need ASP.NET Core; used by the sample `src/Bermuda.NativeApp`) is a ~100-line .NET reference (`SocketsHttpHandler.ConnectCallback` returning a `NamedPipeClientStream`). -- **Sample app and packaging**: `src/Bermuda.NativeApp` connects as `native-incidents` (in `fdc3-appd.json`), joins a channel and acknowledges incidents; Aspire starts it next to the host in development. For installs it ships **inside Bermuda's MSIX** as a second application of that package (`Package.appxmanifest`: full trust, no Start menu entry, no startup task of its own), so it deploys, updates and is signed exactly like Bermuda, from the same `.appinstaller`. `CreateMsix` publishes it into the same folder as the host, and CI does the same for tagged releases. **Bermuda starts it** when the host starts (`App.StartNativeApp`; `NATIVE_APP_AUTOSTART=false` turns that off) and closes it on exit; the app allows one copy per user, so a second start is harmless. It retries until the host's pipe is up. +- **Native apps are discovered from the App Directory.** `fdc3-appd.json` is the one list of side apps. An entry with `"type": "native"` and `details.path` (its exe, relative to Bermuda's folder) is a native app; `details.project` (Bermuda extension: the .csproj that builds it, relative to the file) tells builds where it comes from. Everything else follows from that entry, so **adding a native app is a one-line edit of `fdc3-appd.json`** plus its project: + - **Aspire** (`Bermuda.AppHost`) starts a resource per native entry next to the host. + - **MSIX** (`CreateMsix`, via `src/Bermuda/native-apps.ps1`) publishes each project into Bermuda's package folder and adds an `` to the manifest where it has the `@NATIVE_APPS@` marker (full trust, no Start menu entry, no startup task). CI publishes them for tagged releases with `dotnet msbuild src/Bermuda -t:PublishNativeApps`. So they deploy, update and are signed exactly like Bermuda, from the same `.appinstaller`. + - **Bermuda** starts each one when the host starts (`App.StartNativeApps`; `NATIVE_APP_AUTOSTART=false` turns that off) and closes them on exit. An app should allow one copy per user, so a second start is harmless, and retry until the host's pipe is up. + The sample is `src/Bermuda.NativeApp` (`native-incidents`): it joins a channel and acknowledges incidents. - Limitations: native apps are not launched by the agent (`open`/intents can target them only while connected), and web windows are still the only apps with launch URLs. ## 8. Known limitations diff --git a/src/Bermuda.AppHost/AppHost.cs b/src/Bermuda.AppHost/AppHost.cs index ce3d386..e5d4f22 100644 --- a/src/Bermuda.AppHost/AppHost.cs +++ b/src/Bermuda.AppHost/AppHost.cs @@ -1,3 +1,5 @@ +using System.Text.Json; + var builder = DistributedApplication.CreateBuilder(args); var api = builder.AddProject("api"); @@ -17,10 +19,20 @@ .WaitFor(web) .WaitFor(api); -// A native FDC3 side app: joins the host's agent over the gRPC named pipe -// (both use the default per-user pipe name; it reconnects until the pipe is up). -builder.AddProject("native-app") - .WaitFor(host); +// The native FDC3 side apps are discovered from the App Directory (type "native" with details.project), so +// adding one is a one-line edit of fdc3-appd.json. They join the host's agent over the gRPC named pipe (the +// default per-user pipe name) and reconnect until it is up. +var appDirectory = Path.Combine(builder.AppHostDirectory, "..", "Bermuda", "fdc3-appd.json"); +foreach (var app in JsonDocument.Parse(File.ReadAllText(appDirectory), new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }) + .RootElement.GetProperty("applications").EnumerateArray()) +{ + if (app.GetProperty("type").GetString() != "native" + || !app.TryGetProperty("details", out var details) + || !details.TryGetProperty("project", out var project)) continue; + + builder.AddProject(app.GetProperty("appId").GetString()!, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(appDirectory)!, project.GetString()!))) + .WaitFor(host); +} builder.Build().Run(); diff --git a/src/Bermuda.AppHost/Bermuda.AppHost.csproj b/src/Bermuda.AppHost/Bermuda.AppHost.csproj index a3300af..1bedc53 100644 --- a/src/Bermuda.AppHost/Bermuda.AppHost.csproj +++ b/src/Bermuda.AppHost/Bermuda.AppHost.csproj @@ -11,7 +11,6 @@ - diff --git a/src/Bermuda.Fdc3/AppDirectory.cs b/src/Bermuda.Fdc3/AppDirectory.cs index db1c592..b34f786 100644 --- a/src/Bermuda.Fdc3/AppDirectory.cs +++ b/src/Bermuda.Fdc3/AppDirectory.cs @@ -30,7 +30,12 @@ public sealed record AppDefinition new Dictionary(); } -public sealed record AppDetails(string? Url); +/// +/// AppD details: url for web apps; path and arguments for native apps (the path is +/// relative to the host's folder). project is a Bermuda extension for native apps: the .csproj that builds +/// them, relative to the directory file, so builds can find and package side apps from this file alone. +/// +public sealed record AppDetails(string? Url = null, string? Path = null, string? Arguments = null, string? Project = null); public sealed record AppInterop(AppInteropIntents? Intents); diff --git a/src/Bermuda/App.xaml.cs b/src/Bermuda/App.xaml.cs index ce94cd1..ccdf493 100644 --- a/src/Bermuda/App.xaml.cs +++ b/src/Bermuda/App.xaml.cs @@ -27,7 +27,7 @@ protected override void OnStartup(StartupEventArgs e) launcher.Agent = fdc3; StartGrpcHost(config, fdc3); - if (_grpcHost is not null) StartNativeApp(config); + if (_grpcHost is not null) StartNativeApps(config, directory); var window = new MainWindow(config, fdc3, MainAppId); window.Show(); @@ -53,30 +53,34 @@ private void StartGrpcHost(IConfiguration config, DesktopAgent agent) } private Fdc3GrpcHost? _grpcHost; - private System.Diagnostics.Process? _nativeApp; + private readonly List _nativeApps = []; /// - /// Starts the sample native FDC3 app that ships in the same package (Bermuda.NativeApp.exe next to this exe), - /// so it is running whenever Bermuda is, however Bermuda was started and whether or not Windows has run the - /// app's own startup task yet. It allows a single copy per user, so a second start is harmless. Not found - /// (development: Aspire runs it) or NATIVE_APP_AUTOSTART=false: nothing happens. + /// Starts every native side app in the App Directory (type "native" with a details.path, relative to this exe), + /// so they run whenever Bermuda does, however Bermuda was started. They ship in the same package. Each allows + /// one copy per user, so starting one that is already running is harmless. NATIVE_APP_AUTOSTART=false turns + /// this off. /// - private void StartNativeApp(IConfiguration config) + private void StartNativeApps(IConfiguration config, AppDirectory directory) { if (bool.TryParse(config["NATIVE_APP_AUTOSTART"], out var enabled) && !enabled) return; - var exe = Path.Combine(AppContext.BaseDirectory, "Bermuda.NativeApp.exe"); - if (!File.Exists(exe)) return; - try + foreach (var app in directory.Apps.Where(a => a.Type == "native" && a.Details?.Path is not null)) { - _nativeApp = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(exe) + var exe = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, app.Details!.Path!)); + if (!File.Exists(exe)) continue; + try { - UseShellExecute = false, - WorkingDirectory = AppContext.BaseDirectory, - }); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine($"Native FDC3 app failed to start: {ex}"); + var process = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(exe, app.Details.Arguments ?? "") + { + UseShellExecute = false, + WorkingDirectory = Path.GetDirectoryName(exe)!, + }); + if (process is not null) _nativeApps.Add(process); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Native FDC3 app {app.AppId} failed to start: {ex}"); + } } } @@ -84,14 +88,17 @@ protected override void OnExit(ExitEventArgs e) { // Close the side app we started. If it was already running (so our copy exited at once because it // allows one per user), or someone else started it, that handle has exited and nothing is killed. - try + foreach (var process in _nativeApps) { - if (_nativeApp is { HasExited: false }) _nativeApp.Kill(); - _nativeApp?.Dispose(); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine($"Native FDC3 app did not stop: {ex.Message}"); + try + { + if (!process.HasExited) process.Kill(); + process.Dispose(); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Native FDC3 app did not stop: {ex.Message}"); + } } if (_grpcHost is { } grpcHost) diff --git a/src/Bermuda/Bermuda.csproj b/src/Bermuda/Bermuda.csproj index dee0936..5351f84 100644 --- a/src/Bermuda/Bermuda.csproj +++ b/src/Bermuda/Bermuda.csproj @@ -112,17 +112,42 @@ + + + + + + + + $([System.String]::Copy('%(_NativeAppLine.Identity)').Split('|')[1]) + $([System.String]::Copy('%(_NativeAppLine.Identity)').Split('|')[2]) + + + + + + + + + + + - + <_PublishDir Condition="'$(MsixInputDir)' == ''">$(MSBuildProjectDirectory)\..\..\artifacts\publish\ @@ -136,10 +161,10 @@ - - - + + + @@ -160,6 +185,8 @@ <_ManifestText>$([System.Text.RegularExpressions.Regex]::Replace('$(_ManifestText)', '(?s)(<Identity[^>]*?Version=")[^"]*(")', '${1}$(MsixVersion)${2}')) + + diff --git a/src/Bermuda/Package.appxmanifest b/src/Bermuda/Package.appxmanifest index a1fdd79..2c335c2 100644 --- a/src/Bermuda/Package.appxmanifest +++ b/src/Bermuda/Package.appxmanifest @@ -60,20 +60,7 @@ - - - - + diff --git a/src/Bermuda/fdc3-appd.json b/src/Bermuda/fdc3-appd.json index 24206da..8e5e6fa 100644 --- a/src/Bermuda/fdc3-appd.json +++ b/src/Bermuda/fdc3-appd.json @@ -6,6 +6,10 @@ "title": "Native Incidents", "description": "Sample native side app (Bermuda.NativeApp) connected over gRPC on a named pipe. Acknowledges incidents it receives.", "type": "native", + "details": { + "path": "Bermuda.NativeApp.exe", + "project": "../Bermuda.NativeApp/Bermuda.NativeApp.csproj" + }, "interop": { "intents": { "listensFor": { diff --git a/src/Bermuda/native-apps.ps1 b/src/Bermuda/native-apps.ps1 new file mode 100644 index 0000000..d5aa6e6 --- /dev/null +++ b/src/Bermuda/native-apps.ps1 @@ -0,0 +1,48 @@ +# Reads the FDC3 App Directory (fdc3-appd.json) for the native side apps that ship in Bermuda's MSIX. +# Used by src/Bermuda/Bermuda.csproj (the CreateMsix and PublishNativeApps targets). +# +# -Mode List prints one line per native app: appId|exe|project (project is an absolute path, or empty) +# -Mode Patch replaces the marker in -Manifest with one per native app +param( + [Parameter(Mandatory)] [string] $Directory, + [Parameter(Mandatory)] [ValidateSet('List', 'Patch')] [string] $Mode, + [string] $Manifest +) +$ErrorActionPreference = 'Stop' + +$dir = Split-Path -Parent (Resolve-Path $Directory) +$apps = (Get-Content -Raw -Path $Directory | ConvertFrom-Json).applications | Where-Object { $_.type -eq 'native' } + +foreach ($app in $apps) { + if (-not $app.details.path) { throw "Native app '$($app.appId)' in fdc3-appd.json needs details.path (its exe in the package)." } +} + +if ($Mode -eq 'List') { + foreach ($app in $apps) { + $project = if ($app.details.project) { [System.IO.Path]::GetFullPath((Join-Path $dir $app.details.project)) } else { '' } + "$($app.appId)|$($app.details.path)|$project" + } + return +} + +if (-not $Manifest) { throw '-Manifest is required for -Mode Patch.' } +$esc = { param($v) [System.Security.SecurityElement]::Escape([string]$v) } +$xml = foreach ($app in $apps) { + # Manifest Application ids are letters and digits only. + $key = 'Native' + ($app.appId -replace '[^A-Za-z0-9]', '') + $title = if ($app.title) { $app.title } else { $app.appId } + $desc = if ($app.description) { $app.description } else { $title } + @" + + + + + +"@ +} +$marker = '' +$text = [System.IO.File]::ReadAllText($Manifest) +if (-not $text.Contains($marker)) { throw "The manifest has no $marker marker." } +[System.IO.File]::WriteAllText($Manifest, $text.Replace($marker, ($xml -join "`n"))) From e1b180acd6fdffde13d2e55020a70609e98c64f1 Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 11 Nov 2026 14:27:37 -0500 Subject: [PATCH 10/14] chore: bump Aspire to 13.6.5, use AddCSharpApp, and read the App Directory with a C# file app The native-apps script is now a .NET file-based app (dotnet run --file) instead of PowerShell; the AppHost registers native apps with Aspire's new AddCSharpApp. Co-Authored-By: Claude Sonnet 5.5 --- Directory.Packages.props | 2 +- docs/fdc3.md | 2 +- src/Bermuda.AppHost/AppHost.cs | 4 +- src/Bermuda.AppHost/Bermuda.AppHost.csproj | 2 +- src/Bermuda/Bermuda.csproj | 10 ++- src/Bermuda/native-apps.ps1 | 48 ------------ src/Bermuda/tools/native-apps.cs | 87 ++++++++++++++++++++++ 7 files changed, 99 insertions(+), 56 deletions(-) delete mode 100644 src/Bermuda/native-apps.ps1 create mode 100644 src/Bermuda/tools/native-apps.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index e27c7b4..b486d76 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,7 +17,7 @@ - + diff --git a/docs/fdc3.md b/docs/fdc3.md index 67d6a89..bae772e 100644 --- a/docs/fdc3.md +++ b/docs/fdc3.md @@ -158,7 +158,7 @@ Both generated files are checked in, like `ipc.d.ts`, and CI fails if they are s - **Client**: any gRPC stack that can dial a named pipe. `Fdc3PipeClient` (in `Bermuda.Fdc3.Proto`, so a client does not need ASP.NET Core; used by the sample `src/Bermuda.NativeApp`) is a ~100-line .NET reference (`SocketsHttpHandler.ConnectCallback` returning a `NamedPipeClientStream`). - **Native apps are discovered from the App Directory.** `fdc3-appd.json` is the one list of side apps. An entry with `"type": "native"` and `details.path` (its exe, relative to Bermuda's folder) is a native app; `details.project` (Bermuda extension: the .csproj that builds it, relative to the file) tells builds where it comes from. Everything else follows from that entry, so **adding a native app is a one-line edit of `fdc3-appd.json`** plus its project: - **Aspire** (`Bermuda.AppHost`) starts a resource per native entry next to the host. - - **MSIX** (`CreateMsix`, via `src/Bermuda/native-apps.ps1`) publishes each project into Bermuda's package folder and adds an `` to the manifest where it has the `@NATIVE_APPS@` marker (full trust, no Start menu entry, no startup task). CI publishes them for tagged releases with `dotnet msbuild src/Bermuda -t:PublishNativeApps`. So they deploy, update and are signed exactly like Bermuda, from the same `.appinstaller`. + - **MSIX** (`CreateMsix`, via `src/Bermuda/tools/native-apps.cs`, a file-based C# app) publishes each project into Bermuda's package folder and adds an `` to the manifest where it has the `@NATIVE_APPS@` marker (full trust, no Start menu entry, no startup task). CI publishes them for tagged releases with `dotnet msbuild src/Bermuda -t:PublishNativeApps`. So they deploy, update and are signed exactly like Bermuda, from the same `.appinstaller`. - **Bermuda** starts each one when the host starts (`App.StartNativeApps`; `NATIVE_APP_AUTOSTART=false` turns that off) and closes them on exit. An app should allow one copy per user, so a second start is harmless, and retry until the host's pipe is up. The sample is `src/Bermuda.NativeApp` (`native-incidents`): it joins a channel and acknowledges incidents. - Limitations: native apps are not launched by the agent (`open`/intents can target them only while connected), and web windows are still the only apps with launch URLs. diff --git a/src/Bermuda.AppHost/AppHost.cs b/src/Bermuda.AppHost/AppHost.cs index e5d4f22..3837a5c 100644 --- a/src/Bermuda.AppHost/AppHost.cs +++ b/src/Bermuda.AppHost/AppHost.cs @@ -30,8 +30,10 @@ || !app.TryGetProperty("details", out var details) || !details.TryGetProperty("project", out var project)) continue; - builder.AddProject(app.GetProperty("appId").GetString()!, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(appDirectory)!, project.GetString()!))) +#pragma warning disable ASPIRECSHARPAPPS001 // AddCSharpApp is Aspire's new file/path-based project API (experimental) + builder.AddCSharpApp(app.GetProperty("appId").GetString()!, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(appDirectory)!, project.GetString()!))) .WaitFor(host); +#pragma warning restore ASPIRECSHARPAPPS001 } builder.Build().Run(); diff --git a/src/Bermuda.AppHost/Bermuda.AppHost.csproj b/src/Bermuda.AppHost/Bermuda.AppHost.csproj index 1bedc53..625a4cd 100644 --- a/src/Bermuda.AppHost/Bermuda.AppHost.csproj +++ b/src/Bermuda.AppHost/Bermuda.AppHost.csproj @@ -1,4 +1,4 @@ - + Exe diff --git a/src/Bermuda/Bermuda.csproj b/src/Bermuda/Bermuda.csproj index 5351f84..4c8aed6 100644 --- a/src/Bermuda/Bermuda.csproj +++ b/src/Bermuda/Bermuda.csproj @@ -108,6 +108,8 @@ + + @@ -115,14 +117,14 @@ - + - + $([System.String]::Copy('%(_NativeAppLine.Identity)').Split('|')[1]) $([System.String]::Copy('%(_NativeAppLine.Identity)').Split('|')[2]) @@ -186,7 +188,7 @@ - + diff --git a/src/Bermuda/native-apps.ps1 b/src/Bermuda/native-apps.ps1 deleted file mode 100644 index d5aa6e6..0000000 --- a/src/Bermuda/native-apps.ps1 +++ /dev/null @@ -1,48 +0,0 @@ -# Reads the FDC3 App Directory (fdc3-appd.json) for the native side apps that ship in Bermuda's MSIX. -# Used by src/Bermuda/Bermuda.csproj (the CreateMsix and PublishNativeApps targets). -# -# -Mode List prints one line per native app: appId|exe|project (project is an absolute path, or empty) -# -Mode Patch replaces the marker in -Manifest with one per native app -param( - [Parameter(Mandatory)] [string] $Directory, - [Parameter(Mandatory)] [ValidateSet('List', 'Patch')] [string] $Mode, - [string] $Manifest -) -$ErrorActionPreference = 'Stop' - -$dir = Split-Path -Parent (Resolve-Path $Directory) -$apps = (Get-Content -Raw -Path $Directory | ConvertFrom-Json).applications | Where-Object { $_.type -eq 'native' } - -foreach ($app in $apps) { - if (-not $app.details.path) { throw "Native app '$($app.appId)' in fdc3-appd.json needs details.path (its exe in the package)." } -} - -if ($Mode -eq 'List') { - foreach ($app in $apps) { - $project = if ($app.details.project) { [System.IO.Path]::GetFullPath((Join-Path $dir $app.details.project)) } else { '' } - "$($app.appId)|$($app.details.path)|$project" - } - return -} - -if (-not $Manifest) { throw '-Manifest is required for -Mode Patch.' } -$esc = { param($v) [System.Security.SecurityElement]::Escape([string]$v) } -$xml = foreach ($app in $apps) { - # Manifest Application ids are letters and digits only. - $key = 'Native' + ($app.appId -replace '[^A-Za-z0-9]', '') - $title = if ($app.title) { $app.title } else { $app.appId } - $desc = if ($app.description) { $app.description } else { $title } - @" - - - - - -"@ -} -$marker = '' -$text = [System.IO.File]::ReadAllText($Manifest) -if (-not $text.Contains($marker)) { throw "The manifest has no $marker marker." } -[System.IO.File]::WriteAllText($Manifest, $text.Replace($marker, ($xml -join "`n"))) diff --git a/src/Bermuda/tools/native-apps.cs b/src/Bermuda/tools/native-apps.cs new file mode 100644 index 0000000..fccb95c --- /dev/null +++ b/src/Bermuda/tools/native-apps.cs @@ -0,0 +1,87 @@ +#:property NuGetAudit=false +#:property PublishAot=false + +// Reads the FDC3 App Directory (fdc3-appd.json) for the native side apps that ship in Bermuda's MSIX. +// A .NET file-based app, run by src/Bermuda/Bermuda.csproj (the CreateMsix and PublishNativeApps targets): +// +// dotnet run --file tools/native-apps.cs -- list +// prints one line per native app: appId|exe|project (project is an absolute path, or empty) +// dotnet run --file tools/native-apps.cs -- patch +// replaces the marker in the manifest with one per native app +// +// A native app is an entry with "type": "native". It needs details.path (its exe in the package); +// details.project (the .csproj that builds it, relative to the directory file) is needed to build it. + +using System.Security; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; + +if (args is not ([var mode, var directory, ..] and var rest) || mode is not ("list" or "patch") + || (mode == "patch" && rest.Length < 3)) +{ + Console.Error.WriteLine("usage: native-apps.cs list | patch "); + return 2; +} + +var baseDir = Path.GetDirectoryName(Path.GetFullPath(directory))!; +var options = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }; +using var document = JsonDocument.Parse(File.ReadAllText(directory), options); + +var apps = document.RootElement.GetProperty("applications").EnumerateArray() + .Where(a => a.GetProperty("type").GetString() == "native") + .ToList(); + +string? Text(JsonElement e, string name) => e.TryGetProperty(name, out var v) ? v.GetString() : null; + +foreach (var app in apps) +{ + if (!app.TryGetProperty("details", out var d) || Text(d, "path") is null) + { + Console.Error.WriteLine($"Native app '{Text(app, "appId")}' in fdc3-appd.json needs details.path (its exe in the package)."); + return 1; + } +} + +if (mode == "list") +{ + foreach (var app in apps) + { + var d = app.GetProperty("details"); + var project = Text(d, "project") is { } p ? Path.GetFullPath(Path.Combine(baseDir, p)) : ""; + Console.WriteLine($"{Text(app, "appId")}|{Text(d, "path")}|{project}"); + } + return 0; +} + +var manifestPath = rest[2]; +const string marker = ""; +var xml = new StringBuilder(); +foreach (var app in apps) +{ + var id = Text(app, "appId")!; + var d = app.GetProperty("details"); + var title = Text(app, "title") ?? id; + var description = Text(app, "description") ?? title; + // Manifest Application ids are letters and digits only. + var key = "Native" + Regex.Replace(id, "[^A-Za-z0-9]", ""); + xml.Append($""" + + + + + + + """); +} + +var manifest = File.ReadAllText(manifestPath); +if (!manifest.Contains(marker)) +{ + Console.Error.WriteLine($"The manifest has no {marker} marker."); + return 1; +} +File.WriteAllText(manifestPath, manifest.Replace(marker, xml.ToString())); +return 0; From a5a8479e3b28b62b933f5916562b574afe2c4c29 Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 11 Nov 2026 15:29:50 -0500 Subject: [PATCH 11/14] fix: address review - native-only pipe, launch on demand, own intent, pipe name and robustness - the native sample handles AcknowledgeIncident, so an untargeted ViewIncident still resolves to the dashboard - Subscribe only accepts type native apps; web apps cannot be claimed over the pipe - fdc3.open / intents start a native app that is down (NativeAppHost), passing FDC3_GRPC_PIPE and FDC3_INSTANCE_ID; Subscribe takes instance_id - details.path must stay inside Bermuda's folder; Aspire passes FDC3_GRPC_PIPE through - the sample reconnects after any failure and tolerates a non-JSON payload Co-Authored-By: Claude Sonnet 5.5 --- docs/fdc3.md | 4 +- src/Bermuda.AppHost/AppHost.cs | 7 +- .../PipeIntegrationTests.cs | 45 +++++++++++-- src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs | 6 +- src/Bermuda.Fdc3.Proto/Fdc3PipeClient.cs | 8 ++- src/Bermuda.Fdc3.Proto/Protos/fdc3.proto | 3 + src/Bermuda.NativeApp/Program.cs | 28 +++++--- src/Bermuda.Web/e2e/native-app.spec.ts | 23 +++++-- src/Bermuda/App.xaml.cs | 42 ++++-------- src/Bermuda/NativeAppHost.cs | 67 +++++++++++++++++++ src/Bermuda/WindowAppLauncher.cs | 10 +++ src/Bermuda/fdc3-appd.json | 4 +- 12 files changed, 192 insertions(+), 55 deletions(-) create mode 100644 src/Bermuda/NativeAppHost.cs diff --git a/docs/fdc3.md b/docs/fdc3.md index bae772e..bb952b2 100644 --- a/docs/fdc3.md +++ b/docs/fdc3.md @@ -160,7 +160,9 @@ Both generated files are checked in, like `ipc.d.ts`, and CI fails if they are s - **Aspire** (`Bermuda.AppHost`) starts a resource per native entry next to the host. - **MSIX** (`CreateMsix`, via `src/Bermuda/tools/native-apps.cs`, a file-based C# app) publishes each project into Bermuda's package folder and adds an `` to the manifest where it has the `@NATIVE_APPS@` marker (full trust, no Start menu entry, no startup task). CI publishes them for tagged releases with `dotnet msbuild src/Bermuda -t:PublishNativeApps`. So they deploy, update and are signed exactly like Bermuda, from the same `.appinstaller`. - **Bermuda** starts each one when the host starts (`App.StartNativeApps`; `NATIVE_APP_AUTOSTART=false` turns that off) and closes them on exit. An app should allow one copy per user, so a second start is harmless, and retry until the host's pipe is up. - The sample is `src/Bermuda.NativeApp` (`native-incidents`): it joins a channel and acknowledges incidents. + - **On demand**: `fdc3.open`, or an intent raised at a native app that is not running, makes Bermuda start it (`NativeAppHost`, the same code as autostart). The host passes the pipe name (`FDC3_GRPC_PIPE`) and the instance id it is expecting (`FDC3_INSTANCE_ID`) in the app's environment, and the app sends that id in `SubscribeRequest.instance_id`, which completes the open. A native app that crashes is therefore started again the next time something needs it. `details.path` must stay inside Bermuda's folder. + - **Only native apps connect over the pipe.** `Subscribe` rejects an App Directory entry that is not `type: native` (`AccessDenied`), so a process cannot claim to be `bermuda-incidents` or another web app. It does not check which program is on the other end of the pipe (anything running as the same user can name a native app); for that, the pipe would need the client's process id, which Kestrel's named-pipe transport does not expose. + The sample is `src/Bermuda.NativeApp` (`native-incidents`): it joins a channel and acknowledges incidents. It handles its own `AcknowledgeIncident` intent rather than `ViewIncident`, so an untargeted `raiseIntent('ViewIncident', …)` still resolves to the dashboard (two running listeners would need the caller to pick one). - Limitations: native apps are not launched by the agent (`open`/intents can target them only while connected), and web windows are still the only apps with launch URLs. ## 8. Known limitations diff --git a/src/Bermuda.AppHost/AppHost.cs b/src/Bermuda.AppHost/AppHost.cs index 3837a5c..74706db 100644 --- a/src/Bermuda.AppHost/AppHost.cs +++ b/src/Bermuda.AppHost/AppHost.cs @@ -13,11 +13,15 @@ .WithEnvironment("RELAY_SCHEMA_URL", api.GetEndpoint("http")) .WaitFor(api); +// An optional pipe name for the host and the native apps (FDC3_GRPC_PIPE in the AppHost's configuration). +var pipeName = builder.Configuration["FDC3_GRPC_PIPE"]; + var host = builder.AddProject("host") .WithEnvironment("WEB_URL", web.GetEndpoint("http")) .WithEnvironment("CDP_PORT", "9222") .WaitFor(web) .WaitFor(api); +if (!string.IsNullOrWhiteSpace(pipeName)) host.WithEnvironment("FDC3_GRPC_PIPE", pipeName); // The native FDC3 side apps are discovered from the App Directory (type "native" with details.project), so // adding one is a one-line edit of fdc3-appd.json. They join the host's agent over the gRPC named pipe (the @@ -31,8 +35,9 @@ || !details.TryGetProperty("project", out var project)) continue; #pragma warning disable ASPIRECSHARPAPPS001 // AddCSharpApp is Aspire's new file/path-based project API (experimental) - builder.AddCSharpApp(app.GetProperty("appId").GetString()!, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(appDirectory)!, project.GetString()!))) + var native = builder.AddCSharpApp(app.GetProperty("appId").GetString()!, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(appDirectory)!, project.GetString()!))) .WaitFor(host); + if (!string.IsNullOrWhiteSpace(pipeName)) native.WithEnvironment("FDC3_GRPC_PIPE", pipeName); #pragma warning restore ASPIRECSHARPAPPS001 } diff --git a/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs b/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs index ffb6325..3c7d746 100644 --- a/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs +++ b/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs @@ -13,10 +13,11 @@ public sealed class PipeIntegrationTests : IAsyncLifetime private const string AppD = """ { "applications": [ - { "appId": "native-app", "title": "Native" }, + { "appId": "native-app", "title": "Native", "type": "native" }, { "appId": "incidents", "title": "Incidents", + "type": "native", "interop": { "intents": { "listensFor": { "ViewIncident": { "contexts": ["bermuda.incident"], "resultType": "fdc3.contact" } } } } @@ -34,11 +35,25 @@ public sealed class PipeIntegrationTests : IAsyncLifetime private const string Incident = """{ "type": "bermuda.incident", "id": { "incidentId": "7" } }"""; - private readonly DesktopAgent _agent = new(AppDirectory.Parse(AppD), launchTimeout: TimeSpan.FromSeconds(2)); + private readonly PipeLauncher _launcher = new(); + private readonly DesktopAgent _agent; private readonly string _pipe = "bermuda-fdc3-test-" + Guid.NewGuid().ToString("N"); private readonly List _clients = []; private Fdc3GrpcHost _host = null!; + public PipeIntegrationTests() + { + _agent = new DesktopAgent(AppDirectory.Parse(AppD), _launcher, launchTimeout: TimeSpan.FromSeconds(2)); + } + + /// Stands in for Bermuda's NativeAppHost: "starts" the native app, which connects with the instance id it was given. + private sealed class PipeLauncher : IFdc3AppLauncher + { + public Func? Start { get; set; } + + public void Launch(AppDefinition app, string instanceId) => _ = Start?.Invoke(app, instanceId); + } + public async Task InitializeAsync() => _host = await Fdc3GrpcHost.StartAsync(_agent, _pipe); public async Task DisposeAsync() @@ -47,9 +62,9 @@ public async Task DisposeAsync() await _host.DisposeAsync(); } - private async Task ConnectAsync(string appId) + private async Task ConnectAsync(string appId, string? instanceId = null) { - var client = await Fdc3PipeClient.ConnectAsync(_pipe, appId); + var client = await Fdc3PipeClient.ConnectAsync(_pipe, appId, instanceId: instanceId); _clients.Add(client); return client; } @@ -65,6 +80,28 @@ public async Task Rejects_an_app_id_that_is_not_in_the_app_directory() Assert.Equal(Fdc3Errors.AppNotFound, ex.Status.Detail); } + [Fact] + public async Task Rejects_a_web_app_because_only_native_apps_use_the_pipe() + { + var ex = await Assert.ThrowsAsync(() => Fdc3PipeClient.ConnectAsync(_pipe, "web-app")); + + Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode); + Assert.Equal(Fdc3Errors.AccessDenied, ex.Status.Detail); + } + + [Fact] + public async Task Open_launches_a_native_app_that_connects_with_the_instance_id_it_was_given() + { + _launcher.Start = async (app, instanceId) => await ConnectAsync(app.AppId, instanceId); + using var web = _agent.Connect("web-app", new RecordingSink()); + + var opened = await web.OpenAsync(new Fdc3OpenRequest(new Fdc3AppIdentifier("native-app", null), null)); + + Assert.Equal("native-app", opened.AppId); + Assert.NotNull(opened.InstanceId); + Assert.Contains(web.FindInstances(new Fdc3AppIdentifier("native-app", null)), i => i.InstanceId == opened.InstanceId); + } + [Fact] public async Task Connecting_registers_an_instance_that_is_removed_when_the_client_goes_away() { diff --git a/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs b/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs index e0c6317..d620443 100644 --- a/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs +++ b/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs @@ -60,9 +60,13 @@ public override async Task Subscribe(SubscribeRequest request, IServerStreamWrit if (string.IsNullOrWhiteSpace(request.AppId)) throw new Fdc3Exception(Fdc3Errors.InvalidArguments); if (agent.Directory.Find(request.AppId) is not { } app) throw new Fdc3Exception(Fdc3Errors.AppNotFound); + // The pipe is for native apps. Web apps get their app id from the host (the window that hosts them), so a + // process on the pipe cannot claim to be one: it could receive that app's intents or speak as it. + if (app.Type != "native") throw new Fdc3Exception(Fdc3Errors.AccessDenied); + var sink = new ChannelSink(); // The directory's casing wins, so instances of one app always share an AppId. - using var connection = agent.Connect(app.AppId, sink); + using var connection = agent.Connect(app.AppId, sink, request.HasInstanceId ? request.InstanceId : null); registry.Add(connection, context.GetHttpContext().Connection.Id); try { diff --git a/src/Bermuda.Fdc3.Proto/Fdc3PipeClient.cs b/src/Bermuda.Fdc3.Proto/Fdc3PipeClient.cs index 735cbb4..54e1516 100644 --- a/src/Bermuda.Fdc3.Proto/Fdc3PipeClient.cs +++ b/src/Bermuda.Fdc3.Proto/Fdc3PipeClient.cs @@ -56,13 +56,13 @@ private Fdc3PipeClient(GrpcChannel channel, Fdc3Agent.Fdc3AgentClient rpc, strin public Metadata Headers { get; } /// Throws (detail = FDC3 error string) if the agent rejects the app id. - public static async Task ConnectAsync(string? pipeName, string appId, CancellationToken cancellationToken = default) + public static async Task ConnectAsync(string? pipeName, string appId, CancellationToken cancellationToken = default, string? instanceId = null) { var handler = new SocketsHttpHandler { ConnectCallback = async (_, token) => { - var pipe = new NamedPipeClientStream(".", pipeName ?? Fdc3Pipe.DefaultName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + var pipe = new NamedPipeClientStream(".", string.IsNullOrWhiteSpace(pipeName) ? Fdc3Pipe.DefaultName : pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); try { await pipe.ConnectAsync(token); @@ -79,7 +79,9 @@ public static async Task ConnectAsync(string? pipeName, string a try { var rpc = new Fdc3Agent.Fdc3AgentClient(channel); - var stream = rpc.Subscribe(new SubscribeRequest { AppId = appId }, cancellationToken: cancellationToken); + var request = new SubscribeRequest { AppId = appId }; + if (!string.IsNullOrWhiteSpace(instanceId)) request.InstanceId = instanceId; + var stream = rpc.Subscribe(request, cancellationToken: cancellationToken); if (!await stream.ResponseStream.MoveNext(cancellationToken) || stream.ResponseStream.Current.Connected is not { } connected) throw new InvalidOperationException("The agent closed the stream before connecting."); return new Fdc3PipeClient(channel, rpc, connected.InstanceId, connected.AppId, stream); diff --git a/src/Bermuda.Fdc3.Proto/Protos/fdc3.proto b/src/Bermuda.Fdc3.Proto/Protos/fdc3.proto index f6389c3..0a1c045 100644 --- a/src/Bermuda.Fdc3.Proto/Protos/fdc3.proto +++ b/src/Bermuda.Fdc3.Proto/Protos/fdc3.proto @@ -282,6 +282,9 @@ message ApiEvent { message SubscribeRequest { string app_id = 1; + // The instance id the host passed in the FDC3_INSTANCE_ID environment variable when it launched this app + // (fdc3.open / an intent raised at it while it was down). Leave unset for an app that was started on its own. + optional string instance_id = 2; } // First message of every Subscribe stream. diff --git a/src/Bermuda.NativeApp/Program.cs b/src/Bermuda.NativeApp/Program.cs index 8ad7439..81ca399 100644 --- a/src/Bermuda.NativeApp/Program.cs +++ b/src/Bermuda.NativeApp/Program.cs @@ -9,15 +9,18 @@ // * joins user channel NATIVE_CHANNEL (default fdc3.channel.1) // * listens for `bermuda.incident` contexts there and answers each by // broadcasting `bermuda.native.ack` carrying the incident it saw -// * handles the `ViewIncident` intent and returns the same ack as its result +// * handles the `AcknowledgeIncident` intent and returns the same ack as its result +// (not `ViewIncident`: the dashboard handles that, and an untargeted raise must keep resolving to it) // -// Config (environment): FDC3_GRPC_PIPE (default: Bermuda's per-user pipe), NATIVE_CHANNEL. +// Config (environment): FDC3_GRPC_PIPE (default: Bermuda's per-user pipe), NATIVE_CHANNEL, and FDC3_INSTANCE_ID, +// which Bermuda sets when it launches the app for fdc3.open or an intent. // It reconnects whenever the host goes away, so start order doesn't matter. const string AppId = "native-incidents"; const string AckType = "bermuda.native.ack"; -var pipe = Environment.GetEnvironmentVariable("FDC3_GRPC_PIPE"); +var pipe = Environment.GetEnvironmentVariable("FDC3_GRPC_PIPE") is { Length: > 0 } p ? p : null; +var launchInstance = Environment.GetEnvironmentVariable("FDC3_INSTANCE_ID") is { Length: > 0 } i ? i : null; var channel = Environment.GetEnvironmentVariable("NATIVE_CHANNEL") is { Length: > 0 } c ? c : "fdc3.channel.1"; // One copy per user: Windows starts it at sign-in and Bermuda starts it too; a second copy just exits. @@ -31,14 +34,17 @@ { try { - await using var client = await Fdc3PipeClient.ConnectAsync(pipe, AppId, shutdown.Token); + // The launch instance id is for the first connection only; a reconnect is a new instance. + await using var client = await Fdc3PipeClient.ConnectAsync(pipe, AppId, shutdown.Token, launchInstance); + launchInstance = null; Console.WriteLine($"[{AppId}] connected as {client.InstanceId}"); await RunAsync(client, shutdown.Token); } catch (OperationCanceledException) when (shutdown.IsCancellationRequested) { } - catch (Exception ex) when (ex is RpcException or IOException or TimeoutException or InvalidOperationException) + // Any failure ends this connection, not the process: Bermuda only starts this exe again on demand. + catch (Exception ex) { Console.WriteLine($"[{AppId}] {ex.GetType().Name}: {ex.Message}"); } @@ -54,7 +60,7 @@ await client.Rpc.AddContextListenerAsync( new AddContextListenerRequest { ListenerId = "incidents", ContextType = "bermuda.incident" }, client.Headers, cancellationToken: cancellationToken); await client.Rpc.AddIntentListenerAsync( - new AddIntentListenerRequest { ListenerId = "view", Intent = "ViewIncident" }, + new AddIntentListenerRequest { ListenerId = "ack", Intent = "AcknowledgeIncident" }, client.Headers, cancellationToken: cancellationToken); while (!cancellationToken.IsCancellationRequested) @@ -78,5 +84,11 @@ await client.Rpc.SendIntentResultAsync( } } -static string Ack(string contextJson) => - JsonSerializer.Serialize(new { type = AckType, of = JsonSerializer.Deserialize(contextJson) }); +// A payload that is not JSON is acknowledged with of: null instead of tearing the app down. +static string Ack(string contextJson) +{ + JsonElement? of = null; + try { of = JsonSerializer.Deserialize(contextJson); } + catch (JsonException) { } + return JsonSerializer.Serialize(new { type = AckType, of }); +} diff --git a/src/Bermuda.Web/e2e/native-app.spec.ts b/src/Bermuda.Web/e2e/native-app.spec.ts index 35a4307..a7edd2c 100644 --- a/src/Bermuda.Web/e2e/native-app.spec.ts +++ b/src/Bermuda.Web/e2e/native-app.spec.ts @@ -6,7 +6,7 @@ import { test, expect } from './fixtures' // Exercises the native side app (src/Bermuda.NativeApp), which Aspire starts // next to the host. It connects to the host's gRPC named pipe as // "native-incidents", joins fdc3.channel.1 and answers every -// bermuda.incident context / ViewIncident intent with a bermuda.native.ack +// bermuda.incident context / AcknowledgeIncident intent with a bermuda.native.ack // that carries the incident it saw. So a round trip here proves both // directions: web -> native (the incident arrives) and native -> web (the ack). @@ -78,19 +78,30 @@ test.describe('FDC3 native side app (gRPC named pipe)', () => { async ([ctx, appId]) => { const agent = window.fdc3 as DesktopAgent const [instance] = await agent.findInstances({ appId }) - const resolution = await agent.raiseIntent('ViewIncident', ctx as Context, instance) + const resolution = await agent.raiseIntent('AcknowledgeIncident', ctx as Context, instance) return { source: resolution.source, intent: resolution.intent, result: await resolution.getResult() } }, [incident('native-2'), NATIVE] as const, ) expect(result.source.appId).toBe(NATIVE) - expect(result.intent).toBe('ViewIncident') + expect(result.intent).toBe('AcknowledgeIncident') expect(result.result).toMatchObject({ type: 'bermuda.native.ack', of: { id: { incidentId: 'native-2' } } }) }) - test('findIntent lists the native app next to the web app', async ({ page }) => { - const apps = await page.evaluate(async () => (await (window.fdc3 as DesktopAgent).findIntent('ViewIncident')).apps.map((a) => a.appId)) - expect(apps).toEqual(expect.arrayContaining([NATIVE, 'bermuda-incidents'])) + test('findIntent lists the native app for its own intent, and the dashboard for ViewIncident', async ({ page }) => { + // A running app is listed once per instance and once more as launchable, so compare the distinct app ids. + const appsFor = (intent: string) => + page.evaluate(async (name) => [...new Set((await (window.fdc3 as DesktopAgent).findIntent(name)).apps.map((a) => a.appId))], intent) + expect(await appsFor('AcknowledgeIncident')).toEqual([NATIVE]) + expect(await appsFor('ViewIncident')).toEqual(['bermuda-incidents']) + }) + + test('an untargeted ViewIncident still resolves to the dashboard while the native app is connected', async ({ page }) => { + const source = await page.evaluate(async (ctx) => { + const resolution = await (window.fdc3 as DesktopAgent).raiseIntent('ViewIncident', ctx as Context) + return resolution.source.appId + }, incident('native-3')) + expect(source).toBe('bermuda-incidents') }) }) diff --git a/src/Bermuda/App.xaml.cs b/src/Bermuda/App.xaml.cs index ccdf493..217b515 100644 --- a/src/Bermuda/App.xaml.cs +++ b/src/Bermuda/App.xaml.cs @@ -27,7 +27,12 @@ protected override void OnStartup(StartupEventArgs e) launcher.Agent = fdc3; StartGrpcHost(config, fdc3); - if (_grpcHost is not null) StartNativeApps(config, directory); + if (_grpcHost is not null) + { + _nativeApps = new NativeAppHost(_grpcHost.PipeName); + launcher.NativeApps = _nativeApps; + StartNativeApps(config, directory); + } var window = new MainWindow(config, fdc3, MainAppId); window.Show(); @@ -53,29 +58,21 @@ private void StartGrpcHost(IConfiguration config, DesktopAgent agent) } private Fdc3GrpcHost? _grpcHost; - private readonly List _nativeApps = []; + private NativeAppHost? _nativeApps; /// - /// Starts every native side app in the App Directory (type "native" with a details.path, relative to this exe), - /// so they run whenever Bermuda does, however Bermuda was started. They ship in the same package. Each allows - /// one copy per user, so starting one that is already running is harmless. NATIVE_APP_AUTOSTART=false turns - /// this off. + /// Starts every native side app in the App Directory so they run whenever Bermuda does, however Bermuda was + /// started. They ship in the same package. NATIVE_APP_AUTOSTART=false turns this off. An app that is down + /// later is started again on demand, when fdc3.open or an intent needs it (see ). /// private void StartNativeApps(IConfiguration config, AppDirectory directory) { if (bool.TryParse(config["NATIVE_APP_AUTOSTART"], out var enabled) && !enabled) return; - foreach (var app in directory.Apps.Where(a => a.Type == "native" && a.Details?.Path is not null)) + foreach (var app in directory.Apps.Where(a => NativeAppHost.ResolvePath(a) is not null)) { - var exe = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, app.Details!.Path!)); - if (!File.Exists(exe)) continue; try { - var process = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(exe, app.Details.Arguments ?? "") - { - UseShellExecute = false, - WorkingDirectory = Path.GetDirectoryName(exe)!, - }); - if (process is not null) _nativeApps.Add(process); + _nativeApps!.Start(app); } catch (Exception ex) { @@ -86,20 +83,7 @@ private void StartNativeApps(IConfiguration config, AppDirectory directory) protected override void OnExit(ExitEventArgs e) { - // Close the side app we started. If it was already running (so our copy exited at once because it - // allows one per user), or someone else started it, that handle has exited and nothing is killed. - foreach (var process in _nativeApps) - { - try - { - if (!process.HasExited) process.Kill(); - process.Dispose(); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine($"Native FDC3 app did not stop: {ex.Message}"); - } - } + _nativeApps?.Dispose(); if (_grpcHost is { } grpcHost) { diff --git a/src/Bermuda/NativeAppHost.cs b/src/Bermuda/NativeAppHost.cs new file mode 100644 index 0000000..5829670 --- /dev/null +++ b/src/Bermuda/NativeAppHost.cs @@ -0,0 +1,67 @@ +using System.Diagnostics; +using System.IO; +using Bermuda.Fdc3; + +namespace Bermuda; + +/// +/// Starts the native side apps of the App Directory (type "native", details.path relative to this exe) and stops +/// the ones it started when Bermuda exits. Used at startup and by when +/// fdc3.open or an intent needs an app that is not running. Each app allows one copy per user, so starting one +/// that is already running is harmless. +/// +public sealed class NativeAppHost(string? pipeName) : IDisposable +{ + private readonly List _processes = []; + + /// Resolves details.path; it must stay inside the folder Bermuda runs from. + public static string? ResolvePath(AppDefinition app) + { + if (app.Type != "native" || app.Details?.Path is not { Length: > 0 } path) return null; + var root = Path.GetFullPath(AppContext.BaseDirectory); + var full = Path.GetFullPath(Path.Combine(root, path)); + return full.StartsWith(root, StringComparison.OrdinalIgnoreCase) && File.Exists(full) ? full : null; + } + + /// Starts the app with the pipe name (and, when launched for FDC3, the instance id) in its environment. + public void Start(AppDefinition app, string? instanceId = null) + { + var exe = ResolvePath(app) ?? throw new InvalidOperationException($"App '{app.AppId}' has no native exe inside the package."); + var info = new ProcessStartInfo(exe, app.Details!.Arguments ?? "") + { + UseShellExecute = false, + WorkingDirectory = Path.GetDirectoryName(exe)!, + }; + if (!string.IsNullOrWhiteSpace(pipeName)) info.Environment["FDC3_GRPC_PIPE"] = pipeName; + if (instanceId is not null) info.Environment["FDC3_INSTANCE_ID"] = instanceId; + + if (Process.Start(info) is { } process) + { + lock (_processes) _processes.Add(process); + } + } + + /// + /// Closes the apps this host started. One that was already running (so its copy exited at once) or that + /// someone else started has a dead handle here and nothing is killed. + /// + public void Dispose() + { + lock (_processes) + { + foreach (var process in _processes) + { + try + { + if (!process.HasExited) process.Kill(); + process.Dispose(); + } + catch (Exception ex) + { + Debug.WriteLine($"Native FDC3 app did not stop: {ex.Message}"); + } + } + _processes.Clear(); + } + } +} diff --git a/src/Bermuda/WindowAppLauncher.cs b/src/Bermuda/WindowAppLauncher.cs index 20a76e4..f92afaf 100644 --- a/src/Bermuda/WindowAppLauncher.cs +++ b/src/Bermuda/WindowAppLauncher.cs @@ -14,9 +14,19 @@ public sealed class WindowAppLauncher(IConfiguration configuration) : IFdc3AppLa { public DesktopAgent? Agent { get; set; } + /// Starts native apps; null while the gRPC pipe is off, because they could not connect anyway. + public NativeAppHost? NativeApps { get; set; } + public void Launch(AppDefinition app, string instanceId) { if (Agent is null) throw new InvalidOperationException("Launcher not attached to a desktop agent."); + if (app.Type == "native" && NativeApps is not null) + { + // The app connects over the pipe with this instance id (FDC3_INSTANCE_ID), which completes the open. + NativeApps.Start(app, instanceId); + return; + } + if (app.Type != "web" || app.Details?.Url is not { Length: > 0 } url) throw new InvalidOperationException($"App '{app.AppId}' has no web URL to launch."); diff --git a/src/Bermuda/fdc3-appd.json b/src/Bermuda/fdc3-appd.json index 8e5e6fa..6724eed 100644 --- a/src/Bermuda/fdc3-appd.json +++ b/src/Bermuda/fdc3-appd.json @@ -13,8 +13,8 @@ "interop": { "intents": { "listensFor": { - "ViewIncident": { - "displayName": "View Incident (native)", + "AcknowledgeIncident": { + "displayName": "Acknowledge Incident (native)", "contexts": ["bermuda.incident"], "resultType": "bermuda.native.ack" } From de023dd9d27dd6d8a40076ef1466c885e2696d39 Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 11 Nov 2026 20:32:20 -0500 Subject: [PATCH 12/14] refactor: package native apps with a validated tool instead of text patching tools/native-apps.cs now does publish, manifest and appinstaller steps with real XML handling and validation, reporting one clear error per problem. The manifest no longer carries a placeholder comment, and the build no longer parses tool output or edits the manifest with regexes. Co-Authored-By: Claude Sonnet 5.5 --- docs/fdc3.md | 2 +- src/Bermuda/Bermuda.csproj | 48 ++----- src/Bermuda/Package.appxmanifest | 1 - src/Bermuda/tools/native-apps.cs | 206 ++++++++++++++++++++++--------- 4 files changed, 162 insertions(+), 95 deletions(-) diff --git a/docs/fdc3.md b/docs/fdc3.md index bb952b2..43c15ad 100644 --- a/docs/fdc3.md +++ b/docs/fdc3.md @@ -158,7 +158,7 @@ Both generated files are checked in, like `ipc.d.ts`, and CI fails if they are s - **Client**: any gRPC stack that can dial a named pipe. `Fdc3PipeClient` (in `Bermuda.Fdc3.Proto`, so a client does not need ASP.NET Core; used by the sample `src/Bermuda.NativeApp`) is a ~100-line .NET reference (`SocketsHttpHandler.ConnectCallback` returning a `NamedPipeClientStream`). - **Native apps are discovered from the App Directory.** `fdc3-appd.json` is the one list of side apps. An entry with `"type": "native"` and `details.path` (its exe, relative to Bermuda's folder) is a native app; `details.project` (Bermuda extension: the .csproj that builds it, relative to the file) tells builds where it comes from. Everything else follows from that entry, so **adding a native app is a one-line edit of `fdc3-appd.json`** plus its project: - **Aspire** (`Bermuda.AppHost`) starts a resource per native entry next to the host. - - **MSIX** (`CreateMsix`, via `src/Bermuda/tools/native-apps.cs`, a file-based C# app) publishes each project into Bermuda's package folder and adds an `` to the manifest where it has the `@NATIVE_APPS@` marker (full trust, no Start menu entry, no startup task). CI publishes them for tagged releases with `dotnet msbuild src/Bermuda -t:PublishNativeApps`. So they deploy, update and are signed exactly like Bermuda, from the same `.appinstaller`. + - **MSIX** (`CreateMsix`, via `src/Bermuda/tools/native-apps.cs`, a file-based C# app) publishes each project into Bermuda's package folder and adds an `` for it to the manifest (full trust, no Start menu entry, no startup task). CI publishes them for tagged releases with `dotnet msbuild src/Bermuda -t:PublishNativeApps`. So they deploy, update and are signed exactly like Bermuda, from the same `.appinstaller`. - **Bermuda** starts each one when the host starts (`App.StartNativeApps`; `NATIVE_APP_AUTOSTART=false` turns that off) and closes them on exit. An app should allow one copy per user, so a second start is harmless, and retry until the host's pipe is up. - **On demand**: `fdc3.open`, or an intent raised at a native app that is not running, makes Bermuda start it (`NativeAppHost`, the same code as autostart). The host passes the pipe name (`FDC3_GRPC_PIPE`) and the instance id it is expecting (`FDC3_INSTANCE_ID`) in the app's environment, and the app sends that id in `SubscribeRequest.instance_id`, which completes the open. A native app that crashes is therefore started again the next time something needs it. `details.path` must stay inside Bermuda's folder. - **Only native apps connect over the pipe.** `Subscribe` rejects an App Directory entry that is not `type: native` (`AccessDenied`), so a process cannot claim to be `bermuda-incidents` or another web app. It does not check which program is on the other end of the pipe (anything running as the same user can name a native app); for that, the pipe would need the client's process id, which Kestrel's named-pipe transport does not expose. diff --git a/src/Bermuda/Bermuda.csproj b/src/Bermuda/Bermuda.csproj index 4c8aed6..a5a0644 100644 --- a/src/Bermuda/Bermuda.csproj +++ b/src/Bermuda/Bermuda.csproj @@ -117,26 +117,15 @@ - - - - - - - $([System.String]::Copy('%(_NativeAppLine.Identity)').Split('|')[1]) - $([System.String]::Copy('%(_NativeAppLine.Identity)').Split('|')[2]) - - - - - + - - + - + <_PublishDir Condition="'$(MsixInputDir)' == ''">$(MSBuildProjectDirectory)\..\..\artifacts\publish\ @@ -166,7 +155,6 @@ - @@ -179,16 +167,10 @@ - - - <_ManifestText>$([System.IO.File]::ReadAllText('$(MSBuildProjectDirectory)\Package.appxmanifest')) - <_ManifestText>$([System.Text.RegularExpressions.Regex]::Replace('$(_ManifestText)', '(?s)(<Identity[^>]*?Version=")[^"]*(")', '${1}$(MsixVersion)${2}')) - - - - + The tool stamps the Identity Version from MsixVersion (Windows compares that value, not the + file name, to decide whether an .appinstaller update is newer) and adds one per native + app in fdc3-appd.json. --> + @@ -206,15 +188,7 @@ - - <_AppInstallerPath>$(MsixOutputDir)Bermuda.appinstaller - <_IdentityName>$([System.Text.RegularExpressions.Regex]::Match('$(_ManifestText)', 'Name="([^"]*)"').Groups[1].Value) - <_IdentityPublisher>$([System.Text.RegularExpressions.Regex]::Match('$(_ManifestText)', 'Publisher="([^"]*)"').Groups[1].Value) - <_AppInstallerText>$([System.IO.File]::ReadAllText('$(MSBuildProjectDirectory)\Bermuda.appinstaller.template')) - <_AppInstallerText>$(_AppInstallerText.Replace('@VERSION@', '$(MsixVersion)').Replace('@NAME@', '$(_IdentityName)').Replace('@PUBLISHER@', '$(_IdentityPublisher)').Replace('@MSIX_URL@', '$(MsixUrl)').Replace('@APPINSTALLER_URL@', '$(AppInstallerUrl)')) - - - + diff --git a/src/Bermuda/Package.appxmanifest b/src/Bermuda/Package.appxmanifest index 2c335c2..4d1c6da 100644 --- a/src/Bermuda/Package.appxmanifest +++ b/src/Bermuda/Package.appxmanifest @@ -60,7 +60,6 @@ - diff --git a/src/Bermuda/tools/native-apps.cs b/src/Bermuda/tools/native-apps.cs index fccb95c..0b3ac52 100644 --- a/src/Bermuda/tools/native-apps.cs +++ b/src/Bermuda/tools/native-apps.cs @@ -1,87 +1,181 @@ #:property NuGetAudit=false #:property PublishAot=false -// Reads the FDC3 App Directory (fdc3-appd.json) for the native side apps that ship in Bermuda's MSIX. -// A .NET file-based app, run by src/Bermuda/Bermuda.csproj (the CreateMsix and PublishNativeApps targets): +// Packaging steps for Bermuda's MSIX that depend on the FDC3 App Directory (fdc3-appd.json). +// A .NET file-based app, run by the CreateMsix and PublishNativeApps targets in src/Bermuda/Bermuda.csproj: // -// dotnet run --file tools/native-apps.cs -- list -// prints one line per native app: appId|exe|project (project is an absolute path, or empty) -// dotnet run --file tools/native-apps.cs -- patch -// replaces the marker in the manifest with one per native app +// dotnet run --file tools/native-apps.cs -- publish +// publishes every native app's project (self-contained, win-x64) into outDir, next to Bermuda, +// and checks that each app's exe is there afterwards +// dotnet run --file tools/native-apps.cs -- manifest +// writes dest: the manifest with Identity/@Version = version and one per native app +// dotnet run --file tools/native-apps.cs -- appinstaller