diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 79f8281..787d2a5 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 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 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') 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). @@ -83,6 +94,10 @@ jobs: name: E2E tests needs: build runs-on: self-hosted + # The runner is one machine with fixed-name resources (the app's windows, ports, the FDC3 pipe): one e2e at a time. + concurrency: + group: e2e-self-hosted + cancel-in-progress: false steps: - uses: actions/checkout@v4 @@ -111,6 +126,32 @@ jobs: working-directory: src/Bermuda.Web run: pnpm exec playwright install chromium + # The runner is a normal user machine: Bermuda may be installed and running, a dev may have Aspire up, and + # an older run may have left processes behind. So every run gets its own FDC3 pipe, ports and dashboard + # endpoints, and nothing here depends on the defaults being free. + - name: Isolate this run from the rest of the machine + shell: pwsh + run: | + function Get-FreePort { + $listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0) + $listener.Start() + $port = $listener.LocalEndpoint.Port + $listener.Stop() + $port + } + $lines = @( + "FDC3_GRPC_PIPE=bermuda-fdc3-ci-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT", + "WEB_PORT=$(Get-FreePort)", + "CDP_PORT=$(Get-FreePort)", + "ASPNETCORE_URLS=http://localhost:$(Get-FreePort)", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL=http://localhost:$(Get-FreePort)", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL=http://localhost:$(Get-FreePort)", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL=http://localhost:$(Get-FreePort)", + "ASPIRE_ALLOW_UNSECURED_TRANSPORT=true" + ) + $lines | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + $lines | ForEach-Object { Write-Host $_ } + - name: Run E2E tests working-directory: src/Bermuda.Web run: pnpm e2e --reporter=list diff --git a/Bermuda.slnx b/Bermuda.slnx index 45011e6..eedad4a 100644 --- a/Bermuda.slnx +++ b/Bermuda.slnx @@ -3,7 +3,12 @@ + + + + + diff --git a/Directory.Packages.props b/Directory.Packages.props index f858674..b486d76 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,7 +17,7 @@ - + @@ -27,6 +27,13 @@ + + + + + + + diff --git a/README.md b/README.md index 69acb62..b5b3fc0 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 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 c778857..43c15ad 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. | @@ -138,6 +138,33 @@ 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 serves `IFdc3Commands`. + +**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.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 `` 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. + 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 - **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 +182,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.AppHost/AppHost.cs b/src/Bermuda.AppHost/AppHost.cs index f25c98f..96a9b17 100644 --- a/src/Bermuda.AppHost/AppHost.cs +++ b/src/Bermuda.AppHost/AppHost.cs @@ -1,21 +1,50 @@ +using System.Text.Json; + var builder = DistributedApplication.CreateBuilder(args); var api = builder.AddProject("api"); +// Ports and the FDC3 pipe name can be overridden (WEB_PORT, CDP_PORT, FDC3_GRPC_PIPE in the AppHost's +// configuration or environment), so a CI run can be isolated from anything else on the machine. +var webPort = builder.Configuration["WEB_PORT"] is { Length: > 0 } wp ? wp : "5555"; +var cdpPort = builder.Configuration["CDP_PORT"] is { Length: > 0 } cp ? cp : "9222"; + var web = builder.AddViteApp("web", "../Bermuda.Web") .WithPnpm() - .WithEnvironment("PORT", "5555") + .WithEnvironment("PORT", webPort) .WithEnvironment("VITE_API_URL", api.GetEndpoint("http")); builder.AddExecutable("relay", "pnpm", "../Bermuda.Web", "run", "relay:watch") .WithEnvironment("RELAY_SCHEMA_URL", api.GetEndpoint("http")) .WaitFor(api); -builder.AddProject("host") +// An optional pipe name for the host and the native apps. +var pipeName = builder.Configuration["FDC3_GRPC_PIPE"]; + +var host = builder.AddProject("host") .WithEnvironment("WEB_URL", web.GetEndpoint("http")) - .WithEnvironment("CDP_PORT", "9222") + .WithEnvironment("CDP_PORT", cdpPort) .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 +// 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; + +#pragma warning disable ASPIRECSHARPAPPS001 // AddCSharpApp is Aspire's new file/path-based project API (experimental) + 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 +} 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.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj b/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj new file mode 100644 index 0000000..03c1da8 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc.Generator/Bermuda.Fdc3.Grpc.Generator.csproj @@ -0,0 +1,18 @@ + + + + + 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..bab602c --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc.Generator/Program.cs @@ -0,0 +1,468 @@ +using System.Text; +using Google.Protobuf; +using Google.Protobuf.Reflection; + +// Usage: Bermuda.Fdc3.Grpc.Generator +// +// 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, errors) = ProtoModel.Build(file, asyncOption); +if (errors.Count > 0) +{ + Console.Error.WriteLine("fdc3.proto breaks the generator's conventions:"); + foreach (var error in errors) Console.Error.WriteLine(" - " + error); + return 1; +} + +Write(args[1], new ContractWriter(model).Generate()); +Write(args[2], new GlueWriter(model).Generate()); +return 0; + +static void Write(string path, string content) +{ + 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).Replace("\r\n", "\n") != content) File.WriteAllText(path, content); +} + +enum Kind { String, Bool, Json, Message } + +/// 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 Nullable => Optional && !Repeated; +} + +sealed record Msg(string Name, string Record, List Fields, string? Doc); + +enum Shape { Void, Direct, Array, Nullable, NullableJson } + +/// 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 static readonly HashSet Transport = ["SubscribeRequest", "Connected", "AgentEvent"]; + + public List Messages { get; } = []; + public List Rpcs { get; } = []; + public List Events { get; } = []; + + public static (ProtoModel Model, List Errors) Build(FileDescriptorProto file, Extension asyncOption) + { + 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 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 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); + + // 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); + + 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."); + + // 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 + { + 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)); + } + } + + // 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))); + } + + 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))); + } + + // 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 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."); + + 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 + { + 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))); + } + + // 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) + { + if (name is null || !used.Add(name) || !messages.TryGetValue(name, out var msg)) return; + foreach (var f in msg.Fields) Use(f.Message); + } + 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); + } + + 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..]; + } +} + +abstract class CodeWriter +{ + private readonly StringBuilder _sb = new(); + private int _indent; + + 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(); + + 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("/// "); + } +} + +/// Fdc3* records and IFdc3Commands: what DesktopAgent, Fdc3Connection and the web bridge are written against. +sealed class ContractWriter(ProtoModel model) : CodeWriter +{ + public string Generate() + { + 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 m in model.Messages) + { + 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) + { + Open(); + L($"public string Type => \"fdc3.{ev.Field}\";"); + Close(); + } + L(); + } + + 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) + { + Doc(rpc.Doc); + var returns = rpc.Shape switch + { + Shape.Void => rpc.Async ? "Task" : "void", + _ => rpc.Async ? $"Task<{ReturnType(rpc)}>" : ReturnType(rpc), + }; + var parameter = rpc.Request is null ? "" : $"Fdc3{rpc.Request} request"; + L($"{returns} {rpc.Name}{(rpc.Async ? "Async" : "")}({parameter});"); + } + Close(); + return Result; + } + + private static string ReturnType(Rpc rpc) => rpc.Shape switch + { + 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 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 ? "?" : ""), + }; +} + +/// The gRPC side: proto message <-> record mapping, and the service overrides that call Fdc3Connection. +sealed class GlueWriter(ProtoModel model) : CodeWriter +{ + public string Generate() + { + L("// "); + L("// Generated by Bermuda.Fdc3.Grpc.Generator from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto. Do not edit."); + L("// "); + L("#nullable enable"); + 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 m in model.Messages) + { + 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.Message.Record} e => new Proto.AgentEvent {{ {e.ProtoCs} = ToProto(e) }},"); + L("_ => null,"); + Close(";"); + Close(); + L(); + + L("internal sealed partial class Fdc3AgentService"); + Open(); + foreach (var rpc in model.Rpcs) WriteRpc(rpc); + Close(); + return Result; + } + + private void WriteToContract(Msg m) + { + L($"public static {m.Record} ToContract(Proto.{m.Name}? p)"); + Open(); + L("if (p is null) throw new Fdc3Exception(Fdc3Errors.InvalidArguments);"); + 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.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})", + _ => f.Optional ? $"{p} is null ? null : ToContract({p})" : $"ToContract({p})", + }; + } + + private void WriteToProto(Msg m) + { + L($"public static Proto.{m.Name} ToProto({m.Record} r)"); + Open(); + L($"var m = new Proto.{m.Name}();"); + foreach (var f in m.Fields) + { + var r = "r." + f.Prop; + var target = "m." + f.ProtoCs; + if (f.Repeated) { L($"{target}.AddRange({r}.Select(ToProto));"); continue; } + switch (f.Kind) + { + 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(Rpc rpc) + { + 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 {(rpc.Async ? "async " : "")}Task<{responseType}> {rpc.Name}({requestType} request, ServerCallContext context)"); + Open(); + if (rpc.Shape == Shape.Void) + { + L(rpc.Async ? $"await {call};" : $"{call};"); + L(rpc.Async ? "return new Empty();" : "return Task.FromResult(new Empty());"); + Close(); + L(); + return; + } + + L($"var result = {(rpc.Async ? "await " : "")}{call};"); + string response; + switch (rpc.Shape) + { + 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(rpc.Async ? $"return {response};" : $"return Task.FromResult({response});"); + Close(); + L(); + } +} 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..b31e311 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc.Tests/Bermuda.Fdc3.Grpc.Tests.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + diff --git a/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs b/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs new file mode 100644 index 0000000..3c7d746 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc.Tests/PipeIntegrationTests.cs @@ -0,0 +1,287 @@ +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", "type": "native" }, + { + "appId": "incidents", + "title": "Incidents", + "type": "native", + "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 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() + { + foreach (var client in _clients) await client.DisposeAsync(); + await _host.DisposeAsync(); + } + + private async Task ConnectAsync(string appId, string? instanceId = null) + { + var client = await Fdc3PipeClient.ConnectAsync(_pipe, appId, instanceId: instanceId); + _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 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() + { + 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.ResultJson); + } + + [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..5b30e7b --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Bermuda.Fdc3.Grpc.csproj @@ -0,0 +1,28 @@ + + + + + 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..d620443 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Fdc3AgentService.cs @@ -0,0 +1,92 @@ +using System.Collections.Concurrent; +using System.Threading.Channels; +using Bermuda.Fdc3.Grpc.Proto; +using Google.Protobuf.WellKnownTypes; +using Grpc.Core; + +namespace Bermuda.Fdc3.Grpc; + +/// 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 (GeneratedMapping.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 (generated, see Generated/Fdc3Generated.g.cs) are served by that instance's +/// . s become gRPC +/// errors in . +/// +internal sealed partial 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); + + // 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, request.HasInstanceId ? request.InstanceId : null); + 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); +} 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..e2a6d51 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Fdc3GrpcHost.cs @@ -0,0 +1,70 @@ +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; } + + /// The pipe name (without \\.\pipe\); null = . + public static async Task StartAsync(DesktopAgent agent, string? pipeName = null, CancellationToken cancellationToken = default) + { + pipeName = string.IsNullOrWhiteSpace(pipeName) ? Fdc3Pipe.DefaultName : 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/Generated/Fdc3Generated.g.cs b/src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs new file mode 100644 index 0000000..1c78fd5 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Generated/Fdc3Generated.g.cs @@ -0,0 +1,619 @@ +// +// Generated by Bermuda.Fdc3.Grpc.Generator from src/Bermuda.Fdc3.Proto/Protos/fdc3.proto. Do not edit. +// +#nullable enable +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 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 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 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; + } + + 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 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 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 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 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 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; + } + + 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 { } contextjson) m.ContextJson = contextjson.GetRawText(); + if (r.ResultType is not null) m.ResultType = r.ResultType; + 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 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 { } contextjson) m.ContextJson = contextjson.GetRawText(); + 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 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 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 { } 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.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; + } + + 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 { Event = 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/Mapping.cs b/src/Bermuda.Fdc3.Grpc/Mapping.cs new file mode 100644 index 0000000..571a404 --- /dev/null +++ b/src/Bermuda.Fdc3.Grpc/Mapping.cs @@ -0,0 +1,24 @@ +using System.Text.Json; + +namespace Bermuda.Fdc3.Grpc; + +/// +/// 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 +{ + 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); + } + } +} 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.Proto/Fdc3PipeClient.cs b/src/Bermuda.Fdc3.Proto/Fdc3PipeClient.cs new file mode 100644 index 0000000..54e1516 --- /dev/null +++ b/src/Bermuda.Fdc3.Proto/Fdc3PipeClient.cs @@ -0,0 +1,138 @@ +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; + +/// 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 +/// 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, string? instanceId = null) + { + var handler = new SocketsHttpHandler + { + ConnectCallback = async (_, token) => + { + var pipe = new NamedPipeClientStream(".", string.IsNullOrWhiteSpace(pipeName) ? Fdc3Pipe.DefaultName : 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 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); + } + 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, CancellationToken cancellationToken = default) + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(timeout ?? TimeSpan.FromSeconds(5)); + try + { + return await _events.Reader.ReadAsync(cts.Token); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + 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.Proto/Protos/fdc3.proto b/src/Bermuda.Fdc3.Proto/Protos/fdc3.proto new file mode 100644 index 0000000..0a1c045 --- /dev/null +++ b/src/Bermuda.Fdc3.Proto/Protos/fdc3.proto @@ -0,0 +1,303 @@ +// Bermuda's FDC3 2.2 Desktop Agent contract. THIS FILE IS THE SOURCE OF TRUTH for it. +// +// 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"; + +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. 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) { 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); + 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); + + // 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) { 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); +} + +// Shapes --------------------------------------------------------------------- + +message AppIdentifier { + string app_id = 1; + optional string instance_id = 2; +} + +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 { + 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 OptionalFeatures { + bool originating_app_metadata = 1; + bool user_channel_membership_apis = 2 [json_name = "userChannelMembershipAPIs"]; + 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; +} + +// 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; +} + +message GetCurrentContextRequest { + string channel_id = 1; + 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; + optional string context_type = 3; +} + +message AddIntentListenerRequest { + string listener_id = 1; + 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; + 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; +} + +// 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; + optional string channel_id = 3; + optional string error = 4; +} + +// Results that are lists or can be absent --------------------------------------- + +message FindInstancesResponse { + repeated AppIdentifier items = 1; +} + +message GetUserChannelsResponse { + repeated ChannelInfo items = 1; +} + +message GetCurrentChannelResponse { + optional ChannelInfo result = 1; +} + +message GetCurrentContextResponse { + optional string result_json = 1; +} + +message FindIntentsByContextResponse { + repeated AppIntent items = 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; + // 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. +message Connected { + string instance_id = 1; + string app_id = 2; +} + +message AgentEvent { + oneof kind { + Connected connected = 1; + ApiEvent event = 2; + ContextEvent context = 3; + IntentEvent intent = 4; + } +} 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.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/Bermuda.NativeApp.csproj b/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj new file mode 100644 index 0000000..c364a4c --- /dev/null +++ b/src/Bermuda.NativeApp/Bermuda.NativeApp.csproj @@ -0,0 +1,25 @@ + + + + + WinExe + net10.0 + enable + enable + + + + + + + + diff --git a/src/Bermuda.NativeApp/Program.cs b/src/Bermuda.NativeApp/Program.cs new file mode 100644 index 0000000..81ca399 --- /dev/null +++ b/src/Bermuda.NativeApp/Program.cs @@ -0,0 +1,94 @@ +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 `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, 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") 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. +using var singleInstance = new Mutex(true, @"Local\Bermuda.NativeApp." + AppId, out var first); +if (!first) return; + +using var shutdown = new CancellationTokenSource(); +Console.CancelKeyPress += (_, e) => { e.Cancel = true; shutdown.Cancel(); }; + +while (!shutdown.IsCancellationRequested) +{ + try + { + // 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) + { + } + // 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}"); + } + + 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 = "ack", Intent = "AcknowledgeIncident" }, + client.Headers, cancellationToken: cancellationToken); + + while (!cancellationToken.IsCancellationRequested) + { + var e = await client.NextEventAsync(Timeout.InfiniteTimeSpan, cancellationToken); + switch (e.KindCase) + { + 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.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) }, + client.Headers, cancellationToken: cancellationToken); + break; + } + } +} + +// 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/fixtures.ts b/src/Bermuda.Web/e2e/fixtures.ts index f460d02..ecd2ac3 100644 --- a/src/Bermuda.Web/e2e/fixtures.ts +++ b/src/Bermuda.Web/e2e/fixtures.ts @@ -3,13 +3,13 @@ import type { Page } from '@playwright/test' /** * Override the default `page` fixture to connect to the live WebView2 instance - * via CDP on port 9222. This lets tests run against the fully wired app + * via CDP on port CDP_PORT (default 9222). This lets tests run against the fully wired app * (Aspire-managed Vite + GraphQL API) without needing a separate web server. */ export const test = base.extend<{ page: Page }>({ // biome-ignore lint/correctness/noEmptyPattern: Playwright's fixture signature requires this shape. page: async ({}, provide: (page: Page) => Promise) => { - const browser = await chromium.connectOverCDP('http://localhost:9222') + const browser = await chromium.connectOverCDP(`http://localhost:${process.env.CDP_PORT ?? '9222'}`) const context = browser.contexts()[0] const page = context.pages()[0] 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..a7edd2c --- /dev/null +++ b/src/Bermuda.Web/e2e/native-app.spec.ts @@ -0,0 +1,107 @@ +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 / 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). + +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('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('AcknowledgeIncident') + expect(result.result).toMatchObject({ type: 'bermuda.native.ack', of: { id: { incidentId: 'native-2' } } }) + }) + + 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.Web/playwright.config.ts b/src/Bermuda.Web/playwright.config.ts index 2b0b9cc..753f81a 100644 --- a/src/Bermuda.Web/playwright.config.ts +++ b/src/Bermuda.Web/playwright.config.ts @@ -1,5 +1,9 @@ import { defineConfig } from '@playwright/test' +// CI picks free ports per run (CDP_PORT, WEB_PORT) so it cannot collide with, or accidentally test, another +// Bermuda or Aspire instance on the same machine; locally the defaults apply. +const cdpPort = process.env.CDP_PORT ?? '9222' + export default defineConfig({ testDir: './e2e', fullyParallel: false, @@ -14,8 +18,9 @@ export default defineConfig({ command: 'aspire run', cwd: '../..', // Wait for the WPF host's CDP endpoint — it's the last resource to start - url: 'http://localhost:9222/json', - reuseExistingServer: true, + url: `http://localhost:${cdpPort}/json`, + // Locally an already running `aspire run` is reused; CI always starts its own. + reuseExistingServer: !process.env.CI, timeout: 120_000, }, projects: [ 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 8d32507..217b515 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,69 @@ protected override void OnStartup(StartupEventArgs e) var fdc3 = new DesktopAgent(directory, launcher); launcher.Agent = fdc3; + StartGrpcHost(config, fdc3); + 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(); } + /// + /// 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; + private NativeAppHost? _nativeApps; + + /// + /// 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 => NativeAppHost.ResolvePath(a) is not null)) + { + try + { + _nativeApps!.Start(app); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Native FDC3 app {app.AppId} failed to start: {ex}"); + } + } + } + protected override void OnExit(ExitEventArgs e) { + _nativeApps?.Dispose(); + + 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..a5a0644 100644 --- a/src/Bermuda/Bermuda.csproj +++ b/src/Bermuda/Bermuda.csproj @@ -108,13 +108,30 @@ + + + + + + + + + + + + + + @@ -146,14 +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. --> + @@ -171,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/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/Package.appxmanifest b/src/Bermuda/Package.appxmanifest index 1c1d414..4d1c6da 100644 --- a/src/Bermuda/Package.appxmanifest +++ b/src/Bermuda/Package.appxmanifest @@ -59,6 +59,7 @@ + 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/appsettings.json b/src/Bermuda/appsettings.json index b9e9841..cba3c3f 100644 --- a/src/Bermuda/appsettings.json +++ b/src/Bermuda/appsettings.json @@ -1,5 +1,7 @@ { "WEB_URL": "http://localhost:5555", "CDP_PORT": 9222, - "TITLE_BAR": "client" + "TITLE_BAR": "client", + "FDC3_GRPC_ENABLED": true, + "NATIVE_APP_AUTOSTART": true } diff --git a/src/Bermuda/fdc3-appd.json b/src/Bermuda/fdc3-appd.json index fcfc2bc..6724eed 100644 --- a/src/Bermuda/fdc3-appd.json +++ b/src/Bermuda/fdc3-appd.json @@ -1,5 +1,31 @@ { "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", + "details": { + "path": "Bermuda.NativeApp.exe", + "project": "../Bermuda.NativeApp/Bermuda.NativeApp.csproj" + }, + "interop": { + "intents": { + "listensFor": { + "AcknowledgeIncident": { + "displayName": "Acknowledge Incident (native)", + "contexts": ["bermuda.incident"], + "resultType": "bermuda.native.ack" + } + } + }, + "userChannels": { + "broadcasts": ["bermuda.native.ack"], + "listensFor": ["bermuda.incident"] + } + } + }, { "appId": "fdc3-probe", "name": "fdc3-probe", diff --git a/src/Bermuda/tools/native-apps.cs b/src/Bermuda/tools/native-apps.cs new file mode 100644 index 0000000..ca83455 --- /dev/null +++ b/src/Bermuda/tools/native-apps.cs @@ -0,0 +1,183 @@ +#:property NuGetAudit=false +#:property PublishAot=false + +// 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 -- 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