| | | 1 | | using MessagePack; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | |
| | | 4 | | namespace NLightning.Daemon.Services.Ipc; |
| | | 5 | | |
| | | 6 | | using Daemon.Ipc.Interfaces; |
| | | 7 | | using Domain.Client.Enums; |
| | | 8 | | using Transport.Ipc; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Default router that uses a map of handlers keyed by command. |
| | | 12 | | /// </summary> |
| | | 13 | | internal sealed class IpcRequestRouter : IIpcRequestRouter |
| | | 14 | | { |
| | | 15 | | private readonly IReadOnlyDictionary<ClientCommand, IIpcCommandHandler> _handlers; |
| | | 16 | | private readonly ILogger<IpcRequestRouter> _logger; |
| | | 17 | | |
| | 0 | 18 | | public IpcRequestRouter(IEnumerable<IIpcCommandHandler> handlers, ILogger<IpcRequestRouter> logger) |
| | | 19 | | { |
| | 0 | 20 | | _handlers = handlers.ToDictionary(h => h.Command); |
| | 0 | 21 | | _logger = logger; |
| | 0 | 22 | | } |
| | | 23 | | |
| | | 24 | | public async Task<IpcEnvelope> RouteAsync(IpcEnvelope request, CancellationToken ct) |
| | | 25 | | { |
| | 0 | 26 | | if (!_handlers.TryGetValue(request.Command, out var handler)) |
| | | 27 | | { |
| | 0 | 28 | | return Error(request, "unknown_command", $"Unknown command: {request.Command}"); |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | try |
| | | 32 | | { |
| | 0 | 33 | | return await handler.HandleAsync(request, ct); |
| | | 34 | | } |
| | 0 | 35 | | catch (Exception ex) |
| | | 36 | | { |
| | 0 | 37 | | _logger.LogError(ex, "IPC handler error for {Command}", request.Command); |
| | 0 | 38 | | return Error(request, "server_error", ex.Message); |
| | | 39 | | } |
| | 0 | 40 | | } |
| | | 41 | | |
| | | 42 | | private static IpcEnvelope Error(IpcEnvelope request, string code, string message) |
| | | 43 | | { |
| | 0 | 44 | | var payload = MessagePackSerializer.Serialize(new IpcError { Code = code, Message = message }); |
| | 0 | 45 | | return new IpcEnvelope |
| | 0 | 46 | | { |
| | 0 | 47 | | Version = request.Version, |
| | 0 | 48 | | Command = request.Command, |
| | 0 | 49 | | CorrelationId = request.CorrelationId, |
| | 0 | 50 | | Kind = IpcEnvelopeKind.Error, |
| | 0 | 51 | | Payload = payload |
| | 0 | 52 | | }; |
| | | 53 | | } |
| | | 54 | | } |