From 3d1bf4f21fd85ff9ff82f6205a14d23d5fd1dbdd Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:48:22 +1000 Subject: [PATCH 01/18] wip: Server-side-persistence --- .do/deploy.template.yaml | 28 +- .fallout/build.schema.json | 5 + .gitignore | 5 +- README.md | 4 +- build/Build.cs | 19 + docker-compose.yml | 32 + docs/docs/server/index.md | 123 +- example.env | 56 +- .../AcarsConnectionCommandHandlerTests.cs | 197 +++ .../GetAtsuSettingsRequestHandlerTests.cs | 13 +- .../Hoppie/HoppieAcarsConnectionTests.cs} | 212 +-- ...efreshAcarsCallsignsRequestHandlerTests.cs | 108 +- .../AdscContractRepositoryTests.cs | 67 + .../AdscContractTests.cs | 4 +- ...MessageReceivedNotificationHandlerTests.cs | 8 +- .../CancelAdscContractCommandHandlerTests.cs | 25 +- ...scContractOnConnectionEndedHandlerTests.cs | 20 +- ...ExpiredAdscContractsRequestHandlerTests.cs | 87 +- .../InMemoryAdscMessageLogRepositoryTests.cs | 5 +- ...PurgeExpiredAdscDataRequestHandlerTests.cs | 79 ++ ...cReportReceivedNotificationHandlerTests.cs | 23 +- .../Reports/AdscReportRepositoryTests.cs | 184 +++ ...uestAdscDemandReportCommandHandlerTests.cs | 24 +- ...ractOnConnectionEstablishedHandlerTests.cs | 8 +- ...tDefaultAdscContractCommandHandlerTests.cs | 31 +- ...SelectedAdscContractCommandHandlerTests.cs | 47 +- .../Auth/Login/ClientIpAddressTests.cs | 52 + .../Auth/Login/LoginCommandHandlerTests.cs | 163 +++ .../Auth/Login/LoginLockoutTests.cs | 99 ++ .../ChangePasswordCommandHandlerTests.cs | 59 + .../Users/CreateUserCommandHandlerTests.cs | 80 ++ ...tionEstablishedNotificationHandlerTests.cs | 17 +- ...tConnectionLostNotificationHandlerTests.cs | 33 +- ...ctionTerminatedNotificationHandlerTests.cs | 13 +- .../Connections/AircraftRepositoryTests.cs | 95 ++ ...tAircraftConnectionsRequestHandlerTests.cs | 103 +- ...GetConnectedAircraftRequestHandlerTests.cs | 18 +- .../Connections}/LogonCommandHandlerTests.cs | 77 +- ...endConnectionRequestCommandHandlerTests.cs | 102 ++ .../TerminateConnectionHandlerTests.cs | 12 +- ...eConnectionOnDialogueClosedHandlerTests.cs | 23 +- ...mitPendingNdaUplinksCommandHandlerTests.cs | 41 +- ...ateNextDataAuthorityCommandHandlerTests.cs | 20 +- ...veCompletedDialoguesRequestHandlerTests.cs | 152 ++ .../ArchiveDialogueCommandHandlerTests.cs | 8 +- ...CheckMessageTimeoutsRequestHandlerTests.cs | 258 ++++ .../Dialogues/DialogueRepositoryTests.cs | 208 +++ .../Dialogues}/DialogueTests.cs | 39 +- ...urgeExpiredCpdlcDataRequestHandlerTests.cs | 36 + .../AcknowledgeDownlinkCommandHandlerTests.cs | 7 +- ...ownlinkReceivedNotificationHandlerTests.cs | 45 +- .../AcknowledgeUplinkCommandHandlerTests.cs | 8 +- .../BeginDialogueCommandHandlerTests.cs | 46 +- .../Uplinks}/MessageIdProviderTests.cs | 44 +- .../ReplyToDownlinkCommandHandlerTests.cs | 59 +- ...endConnectionRequestCommandHandlerTests.cs | 103 -- .../Logging/LogBufferTests.cs | 105 ++ ...tAcarsClient.cs => TestAcarsConnection.cs} | 8 +- .../Mocks/TestAcarsConnectionManager.cs | 117 ++ .../Mocks/TestAdscContractRepository.cs | 14 +- .../Mocks/TestAdscMessageLogRepository.cs | 3 +- .../Mocks/TestAdscReportRepository.cs | 35 +- .../Mocks/TestAircraftRepository.cs | 14 +- .../Mocks/TestClientManager.cs | 87 -- .../Mocks/TestControllerManager.cs | 3 +- .../CPDLCServer.Tests/Mocks/TestDatabase.cs | 35 + .../Mocks/TestDialogueRepository.cs | 42 +- .../Mocks/TestMessageIdProvider.cs | 2 +- .../Mocks/TestServerSettingsProvider.cs | 19 + .../CPDLCServer.Tests/Mocks/TestUnitOfWork.cs | 12 + .../Mocks/TestUserRepository.cs | 34 + .../InMemoryAdscReportRepositoryTests.cs | 127 -- .../PostgreSqlConnectionStringTests.cs | 47 + .../Persistence/UnitOfWorkTests.cs | 105 ++ .../Security/MasterKeyEncryptionTests.cs | 54 + .../Services/MessageMonitorServiceTests.cs | 482 ------- .../Settings/ServerSettingsProviderTests.cs | 114 ++ .../Setup/SetupStateTests.cs | 74 + ...uceVatsimAdscReportsRequestHandlerTests.cs | 13 +- .../VatsimPilotTests.cs | 4 +- .../AcarsConnectionManager.cs | 412 ++++++ ...sConnectionsServiceCollectionExtensions.cs | 18 + .../ConfigurationNotFoundException.cs | 4 + .../AcarsConnectionSettings.cs | 48 + .../AcarsConnectionSettingsConfiguration.cs | 21 + .../CreateAcarsConnectionCommand.cs | 6 + .../CreateAcarsConnectionCommandHandler.cs | 33 + .../DeleteAcarsConnectionCommand.cs | 5 + .../DeleteAcarsConnectionCommandHandler.cs | 28 + .../UpdateAcarsConnectionCommand.cs | 6 + .../UpdateAcarsConnectionCommandHandler.cs | 45 + .../GetAtsuSettingsRequest.cs | 2 +- .../GetAtsuSettingsRequestHandler.cs | 8 +- .../Hoppie/HoppieAcarsConnection.cs} | 1251 +++++++++-------- .../Hoppie}/MessageParseException.cs | 2 +- .../HoppiesConfiguration.cs | 6 +- .../IAcarsConnection.cs} | 8 +- .../AcarsConnectivityCheckService.cs | 61 +- .../AcarsStationsChangedNotification.cs | 2 +- ...AcarsStationsChangedNotificationHandler.cs | 15 +- .../Stations}/IAcarsStationRepository.cs | 2 +- .../InMemoryAcarsStationRepository.cs | 4 +- .../Stations/RefreshAcarsCallsignsRequest.cs | 5 + .../RefreshAcarsCallsignsRequestHandler.cs | 14 +- .../{Model => AdscContracts}/AdscContract.cs | 4 +- .../AdscContractChangedNotification.cs | 3 +- .../AdscContractChangedNotificationHandler.cs | 13 +- .../AdscContractConfiguration.cs | 30 + .../AdscContractConverter.cs | 9 +- .../AdscContractExpiryService.cs | 24 +- .../AdscContractRemovedNotification.cs | 2 +- .../AdscContractRemovedNotificationHandler.cs | 11 +- .../AdscContracts/AdscContractRepository.cs | 46 + .../AdscContractState.cs | 2 +- ...dscContractsServiceCollectionExtensions.cs | 18 + .../AdscMessageReceivedNotification.cs | 5 +- .../AdscMessageReceivedNotificationHandler.cs | 6 +- .../CancelAdscContractCommand.cs | 2 +- .../CancelAdscContractCommandHandler.cs | 12 +- ...celAdscContractOnConnectionEndedHandler.cs | 13 +- .../EndExpiredAdscContractsRequest.cs | 2 +- .../EndExpiredAdscContractsRequestHandler.cs | 42 +- .../GetAdscContractsRequest.cs | 2 +- .../GetAdscContractsRequestHandler.cs | 5 +- .../IAdscContractRepository.cs | 4 +- .../MessageLog}/AdscMessageLogEntry.cs | 4 +- .../MessageLog}/IAdscMessageLogRepository.cs | 4 +- .../InMemoryAdscMessageLogRepository.cs | 5 +- .../PurgeExpiredAdscDataRequest.cs | 5 + .../PurgeExpiredAdscDataRequestHandler.cs | 23 + .../ReceivedAdscMessage.cs | 3 +- .../Reports}/AdscReport.cs | 2 +- .../AdscReportReceivedNotification.cs | 3 +- .../AdscReportReceivedNotificationHandler.cs | 12 +- .../Reports/AdscReportRepository.cs | 70 + .../Reports}/AdscReportSource.cs | 2 +- .../Reports/AircraftAdscReport.cs | 14 + .../AircraftAdscReportConfiguration.cs | 39 + .../Reports}/GetAdscReportsRequest.cs | 2 +- .../Reports}/GetAdscReportsRequestHandler.cs | 7 +- .../Reports/IAdscReportRepository.cs | 14 + .../RequestAdscDemandReportCommand.cs | 2 +- .../RequestAdscDemandReportCommandHandler.cs | 13 +- ...cContractOnConnectionEstablishedHandler.cs | 5 +- .../RequestDefaultAdscContractCommand.cs | 2 +- ...equestDefaultAdscContractCommandHandler.cs | 15 +- .../RequestSelectedAdscContractCommand.cs | 2 +- ...questSelectedAdscContractCommandHandler.cs | 15 +- .../Auth/AuthServiceCollectionExtensions.cs | 39 + .../Auth/Login/AdminAuthentication.cs | 25 + .../CPDLCServer/Auth/Login/ClientIpAddress.cs | 36 + source/CPDLCServer/Auth/Login/LoginCommand.cs | 8 + .../Auth/Login/LoginCommandHandler.cs | 50 + source/CPDLCServer/Auth/Login/LoginLockout.cs | 79 ++ .../Auth/Login/PasswordRateLimit.cs | 39 + .../Auth/Users/ChangePasswordCommand.cs | 5 + .../Users/ChangePasswordCommandHandler.cs | 21 + .../Auth/Users/CreateUserCommand.cs | 5 + .../Auth/Users/CreateUserCommandHandler.cs | 43 + .../CPDLCServer/Auth/Users/IUserRepository.cs | 10 + source/CPDLCServer/Auth/Users/User.cs | 10 + .../Auth/Users/UserConfiguration.cs | 17 + .../CPDLCServer/Auth/Users/UserRepository.cs | 42 + source/CPDLCServer/CPDLCServer.csproj | 29 +- source/CPDLCServer/Clients/ClientManager.cs | 353 ----- .../ControllerConnectedNotification.cs | 2 +- .../ControllerConnectedNotificationHandler.cs | 21 +- .../ControllerDisconnectedNotification.cs | 2 +- ...ntrollerDisconnectedNotificationHandler.cs | 10 +- .../{Model => Controllers}/ControllerInfo.cs | 2 +- .../ControllersServiceCollectionExtensions.cs | 12 + .../GetConnectedControllersRequest.cs | 2 +- .../GetConnectedControllersRequestHandler.cs | 4 +- .../IControllerRepository.cs | 4 +- .../InMemoryControllerRepository.cs | 5 +- .../Connections}/AircraftConnection.cs | 6 +- .../AircraftConnectionConfiguration.cs | 32 + .../AircraftConnectionEstablished.cs | 5 +- ...onnectionEstablishedNotificationHandler.cs | 20 +- .../Connections}/AircraftConnectionLost.cs | 4 +- ...rcraftConnectionLostNotificationHandler.cs | 32 +- .../AircraftConnectionTerminated.cs | 4 +- ...ConnectionTerminatedNotificationHandler.cs | 15 +- .../Cpdlc/Connections/AircraftRepository.cs | 46 + .../CheckLostAircraftConnectionsRequest.cs | 2 +- ...ckLostAircraftConnectionsRequestHandler.cs | 17 +- .../Connections}/ConnectionState.cs | 2 +- .../Connections}/DataAuthorityState.cs | 2 +- .../GetConnectedAircraftRequest.cs | 2 +- .../GetConnectedAircraftRequestHandler.cs | 6 +- .../Connections}/IAircraftRepository.cs | 6 +- .../Connections}/LogonCommand.cs | 7 +- .../Connections}/LogonCommandHandler.cs | 50 +- .../Connections}/LostConnectionService.cs | 33 +- .../Connections}/NdaUplinkService.cs | 11 +- .../SendConnectionRequestCommand.cs | 2 +- .../SendConnectionRequestCommandHandler.cs | 49 + .../TerminateConnectionHandler.cs | 11 +- ...minateConnectionOnDialogueClosedHandler.cs | 9 +- .../Connections/TerminateConnectionRequest.cs | 7 + .../TransmitPendingNdaUplinksCommand.cs | 2 +- ...TransmitPendingNdaUplinksCommandHandler.cs | 18 +- .../UpdateNextDataAuthorityCommand.cs | 2 +- .../UpdateNextDataAuthorityCommandHandler.cs | 4 +- .../Cpdlc/CpdlcServiceCollectionExtensions.cs | 22 + .../{Model => Cpdlc/Dialogues}/AlertType.cs | 2 +- .../ArchiveCompletedDialoguesRequest.cs | 5 + ...ArchiveCompletedDialoguesRequestHandler.cs | 46 + .../Dialogues}/ArchiveDialogueCommand.cs | 2 +- .../ArchiveDialogueCommandHandler.cs | 100 +- .../Dialogues/CheckMessageTimeoutsRequest.cs | 5 + .../CheckMessageTimeoutsRequestHandler.cs | 96 ++ .../Dialogues}/ControlMessages.cs | 4 +- .../Cpdlc/Dialogues/CpdlcMessage.cs | 26 + .../Dialogues/CpdlcMessageConfiguration.cs | 61 + .../{Model => Cpdlc/Dialogues}/Dialogue.cs | 44 +- .../Dialogues}/DialogueChangedNotification.cs | 3 +- .../DialogueChangedNotificationHandler.cs | 100 +- .../Cpdlc/Dialogues/DialogueConfiguration.cs | 31 + .../Dialogues}/DialogueConverter.cs | 28 +- .../Cpdlc/Dialogues/DialogueRepository.cs | 97 ++ .../Dialogues}/IDialogueRepository.cs | 9 +- .../Cpdlc/Dialogues/MessageMonitorService.cs | 51 + .../Dialogues/PurgeExpiredCpdlcDataRequest.cs | 5 + .../PurgeExpiredCpdlcDataRequestHandler.cs | 26 + .../Downlinks}/AcknowledgeDownlinkCommand.cs | 2 +- .../AcknowledgeDownlinkCommandHandler.cs | 73 +- .../Downlinks}/CpdlcDownlinkResponseType.cs | 2 +- .../Cpdlc/Downlinks/DownlinkMessage.cs | 45 + .../DownlinkReceivedNotification.cs | 5 +- .../DownlinkReceivedNotificationHandler.cs | 31 +- .../Downlinks}/ReceivedDownlink.cs | 3 +- .../Uplinks}/AcknowledgeUplinkCommand.cs | 2 +- .../AcknowledgeUplinkCommandHandler.cs | 6 +- .../Uplinks}/BeginDialogueCommand.cs | 3 +- .../Uplinks}/BeginDialogueCommandHandler.cs | 23 +- .../Uplinks}/CpdlcUplinkResponseType.cs | 2 +- .../Cpdlc/Uplinks/MessageIdProvider.cs | 30 + .../Cpdlc/Uplinks/MessageIdSequence.cs | 15 + .../Uplinks/MessageIdSequenceConfiguration.cs | 18 + .../Uplinks}/ReplyToDownlinkCommand.cs | 3 +- .../Uplinks}/ReplyToDownlinkCommandHandler.cs | 23 +- .../Cpdlc/Uplinks/UplinkMessage.cs | 55 + source/CPDLCServer/Dockerfile | 3 + .../ConfigurationNotFoundException.cs | 4 - .../SendConnectionRequestCommandHandler.cs | 45 - .../Infrastructure/ApiKeyHasher.cs | 13 - .../ConfigurationExtensionMethods.cs | 9 + ...frastructureServiceCollectionExtensions.cs | 17 + .../SemaphoreSlimExtensionMethods.cs | 2 +- .../Infrastructure/ServerStartTime.cs | 9 + .../Infrastructure/UnitOfWorkMediator.cs | 68 + source/CPDLCServer/Logging/LogBuffer.cs | 64 + source/CPDLCServer/Logging/LogBufferSink.cs | 41 + source/CPDLCServer/Logging/LogEntry.cs | 11 + .../CPDLCServer/Logging/LogStreamEndpoint.cs | 51 + .../Messages/RefreshAcarsCallsignsRequest.cs | 5 - .../Messages/TerminateConnectionRequest.cs | 7 - .../CPDLCServer/Model/AircraftAdscReport.cs | 8 - source/CPDLCServer/Model/DownlinkMessage.cs | 43 - source/CPDLCServer/Model/ICpdlcMessage.cs | 18 - source/CPDLCServer/Model/UplinkMessage.cs | 49 - .../Pages/Connections/Index.cshtml | 96 -- .../Pages/Connections/Index.cshtml.cs | 28 - source/CPDLCServer/Pages/Index.cshtml | 53 - source/CPDLCServer/Pages/Index.cshtml.cs | 38 - .../CPDLCServer/Pages/Messages/Index.cshtml | 71 - .../Pages/Messages/Index.cshtml.cs | 88 -- .../Pages/ViewModels/MessageRowViewModel.cs | 13 - .../CPDLCServer/Persistence/CpdlcDbContext.cs | 57 + .../Persistence/DatabaseProvider.cs | 7 + .../Persistence/IAdscReportRepository.cs | 15 - .../InMemoryAdscContractRepository.cs | 46 - .../InMemoryAdscReportRepository.cs | 55 - .../Persistence/InMemoryAircraftRepository.cs | 46 - .../Persistence/InMemoryDialogueRepository.cs | 67 - .../20261107042236_InitialCreate.Designer.cs | 462 ++++++ .../20261107042236_InitialCreate.cs | 275 ++++ .../PostgreSqlCpdlcDbContextModelSnapshot.cs | 459 ++++++ .../20261107042233_InitialCreate.Designer.cs | 447 ++++++ .../Sqlite/20261107042233_InitialCreate.cs | 274 ++++ .../SqliteCpdlcDbContextModelSnapshot.cs | 444 ++++++ .../PersistenceServiceCollectionExtensions.cs | 41 + .../Persistence/PostgreSqlConnectionString.cs | 40 + .../Persistence/PostgreSqlCpdlcDbContext.cs | 21 + .../Persistence/SqliteCpdlcDbContext.cs | 20 + source/CPDLCServer/Persistence/UnitOfWork.cs | 45 + .../Persistence/UtcTicksConverter.cs | 8 + source/CPDLCServer/Program.cs | 181 ++- .../Security/MasterKeyEncryption.cs | 69 + .../SecurityServiceCollectionExtensions.cs | 15 + .../Services/IStatisticsService.cs | 22 - .../CPDLCServer/Services/MessageIdProvider.cs | 44 - .../Services/MessageMonitorService.cs | 212 --- .../Services/VatsimStatusConfiguration.cs | 16 - .../Settings/GetServerSettingsRequest.cs | 5 + .../GetServerSettingsRequestHandler.cs | 12 + .../Settings/SaveServerSettingsCommand.cs | 5 + .../SaveServerSettingsCommandHandler.cs | 22 + source/CPDLCServer/Settings/ServerSettings.cs | 33 + .../Settings/ServerSettingsConfiguration.cs | 21 + .../Settings/ServerSettingsProvider.cs | 36 + .../SettingsServiceCollectionExtensions.cs | 12 + .../Setup/RedirectToSetupMiddleware.cs | 25 + .../Setup/SetupServiceCollectionExtensions.cs | 11 + source/CPDLCServer/Setup/SetupState.cs | 41 + .../IVatsimPilotRepository.cs | 4 +- .../InMemoryVatsimPilotRepository.cs | 5 +- .../ProduceVatsimAdscReportsRequest.cs | 2 +- .../ProduceVatsimAdscReportsRequestHandler.cs | 20 +- .../{Model => VatsimStatus}/VatsimPilot.cs | 2 +- .../VatsimStatusService.cs | 44 +- ...VatsimStatusServiceCollectionExtensions.cs | 12 + .../{Hubs => Web}/ControllerHub.cs | 34 +- .../Web/Pages/Account/Login.cshtml | 38 + .../Web/Pages/Account/Login.cshtml.cs | 64 + .../Web/Pages/Account/Logout.cshtml | 2 + .../Web/Pages/Account/Logout.cshtml.cs | 20 + .../{ => Web}/Pages/Adsc/Index.cshtml | 7 +- .../{ => Web}/Pages/Adsc/Index.cshtml.cs | 9 +- .../{ => Web}/Pages/Atsu/Index.cshtml | 3 +- .../{ => Web}/Pages/Atsu/Index.cshtml.cs | 11 +- .../{ => Web}/Pages/Dialogue/Index.cshtml | 3 +- .../{ => Web}/Pages/Dialogue/Index.cshtml.cs | 14 +- source/CPDLCServer/Web/Pages/Index.cshtml | 196 +++ source/CPDLCServer/Web/Pages/Index.cshtml.cs | 64 + .../CPDLCServer/Web/Pages/Logs/Index.cshtml | 174 +++ .../Web/Pages/Logs/Index.cshtml.cs | 11 + .../{ => Web}/Pages/Pilot/Index.cshtml | 5 +- .../{ => Web}/Pages/Pilot/Index.cshtml.cs | 10 +- .../Web/Pages/Settings/Acars/Edit.cshtml | 156 ++ .../Web/Pages/Settings/Acars/Edit.cshtml.cs | 109 ++ .../Web/Pages/Settings/Acars/Index.cshtml | 92 ++ .../Web/Pages/Settings/Acars/Index.cshtml.cs | 63 + .../Web/Pages/Settings/Index.cshtml | 213 +++ .../Web/Pages/Settings/Index.cshtml.cs | 49 + .../Settings/Users/ChangePassword.cshtml | 44 + .../Settings/Users/ChangePassword.cshtml.cs | 71 + .../Web/Pages/Settings/Users/Index.cshtml | 54 + .../Web/Pages/Settings/Users/Index.cshtml.cs | 28 + .../Web/Pages/Settings/_SettingsLayout.cshtml | 25 + .../Web/Pages/Settings/_ViewStart.cshtml | 3 + .../CPDLCServer/Web/Pages/Setup/Index.cshtml | 64 + .../Web/Pages/Setup/Index.cshtml.cs | 94 ++ .../{ => Web}/Pages/Shared/_Layout.cshtml | 22 +- .../Pages/Shared/_MessageTable.cshtml | 2 +- .../Pages/ViewModels/MessageRowViewModel.cs | 58 + .../{ => Web}/Pages/_ViewImports.cshtml | 2 +- .../{ => Web}/Pages/_ViewStart.cshtml | 0 .../Web/WebServiceCollectionExtensions.cs | 19 + 350 files changed, 11990 insertions(+), 4290 deletions(-) create mode 100644 source/CPDLCServer.Tests/AcarsConnections/ConnectionSettings/AcarsConnectionCommandHandlerTests.cs rename source/CPDLCServer.Tests/{Handlers => AcarsConnections}/GetAtsuSettingsRequestHandlerTests.cs (68%) rename source/CPDLCServer.Tests/{Clients/HoppieAcarsClientTests.cs => AcarsConnections/Hoppie/HoppieAcarsConnectionTests.cs} (79%) rename source/CPDLCServer.Tests/{Handlers => AcarsConnections/Stations}/RefreshAcarsCallsignsRequestHandlerTests.cs (78%) create mode 100644 source/CPDLCServer.Tests/AdscContracts/AdscContractRepositoryTests.cs rename source/CPDLCServer.Tests/{Model => AdscContracts}/AdscContractTests.cs (99%) rename source/CPDLCServer.Tests/{Handlers => AdscContracts}/AdscMessageReceivedNotificationHandlerTests.cs (98%) rename source/CPDLCServer.Tests/{Handlers => AdscContracts}/CancelAdscContractCommandHandlerTests.cs (69%) rename source/CPDLCServer.Tests/{Handlers => AdscContracts}/CancelAdscContractOnConnectionEndedHandlerTests.cs (86%) rename source/CPDLCServer.Tests/{Handlers => AdscContracts}/EndExpiredAdscContractsRequestHandlerTests.cs (66%) rename source/CPDLCServer.Tests/{Persistence => AdscContracts/MessageLog}/InMemoryAdscMessageLogRepositoryTests.cs (95%) create mode 100644 source/CPDLCServer.Tests/AdscContracts/PurgeExpiredAdscDataRequestHandlerTests.cs rename source/CPDLCServer.Tests/{Handlers => AdscContracts/Reports}/AdscReportReceivedNotificationHandlerTests.cs (85%) create mode 100644 source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs rename source/CPDLCServer.Tests/{Handlers => AdscContracts/Reports}/RequestAdscDemandReportCommandHandlerTests.cs (73%) rename source/CPDLCServer.Tests/{Handlers => AdscContracts}/RequestAdscContractOnConnectionEstablishedHandlerTests.cs (96%) rename source/CPDLCServer.Tests/{Handlers => AdscContracts}/RequestDefaultAdscContractCommandHandlerTests.cs (68%) rename source/CPDLCServer.Tests/{Handlers => AdscContracts}/RequestSelectedAdscContractCommandHandlerTests.cs (66%) create mode 100644 source/CPDLCServer.Tests/Auth/Login/ClientIpAddressTests.cs create mode 100644 source/CPDLCServer.Tests/Auth/Login/LoginCommandHandlerTests.cs create mode 100644 source/CPDLCServer.Tests/Auth/Login/LoginLockoutTests.cs create mode 100644 source/CPDLCServer.Tests/Auth/Users/ChangePasswordCommandHandlerTests.cs create mode 100644 source/CPDLCServer.Tests/Auth/Users/CreateUserCommandHandlerTests.cs rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Connections}/AircraftConnectionEstablishedNotificationHandlerTests.cs (88%) rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Connections}/AircraftConnectionLostNotificationHandlerTests.cs (94%) rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Connections}/AircraftConnectionTerminatedNotificationHandlerTests.cs (92%) create mode 100644 source/CPDLCServer.Tests/Cpdlc/Connections/AircraftRepositoryTests.cs rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Connections}/CheckLostAircraftConnectionsRequestHandlerTests.cs (60%) rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Connections}/GetConnectedAircraftRequestHandlerTests.cs (87%) rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Connections}/LogonCommandHandlerTests.cs (72%) create mode 100644 source/CPDLCServer.Tests/Cpdlc/Connections/SendConnectionRequestCommandHandlerTests.cs rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Connections}/TerminateConnectionHandlerTests.cs (96%) rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Connections}/TerminateConnectionOnDialogueClosedHandlerTests.cs (93%) rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Connections}/TransmitPendingNdaUplinksCommandHandlerTests.cs (88%) rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Connections}/UpdateNextDataAuthorityCommandHandlerTests.cs (94%) create mode 100644 source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandlerTests.cs rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Dialogues}/ArchiveDialogueCommandHandlerTests.cs (96%) create mode 100644 source/CPDLCServer.Tests/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandlerTests.cs create mode 100644 source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueRepositoryTests.cs rename source/CPDLCServer.Tests/{Model => Cpdlc/Dialogues}/DialogueTests.cs (86%) create mode 100644 source/CPDLCServer.Tests/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandlerTests.cs rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Downlinks}/AcknowledgeDownlinkCommandHandlerTests.cs (97%) rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Downlinks}/DownlinkReceivedNotificationHandlerTests.cs (96%) rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Uplinks}/AcknowledgeUplinkCommandHandlerTests.cs (98%) rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Uplinks}/BeginDialogueCommandHandlerTests.cs (73%) rename source/CPDLCServer.Tests/{Services => Cpdlc/Uplinks}/MessageIdProviderTests.cs (57%) rename source/CPDLCServer.Tests/{Handlers => Cpdlc/Uplinks}/ReplyToDownlinkCommandHandlerTests.cs (79%) delete mode 100644 source/CPDLCServer.Tests/Handlers/SendConnectionRequestCommandHandlerTests.cs create mode 100644 source/CPDLCServer.Tests/Logging/LogBufferTests.cs rename source/CPDLCServer.Tests/Mocks/{TestAcarsClient.cs => TestAcarsConnection.cs} (90%) create mode 100644 source/CPDLCServer.Tests/Mocks/TestAcarsConnectionManager.cs delete mode 100644 source/CPDLCServer.Tests/Mocks/TestClientManager.cs create mode 100644 source/CPDLCServer.Tests/Mocks/TestDatabase.cs create mode 100644 source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs create mode 100644 source/CPDLCServer.Tests/Mocks/TestUnitOfWork.cs create mode 100644 source/CPDLCServer.Tests/Mocks/TestUserRepository.cs delete mode 100644 source/CPDLCServer.Tests/Persistence/InMemoryAdscReportRepositoryTests.cs create mode 100644 source/CPDLCServer.Tests/Persistence/PostgreSqlConnectionStringTests.cs create mode 100644 source/CPDLCServer.Tests/Persistence/UnitOfWorkTests.cs create mode 100644 source/CPDLCServer.Tests/Security/MasterKeyEncryptionTests.cs delete mode 100644 source/CPDLCServer.Tests/Services/MessageMonitorServiceTests.cs create mode 100644 source/CPDLCServer.Tests/Settings/ServerSettingsProviderTests.cs create mode 100644 source/CPDLCServer.Tests/Setup/SetupStateTests.cs rename source/CPDLCServer.Tests/{Handlers => VatsimStatus}/ProduceVatsimAdscReportsRequestHandlerTests.cs (97%) rename source/CPDLCServer.Tests/{Model => VatsimStatus}/VatsimPilotTests.cs (90%) create mode 100644 source/CPDLCServer/AcarsConnections/AcarsConnectionManager.cs create mode 100644 source/CPDLCServer/AcarsConnections/AcarsConnectionsServiceCollectionExtensions.cs create mode 100644 source/CPDLCServer/AcarsConnections/ConfigurationNotFoundException.cs create mode 100644 source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettings.cs create mode 100644 source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettingsConfiguration.cs create mode 100644 source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommand.cs create mode 100644 source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommandHandler.cs create mode 100644 source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommand.cs create mode 100644 source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommandHandler.cs create mode 100644 source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommand.cs create mode 100644 source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommandHandler.cs rename source/CPDLCServer/{Messages => AcarsConnections}/GetAtsuSettingsRequest.cs (76%) rename source/CPDLCServer/{Handlers => AcarsConnections}/GetAtsuSettingsRequestHandler.cs (58%) rename source/CPDLCServer/{Clients/HoppieAcarsClient.cs => AcarsConnections/Hoppie/HoppieAcarsConnection.cs} (95%) rename source/CPDLCServer/{Exceptions => AcarsConnections/Hoppie}/MessageParseException.cs (72%) rename source/CPDLCServer/{Clients => AcarsConnections}/HoppiesConfiguration.cs (83%) rename source/CPDLCServer/{Clients/IAcarsClient.cs => AcarsConnections/IAcarsConnection.cs} (79%) rename source/CPDLCServer/{Services => AcarsConnections/Stations}/AcarsConnectivityCheckService.cs (66%) rename source/CPDLCServer/{Messages => AcarsConnections/Stations}/AcarsStationsChangedNotification.cs (67%) rename source/CPDLCServer/{Handlers => AcarsConnections/Stations}/AcarsStationsChangedNotificationHandler.cs (55%) rename source/CPDLCServer/{Persistence => AcarsConnections/Stations}/IAcarsStationRepository.cs (79%) rename source/CPDLCServer/{Persistence => AcarsConnections/Stations}/InMemoryAcarsStationRepository.cs (92%) create mode 100644 source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequest.cs rename source/CPDLCServer/{Handlers => AcarsConnections/Stations}/RefreshAcarsCallsignsRequestHandler.cs (76%) rename source/CPDLCServer/{Model => AdscContracts}/AdscContract.cs (97%) rename source/CPDLCServer/{Messages => AdscContracts}/AdscContractChangedNotification.cs (64%) rename source/CPDLCServer/{Handlers => AdscContracts}/AdscContractChangedNotificationHandler.cs (77%) create mode 100644 source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs rename source/CPDLCServer/{Model => AdscContracts}/AdscContractConverter.cs (82%) rename source/CPDLCServer/{Services => AdscContracts}/AdscContractExpiryService.cs (76%) rename source/CPDLCServer/{Messages => AdscContracts}/AdscContractRemovedNotification.cs (75%) rename source/CPDLCServer/{Handlers => AdscContracts}/AdscContractRemovedNotificationHandler.cs (83%) create mode 100644 source/CPDLCServer/AdscContracts/AdscContractRepository.cs rename source/CPDLCServer/{Model => AdscContracts}/AdscContractState.cs (81%) create mode 100644 source/CPDLCServer/AdscContracts/AdscContractsServiceCollectionExtensions.cs rename source/CPDLCServer/{Messages => AdscContracts}/AdscMessageReceivedNotification.cs (62%) rename source/CPDLCServer/{Handlers => AdscContracts}/AdscMessageReceivedNotificationHandler.cs (96%) rename source/CPDLCServer/{Messages => AdscContracts}/CancelAdscContractCommand.cs (75%) rename source/CPDLCServer/{Handlers => AdscContracts}/CancelAdscContractCommandHandler.cs (75%) rename source/CPDLCServer/{Handlers => AdscContracts}/CancelAdscContractOnConnectionEndedHandler.cs (78%) rename source/CPDLCServer/{Messages => AdscContracts}/EndExpiredAdscContractsRequest.cs (72%) rename source/CPDLCServer/{Handlers => AdscContracts}/EndExpiredAdscContractsRequestHandler.cs (72%) rename source/CPDLCServer/{Messages => AdscContracts}/GetAdscContractsRequest.cs (83%) rename source/CPDLCServer/{Handlers => AdscContracts}/GetAdscContractsRequestHandler.cs (83%) rename source/CPDLCServer/{Persistence => AdscContracts}/IAdscContractRepository.cs (88%) rename source/CPDLCServer/{Model => AdscContracts/MessageLog}/AdscMessageLogEntry.cs (79%) rename source/CPDLCServer/{Persistence => AdscContracts/MessageLog}/IAdscMessageLogRepository.cs (83%) rename source/CPDLCServer/{Persistence => AdscContracts/MessageLog}/InMemoryAdscMessageLogRepository.cs (93%) create mode 100644 source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequest.cs create mode 100644 source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs rename source/CPDLCServer/{Model => AdscContracts}/ReceivedAdscMessage.cs (87%) rename source/CPDLCServer/{Model => AdscContracts/Reports}/AdscReport.cs (80%) rename source/CPDLCServer/{Messages => AdscContracts/Reports}/AdscReportReceivedNotification.cs (75%) rename source/CPDLCServer/{Handlers => AdscContracts/Reports}/AdscReportReceivedNotificationHandler.cs (86%) create mode 100644 source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs rename source/CPDLCServer/{Model => AdscContracts/Reports}/AdscReportSource.cs (83%) create mode 100644 source/CPDLCServer/AdscContracts/Reports/AircraftAdscReport.cs create mode 100644 source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs rename source/CPDLCServer/{Messages => AdscContracts/Reports}/GetAdscReportsRequest.cs (79%) rename source/CPDLCServer/{Handlers => AdscContracts/Reports}/GetAdscReportsRequestHandler.cs (73%) create mode 100644 source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs rename source/CPDLCServer/{Messages => AdscContracts/Reports}/RequestAdscDemandReportCommand.cs (73%) rename source/CPDLCServer/{Handlers => AdscContracts/Reports}/RequestAdscDemandReportCommandHandler.cs (77%) rename source/CPDLCServer/{Handlers => AdscContracts}/RequestAdscContractOnConnectionEstablishedHandler.cs (94%) rename source/CPDLCServer/{Messages => AdscContracts}/RequestDefaultAdscContractCommand.cs (77%) rename source/CPDLCServer/{Handlers => AdscContracts}/RequestDefaultAdscContractCommandHandler.cs (72%) rename source/CPDLCServer/{Messages => AdscContracts}/RequestSelectedAdscContractCommand.cs (81%) rename source/CPDLCServer/{Handlers => AdscContracts}/RequestSelectedAdscContractCommandHandler.cs (77%) create mode 100644 source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs create mode 100644 source/CPDLCServer/Auth/Login/AdminAuthentication.cs create mode 100644 source/CPDLCServer/Auth/Login/ClientIpAddress.cs create mode 100644 source/CPDLCServer/Auth/Login/LoginCommand.cs create mode 100644 source/CPDLCServer/Auth/Login/LoginCommandHandler.cs create mode 100644 source/CPDLCServer/Auth/Login/LoginLockout.cs create mode 100644 source/CPDLCServer/Auth/Login/PasswordRateLimit.cs create mode 100644 source/CPDLCServer/Auth/Users/ChangePasswordCommand.cs create mode 100644 source/CPDLCServer/Auth/Users/ChangePasswordCommandHandler.cs create mode 100644 source/CPDLCServer/Auth/Users/CreateUserCommand.cs create mode 100644 source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs create mode 100644 source/CPDLCServer/Auth/Users/IUserRepository.cs create mode 100644 source/CPDLCServer/Auth/Users/User.cs create mode 100644 source/CPDLCServer/Auth/Users/UserConfiguration.cs create mode 100644 source/CPDLCServer/Auth/Users/UserRepository.cs delete mode 100644 source/CPDLCServer/Clients/ClientManager.cs rename source/CPDLCServer/{Messages => Controllers}/ControllerConnectedNotification.cs (78%) rename source/CPDLCServer/{Handlers => Controllers}/ControllerConnectedNotificationHandler.cs (76%) rename source/CPDLCServer/{Messages => Controllers}/ControllerDisconnectedNotification.cs (76%) rename source/CPDLCServer/{Handlers => Controllers}/ControllerDisconnectedNotificationHandler.cs (89%) rename source/CPDLCServer/{Model => Controllers}/ControllerInfo.cs (91%) create mode 100644 source/CPDLCServer/Controllers/ControllersServiceCollectionExtensions.cs rename source/CPDLCServer/{Messages => Controllers}/GetConnectedControllersRequest.cs (86%) rename source/CPDLCServer/{Handlers => Controllers}/GetConnectedControllersRequestHandler.cs (88%) rename source/CPDLCServer/{Persistence => Controllers}/IControllerRepository.cs (86%) rename source/CPDLCServer/{Persistence => Controllers}/InMemoryControllerRepository.cs (93%) rename source/CPDLCServer/{Model => Cpdlc/Connections}/AircraftConnection.cs (94%) create mode 100644 source/CPDLCServer/Cpdlc/Connections/AircraftConnectionConfiguration.cs rename source/CPDLCServer/{Messages => Cpdlc/Connections}/AircraftConnectionEstablished.cs (67%) rename source/CPDLCServer/{Handlers => Cpdlc/Connections}/AircraftConnectionEstablishedNotificationHandler.cs (78%) rename source/CPDLCServer/{Messages => Cpdlc/Connections}/AircraftConnectionLost.cs (57%) rename source/CPDLCServer/{Handlers => Cpdlc/Connections}/AircraftConnectionLostNotificationHandler.cs (86%) rename source/CPDLCServer/{Messages => Cpdlc/Connections}/AircraftConnectionTerminated.cs (63%) rename source/CPDLCServer/{Handlers => Cpdlc/Connections}/AircraftConnectionTerminatedNotificationHandler.cs (77%) create mode 100644 source/CPDLCServer/Cpdlc/Connections/AircraftRepository.cs rename source/CPDLCServer/{Messages => Cpdlc/Connections}/CheckLostAircraftConnectionsRequest.cs (72%) rename source/CPDLCServer/{Handlers => Cpdlc/Connections}/CheckLostAircraftConnectionsRequestHandler.cs (67%) rename source/CPDLCServer/{Model => Cpdlc/Connections}/ConnectionState.cs (59%) rename source/CPDLCServer/{Model => Cpdlc/Connections}/DataAuthorityState.cs (66%) rename source/CPDLCServer/{Messages => Cpdlc/Connections}/GetConnectedAircraftRequest.cs (83%) rename source/CPDLCServer/{Handlers => Cpdlc/Connections}/GetConnectedAircraftRequestHandler.cs (86%) rename source/CPDLCServer/{Persistence => Cpdlc/Connections}/IAircraftRepository.cs (76%) rename source/CPDLCServer/{Messages => Cpdlc/Connections}/LogonCommand.cs (63%) rename source/CPDLCServer/{Handlers => Cpdlc/Connections}/LogonCommandHandler.cs (66%) rename source/CPDLCServer/{Services => Cpdlc/Connections}/LostConnectionService.cs (64%) rename source/CPDLCServer/{Services => Cpdlc/Connections}/NdaUplinkService.cs (90%) rename source/CPDLCServer/{Messages => Cpdlc/Connections}/SendConnectionRequestCommand.cs (74%) create mode 100644 source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommandHandler.cs rename source/CPDLCServer/{Handlers => Cpdlc/Connections}/TerminateConnectionHandler.cs (89%) rename source/CPDLCServer/{Handlers => Cpdlc/Connections}/TerminateConnectionOnDialogueClosedHandler.cs (90%) create mode 100644 source/CPDLCServer/Cpdlc/Connections/TerminateConnectionRequest.cs rename source/CPDLCServer/{Messages => Cpdlc/Connections}/TransmitPendingNdaUplinksCommand.cs (64%) rename source/CPDLCServer/{Handlers => Cpdlc/Connections}/TransmitPendingNdaUplinksCommandHandler.cs (86%) rename source/CPDLCServer/{Messages => Cpdlc/Connections}/UpdateNextDataAuthorityCommand.cs (82%) rename source/CPDLCServer/{Handlers => Cpdlc/Connections}/UpdateNextDataAuthorityCommandHandler.cs (94%) create mode 100644 source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs rename source/CPDLCServer/{Model => Cpdlc/Dialogues}/AlertType.cs (62%) create mode 100644 source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequest.cs create mode 100644 source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandler.cs rename source/CPDLCServer/{Messages => Cpdlc/Dialogues}/ArchiveDialogueCommand.cs (68%) rename source/CPDLCServer/{Handlers => Cpdlc/Dialogues}/ArchiveDialogueCommandHandler.cs (91%) create mode 100644 source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequest.cs create mode 100644 source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandler.cs rename source/CPDLCServer/{Model => Cpdlc/Dialogues}/ControlMessages.cs (84%) create mode 100644 source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessage.cs create mode 100644 source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessageConfiguration.cs rename source/CPDLCServer/{Model => Cpdlc/Dialogues}/Dialogue.cs (82%) rename source/CPDLCServer/{Messages => Cpdlc/Dialogues}/DialogueChangedNotification.cs (62%) rename source/CPDLCServer/{Handlers => Cpdlc/Dialogues}/DialogueChangedNotificationHandler.cs (84%) create mode 100644 source/CPDLCServer/Cpdlc/Dialogues/DialogueConfiguration.cs rename source/CPDLCServer/{Model => Cpdlc/Dialogues}/DialogueConverter.cs (68%) create mode 100644 source/CPDLCServer/Cpdlc/Dialogues/DialogueRepository.cs rename source/CPDLCServer/{Persistence => Cpdlc/Dialogues}/IDialogueRepository.cs (63%) create mode 100644 source/CPDLCServer/Cpdlc/Dialogues/MessageMonitorService.cs create mode 100644 source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequest.cs create mode 100644 source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs rename source/CPDLCServer/{Messages => Cpdlc/Downlinks}/AcknowledgeDownlinkCommand.cs (73%) rename source/CPDLCServer/{Handlers => Cpdlc/Downlinks}/AcknowledgeDownlinkCommandHandler.cs (90%) rename source/CPDLCServer/{Model => Cpdlc/Downlinks}/CpdlcDownlinkResponseType.cs (66%) create mode 100644 source/CPDLCServer/Cpdlc/Downlinks/DownlinkMessage.cs rename source/CPDLCServer/{Messages => Cpdlc/Downlinks}/DownlinkReceivedNotification.cs (61%) rename source/CPDLCServer/{Handlers => Cpdlc/Downlinks}/DownlinkReceivedNotificationHandler.cs (88%) rename source/CPDLCServer/{Model => Cpdlc/Downlinks}/ReceivedDownlink.cs (80%) rename source/CPDLCServer/{Messages => Cpdlc/Uplinks}/AcknowledgeUplinkCommand.cs (73%) rename source/CPDLCServer/{Handlers => Cpdlc/Uplinks}/AcknowledgeUplinkCommandHandler.cs (93%) rename source/CPDLCServer/{Messages => Cpdlc/Uplinks}/BeginDialogueCommand.cs (75%) rename source/CPDLCServer/{Handlers => Cpdlc/Uplinks}/BeginDialogueCommandHandler.cs (74%) rename source/CPDLCServer/{Model => Cpdlc/Uplinks}/CpdlcUplinkResponseType.cs (74%) create mode 100644 source/CPDLCServer/Cpdlc/Uplinks/MessageIdProvider.cs create mode 100644 source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequence.cs create mode 100644 source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequenceConfiguration.cs rename source/CPDLCServer/{Messages => Cpdlc/Uplinks}/ReplyToDownlinkCommand.cs (77%) rename source/CPDLCServer/{Handlers => Cpdlc/Uplinks}/ReplyToDownlinkCommandHandler.cs (76%) create mode 100644 source/CPDLCServer/Cpdlc/Uplinks/UplinkMessage.cs delete mode 100644 source/CPDLCServer/Exceptions/ConfigurationNotFoundException.cs delete mode 100644 source/CPDLCServer/Handlers/SendConnectionRequestCommandHandler.cs delete mode 100644 source/CPDLCServer/Infrastructure/ApiKeyHasher.cs create mode 100644 source/CPDLCServer/Infrastructure/ConfigurationExtensionMethods.cs create mode 100644 source/CPDLCServer/Infrastructure/InfrastructureServiceCollectionExtensions.cs rename source/CPDLCServer/{Extensions => Infrastructure}/SemaphoreSlimExtensionMethods.cs (92%) create mode 100644 source/CPDLCServer/Infrastructure/ServerStartTime.cs create mode 100644 source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs create mode 100644 source/CPDLCServer/Logging/LogBuffer.cs create mode 100644 source/CPDLCServer/Logging/LogBufferSink.cs create mode 100644 source/CPDLCServer/Logging/LogEntry.cs create mode 100644 source/CPDLCServer/Logging/LogStreamEndpoint.cs delete mode 100644 source/CPDLCServer/Messages/RefreshAcarsCallsignsRequest.cs delete mode 100644 source/CPDLCServer/Messages/TerminateConnectionRequest.cs delete mode 100644 source/CPDLCServer/Model/AircraftAdscReport.cs delete mode 100644 source/CPDLCServer/Model/DownlinkMessage.cs delete mode 100644 source/CPDLCServer/Model/ICpdlcMessage.cs delete mode 100644 source/CPDLCServer/Model/UplinkMessage.cs delete mode 100644 source/CPDLCServer/Pages/Connections/Index.cshtml delete mode 100644 source/CPDLCServer/Pages/Connections/Index.cshtml.cs delete mode 100644 source/CPDLCServer/Pages/Index.cshtml delete mode 100644 source/CPDLCServer/Pages/Index.cshtml.cs delete mode 100644 source/CPDLCServer/Pages/Messages/Index.cshtml delete mode 100644 source/CPDLCServer/Pages/Messages/Index.cshtml.cs delete mode 100644 source/CPDLCServer/Pages/ViewModels/MessageRowViewModel.cs create mode 100644 source/CPDLCServer/Persistence/CpdlcDbContext.cs create mode 100644 source/CPDLCServer/Persistence/DatabaseProvider.cs delete mode 100644 source/CPDLCServer/Persistence/IAdscReportRepository.cs delete mode 100644 source/CPDLCServer/Persistence/InMemoryAdscContractRepository.cs delete mode 100644 source/CPDLCServer/Persistence/InMemoryAdscReportRepository.cs delete mode 100644 source/CPDLCServer/Persistence/InMemoryAircraftRepository.cs delete mode 100644 source/CPDLCServer/Persistence/InMemoryDialogueRepository.cs create mode 100644 source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.Designer.cs create mode 100644 source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.cs create mode 100644 source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs create mode 100644 source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.Designer.cs create mode 100644 source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.cs create mode 100644 source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs create mode 100644 source/CPDLCServer/Persistence/PersistenceServiceCollectionExtensions.cs create mode 100644 source/CPDLCServer/Persistence/PostgreSqlConnectionString.cs create mode 100644 source/CPDLCServer/Persistence/PostgreSqlCpdlcDbContext.cs create mode 100644 source/CPDLCServer/Persistence/SqliteCpdlcDbContext.cs create mode 100644 source/CPDLCServer/Persistence/UnitOfWork.cs create mode 100644 source/CPDLCServer/Persistence/UtcTicksConverter.cs create mode 100644 source/CPDLCServer/Security/MasterKeyEncryption.cs create mode 100644 source/CPDLCServer/Security/SecurityServiceCollectionExtensions.cs delete mode 100644 source/CPDLCServer/Services/IStatisticsService.cs delete mode 100644 source/CPDLCServer/Services/MessageIdProvider.cs delete mode 100644 source/CPDLCServer/Services/MessageMonitorService.cs delete mode 100644 source/CPDLCServer/Services/VatsimStatusConfiguration.cs create mode 100644 source/CPDLCServer/Settings/GetServerSettingsRequest.cs create mode 100644 source/CPDLCServer/Settings/GetServerSettingsRequestHandler.cs create mode 100644 source/CPDLCServer/Settings/SaveServerSettingsCommand.cs create mode 100644 source/CPDLCServer/Settings/SaveServerSettingsCommandHandler.cs create mode 100644 source/CPDLCServer/Settings/ServerSettings.cs create mode 100644 source/CPDLCServer/Settings/ServerSettingsConfiguration.cs create mode 100644 source/CPDLCServer/Settings/ServerSettingsProvider.cs create mode 100644 source/CPDLCServer/Settings/SettingsServiceCollectionExtensions.cs create mode 100644 source/CPDLCServer/Setup/RedirectToSetupMiddleware.cs create mode 100644 source/CPDLCServer/Setup/SetupServiceCollectionExtensions.cs create mode 100644 source/CPDLCServer/Setup/SetupState.cs rename source/CPDLCServer/{Persistence => VatsimStatus}/IVatsimPilotRepository.cs (83%) rename source/CPDLCServer/{Persistence => VatsimStatus}/InMemoryVatsimPilotRepository.cs (90%) rename source/CPDLCServer/{Messages => VatsimStatus}/ProduceVatsimAdscReportsRequest.cs (80%) rename source/CPDLCServer/{Handlers => VatsimStatus}/ProduceVatsimAdscReportsRequestHandler.cs (86%) rename source/CPDLCServer/{Model => VatsimStatus}/VatsimPilot.cs (96%) rename source/CPDLCServer/{Services => VatsimStatus}/VatsimStatusService.cs (78%) create mode 100644 source/CPDLCServer/VatsimStatus/VatsimStatusServiceCollectionExtensions.cs rename source/CPDLCServer/{Hubs => Web}/ControllerHub.cs (92%) create mode 100644 source/CPDLCServer/Web/Pages/Account/Login.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Account/Logout.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Account/Logout.cshtml.cs rename source/CPDLCServer/{ => Web}/Pages/Adsc/Index.cshtml (97%) rename source/CPDLCServer/{ => Web}/Pages/Adsc/Index.cshtml.cs (89%) rename source/CPDLCServer/{ => Web}/Pages/Atsu/Index.cshtml (92%) rename source/CPDLCServer/{ => Web}/Pages/Atsu/Index.cshtml.cs (86%) rename source/CPDLCServer/{ => Web}/Pages/Dialogue/Index.cshtml (93%) rename source/CPDLCServer/{ => Web}/Pages/Dialogue/Index.cshtml.cs (78%) create mode 100644 source/CPDLCServer/Web/Pages/Index.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Index.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Logs/Index.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Logs/Index.cshtml.cs rename source/CPDLCServer/{ => Web}/Pages/Pilot/Index.cshtml (87%) rename source/CPDLCServer/{ => Web}/Pages/Pilot/Index.cshtml.cs (83%) create mode 100644 source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Settings/Index.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Settings/Index.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Settings/_SettingsLayout.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Settings/_ViewStart.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Setup/Index.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs rename source/CPDLCServer/{ => Web}/Pages/Shared/_Layout.cshtml (63%) rename source/CPDLCServer/{ => Web}/Pages/Shared/_MessageTable.cshtml (95%) create mode 100644 source/CPDLCServer/Web/Pages/ViewModels/MessageRowViewModel.cs rename source/CPDLCServer/{ => Web}/Pages/_ViewImports.cshtml (61%) rename source/CPDLCServer/{ => Web}/Pages/_ViewStart.cshtml (100%) create mode 100644 source/CPDLCServer/Web/WebServiceCollectionExtensions.cs diff --git a/.do/deploy.template.yaml b/.do/deploy.template.yaml index 2a39445..2e8e5d7 100644 --- a/.do/deploy.template.yaml +++ b/.do/deploy.template.yaml @@ -1,5 +1,10 @@ spec: name: cpdlc-server + # App Platform has no persistent disk, so the server keeps its data in a PostgreSQL database + databases: + - name: db + engine: PG + production: false services: - name: cpdlc-server instance_count: 1 @@ -13,16 +18,15 @@ spec: envs: - key: Logging__Level value: Information - - key: Acars__0__Type - value: Hoppie - - key: Acars__0__FlightSimulationNetwork - value: VATSIM - - key: Acars__0__StationIdentifier - value: CHANGE_ME - - key: Acars__0__Url - value: http://www.hoppie.nl/acars/system/connect.html - - key: Acars__0__AuthenticationCode - value: CHANGE_ME + - key: DatabaseProvider + value: PostgreSql + - key: DatabaseConnectionString + scope: RUN_TIME + value: ${db.DATABASE_URL} + # You must set the master key before you deploy. Without it, the server does not start. + # Make a key with: openssl rand -base64 32 + # Keep a copy of the key in a safe place. If the key changes, you must enter the ACARS authentication codes again. + - key: MasterKey + scope: RUN_TIME type: SECRET - - key: Handoff__NotificationLeadTime - value: "10" + value: "" diff --git a/.fallout/build.schema.json b/.fallout/build.schema.json index a4dd618..45a5342 100644 --- a/.fallout/build.schema.json +++ b/.fallout/build.schema.json @@ -24,6 +24,7 @@ "ExecutableTarget": { "type": "string", "enum": [ + "AddMigration", "CheckVersion", "CompilePlugin", "CompileServer", @@ -131,6 +132,10 @@ "description": "GitHub token for creating releases", "default": "Secrets must be entered via 'fallout :secrets [profile]'" }, + "MigrationName": { + "type": "string", + "description": "Name of the migration to add" + }, "ProfileName": { "type": "string" }, diff --git a/.gitignore b/.gitignore index 1719b69..e67900b 100644 --- a/.gitignore +++ b/.gitignore @@ -149,4 +149,7 @@ npm-debug.log # Database *.db* -/logs \ No newline at end of file +/logs + +# Local SQLite database of the CPDLC server +.data/ diff --git a/README.md b/README.md index 20f54a0..6512d98 100644 --- a/README.md +++ b/README.md @@ -26,9 +26,7 @@ Deploy your own CPDLC Server instance: [![Deploy to DigitalOcean](https://www.deploytodo.com/do-btn-blue.svg)](https://cloud.digitalocean.com/apps/new?repo=https://github.com/YuKitsune/CPDLCPlugin/tree/main) -After deployment, configure the following environment variables: -- `Acars__0__StationIdentifier`: Your station identifier (e.g., YZZZ) -- `Acars__0__AuthenticationCode`: Your Hoppie ACARS authentication code +Before you deploy, set the `MasterKey` environment variable to a key from `openssl rand -base64 32`, and keep a copy of the key in a safe place. After deployment, open the setup URL from the server log to create the administrator. Then add your ACARS connection (station identifier and Hoppie authentication code) in Settings → ACARS on the server dashboard (`/settings/acars`). ## Installation diff --git a/build/Build.cs b/build/Build.cs index fa9e694..fd3083c 100644 --- a/build/Build.cs +++ b/build/Build.cs @@ -57,6 +57,9 @@ class Build : FalloutBuild [Parameter("Output directory for server build")] readonly string ServerOutputDirectory; + [Parameter("Name of the migration to add")] + readonly string MigrationName; + [GitRepository] readonly GitRepository GitRepository; @@ -372,6 +375,22 @@ class Build : FalloutBuild Log.Information("Server published to {OutputDirectory}", ServerBuildOutputDirectory); }); + Target AddMigration => _ => _ + .Description("Adds an EF Core migration for each database provider of the server (SQLite and PostgreSQL).") + .Requires(() => MigrationName) + .Executes(() => + { + AddServerMigration("SqliteCpdlcDbContext", "Persistence/Migrations/Sqlite"); + AddServerMigration("PostgreSqlCpdlcDbContext", "Persistence/Migrations/PostgreSql"); + + void AddServerMigration(string context, string outputDirectory) + { + Log.Information("Adding migration {MigrationName} for {Context}", MigrationName, context); + DotNetTasks.DotNet( + $"ef migrations add {MigrationName} --project {ServerProjectPath} --context {context} --output-dir {outputDirectory}"); + } + }); + Target PackageServer => _ => _ .Description("Bundles the server into a zip archive.") .DependsOn(CompileServer) diff --git a/docker-compose.yml b/docker-compose.yml index 1d971be..2fd8761 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,8 +12,36 @@ services: dockerfile: source/CPDLCServer/Dockerfile env_file: - .env + environment: + DataPath: /data + # Used only when DatabaseProvider=PostgreSql. In the container, the database is at the postgres service. + DatabaseConnectionString: Host=postgres;Port=5432;Database=cpdlc;Username=cpdlc;Password=cpdlc + depends_on: + postgres: + condition: service_healthy + required: false ports: - "8080:8080" + volumes: + - server-data:/data + + # A PostgreSQL server for local development. Start it with: docker compose --profile postgres up + postgres: + profiles: [postgres] + image: postgres:17-alpine + environment: + POSTGRES_DB: cpdlc + POSTGRES_USER: cpdlc + POSTGRES_PASSWORD: cpdlc + ports: + - "127.0.0.1:5432:5432" + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U cpdlc -d cpdlc"] + interval: 5s + timeout: 5s + retries: 10 ngrok: profiles: [ngrok] @@ -25,3 +53,7 @@ services: - .env ports: - 4040:4040 + +volumes: + server-data: + postgres-data: diff --git a/docs/docs/server/index.md b/docs/docs/server/index.md index ccc633f..a9a35c9 100644 --- a/docs/docs/server/index.md +++ b/docs/docs/server/index.md @@ -19,9 +19,15 @@ Deploy your own CPDLC Server instance to DigitalOcean: [![Deploy to DigitalOcean](https://www.deploytodo.com/do-btn-blue.svg)](https://cloud.digitalocean.com/apps/new?repo=https://github.com/YuKitsune/CPDLCPlugin/tree/main) -After deployment, configure the following environment variables in the DigitalOcean dashboard: -- `Acars__0__StationIdentifier`: Your station identifier (e.g., YBBB) -- `Acars__0__AuthenticationCode`: Your Hoppie ACARS authentication code +Since App Platform doesn't offer persistent disks, the template makes a PostgreSQL development database for the server data. + +:::warning +You must set the `MasterKey` environment variable before you deploy. If `MasterKey` is not set, the server does not start. + +Make a key with `openssl rand -base64 32`, and keep a copy in a safe place. +::: + +After deployment, open the setup URL from the server log (see [Setup](#setup)). Then add your ACARS connection in Settings → ACARS on the server dashboard (`/settings/acars`). ## Prerequisites @@ -31,86 +37,99 @@ Before running the CPDLC Server, ensure you have: - [Docker](https://www.docker.com/get-started) (for Docker deployment) - A Hoppies ACARS account and logon code from [hoppie.nl](https://www.hoppie.nl/acars/system/register.html) +## Setup + +When the server starts for the first time, it is not set up. All the pages of the dashboard will redirect to the setup page. The server will write the setup URL to the log: + +``` +[12:00:00 WRN] The server is not set up. Open http://localhost:8080/setup?token=... to set it up +``` + +### Master Key + +The master key encrypts the secrets in the database, for example the authentication codes of the ACARS connections. Set it in the `MasterKey` environment variable before the first start. You can make a key with `openssl rand -base64 32`, and keep a copy in a safe place. + +If `MasterKey` is not set, or the key is not valid, the server does not start. + +If the key is lost, the server cannot decrypt the secrets. + ## Configuration -The server can be configured using environment variables. -Copy `example.env` to `.env` and update with your settings: +The logging level, the master key, the data directory and the database are configured with environment variables. Only `MasterKey` is required. +For local development, copy `example.env` to `.env` and update with your settings: ```bash # Logging Logging__Level=Information -# ACARS Client Configuration -Acars__0__Type=Hoppie -Acars__0__FlightSimulationNetwork=VATSIM -Acars__0__StationIdentifier=YBBB -Acars__0__Url=http://www.hoppie.nl/acars/system/connect.html -Acars__0__AuthenticationCode=your-hoppie-logon-code -# Reporting interval in minutes of the ADS-C contract requested on CPDLC logon (default: 10) -Acars__0__DefaultAdscReportingInterval=10 -# Minutes from the request of a selected ADS-C contract to its end. Then the default contract is requested again (default: 60) -Acars__0__SelectedAdscContractDuration=60 - -# Handoff Configuration -# How many minutes before the expected transfer time to send the NEXT DATA AUTHORITY message (default: 10) -Handoff__NotificationLeadTime=10 - -# ADS-C from VATSIM status data -# Make ADS-C reports from the VATSIM status data for aircraft that do not support ADS-C over Hoppie (default: false) -VatsimStatus__Enabled=false -# The URL of the VATSIM status data (default: https://data.vatsim.net/v3/vatsim-data.json) -VatsimStatus__Url=https://data.vatsim.net/v3/vatsim-data.json -# The time in seconds between downloads of the VATSIM status data (default: 120) -VatsimStatus__PollingIntervalSeconds=120 -# Also make reports for aircraft that do not have D1 or G1 in Item 10b of the flight plan (default: false) -VatsimStatus__AllowNonEquippedAircraft=false +# Master Key (required) +# Encrypts the secrets in the database. Make a key with: openssl rand -base64 32 +MasterKey=your-master-key + +# Data Directory +# The directory of the SQLite database (cpdlc.db) (default: /data) +DataPath=/data + +# Database Configuration +# The database provider: Sqlite or PostgreSql (default: Sqlite) +DatabaseProvider=Sqlite +# PostgreSQL: the connection string. A URL (postgresql://...) is also accepted. +# DatabaseConnectionString=Host=localhost;Database=cpdlc;Username=cpdlc;Password=your-password ``` -### Multiple ACARS Connections +### Persistence -You can configure multiple ACARS clients by incrementing the index (`Acars__1__`, `Acars__2__`, etc.). This is useful when serving multiple ATSUs (e.g., YBBB and YMMM) +The server keeps the CPDLC connections, the dialogues, the ADS-C contracts, the ADS-C reports, settings, and the ACARS connections in a database. -Example configuration for multiple connections: +The server can use SQLite or PostgreSQL (`DatabaseProvider`): -```bash -# Brisbane FIR -Acars__0__Type=Hoppie -Acars__0__FlightSimulationNetwork=VATSIM -Acars__0__StationIdentifier=YBBB -Acars__0__Url=http://www.hoppie.nl/acars/system/connect.html -Acars__0__AuthenticationCode=your-ybbb-hoppie-code - -# Melbourne FIR -Acars__1__Type=Hoppie -Acars__1__FlightSimulationNetwork=VATSIM -Acars__1__StationIdentifier=YMMM -Acars__1__Url=http://www.hoppie.nl/acars/system/connect.html -Acars__1__AuthenticationCode=your-ymmm-hoppie-code -``` +- **SQLite** (default): the database is the file `cpdlc.db` in the data directory (`DataPath`). In the Docker image, the data directory is the `/data` volume. For local development, it is the `.data` directory at the root of the repository. +- **PostgreSQL**: set `DatabaseConnectionString`. Use PostgreSQL when the platform has no persistent disk, for example DigitalOcean App Platform. + +The server applies the migrations when it starts. With SQLite, it also makes the database file. + +The server deletes dialogues 24 hours after they open. It deletes ADS-C reports after the configured ADS-C report retention period. These periods start when the dialogue opens or the report is received, not when the server starts. Thus, after a restart, the server immediately deletes the data that is older than the period. + +### ACARS Connections + +The ACARS connections connect the server to the upstream ACARS networks. Add, change and delete them in Settings → ACARS on the dashboard (`/settings/acars`). + +- When you add a connection, the server connects to the ACARS network. +- When you change a connection, the server will reconnect to the upstream ACARS network with the new settings. + +You can add more than one connection, for example when the server serves more than one ATSU (YBBB and YMMM). Only one connection can use a station identifier. + +The server keeps the authentication code of each connection encrypted with the master key (`MasterKey`). The dashboard does not show the code. If the master key changes, the server cannot decrypt the codes, and you must enter them again. :::note `Hoppie` is currently the only supported ACARS network type. ::: +### Logs + +The Logs page of the dashboard (`/logs`) shows the live log of the server, with the same text and level colours as the console output. + +You can show only the entries at or above a level, pause the log, and clear the page. The logging level of the server (`Logging__Level`) sets which entries the server writes. + ### ADS-C When an aircraft logs on with CPDLC, the server requests the default ADS-C contract with the aircraft. When the CPDLC connection ends, the server cancels the contract. -Each ATSU has its own default reporting interval, set with `Acars____DefaultAdscReportingInterval`. Controllers can read this value. +Each ATSU has its own default reporting interval, set on its ACARS connection. Controllers can read this value. -A controller can select a different reporting interval for an aircraft. The selected contract ends `Acars____SelectedAdscContractDuration` minutes after the server sends the request. Then the server requests the default contract again. A controller can also go back to the default contract at any time. +A controller can select a different reporting interval for an aircraft. The selected contract ends after the selected ADS-C contract duration of the ACARS connection. Then the server requests the default contract again. A controller can also go back to the default contract at any time. The aircraft does not acknowledge a request. The first report after a request accepts it. If the aircraft rejects a selected contract, the server requests the default contract again. If the aircraft rejects the default contract, the server does not send it again. -The server keeps the latest report for each aircraft. When a controller connects, the plugin loads these reports, so that the controller sees the ADS-C tracks immediately. +The server keeps a history of the reports for the ADS-C report retention period. When a controller connects, the plugin loads the latest report for each aircraft, so that the controller sees the ADS-C tracks immediately. The ADS-C page of the dashboard (`/adsc`) shows all the contracts and their states, and a log of all the ADS-C messages that the server sent and received. ### ADS-C from VATSIM Status Data -Not all aircraft support ADS-C over Hoppie's network. When `VatsimStatus__Enabled` is `true`, the server fakes ADS-C reports using data from the [VATSIM status API](https://data.vatsim.net/v3/vatsim-data.json). +Not all aircraft support ADS-C over Hoppie's network. When the "ADS-C from VATSIM status data" setting is on, the server fakes ADS-C reports using data from the [VATSIM status API](https://data.vatsim.net/v3/vatsim-data.json). -This is only done for aircraft that have `D1` or `G1` in Item 10b of the flight plan, unless `VatsimStatus__AllowNonEquippedAircraft` is `true`. A report from Hoppie always has priority. If the Hoppie reports stop for more than two reporting intervals, the server uses the VATSIM status data again. +This is only done for aircraft that have `D1` or `G1` in Item 10b of the flight plan, unless the "allow aircraft without ADS-C equipment" setting is on. A report from Hoppie always has priority. If the Hoppie reports stop for more than two reporting intervals, the server uses the VATSIM status data again. ## Running diff --git a/example.env b/example.env index 284a1f4..c677f8f 100644 --- a/example.env +++ b/example.env @@ -4,45 +4,23 @@ ASPNETCORE_ENVIRONMENT=Development # Logging Configuration Logging__Level=Debug -# ACARS Network Configuration -# Multiple configurations can be added by incrementing the index (0, 1, 2, etc.) - -# First ACARS Configuration -Acars__0__Type=Hoppie -Acars__0__FlightSimulationNetwork=VATSIM -Acars__0__StationIdentifier=YBBB -Acars__0__Url=http://www.hoppie.nl/acars/system/connect.html -Acars__0__AuthenticationCode=your-authentication-code-here -# Reporting interval in minutes of the ADS-C contract requested on CPDLC logon (default: 10) -Acars__0__DefaultAdscReportingInterval=10 -# Minutes from the request of a selected ADS-C contract to its end. Then the default contract is requested again (default: 60) -Acars__0__SelectedAdscContractDuration=60 - -# Example: Second ACARS Configuration (uncomment to use) -# Acars__1__Type=Hoppie -# Acars__1__FlightSimulationNetwork=IVAO -# Acars__1__StationIdentifier=KJFK -# Acars__1__Url=http://www.hoppie.nl/acars/system/connect.html -# Acars__1__AuthenticationCode=your-other-authentication-code - -# Connection Monitoring Configuration -# The time in minutes between checks of the connected callsigns on the ACARS network (default: 15) -ConnectivityCheckIntervalMinutes=15 -# The time (hh:mm:ss) without contact from an aircraft before its connection times out (default: 3 times ConnectivityCheckIntervalMinutes) -# Use a value of more than 2 times ConnectivityCheckIntervalMinutes. If not, one failed check will cause connections to time out. -AircraftConnectionTimeout=00:45:00 - -# Handoff Configuration -# How many minutes before the expected transfer time to send the NEXT DATA AUTHORITY message (default: 20) -Handoff__NotificationLeadTime=20 - -# ADS-C from VATSIM status data -# Make ADS-C reports from the VATSIM status data for aircraft that do not support ADS-C over Hoppie (default: false) -VatsimStatus__Enabled=false -# The time in seconds between downloads of the VATSIM status data (default: 120) -VatsimStatus__PollingIntervalSeconds=120 -# Also make reports for aircraft that do not have D1 or G1 in Item 10b of the flight plan (default: false) -VatsimStatus__AllowNonEquippedAircraft=false +# Master Key (required) +# Encrypts the secrets in the database, for example the authentication codes of the ACARS connections. +# Make a key with: openssl rand -base64 32 +# Keep the key safe. If the key changes, the server cannot decrypt the secrets, and you must enter them again. +MasterKey=your-master-key-here + +# Data Directory +# The directory of the SQLite database (cpdlc.db). The server makes it if it does not exist. +# (default: .data at the root of the repository in Development, /data in other environments) +# DataPath=/data + +# Database Configuration +# The database provider: Sqlite or PostgreSql (default: Sqlite) +# DatabaseProvider=Sqlite + +# PostgreSQL: the connection string. A URL (postgresql://user:password@host:port/database?sslmode=require) is also accepted. +# DatabaseConnectionString=Host=localhost;Database=cpdlc;Username=cpdlc;Password=your-password # ngrok auth token to allow remote connections to your local debug server # https://ngrok.com/ diff --git a/source/CPDLCServer.Tests/AcarsConnections/ConnectionSettings/AcarsConnectionCommandHandlerTests.cs b/source/CPDLCServer.Tests/AcarsConnections/ConnectionSettings/AcarsConnectionCommandHandlerTests.cs new file mode 100644 index 0000000..4524d7f --- /dev/null +++ b/source/CPDLCServer.Tests/AcarsConnections/ConnectionSettings/AcarsConnectionCommandHandlerTests.cs @@ -0,0 +1,197 @@ +using System.Security.Cryptography; +using CPDLCServer.AcarsConnections.ConnectionSettings; +using CPDLCServer.Security; +using CPDLCServer.Tests.Mocks; +using Microsoft.EntityFrameworkCore; +using Serilog.Core; + +namespace CPDLCServer.Tests.AcarsConnections.ConnectionSettings; + +public sealed class AcarsConnectionCommandHandlerTests : IDisposable +{ + readonly MasterKeyEncryption _masterKeyEncryption = new(Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))); + readonly TestDatabase _database = new(); + readonly TestAcarsConnectionManager _acarsConnectionManager = new(); + + [Fact] + public async Task Create_SavesSettingsWithEncryptedCode_AndStartsConnection() + { + // Arrange + var connection = new AcarsConnectionSettings { StationIdentifier = "ybbb" }; + + // Act + Guid id; + await using (var dbContext = _database.CreateDbContext()) + { + var handler = new CreateAcarsConnectionCommandHandler(dbContext, _masterKeyEncryption, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + id = await handler.Handle(new CreateAcarsConnectionCommand(connection, "LOGON123"), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + var saved = Assert.Single(await AllSettings()); + Assert.Equal(id, saved.Id); + Assert.Equal("YBBB", saved.StationIdentifier); + Assert.NotEqual("LOGON123", saved.EncryptedAuthenticationCode); + Assert.Equal("LOGON123", _masterKeyEncryption.Decrypt(saved.EncryptedAuthenticationCode)); + Assert.Equal([id], _acarsConnectionManager.StartedConnections.Select(s => s.Id)); + } + + [Fact] + public async Task Create_WhenDisabled_DoesNotStartConnection() + { + // Arrange + var connection = new AcarsConnectionSettings { StationIdentifier = "YBBB", Enabled = false }; + + // Act + await using (var dbContext = _database.CreateDbContext()) + { + var handler = new CreateAcarsConnectionCommandHandler(dbContext, _masterKeyEncryption, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + await handler.Handle(new CreateAcarsConnectionCommand(connection, "LOGON123"), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + Assert.Single(await AllSettings()); + Assert.Empty(_acarsConnectionManager.StartedConnections); + } + + [Fact] + public async Task Create_WithoutAuthenticationCode_Throws() + { + // Arrange + await using var dbContext = _database.CreateDbContext(); + var handler = new CreateAcarsConnectionCommandHandler(dbContext, _masterKeyEncryption, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + var connection = new AcarsConnectionSettings { StationIdentifier = "YBBB" }; + + // Act & Assert + await Assert.ThrowsAsync(() => handler.Handle(new CreateAcarsConnectionCommand(connection, null), CancellationToken.None)); + Assert.Empty(dbContext.AcarsConnections.Local); + } + + [Fact] + public async Task Update_StopsThenStartsConnectionWithNewSettings() + { + // Arrange + var id = await AddSettings(enabled: true); + var changes = new AcarsConnectionSettings { StationIdentifier = "YBBB", DefaultAdscReportingInterval = 5, Notes = "Brisbane FIR" }; + + // Act + await Update(id, changes, null); + + // Assert + Assert.Equal([$"Stop {id}", $"Start {id}"], _acarsConnectionManager.StartStopCalls); + var saved = Assert.Single(await AllSettings()); + Assert.Equal(5, saved.DefaultAdscReportingInterval); + Assert.Equal("Brisbane FIR", saved.Notes); + } + + [Fact] + public async Task Update_WhenDisabled_StopsConnection() + { + // Arrange + var id = await AddSettings(enabled: true); + + // Act + await Update(id, new AcarsConnectionSettings { StationIdentifier = "YBBB", Enabled = false }, null); + + // Assert + Assert.Equal([$"Stop {id}"], _acarsConnectionManager.StartStopCalls); + Assert.False(Assert.Single(await AllSettings()).Enabled); + } + + [Fact] + public async Task Update_WithoutAuthenticationCode_KeepsCurrentCode() + { + // Arrange + var id = await AddSettings(enabled: true); + + // Act + await Update(id, new AcarsConnectionSettings { StationIdentifier = "YBBB" }, ""); + + // Assert + var saved = Assert.Single(await AllSettings()); + Assert.Equal("LOGON123", _masterKeyEncryption.Decrypt(saved.EncryptedAuthenticationCode)); + } + + [Fact] + public async Task Update_WithAuthenticationCode_ReplacesCode() + { + // Arrange + var id = await AddSettings(enabled: true); + + // Act + await Update(id, new AcarsConnectionSettings { StationIdentifier = "YBBB" }, "NEWCODE"); + + // Assert + var saved = Assert.Single(await AllSettings()); + Assert.Equal("NEWCODE", _masterKeyEncryption.Decrypt(saved.EncryptedAuthenticationCode)); + } + + [Fact] + public async Task Delete_RemovesSettingsAndStopsConnection() + { + // Arrange + var id = await AddSettings(enabled: true); + + // Act + await using (var dbContext = _database.CreateDbContext()) + { + var handler = new DeleteAcarsConnectionCommandHandler(dbContext, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + await handler.Handle(new DeleteAcarsConnectionCommand(id), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + Assert.Empty(await AllSettings()); + Assert.Equal([id], _acarsConnectionManager.StoppedConnections); + } + + [Fact] + public async Task Delete_WhenNotFound_DoesNothing() + { + // Arrange + await using var dbContext = _database.CreateDbContext(); + var handler = new DeleteAcarsConnectionCommandHandler(dbContext, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new DeleteAcarsConnectionCommand(Guid.NewGuid()), CancellationToken.None); + + // Assert + Assert.Empty(_acarsConnectionManager.StoppedConnections); + } + + async Task Update(Guid id, AcarsConnectionSettings changes, string? authenticationCode) + { + await using var dbContext = _database.CreateDbContext(); + var handler = new UpdateAcarsConnectionCommandHandler(dbContext, _masterKeyEncryption, _acarsConnectionManager, new TestUnitOfWork(), Logger.None); + await handler.Handle(new UpdateAcarsConnectionCommand(id, changes, authenticationCode), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + async Task AddSettings(bool enabled) + { + var settings = new AcarsConnectionSettings + { + Enabled = enabled, + StationIdentifier = "YBBB", + EncryptedAuthenticationCode = _masterKeyEncryption.Encrypt("LOGON123") + }; + + await using var dbContext = _database.CreateDbContext(); + dbContext.AcarsConnections.Add(settings); + await dbContext.SaveChangesAsync(); + return settings.Id; + } + + async Task AllSettings() + { + await using var dbContext = _database.CreateDbContext(); + return await dbContext.AcarsConnections.ToArrayAsync(); + } + + public void Dispose() + { + _database.Dispose(); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/GetAtsuSettingsRequestHandlerTests.cs b/source/CPDLCServer.Tests/AcarsConnections/GetAtsuSettingsRequestHandlerTests.cs similarity index 68% rename from source/CPDLCServer.Tests/Handlers/GetAtsuSettingsRequestHandlerTests.cs rename to source/CPDLCServer.Tests/AcarsConnections/GetAtsuSettingsRequestHandlerTests.cs index 33c3749..5bf3b85 100644 --- a/source/CPDLCServer.Tests/Handlers/GetAtsuSettingsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/AcarsConnections/GetAtsuSettingsRequestHandlerTests.cs @@ -1,8 +1,7 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; +using CPDLCServer.AcarsConnections; using CPDLCServer.Tests.Mocks; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AcarsConnections; public class GetAtsuSettingsRequestHandlerTests { @@ -10,9 +9,9 @@ public class GetAtsuSettingsRequestHandlerTests public async Task Handle_ReturnsSettingsForStation() { // Arrange - var clientManager = new TestClientManager(); - clientManager.AddConfiguration(TestClientManager.CreateConfiguration("NZZO", 27)); - var handler = new GetAtsuSettingsRequestHandler(clientManager); + var acarsConnectionManager = new TestAcarsConnectionManager(); + acarsConnectionManager.AddConfiguration(TestAcarsConnectionManager.CreateConfiguration("NZZO", 27)); + var handler = new GetAtsuSettingsRequestHandler(acarsConnectionManager); // Act var result = await handler.Handle(new GetAtsuSettingsRequest("NZZO"), CancellationToken.None); @@ -26,7 +25,7 @@ public async Task Handle_ReturnsSettingsForStation() public async Task Handle_WhenStationNotConfigured_Throws() { // Arrange - var handler = new GetAtsuSettingsRequestHandler(new TestClientManager()); + var handler = new GetAtsuSettingsRequestHandler(new TestAcarsConnectionManager()); // Act & Assert await Assert.ThrowsAnyAsync(() => diff --git a/source/CPDLCServer.Tests/Clients/HoppieAcarsClientTests.cs b/source/CPDLCServer.Tests/AcarsConnections/Hoppie/HoppieAcarsConnectionTests.cs similarity index 79% rename from source/CPDLCServer.Tests/Clients/HoppieAcarsClientTests.cs rename to source/CPDLCServer.Tests/AcarsConnections/Hoppie/HoppieAcarsConnectionTests.cs index 88db370..6484d73 100644 --- a/source/CPDLCServer.Tests/Clients/HoppieAcarsClientTests.cs +++ b/source/CPDLCServer.Tests/AcarsConnections/Hoppie/HoppieAcarsConnectionTests.cs @@ -1,13 +1,17 @@ using System.Net; -using CPDLCServer.Clients; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AcarsConnections; +using CPDLCServer.AcarsConnections.Hoppie; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using Serilog.Core; -namespace CPDLCServer.Tests.Clients; +namespace CPDLCServer.Tests.AcarsConnections.Hoppie; -public class HoppieAcarsClientTests : IDisposable +public class HoppieAcarsConnectionTests : IDisposable { private readonly HoppiesConfiguration _configuration = new() { @@ -17,16 +21,16 @@ public class HoppieAcarsClientTests : IDisposable StationIdentifier = "YBBB" }; - private readonly List _clients = new(); + private readonly List _connections = new(); private readonly TestAdscMessageLogRepository _adscMessageLogRepository = new(); public void Dispose() { - foreach (var client in _clients) + foreach (var connection in _connections) { try { - client.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(1)); + connection.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(1)); } catch (ObjectDisposedException) { @@ -39,17 +43,17 @@ public void Dispose() } } - private HoppieAcarsClient CreateClient(TestHttpMessageHandler httpHandler, TestClock? clock = null) + private HoppieAcarsConnection CreateConnection(TestHttpMessageHandler httpHandler, TestClock? clock = null) { var httpClient = new HttpClient(httpHandler) { BaseAddress = _configuration.Url }; - var client = new HoppieAcarsClient( + var connection = new HoppieAcarsConnection( _configuration, httpClient, clock ?? new TestClock(), _adscMessageLogRepository, Logger.None); - _clients.Add(client); - return client; + _connections.Add(connection); + return connection; } [Fact] @@ -59,9 +63,9 @@ public async Task Send_CpdlcMessage_FormatsPayloadCorrectly() var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); var message = new UplinkMessage( Guid.NewGuid(), @@ -75,7 +79,7 @@ public async Task Send_CpdlcMessage_FormatsPayloadCorrectly() clock.UtcNow()); // Act - await client.Send(message, CancellationToken.None); + await connection.Send(message, CancellationToken.None); // Assert var sendRequest = httpHandler.Requests.FirstOrDefault(r => @@ -98,9 +102,9 @@ public async Task Send_CpdlcReply_IncludesReplyToId() var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); var reply = new UplinkMessage( Guid.NewGuid(), @@ -114,7 +118,7 @@ public async Task Send_CpdlcReply_IncludesReplyToId() clock.UtcNow()); // Act - await client.Send(reply, CancellationToken.None); + await connection.Send(reply, CancellationToken.None); // Assert var sendRequest = httpHandler.Requests.FirstOrDefault(r => @@ -139,9 +143,9 @@ public async Task Send_CpdlcMessage_MapsResponseTypesCorrectly(CpdlcUplinkRespon var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); var message = new UplinkMessage( Guid.NewGuid(), @@ -155,7 +159,7 @@ public async Task Send_CpdlcMessage_MapsResponseTypesCorrectly(CpdlcUplinkRespon clock.UtcNow()); // Act - await client.Send(message, CancellationToken.None); + await connection.Send(message, CancellationToken.None); // Assert var sendRequest = httpHandler.Requests.FirstOrDefault(r => @@ -168,8 +172,8 @@ public async Task Send_CpdlcMessage_MapsResponseTypesCorrectly(CpdlcUplinkRespon var formData = await ParseFormDataFromRequest(sendRequest); Assert.Equal($"/data2/1//{expectedCode}/TEST", formData["packet"]); - await client.DisposeAsync(); - _clients.Remove(client); + await connection.DisposeAsync(); + _connections.Remove(connection); } [Fact] @@ -179,9 +183,9 @@ public async Task Send_CpdlcMessage_TranslatesContent() var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); var message = new UplinkMessage( Guid.NewGuid(), @@ -195,7 +199,7 @@ public async Task Send_CpdlcMessage_TranslatesContent() clock.UtcNow()); // Act - await client.Send(message, CancellationToken.None); + await connection.Send(message, CancellationToken.None); // Assert var sendRequest = httpHandler.Requests.FirstOrDefault(r => @@ -216,9 +220,9 @@ public async Task Send_CpdlcMessage_UrlEncodesContent() var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); var message = new UplinkMessage( Guid.NewGuid(), @@ -232,7 +236,7 @@ public async Task Send_CpdlcMessage_UrlEncodesContent() clock.UtcNow()); // Act - await client.Send(message, CancellationToken.None); + await connection.Send(message, CancellationToken.None); // Assert var sendRequest = httpHandler.Requests.FirstOrDefault(r => @@ -253,14 +257,14 @@ public async Task Poll_CpdlcMessage_ParsesCorrectly() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 cpdlc {/data2/5//Y/REQUEST DESCENT}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("UAL123", message.Sender); @@ -276,14 +280,14 @@ public async Task Poll_CpdlcReply_ParsesCorrectly() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 cpdlc {/data2/7/3/N/WILCO}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("UAL123", message.Sender); @@ -301,15 +305,15 @@ public async Task Poll_MultipleMessages_ParsesAllCorrectly() var response = "ok {UAL123 cpdlc {/data2/1//Y/REQUEST DESCENT}} {DAL456 cpdlc {/data2/2//Y/REQUEST CLIMB}}"; httpHandler.QueueResponse(HttpStatusCode.OK, response); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message1 = await client.MessageReader.ReadAsync(cts.Token); - var message2 = await client.MessageReader.ReadAsync(cts.Token); + var message1 = await connection.MessageReader.ReadAsync(cts.Token); + var message2 = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("UAL123", message1.Sender); @@ -327,14 +331,14 @@ public async Task Poll_MessageWithSeparator_ParsesCorrectly() var response = "ok {UAL123 cpdlc {/data2/1//Y/REQUEST CLIMB DUE TO A/C PERFORMANCE}}"; httpHandler.QueueResponse(HttpStatusCode.OK, response); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("REQUEST CLIMB DUE TO A/C PERFORMANCE", message.Content); @@ -349,20 +353,20 @@ public async Task Poll_ResponseTypeCodes_MapCorrectly(string code, CpdlcDownlink var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, $"ok {{UAL123 cpdlc {{/data2/1//{code}/TEST}}}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal(expectedType, message.ResponseType); - await client.DisposeAsync(); - _clients.Remove(client); + await connection.DisposeAsync(); + _connections.Remove(connection); } [Fact] @@ -372,20 +376,20 @@ public async Task Poll_WithoutMessageReferenceNumbers_MapsCorrectly() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, $"ok {{UAL123 cpdlc {{/data2///N/LOGOFF}}}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal(-1, message.MessageId); - await client.DisposeAsync(); - _clients.Remove(client); + await connection.DisposeAsync(); + _connections.Remove(connection); } [Fact] @@ -397,14 +401,14 @@ public async Task Poll_Data1PositionReport_ParsesCorrectly() HttpStatusCode.OK, "ok {UAL123 cpdlc {/DATA1/*/*/*/*/FL380/*/0.84/\n\nOVER MEPAB AT 0501Z, FL380,\nESTIMATING ISTEM AT 0533Z,\nNEXT MISLY.\n\nETA AT 0736Z,\n39.60 X 1000 KG FUEL REMAINING.}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.MessageReader.ReadAsync(cts.Token); + var message = await connection.MessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("UAL123", message.Sender); @@ -415,8 +419,8 @@ public async Task Poll_Data1PositionReport_ParsesCorrectly() "OVER MEPAB AT 0501Z, FL380, ESTIMATING ISTEM AT 0533Z, NEXT MISLY. ETA AT 0736Z, 39.60 X 1000 KG FUEL REMAINING.", message.Content); - await client.DisposeAsync(); - _clients.Remove(client); + await connection.DisposeAsync(); + _connections.Remove(connection); } [Fact] @@ -425,10 +429,10 @@ public async Task ListConnections_ReturnsCallsigns() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok {UAL123 DAL456 AAL789}"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - var callsigns = await client.ListConnections(CancellationToken.None); + var callsigns = await connection.ListConnections(CancellationToken.None); // Assert Assert.Equal(3, callsigns.Length); @@ -455,10 +459,10 @@ public async Task ListConnections_EmptyResponse_ReturnsEmptyArray() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - var callsigns = await client.ListConnections(CancellationToken.None); + var callsigns = await connection.ListConnections(CancellationToken.None); // Assert Assert.Empty(callsigns); @@ -470,10 +474,10 @@ public async Task RequestPeriodicAdscContract_FormatsPayloadCorrectly() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.RequestPeriodicAdscContract("UAL123", TimeSpan.FromMinutes(5), CancellationToken.None); + await connection.RequestPeriodicAdscContract("UAL123", TimeSpan.FromMinutes(5), CancellationToken.None); // Assert var formData = await ParseFormDataFromRequest(httpHandler.Requests.Single()); @@ -488,11 +492,11 @@ public async Task RequestPeriodicAdscContract_WhenIntervalIsZero_Throws() { // Arrange var httpHandler = new TestHttpMessageHandler(); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act & Assert await Assert.ThrowsAsync(() => - client.RequestPeriodicAdscContract("UAL123", TimeSpan.Zero, CancellationToken.None)); + connection.RequestPeriodicAdscContract("UAL123", TimeSpan.Zero, CancellationToken.None)); Assert.Empty(httpHandler.Requests); } @@ -502,10 +506,10 @@ public async Task RequestAdscDemandReport_FormatsPayloadCorrectly() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.RequestAdscDemandReport("UAL123", CancellationToken.None); + await connection.RequestAdscDemandReport("UAL123", CancellationToken.None); // Assert var formData = await ParseFormDataFromRequest(httpHandler.Requests.Single()); @@ -520,10 +524,10 @@ public async Task CancelAdscContract_FormatsPayloadCorrectly() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.CancelAdscContract("UAL123", CancellationToken.None); + await connection.CancelAdscContract("UAL123", CancellationToken.None); // Assert var formData = await ParseFormDataFromRequest(httpHandler.Requests.Single()); @@ -541,14 +545,14 @@ public async Task Poll_AdscReport_ParsesBasicGroup() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 ads-c {REPORT UAL123 131155 -33.946100 151.177200 37000}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var reportMessage = Assert.IsType(message); @@ -569,14 +573,14 @@ public async Task Poll_AdscReportWithOptionalGroups_ParsesBasicGroup() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 ads-c {REPORT UAL123 131155 -33.946100 151.177200 37000 045 480 270/35 -56 LVL}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var reportMessage = Assert.IsType(message); @@ -594,14 +598,14 @@ public async Task Poll_AdscReportFromPreviousMonth_ParsesTimestamp() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 ads-c {REPORT UAL123 312359 -33.946100 151.177200 37000}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var reportMessage = Assert.IsType(message); @@ -622,14 +626,14 @@ public async Task Poll_AdscReportPositionFormats_ParsesPosition(string position, var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, $"ok {{UAL123 ads-c {{REPORT UAL123 131155 {position} 37000}}}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var reportMessage = Assert.IsType(message); @@ -650,14 +654,14 @@ public async Task Poll_AdscReportAltitude_ParsesAltitudeInFeet(string altitude, var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, $"ok {{UAL123 ads-c {{REPORT UAL123 131155 -33.946100 151.177200 {altitude}}}}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var reportMessage = Assert.IsType(message); @@ -676,14 +680,14 @@ public async Task Poll_AdscReportWithInvalidPosition_IgnoresReport(string positi var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, $"ok {{UAL123 ads-c {{REPORT UAL123 131155 {position} 37000}}}} {{DAL456 ads-c {{REJECT}}}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var rejection = Assert.IsType(message); @@ -697,14 +701,14 @@ public async Task Poll_AdscReject_ParsesCorrectly() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 ads-c {REJECT}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var message = await client.AdscMessageReader.ReadAsync(cts.Token); + var message = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var rejection = Assert.IsType(message); @@ -718,21 +722,21 @@ public async Task Poll_CpdlcAndAdscMessages_AreWrittenToSeparateReaders() var httpHandler = new TestHttpMessageHandler(); httpHandler.QueueResponse(HttpStatusCode.OK, "ok {UAL123 cpdlc {/data2/5//Y/REQUEST DESCENT}} {DAL456 ads-c {REJECT}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - var downlink = await client.MessageReader.ReadAsync(cts.Token); - var adscMessage = await client.AdscMessageReader.ReadAsync(cts.Token); + var downlink = await connection.MessageReader.ReadAsync(cts.Token); + var adscMessage = await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert Assert.Equal("UAL123", downlink.Sender); Assert.Equal("DAL456", adscMessage.Sender); - Assert.False(client.MessageReader.TryRead(out _)); - Assert.False(client.AdscMessageReader.TryRead(out _)); + Assert.False(connection.MessageReader.TryRead(out _)); + Assert.False(connection.AdscMessageReader.TryRead(out _)); } [Fact] @@ -742,15 +746,15 @@ public async Task RequestPeriodicAdscContract_LogsUplinkPacket() var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); var clock = new TestClock(); - var client = CreateClient(httpHandler, clock); + var connection = CreateConnection(httpHandler, clock); // Act - await client.RequestPeriodicAdscContract("UAL123", TimeSpan.FromMinutes(5), CancellationToken.None); + await connection.RequestPeriodicAdscContract("UAL123", TimeSpan.FromMinutes(5), CancellationToken.None); // Assert var entry = Assert.Single(await _adscMessageLogRepository.All(CancellationToken.None)); Assert.Equal(clock.UtcNow(), entry.Time); - Assert.Equal("Hoppies/YBBB", entry.AcarsClientId); + Assert.Equal("Hoppies/YBBB", entry.AcarsConnectionId); Assert.Equal("YBBB", entry.StationId); Assert.Equal("UAL123", entry.Callsign); Assert.Equal(AdscMessageDirection.Uplink, entry.Direction); @@ -763,11 +767,11 @@ public async Task RequestAdscDemandReport_WhenSendFails_DoesNotLogPacket() // Arrange var httpHandler = new TestHttpMessageHandler(); httpHandler.SetResponse(HttpStatusCode.InternalServerError, "error"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act & Assert await Assert.ThrowsAsync(() => - client.RequestAdscDemandReport("UAL123", CancellationToken.None)); + connection.RequestAdscDemandReport("UAL123", CancellationToken.None)); Assert.Empty(await _adscMessageLogRepository.All(CancellationToken.None)); } @@ -780,15 +784,15 @@ public async Task Poll_AdscMessages_LogsDownlinkPackets() HttpStatusCode.OK, "ok {UAL123 cpdlc {/data2/5//Y/REQUEST DESCENT}} {UAL123 ads-c {REPORT UAL123 131155 ABC 151.177200 37000}} {DAL456 ads-c {REJECT}}"); httpHandler.SetResponse(HttpStatusCode.OK, "ok"); - var client = CreateClient(httpHandler); + var connection = CreateConnection(httpHandler); // Act - await client.Connect(CancellationToken.None); + await connection.Connect(CancellationToken.None); await Task.Delay(100); // Give polling task time to start // The packet is logged before the message is written to the reader using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - await client.AdscMessageReader.ReadAsync(cts.Token); + await connection.AdscMessageReader.ReadAsync(cts.Token); // Assert var entries = await _adscMessageLogRepository.All(CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/RefreshAcarsCallsignsRequestHandlerTests.cs b/source/CPDLCServer.Tests/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandlerTests.cs similarity index 78% rename from source/CPDLCServer.Tests/Handlers/RefreshAcarsCallsignsRequestHandlerTests.cs rename to source/CPDLCServer.Tests/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandlerTests.cs index a390738..09e1b21 100644 --- a/source/CPDLCServer.Tests/Handlers/RefreshAcarsCallsignsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandlerTests.cs @@ -1,13 +1,11 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AcarsConnections.Stations; public class RefreshAcarsCallsignsRequestHandlerTests { @@ -15,9 +13,9 @@ public class RefreshAcarsCallsignsRequestHandlerTests public async Task Handle_UpdatesLastSeenForConnectedAircraft() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -30,13 +28,13 @@ public async Task Handle_UpdatesLastSeenForConnectedAircraft() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(initialTime); aircraft.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); // Simulate the aircraft being connected on the ACARS network - acarsClient.Connections.Add("UAL123"); + acarsConnection.Connections.Add("UAL123"); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -62,9 +60,9 @@ public async Task Handle_UpdatesLastSeenForConnectedAircraft() public async Task Handle_DoesNotUpdateLastSeenForDisconnectedAircraft() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -77,13 +75,13 @@ public async Task Handle_DoesNotUpdateLastSeenForDisconnectedAircraft() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(initialTime); aircraft.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); // Aircraft is NOT in the ACARS connections list (disconnected) - // acarsClient.Connections remains empty + // acarsConnection.Connections remains empty var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -106,14 +104,14 @@ public async Task Handle_DoesNotUpdateLastSeenForDisconnectedAircraft() } [Fact] - public async Task Handle_OnlyUpdatesAircraftForMatchingAcarsClient() + public async Task Handle_OnlyUpdatesAircraftForMatchingAcarsConnection() { // Arrange - var clientManager = new TestClientManager(); - var acarsClientYbbb = new TestAcarsClient("YBBB"); - var acarsClientYmmm = new TestAcarsClient("YMMM"); - clientManager.AddClient("hoppies-ybbb", acarsClientYbbb); - clientManager.AddClient("hoppies-ymmm", acarsClientYmmm); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnectionYbbb = new TestAcarsConnection("YBBB"); + var acarsConnectionYmmm = new TestAcarsConnection("YMMM"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnectionYbbb); + acarsConnectionManager.AddConnection("hoppies-ymmm", acarsConnectionYmmm); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -127,20 +125,20 @@ public async Task Handle_OnlyUpdatesAircraftForMatchingAcarsClient() var aircraftYbbb = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraftYbbb.RequestLogon(initialTime); aircraftYbbb.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraftYbbb.Callsign, aircraftYbbb.AcarsClientId), aircraftYbbb, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraftYbbb.Callsign, aircraftYbbb.AcarsConnectionId), aircraftYbbb, CancellationToken.None); // Aircraft on YMMM var aircraftYmmm = new AircraftConnection("QFA456", "hoppies-ymmm", "YMMM", DataAuthorityState.CurrentDataAuthority); aircraftYmmm.RequestLogon(initialTime); aircraftYmmm.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraftYmmm.Callsign, aircraftYmmm.AcarsClientId), aircraftYmmm, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraftYmmm.Callsign, aircraftYmmm.AcarsConnectionId), aircraftYmmm, CancellationToken.None); // Both aircraft are connected on their respective ACARS networks - acarsClientYbbb.Connections.Add("UAL123"); - acarsClientYmmm.Connections.Add("QFA456"); + acarsConnectionYbbb.Connections.Add("UAL123"); + acarsConnectionYmmm.Connections.Add("QFA456"); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -171,9 +169,9 @@ public async Task Handle_OnlyUpdatesAircraftForMatchingAcarsClient() public async Task Handle_UpdatesRepositoryWithConnectedCallsigns() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -184,11 +182,11 @@ public async Task Handle_UpdatesRepositoryWithConnectedCallsigns() clock.SetUtcNow(initialTime); // Simulate aircraft connected on the ACARS network - acarsClient.Connections.Add("UAL123"); - acarsClient.Connections.Add("QFA456"); + acarsConnection.Connections.Add("UAL123"); + acarsConnection.Connections.Add("QFA456"); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -211,9 +209,9 @@ public async Task Handle_UpdatesRepositoryWithConnectedCallsigns() public async Task Handle_PublishesNotificationWhenCallsignsChange() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -224,10 +222,10 @@ public async Task Handle_PublishesNotificationWhenCallsignsChange() clock.SetUtcNow(initialTime); // Simulate aircraft connected on the ACARS network - acarsClient.Connections.Add("UAL123"); + acarsConnection.Connections.Add("UAL123"); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -250,9 +248,9 @@ await mediator.Received(1).Publish( public async Task Handle_DoesNotPublishNotificationWhenCallsignsUnchanged() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -263,13 +261,13 @@ public async Task Handle_DoesNotPublishNotificationWhenCallsignsUnchanged() clock.SetUtcNow(initialTime); // Simulate aircraft connected on the ACARS network - acarsClient.Connections.Add("UAL123"); + acarsConnection.Connections.Add("UAL123"); // Pre-populate the repository with the same callsign await acarsConnectedCallsignsRepository.Update(["UAL123"], CancellationToken.None); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -291,9 +289,9 @@ await mediator.DidNotReceive().Publish( public async Task Handle_PublishesNotificationWhenCallsignAdded() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -307,11 +305,11 @@ public async Task Handle_PublishesNotificationWhenCallsignAdded() await acarsConnectedCallsignsRepository.Update(["UAL123"], CancellationToken.None); // Simulate a new aircraft joining the ACARS network - acarsClient.Connections.Add("UAL123"); - acarsClient.Connections.Add("QFA456"); + acarsConnection.Connections.Add("UAL123"); + acarsConnection.Connections.Add("QFA456"); var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, @@ -336,9 +334,9 @@ await mediator.Received(1).Publish( public async Task Handle_PublishesNotificationWhenCallsignRemoved() { // Arrange - var clientManager = new TestClientManager(); - var acarsClient = new TestAcarsClient("YBBB"); - clientManager.AddClient("hoppies-ybbb", acarsClient); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var acarsConnection = new TestAcarsConnection("YBBB"); + acarsConnectionManager.AddConnection("hoppies-ybbb", acarsConnection); var aircraftRepository = new TestAircraftRepository(); var acarsConnectedCallsignsRepository = new InMemoryAcarsStationRepository(); @@ -352,11 +350,11 @@ public async Task Handle_PublishesNotificationWhenCallsignRemoved() await acarsConnectedCallsignsRepository.Update(["UAL123", "QFA456"], CancellationToken.None); // Simulate one aircraft leaving the ACARS network - acarsClient.Connections.Add("UAL123"); + acarsConnection.Connections.Add("UAL123"); // QFA456 is no longer connected var handler = new RefreshAcarsCallsignsRequestHandler( - clientManager, + acarsConnectionManager, aircraftRepository, acarsConnectedCallsignsRepository, mediator, diff --git a/source/CPDLCServer.Tests/AdscContracts/AdscContractRepositoryTests.cs b/source/CPDLCServer.Tests/AdscContracts/AdscContractRepositoryTests.cs new file mode 100644 index 0000000..54b63dd --- /dev/null +++ b/source/CPDLCServer.Tests/AdscContracts/AdscContractRepositoryTests.cs @@ -0,0 +1,67 @@ +using CPDLCServer.AdscContracts; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.AdscContracts; + +public class AdscContractRepositoryTests +{ + static readonly DateTimeOffset Start = new(2026, 10, 13, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task Find_ReturnsSavedContract() + { + // Arrange + using var database = new TestDatabase(); + var contract = new AdscContract("UAL123", "YBBB"); + contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); + contract.ReportReceived(); + contract.RequestSelectedContract(TimeSpan.FromMinutes(2), Start.AddHours(1)); + contract.RequestDemandReport(); + contract.LogActivity(Start); + + await using (var dbContext = database.CreateDbContext()) + { + await new AdscContractRepository(dbContext).Add(new("UAL123", "YBBB"), contract, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using var readDbContext = database.CreateDbContext(); + var saved = await new AdscContractRepository(readDbContext).Find(new("UAL123", "YBBB"), CancellationToken.None); + + // Assert + Assert.NotNull(saved); + Assert.Equal(TimeSpan.FromMinutes(2), saved.ReportingInterval); + Assert.Equal(AdscContractState.Accepted, saved.DefaultContractState); + Assert.Equal(TimeSpan.FromMinutes(2), saved.SelectedReportingInterval); + Assert.Equal(AdscContractState.Sent, saved.SelectedContractState); + Assert.Equal(Start.AddHours(1), saved.SelectedContractEnds); + Assert.Equal(AdscContractState.Sent, saved.DemandContractState); + Assert.Equal(Start, saved.LastActivity); + } + + [Fact] + public async Task Remove_DeletesContract() + { + // Arrange + using var database = new TestDatabase(); + await using (var dbContext = database.CreateDbContext()) + { + await new AdscContractRepository(dbContext).Add(new("UAL123", "YBBB"), new AdscContract("UAL123", "YBBB"), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + bool removed; + await using (var dbContext = database.CreateDbContext()) + { + removed = await new AdscContractRepository(dbContext).Remove(new("UAL123", "YBBB"), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + Assert.True(removed); + await using var readDbContext = database.CreateDbContext(); + Assert.Empty(await new AdscContractRepository(readDbContext).All(CancellationToken.None)); + } +} diff --git a/source/CPDLCServer.Tests/Model/AdscContractTests.cs b/source/CPDLCServer.Tests/AdscContracts/AdscContractTests.cs similarity index 99% rename from source/CPDLCServer.Tests/Model/AdscContractTests.cs rename to source/CPDLCServer.Tests/AdscContracts/AdscContractTests.cs index c09483b..b749b68 100644 --- a/source/CPDLCServer.Tests/Model/AdscContractTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/AdscContractTests.cs @@ -1,6 +1,6 @@ -using CPDLCServer.Model; +using CPDLCServer.AdscContracts; -namespace CPDLCServer.Tests.Model; +namespace CPDLCServer.Tests.AdscContracts; public class AdscContractTests { diff --git a/source/CPDLCServer.Tests/Handlers/AdscMessageReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/AdscMessageReceivedNotificationHandlerTests.cs similarity index 98% rename from source/CPDLCServer.Tests/Handlers/AdscMessageReceivedNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/AdscMessageReceivedNotificationHandlerTests.cs index ae7e833..5ba816b 100644 --- a/source/CPDLCServer.Tests/Handlers/AdscMessageReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/AdscMessageReceivedNotificationHandlerTests.cs @@ -1,13 +1,11 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class AdscMessageReceivedNotificationHandlerTests { diff --git a/source/CPDLCServer.Tests/Handlers/CancelAdscContractCommandHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractCommandHandlerTests.cs similarity index 69% rename from source/CPDLCServer.Tests/Handlers/CancelAdscContractCommandHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/CancelAdscContractCommandHandlerTests.cs index 0be85e6..15a70e2 100644 --- a/source/CPDLCServer.Tests/Handlers/CancelAdscContractCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractCommandHandlerTests.cs @@ -1,13 +1,10 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class CancelAdscContractCommandHandlerTests { @@ -15,20 +12,20 @@ public class CancelAdscContractCommandHandlerTests public async Task Handle_WhenContractExists_SendsCancelAndRemovesContract() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var contractRepository = new TestAdscContractRepository(); var contract = new AdscContract("UAL123", "YBBB"); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); - var handler = new CancelAdscContractCommandHandler(clientManager, contractRepository, mediator, Logger.None); + var handler = new CancelAdscContractCommandHandler(acarsConnectionManager, contractRepository, mediator, new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new CancelAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Equal("UAL123", Assert.Single(client.CancelledAdscContracts)); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Equal("UAL123", Assert.Single(acarsConnection.CancelledAdscContracts)); Assert.Empty(await contractRepository.All(CancellationToken.None)); await mediator.Received(1).Publish( @@ -40,17 +37,17 @@ await mediator.Received(1).Publish( public async Task Handle_WhenContractNotFound_SendsNothing() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var mediator = Substitute.For(); var handler = new CancelAdscContractCommandHandler( - clientManager, new TestAdscContractRepository(), mediator, Logger.None); + acarsConnectionManager, new TestAdscContractRepository(), mediator, new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new CancelAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Empty(client.CancelledAdscContracts); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Empty(acarsConnection.CancelledAdscContracts); await mediator.DidNotReceive().Publish( Arg.Any(), @@ -68,7 +65,7 @@ public async Task Handle_OnlyRemovesContractForStation() await contractRepository.Add(new AdscContractKey("UAL123", "YMMM"), ymmmContract, CancellationToken.None); var handler = new CancelAdscContractCommandHandler( - new TestClientManager(), contractRepository, Substitute.For(), Logger.None); + new TestAcarsConnectionManager(), contractRepository, Substitute.For(), new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new CancelAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/CancelAdscContractOnConnectionEndedHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs similarity index 86% rename from source/CPDLCServer.Tests/Handlers/CancelAdscContractOnConnectionEndedHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs index ba35c58..3279644 100644 --- a/source/CPDLCServer.Tests/Handlers/CancelAdscContractOnConnectionEndedHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs @@ -1,13 +1,11 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class CancelAdscContractOnConnectionEndedHandlerTests { @@ -21,7 +19,7 @@ public async Task Handle_ConnectionTerminated_CancelsContract() var mediator = Substitute.For(); var handler = new CancelAdscContractOnConnectionEndedHandler( - new TestClientManager(), contractRepository, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle( @@ -35,7 +33,7 @@ await mediator.Received(1).Send( } [Fact] - public async Task Handle_ConnectionLost_CancelsContractForStationOfAcarsClient() + public async Task Handle_ConnectionLost_CancelsContractForStationOfAcarsConnection() { // Arrange var contractRepository = new TestAdscContractRepository(); @@ -44,7 +42,7 @@ public async Task Handle_ConnectionLost_CancelsContractForStationOfAcarsClient() var mediator = Substitute.For(); var handler = new CancelAdscContractOnConnectionEndedHandler( - new TestClientManager(), contractRepository, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle( @@ -63,7 +61,7 @@ public async Task Handle_WhenNoContract_DoesNotCancel() // Arrange var mediator = Substitute.For(); var handler = new CancelAdscContractOnConnectionEndedHandler( - new TestClientManager(), new TestAdscContractRepository(), mediator, Logger.None); + new TestAcarsConnectionManager(), new TestAdscContractRepository(), mediator, Logger.None); // Act await handler.Handle( @@ -84,7 +82,7 @@ public async Task Handle_WhenContractIsWithOtherStation_DoesNotCancel() var mediator = Substitute.For(); var handler = new CancelAdscContractOnConnectionEndedHandler( - new TestClientManager(), contractRepository, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act await handler.Handle( @@ -109,7 +107,7 @@ public async Task Handle_WhenCancelFails_DoesNotThrow() .Returns(Task.FromException(new HttpRequestException("Hoppie is down"))); var handler = new CancelAdscContractOnConnectionEndedHandler( - new TestClientManager(), contractRepository, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); // Act & Assert - should not throw await handler.Handle( diff --git a/source/CPDLCServer.Tests/Handlers/EndExpiredAdscContractsRequestHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/EndExpiredAdscContractsRequestHandlerTests.cs similarity index 66% rename from source/CPDLCServer.Tests/Handlers/EndExpiredAdscContractsRequestHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/EndExpiredAdscContractsRequestHandlerTests.cs index 0c619cb..316ae58 100644 --- a/source/CPDLCServer.Tests/Handlers/EndExpiredAdscContractsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/EndExpiredAdscContractsRequestHandlerTests.cs @@ -1,18 +1,19 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; +using CPDLCServer.Infrastructure; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class EndExpiredAdscContractsRequestHandlerTests { static readonly TimeSpan ContractTimeout = TimeSpan.FromMinutes(120); + // The server has been online for longer than any timeout + static readonly ServerStartTime StartedLongAgo = new(DateTimeOffset.MinValue); + [Fact] public async Task Handle_WhenSelectedContractHasEnded_RequestsDefaultContract() { @@ -26,7 +27,7 @@ public async Task Handle_WhenSelectedContractHasEnded_RequestsDefaultContract() var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); @@ -50,7 +51,7 @@ public async Task Handle_WhenSelectedContractHasNotEnded_DoesNothing() var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); @@ -72,7 +73,7 @@ public async Task Handle_WhenNoSelectedContract_DoesNothing() var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); @@ -101,7 +102,7 @@ public async Task Handle_WhenRequestFails_ContinuesWithOtherContracts() .Returns(Task.FromException(new HttpRequestException("Hoppie is down"))); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); @@ -123,28 +124,80 @@ public async Task Handle_WhenContractIsInactive_CancelsAndRemovesContract() contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - clientManager, contractRepository, clock, mediator, Logger.None); + acarsConnectionManager, contractRepository, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act clock.SetUtcNow(clock.UtcNow() + ContractTimeout + TimeSpan.FromMinutes(1)); await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Equal(["UAL123"], client.CancelledAdscContracts); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Equal(["UAL123"], acarsConnection.CancelledAdscContracts); Assert.Empty(await contractRepository.All(CancellationToken.None)); await mediator.Received(1).Publish( Arg.Is(n => n.Callsign == "UAL123" && n.StationId == "YBBB"), Arg.Any()); } + [Fact] + public async Task Handle_WhenServerOnlineForLessThanTimeout_KeepsInactiveContract() + { + // Arrange - the last activity was long before the server started + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = new AdscContract("UAL123", "YBBB"); + contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); + contract.LogActivity(clock.UtcNow()); + await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); + + var serverStarted = clock.UtcNow() + ContractTimeout; + var acarsConnectionManager = new TestAcarsConnectionManager(); + var mediator = Substitute.For(); + var handler = new EndExpiredAdscContractsRequestHandler( + acarsConnectionManager, contractRepository, clock, new ServerStartTime(serverStarted), mediator, new TestUnitOfWork(), Logger.None); + + // Act + clock.SetUtcNow(serverStarted + ContractTimeout); + await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); + + // Assert + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Empty(acarsConnection.CancelledAdscContracts); + Assert.Equal([contract], await contractRepository.All(CancellationToken.None)); + Assert.Empty(mediator.ReceivedCalls()); + } + + [Fact] + public async Task Handle_WhenServerOnlineForLessThanTimeout_StillEndsSelectedContract() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = new AdscContract("UAL123", "YBBB"); + contract.RequestSelectedContract(TimeSpan.FromMinutes(2), clock.UtcNow()); + contract.LogActivity(clock.UtcNow()); + await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); + + var mediator = Substitute.For(); + var handler = new EndExpiredAdscContractsRequestHandler( + new TestAcarsConnectionManager(), contractRepository, clock, new ServerStartTime(clock.UtcNow()), mediator, new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new EndExpiredAdscContractsRequest(ContractTimeout), CancellationToken.None); + + // Assert + await mediator.Received(1).Send( + Arg.Is(c => c.StationId == "YBBB" && c.Callsign == "UAL123"), + Arg.Any()); + } + [Fact] public async Task Handle_WhenContractIsInactiveAndAcarsCancelFails_RemovesContract() { - // Arrange - TestClientManager has no ACARS client for YSSY, so the cancel fails + // Arrange - TestAcarsConnectionManager has no ACARS connection for YSSY, so the cancel fails var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); var contract = new AdscContract("UAL123", "YSSY"); @@ -154,7 +207,7 @@ public async Task Handle_WhenContractIsInactiveAndAcarsCancelFails_RemovesContra var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act clock.SetUtcNow(clock.UtcNow() + ContractTimeout + TimeSpan.FromMinutes(1)); @@ -180,7 +233,7 @@ public async Task Handle_WhenContractHasRecentActivity_KeepsContract() var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act clock.SetUtcNow(clock.UtcNow() + ContractTimeout - TimeSpan.FromMinutes(1)); @@ -204,7 +257,7 @@ public async Task Handle_WhenSelectedContractIsInactive_CancelsInsteadOfRequesti var mediator = Substitute.For(); var handler = new EndExpiredAdscContractsRequestHandler( - new TestClientManager(), contractRepository, clock, mediator, Logger.None); + new TestAcarsConnectionManager(), contractRepository, clock, StartedLongAgo, mediator, new TestUnitOfWork(), Logger.None); // Act clock.SetUtcNow(clock.UtcNow() + ContractTimeout + TimeSpan.FromMinutes(1)); diff --git a/source/CPDLCServer.Tests/Persistence/InMemoryAdscMessageLogRepositoryTests.cs b/source/CPDLCServer.Tests/AdscContracts/MessageLog/InMemoryAdscMessageLogRepositoryTests.cs similarity index 95% rename from source/CPDLCServer.Tests/Persistence/InMemoryAdscMessageLogRepositoryTests.cs rename to source/CPDLCServer.Tests/AdscContracts/MessageLog/InMemoryAdscMessageLogRepositoryTests.cs index 0cf7622..7ec61ef 100644 --- a/source/CPDLCServer.Tests/Persistence/InMemoryAdscMessageLogRepositoryTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/MessageLog/InMemoryAdscMessageLogRepositoryTests.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts.MessageLog; -namespace CPDLCServer.Tests.Persistence; +namespace CPDLCServer.Tests.AdscContracts.MessageLog; public class InMemoryAdscMessageLogRepositoryTests { diff --git a/source/CPDLCServer.Tests/AdscContracts/PurgeExpiredAdscDataRequestHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/PurgeExpiredAdscDataRequestHandlerTests.cs new file mode 100644 index 0000000..a55a79a --- /dev/null +++ b/source/CPDLCServer.Tests/AdscContracts/PurgeExpiredAdscDataRequestHandlerTests.cs @@ -0,0 +1,79 @@ +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.AdscContracts; + +public class PurgeExpiredAdscDataRequestHandlerTests +{ + [Fact] + public async Task Handle_RemovesAdscMessagesOlderThan24Hours() + { + // Arrange + var clock = new TestClock(); + var adscMessageLogRepository = new TestAdscMessageLogRepository(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var oldEntry = new AdscMessageLogEntry( + startTime, + "Hoppies/YBBB", + "YBBB", + "UAL123", + AdscMessageDirection.Uplink, + "REQUEST PERIODIC 1"); + var newEntry = new AdscMessageLogEntry( + startTime.AddHours(2), + "Hoppies/YBBB", + "YBBB", + "UAL123", + AdscMessageDirection.Uplink, + "REQUEST PERIODIC 2"); + await adscMessageLogRepository.Add(oldEntry, CancellationToken.None); + await adscMessageLogRepository.Add(newEntry, CancellationToken.None); + + var handler = new PurgeExpiredAdscDataRequestHandler(adscMessageLogRepository, new TestAdscReportRepository(), clock); + + // Act - advance time beyond the purge timeout (24 hours) for the old entry only + clock.SetUtcNow(startTime.AddHours(25)); + await handler.Handle(new PurgeExpiredAdscDataRequest(TimeSpan.FromHours(24)), CancellationToken.None); + + // Assert + Assert.Equal([newEntry], await adscMessageLogRepository.All(CancellationToken.None)); + } + + [Fact] + public async Task Handle_RemovesAdscReportsOlderThanRetention() + { + // Arrange + var clock = new TestClock(); + var adscReportRepository = new TestAdscReportRepository(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var oldReport = new AircraftAdscReport( + "UAL123", + "YBBB", + new AdscReport(startTime, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie), + startTime); + var newReport = new AircraftAdscReport( + "QFA1", + "YBBB", + new AdscReport(startTime.AddHours(2), -33.9461, 151.1772, 37000, AdscReportSource.Hoppie), + startTime.AddHours(2)); + await adscReportRepository.Add(oldReport, CancellationToken.None); + await adscReportRepository.Add(newReport, CancellationToken.None); + + var handler = new PurgeExpiredAdscDataRequestHandler(new TestAdscMessageLogRepository(), adscReportRepository, clock); + + // Act - advance time beyond the retention (24 hours) for the old report only + clock.SetUtcNow(startTime.AddHours(25)); + await handler.Handle(new PurgeExpiredAdscDataRequest(TimeSpan.FromHours(24)), CancellationToken.None); + + // Assert + Assert.Equal([newReport], await adscReportRepository.AllLatest(CancellationToken.None)); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/AdscReportReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs similarity index 85% rename from source/CPDLCServer.Tests/Handlers/AdscReportReceivedNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs index 5b1bcfb..5863dd1 100644 --- a/source/CPDLCServer.Tests/Handlers/AdscReportReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs @@ -1,14 +1,13 @@ using CPDLCServer.Contracts; -using CPDLCServer.Handlers; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Controllers; +using CPDLCServer.Web; using CPDLCServer.Tests.Mocks; using Microsoft.AspNetCore.SignalR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts.Reports; public class AdscReportReceivedNotificationHandlerTests { @@ -29,14 +28,14 @@ await controllerRepository.Add( hubContext.Clients.Clients(Arg.Any>()).Returns(clientProxy); var handler = new AdscReportReceivedNotificationHandler( - new TestAdscReportRepository(), controllerRepository, hubContext, Logger.None); + new TestAdscReportRepository(), controllerRepository, hubContext, new TestUnitOfWork(), Logger.None); var timestamp = new DateTimeOffset(2026, 10, 13, 11, 55, 0, TimeSpan.Zero); var received = timestamp.AddSeconds(40); var notification = new AdscReportReceivedNotification( "UAL123", "YBBB", - new AdscReport(timestamp, -33.9461, 151.1772, 37000, CPDLCServer.Model.AdscReportSource.Hoppie), + new AdscReport(timestamp, -33.9461, 151.1772, 37000, CPDLCServer.AdscContracts.Reports.AdscReportSource.Hoppie), received); // Act @@ -62,12 +61,12 @@ public async Task Handle_DoesNotNotifyWhenNoControllersConnected() // Arrange var hubContext = Substitute.For>(); var handler = new AdscReportReceivedNotificationHandler( - new TestAdscReportRepository(), new TestControllerRepository(), hubContext, Logger.None); + new TestAdscReportRepository(), new TestControllerRepository(), hubContext, new TestUnitOfWork(), Logger.None); var notification = new AdscReportReceivedNotification( "UAL123", "YBBB", - new AdscReport(DateTimeOffset.UtcNow, -33.9461, 151.1772, 37000, CPDLCServer.Model.AdscReportSource.Hoppie), + new AdscReport(DateTimeOffset.UtcNow, -33.9461, 151.1772, 37000, CPDLCServer.AdscContracts.Reports.AdscReportSource.Hoppie), DateTimeOffset.UtcNow); // Act @@ -83,10 +82,10 @@ public async Task Handle_StoresReportWhenNoControllersConnected() // Arrange var reportRepository = new TestAdscReportRepository(); var handler = new AdscReportReceivedNotificationHandler( - reportRepository, new TestControllerRepository(), Substitute.For>(), Logger.None); + reportRepository, new TestControllerRepository(), Substitute.For>(), new TestUnitOfWork(), Logger.None); var timestamp = new DateTimeOffset(2026, 10, 13, 11, 55, 0, TimeSpan.Zero); - var report = new AdscReport(timestamp, -33.9461, 151.1772, 37000, CPDLCServer.Model.AdscReportSource.Hoppie); + var report = new AdscReport(timestamp, -33.9461, 151.1772, 37000, CPDLCServer.AdscContracts.Reports.AdscReportSource.Hoppie); var received = timestamp.AddSeconds(40); var notification = new AdscReportReceivedNotification("UAL123", "YBBB", report, received); @@ -96,6 +95,6 @@ public async Task Handle_StoresReportWhenNoControllersConnected() // Assert Assert.Equal( [new AircraftAdscReport("UAL123", "YBBB", report, received)], - await reportRepository.All(CancellationToken.None)); + await reportRepository.AllLatest(CancellationToken.None)); } } diff --git a/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs new file mode 100644 index 0000000..3ed2def --- /dev/null +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs @@ -0,0 +1,184 @@ +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Tests.Mocks; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Tests.AdscContracts.Reports; + +public class AdscReportRepositoryTests +{ + static readonly DateTimeOffset Start = new(2026, 10, 13, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task Add_KeepsLatestReportForEachAircraft() + { + // Arrange + using var database = new TestDatabase(); + var first = CreateReport("UAL123", "YBBB", 0); + var second = CreateReport("UAL123", "YBBB", 5); + var other = CreateReport("QFA1", "YBBB", 0); + + // Act + await AddAndSave(database, first, second, other); + + // Assert + var reports = await AllLatest(database); + Assert.Equal(2, reports.Length); + Assert.Contains(second, reports); + Assert.Contains(other, reports); + } + + [Fact] + public async Task Add_KeepsHistoryOfReports() + { + // Arrange + using var database = new TestDatabase(); + var first = CreateReport("UAL123", "YBBB", 0); + var second = CreateReport("UAL123", "YBBB", 5); + + // Act + await AddAndSave(database, first); + await AddAndSave(database, second); + + // Assert + await using var dbContext = database.CreateDbContext(); + var history = await dbContext.AdscReports.ToArrayAsync(); + Assert.Equal(2, history.Length); + Assert.Contains(first, history); + Assert.Contains(second, history); + } + + [Fact] + public async Task Add_WhenReportIsOlder_KeepsNewerReport() + { + // Arrange + using var database = new TestDatabase(); + var newer = CreateReport("UAL123", "YBBB", 5); + var older = CreateReport("UAL123", "YMMM", 0); + + // Act + await AddAndSave(database, newer); + await AddAndSave(database, older); + + // Assert + Assert.Equal([newer], await AllLatest(database)); + } + + [Fact] + public async Task Add_InSameUnitOfWork_KeepsOneLatestReport() + { + // Arrange + using var database = new TestDatabase(); + var first = CreateReport("UAL123", "YBBB", 0); + var second = CreateReport("UAL123", "YMMM", 5); + + // Act + await AddAndSave(database, first, second); + + // Assert + Assert.Equal([second], await AllLatest(database)); + } + + [Fact] + public async Task Add_WhenHoppieReportIsOlderThanVatsimReport_ReplacesVatsimReport() + { + // Arrange + using var database = new TestDatabase(); + var vatsimReport = CreateReport("UAL123", "YBBB", 5, AdscReportSource.VATSIM); + var hoppieReport = CreateReport("UAL123", "YBBB", 0); + + // Act + await AddAndSave(database, vatsimReport); + await AddAndSave(database, hoppieReport); + + // Assert + Assert.Equal([hoppieReport], await AllLatest(database)); + } + + [Fact] + public async Task Add_WhenVatsimReportIsOlderThanHoppieReport_KeepsHoppieReport() + { + // Arrange + using var database = new TestDatabase(); + var hoppieReport = CreateReport("UAL123", "YBBB", 5); + var vatsimReport = CreateReport("UAL123", "YBBB", 0, AdscReportSource.VATSIM); + + // Act + await AddAndSave(database, hoppieReport); + await AddAndSave(database, vatsimReport); + + // Assert + Assert.Equal([hoppieReport], await AllLatest(database)); + } + + [Fact] + public async Task FindLatest_ReturnsLatestReportForAircraft() + { + // Arrange + using var database = new TestDatabase(); + var report = CreateReport("UAL123", "YBBB", 0); + await AddAndSave(database, report); + + // Act & Assert + await using var dbContext = database.CreateDbContext(); + var repository = new AdscReportRepository(dbContext); + Assert.Equal(report, await repository.FindLatest("UAL123", CancellationToken.None)); + Assert.Null(await repository.FindLatest("QFA1", CancellationToken.None)); + } + + [Fact] + public async Task RemoveOlderThan_RemovesOnlyOlderReports() + { + // Arrange + using var database = new TestDatabase(); + var older = CreateReport("UAL123", "YBBB", 0); + var atCutoff = CreateReport("QFA1", "YBBB", 5); + var newer = CreateReport("VOZ1", "YBBB", 10); + await AddAndSave(database, older, atCutoff, newer); + + // Act + await using (var dbContext = database.CreateDbContext()) + { + var repository = new AdscReportRepository(dbContext); + await repository.RemoveOlderThan(atCutoff.Received, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + var reports = await AllLatest(database); + Assert.Equal(2, reports.Length); + Assert.Contains(atCutoff, reports); + Assert.Contains(newer, reports); + } + + static async Task AddAndSave(TestDatabase database, params AircraftAdscReport[] reports) + { + await using var dbContext = database.CreateDbContext(); + var repository = new AdscReportRepository(dbContext); + + foreach (var report in reports) + await repository.Add(report, CancellationToken.None); + + await dbContext.SaveChangesAsync(); + } + + static async Task AllLatest(TestDatabase database) + { + await using var dbContext = database.CreateDbContext(); + var repository = new AdscReportRepository(dbContext); + return await repository.AllLatest(CancellationToken.None); + } + + static AircraftAdscReport CreateReport( + string callsign, + string stationId, + int minutes, + AdscReportSource source = AdscReportSource.Hoppie) + { + var timestamp = Start.AddMinutes(minutes); + return new AircraftAdscReport( + callsign, + stationId, + new AdscReport(timestamp, -33.9461, 151.1772, 37000, source), + timestamp.AddSeconds(30)); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/RequestAdscDemandReportCommandHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/RequestAdscDemandReportCommandHandlerTests.cs similarity index 73% rename from source/CPDLCServer.Tests/Handlers/RequestAdscDemandReportCommandHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/Reports/RequestAdscDemandReportCommandHandlerTests.cs index 42b02c8..a122816 100644 --- a/source/CPDLCServer.Tests/Handlers/RequestAdscDemandReportCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/RequestAdscDemandReportCommandHandlerTests.cs @@ -1,31 +1,29 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts.Reports; public class RequestAdscDemandReportCommandHandlerTests { [Fact] - public async Task Handle_SendsRequestViaAcarsClientForStation() + public async Task Handle_SendsRequestViaAcarsConnectionForStation() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var handler = new RequestAdscDemandReportCommandHandler( - clientManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), Logger.None); + acarsConnectionManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new RequestAdscDemandReportCommand("YBBB", "UAL123"), CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Equal("UAL123", Assert.Single(client.RequestedAdscDemandReports)); - Assert.Empty(client.RequestedAdscContracts); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Equal("UAL123", Assert.Single(acarsConnection.RequestedAdscDemandReports)); + Assert.Empty(acarsConnection.RequestedAdscContracts); } [Fact] @@ -35,7 +33,7 @@ public async Task Handle_WhenNoContractExists_AddsContractWithOnlyDemandReport() var contractRepository = new TestAdscContractRepository(); var mediator = Substitute.For(); var handler = new RequestAdscDemandReportCommandHandler( - new TestClientManager(), contractRepository, mediator, new TestClock(), Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, new TestClock(), new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new RequestAdscDemandReportCommand("YBBB", "UAL123"), CancellationToken.None); @@ -65,7 +63,7 @@ public async Task Handle_WhenPeriodicContractExists_KeepsPeriodicContractAndSend var mediator = Substitute.For(); var handler = new RequestAdscDemandReportCommandHandler( - new TestClientManager(), contractRepository, mediator, new TestClock(), Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, new TestClock(), new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new RequestAdscDemandReportCommand("YBBB", "UAL123"), CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/RequestAdscContractOnConnectionEstablishedHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/RequestAdscContractOnConnectionEstablishedHandlerTests.cs similarity index 96% rename from source/CPDLCServer.Tests/Handlers/RequestAdscContractOnConnectionEstablishedHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/RequestAdscContractOnConnectionEstablishedHandlerTests.cs index 11faa3c..a61f6b0 100644 --- a/source/CPDLCServer.Tests/Handlers/RequestAdscContractOnConnectionEstablishedHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/RequestAdscContractOnConnectionEstablishedHandlerTests.cs @@ -1,13 +1,11 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class RequestAdscContractOnConnectionEstablishedHandlerTests { diff --git a/source/CPDLCServer.Tests/Handlers/RequestDefaultAdscContractCommandHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/RequestDefaultAdscContractCommandHandlerTests.cs similarity index 68% rename from source/CPDLCServer.Tests/Handlers/RequestDefaultAdscContractCommandHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/RequestDefaultAdscContractCommandHandlerTests.cs index ac4bd03..bdeb180 100644 --- a/source/CPDLCServer.Tests/Handlers/RequestDefaultAdscContractCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/RequestDefaultAdscContractCommandHandlerTests.cs @@ -1,32 +1,29 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class RequestDefaultAdscContractCommandHandlerTests { [Fact] - public async Task Handle_SendsDefaultIntervalViaAcarsClientForStation() + public async Task Handle_SendsDefaultIntervalViaAcarsConnectionForStation() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var handler = new RequestDefaultAdscContractCommandHandler( - clientManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), Logger.None); + acarsConnectionManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new RequestDefaultAdscContractCommand("YMMM", "UAL123"), CancellationToken.None); - // Assert - TestClientManager sets the YMMM default to 20 minutes - var ybbbClient = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - var ymmmClient = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ymmm", CancellationToken.None); - Assert.Equal(TimeSpan.FromMinutes(20), ymmmClient.RequestedAdscContracts["UAL123"]); - Assert.Empty(ybbbClient.RequestedAdscContracts); + // Assert - TestAcarsConnectionManager sets the YMMM default to 20 minutes + var ybbbConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + var ymmmConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ymmm", CancellationToken.None); + Assert.Equal(TimeSpan.FromMinutes(20), ymmmConnection.RequestedAdscContracts["UAL123"]); + Assert.Empty(ybbbConnection.RequestedAdscContracts); } [Fact] @@ -36,12 +33,12 @@ public async Task Handle_WhenNoContractExists_AddsDefaultContract() var contractRepository = new TestAdscContractRepository(); var mediator = Substitute.For(); var handler = new RequestDefaultAdscContractCommandHandler( - new TestClientManager(), contractRepository, mediator, new TestClock(), Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, new TestClock(), new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new RequestDefaultAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); - // Assert - TestClientManager sets the YBBB default to 10 minutes + // Assert - TestAcarsConnectionManager sets the YBBB default to 10 minutes var contract = await contractRepository.Find(new AdscContractKey("UAL123", "YBBB"), CancellationToken.None); Assert.NotNull(contract); Assert.Equal(TimeSpan.FromMinutes(10), contract.ReportingInterval); @@ -59,7 +56,7 @@ public async Task Handle_LogsActivity() var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); var handler = new RequestDefaultAdscContractCommandHandler( - new TestClientManager(), contractRepository, Substitute.For(), clock, Logger.None); + new TestAcarsConnectionManager(), contractRepository, Substitute.For(), clock, new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new RequestDefaultAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); @@ -81,7 +78,7 @@ public async Task Handle_WhenSelectedContractIsInUse_EndsSelectedContract() await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), existingContract, CancellationToken.None); var handler = new RequestDefaultAdscContractCommandHandler( - new TestClientManager(), contractRepository, Substitute.For(), new TestClock(), Logger.None); + new TestAcarsConnectionManager(), contractRepository, Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); // Act await handler.Handle(new RequestDefaultAdscContractCommand("YBBB", "UAL123"), CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/RequestSelectedAdscContractCommandHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/RequestSelectedAdscContractCommandHandlerTests.cs similarity index 66% rename from source/CPDLCServer.Tests/Handlers/RequestSelectedAdscContractCommandHandlerTests.cs rename to source/CPDLCServer.Tests/AdscContracts/RequestSelectedAdscContractCommandHandlerTests.cs index cb871af..9573419 100644 --- a/source/CPDLCServer.Tests/Handlers/RequestSelectedAdscContractCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/RequestSelectedAdscContractCommandHandlerTests.cs @@ -1,23 +1,20 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.AdscContracts; public class RequestSelectedAdscContractCommandHandlerTests { [Fact] - public async Task Handle_SendsRequestViaAcarsClientForStation() + public async Task Handle_SendsRequestViaAcarsConnectionForStation() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var handler = new RequestSelectedAdscContractCommandHandler( - clientManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), Logger.None); + acarsConnectionManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); var command = new RequestSelectedAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(5)); @@ -25,10 +22,10 @@ public async Task Handle_SendsRequestViaAcarsClientForStation() await handler.Handle(command, CancellationToken.None); // Assert - var ybbbClient = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - var ymmmClient = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ymmm", CancellationToken.None); - Assert.Equal(TimeSpan.FromMinutes(5), ybbbClient.RequestedAdscContracts["UAL123"]); - Assert.Empty(ymmmClient.RequestedAdscContracts); + var ybbbConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + var ymmmConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ymmm", CancellationToken.None); + Assert.Equal(TimeSpan.FromMinutes(5), ybbbConnection.RequestedAdscContracts["UAL123"]); + Assert.Empty(ymmmConnection.RequestedAdscContracts); } [Fact] @@ -39,7 +36,7 @@ public async Task Handle_WhenNoContractExists_AddsSelectedContract() var contractRepository = new TestAdscContractRepository(); var mediator = Substitute.For(); var handler = new RequestSelectedAdscContractCommandHandler( - new TestClientManager(), contractRepository, mediator, clock, Logger.None); + new TestAcarsConnectionManager(), contractRepository, mediator, clock, new TestUnitOfWork(), Logger.None); var command = new RequestSelectedAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(5)); @@ -64,12 +61,12 @@ public async Task Handle_SetsEndTimeFromRequestTime() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); - clientManager.AddConfiguration(TestClientManager.CreateConfiguration("YBBB", 10, selectedAdscContractDuration: 30)); + var acarsConnectionManager = new TestAcarsConnectionManager(); + acarsConnectionManager.AddConfiguration(TestAcarsConnectionManager.CreateConfiguration("YBBB", 10, selectedAdscContractDuration: 30)); var contractRepository = new TestAdscContractRepository(); var handler = new RequestSelectedAdscContractCommandHandler( - clientManager, contractRepository, Substitute.For(), clock, Logger.None); + acarsConnectionManager, contractRepository, Substitute.For(), clock, new TestUnitOfWork(), Logger.None); var command = new RequestSelectedAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(5)); @@ -93,7 +90,7 @@ public async Task Handle_WhenDefaultContractExists_KeepsDefaultContractUntilAcce await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), existingContract, CancellationToken.None); var handler = new RequestSelectedAdscContractCommandHandler( - new TestClientManager(), contractRepository, Substitute.For(), new TestClock(), Logger.None); + new TestAcarsConnectionManager(), contractRepository, Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); var command = new RequestSelectedAdscContractCommand("YBBB", "UAL123", TimeSpan.FromMinutes(2)); @@ -112,18 +109,18 @@ public async Task Handle_WhenDefaultContractExists_KeepsDefaultContractUntilAcce public async Task Handle_WhenIntervalIsLessThanMinimum_ThrowsAndSendsNothing() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var contractRepository = new TestAdscContractRepository(); var handler = new RequestSelectedAdscContractCommandHandler( - clientManager, contractRepository, Substitute.For(), new TestClock(), Logger.None); + acarsConnectionManager, contractRepository, Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); var command = new RequestSelectedAdscContractCommand("YBBB", "UAL123", TimeSpan.FromSeconds(59)); // Act & Assert await Assert.ThrowsAsync(() => handler.Handle(command, CancellationToken.None)); - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Empty(client.RequestedAdscContracts); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Empty(acarsConnection.RequestedAdscContracts); Assert.Empty(await contractRepository.All(CancellationToken.None)); } @@ -131,9 +128,9 @@ public async Task Handle_WhenIntervalIsLessThanMinimum_ThrowsAndSendsNothing() public async Task Handle_WhenIntervalIsMinimum_SendsRequest() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var handler = new RequestSelectedAdscContractCommandHandler( - clientManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), Logger.None); + acarsConnectionManager, new TestAdscContractRepository(), Substitute.For(), new TestClock(), new TestUnitOfWork(), Logger.None); var command = new RequestSelectedAdscContractCommand( "YBBB", @@ -144,7 +141,7 @@ public async Task Handle_WhenIntervalIsMinimum_SendsRequest() await handler.Handle(command, CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.RequestedAdscContracts); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.RequestedAdscContracts); } } diff --git a/source/CPDLCServer.Tests/Auth/Login/ClientIpAddressTests.cs b/source/CPDLCServer.Tests/Auth/Login/ClientIpAddressTests.cs new file mode 100644 index 0000000..9eeb073 --- /dev/null +++ b/source/CPDLCServer.Tests/Auth/Login/ClientIpAddressTests.cs @@ -0,0 +1,52 @@ +using System.Net; +using CPDLCServer.Auth.Login; +using Microsoft.AspNetCore.Http; + +namespace CPDLCServer.Tests.Auth.Login; + +public class ClientIpAddressTests +{ + [Fact] + public void Get_WithoutHeaders_ReturnsTheConnectionAddress() + { + var httpContext = CreateHttpContext(); + + Assert.Equal("10.0.0.1", ClientIpAddress.Get(httpContext)); + } + + [Fact] + public void Get_WithDigitalOceanHeader_ReturnsTheHeaderAddress() + { + var httpContext = CreateHttpContext(); + httpContext.Request.Headers["do-connecting-ip"] = "203.0.113.10"; + httpContext.Request.Headers["x-forwarded-for"] = "10.0.0.2"; + + Assert.Equal("203.0.113.10", ClientIpAddress.Get(httpContext)); + } + + [Fact] + public void Get_WithForwardedForList_ReturnsTheFirstAddress() + { + var httpContext = CreateHttpContext(); + httpContext.Request.Headers["x-forwarded-for"] = "203.0.113.10, 10.0.0.2"; + + Assert.Equal("203.0.113.10", ClientIpAddress.Get(httpContext)); + } + + [Fact] + public void Get_WithInvalidHeaderValue_UsesTheNextHeader() + { + var httpContext = CreateHttpContext(); + httpContext.Request.Headers["do-connecting-ip"] = "not an address"; + httpContext.Request.Headers["x-real-ip"] = "2001:db8::1"; + + Assert.Equal("2001:db8::1", ClientIpAddress.Get(httpContext)); + } + + static DefaultHttpContext CreateHttpContext() + { + var httpContext = new DefaultHttpContext(); + httpContext.Connection.RemoteIpAddress = IPAddress.Parse("10.0.0.1"); + return httpContext; + } +} diff --git a/source/CPDLCServer.Tests/Auth/Login/LoginCommandHandlerTests.cs b/source/CPDLCServer.Tests/Auth/Login/LoginCommandHandlerTests.cs new file mode 100644 index 0000000..c3dca9f --- /dev/null +++ b/source/CPDLCServer.Tests/Auth/Login/LoginCommandHandlerTests.cs @@ -0,0 +1,163 @@ +using CPDLCServer.Auth.Login; +using CPDLCServer.Auth.Users; +using CPDLCServer.Tests.Mocks; +using Microsoft.AspNetCore.Identity; +using Serilog.Core; + +namespace CPDLCServer.Tests.Auth.Login; + +public class LoginCommandHandlerTests +{ + const string Password = "correct horse battery"; + const string IpAddress = "203.0.113.10"; + + readonly TestUserRepository _repository = new(); + readonly PasswordHasher _passwordHasher = new(); + readonly TestClock _clock = new(); + readonly LoginLockout _loginLockout; + readonly User _user; + + public LoginCommandHandlerTests() + { + _loginLockout = new LoginLockout(_clock); + _user = new User { Id = Guid.NewGuid(), Username = "admin" }; + _user.PasswordHash = _passwordHasher.HashPassword(_user, Password); + _repository.Add(_user, CancellationToken.None); + } + + [Fact] + public async Task Handle_WithCorrectPassword_ReturnsTheUser() + { + // Arrange + var handler = CreateHandler(); + + // Act + var result = await handler.Handle(new LoginCommand(" admin ", Password, IpAddress), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(_user.Id, result.UserId); + Assert.Equal("admin", result.Username); + } + + [Fact] + public async Task Handle_WithWrongPassword_ReturnsNull() + { + // Arrange + var handler = CreateHandler(); + + // Act + var result = await handler.Handle(new LoginCommand("admin", "wrong password", IpAddress), CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task Handle_WithUnknownUser_ReturnsNull() + { + // Arrange + var handler = CreateHandler(); + + // Act + var result = await handler.Handle(new LoginCommand("intruder", Password, IpAddress), CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task Handle_AfterTooManyFailures_LocksOutTheIpAddress() + { + // Arrange + var handler = CreateHandler(); + + // Act + await FailLogins(handler, "admin", LoginLockout.MaxFailedLogins); + + // Assert + Assert.True(_loginLockout.IsLockedOut(IpAddress)); + } + + [Fact] + public async Task Handle_FailuresWithUnknownUsers_LockOutTheIpAddress() + { + // Arrange + var handler = CreateHandler(); + + // Act + await FailLogins(handler, "intruder", LoginLockout.MaxFailedLogins); + + // Assert + Assert.True(_loginLockout.IsLockedOut(IpAddress)); + } + + [Fact] + public async Task Handle_DuringLockout_RejectsTheCorrectPassword() + { + // Arrange + var handler = CreateHandler(); + await FailLogins(handler, "admin", LoginLockout.MaxFailedLogins); + + // Act + var result = await handler.Handle(new LoginCommand("admin", Password, IpAddress), CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task Handle_DuringLockout_AcceptsTheCorrectPasswordFromAnotherIpAddress() + { + // Arrange + var handler = CreateHandler(); + await FailLogins(handler, "admin", LoginLockout.MaxFailedLogins); + + // Act + var result = await handler.Handle(new LoginCommand("admin", Password, "198.51.100.20"), CancellationToken.None); + + // Assert + Assert.NotNull(result); + } + + [Fact] + public async Task Handle_AfterLockout_AcceptsTheCorrectPassword() + { + // Arrange + var handler = CreateHandler(); + await FailLogins(handler, "admin", LoginLockout.MaxFailedLogins); + _clock.SetUtcNow(_clock.UtcNow() + LoginLockout.LockoutDuration); + + // Act + var result = await handler.Handle(new LoginCommand("admin", Password, IpAddress), CancellationToken.None); + + // Assert + Assert.NotNull(result); + } + + [Fact] + public async Task Handle_WithCorrectPassword_ResetsTheFailedLogins() + { + // Arrange + var handler = CreateHandler(); + await FailLogins(handler, "admin", LoginLockout.MaxFailedLogins - 1); + + // Act + await handler.Handle(new LoginCommand("admin", Password, IpAddress), CancellationToken.None); + await FailLogins(handler, "admin", 1); + + // Assert + Assert.False(_loginLockout.IsLockedOut(IpAddress)); + } + + static async Task FailLogins(LoginCommandHandler handler, string username, int count) + { + for (var i = 0; i < count; i++) + await handler.Handle(new LoginCommand(username, "wrong password", IpAddress), CancellationToken.None); + } + + LoginCommandHandler CreateHandler() + { + return new LoginCommandHandler(_repository, _passwordHasher, _loginLockout, Logger.None); + } +} diff --git a/source/CPDLCServer.Tests/Auth/Login/LoginLockoutTests.cs b/source/CPDLCServer.Tests/Auth/Login/LoginLockoutTests.cs new file mode 100644 index 0000000..cb38a5e --- /dev/null +++ b/source/CPDLCServer.Tests/Auth/Login/LoginLockoutTests.cs @@ -0,0 +1,99 @@ +using CPDLCServer.Auth.Login; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.Auth.Login; + +public class LoginLockoutTests +{ + const string IpAddress = "203.0.113.10"; + + readonly TestClock _clock = new(); + readonly LoginLockout _loginLockout; + + public LoginLockoutTests() + { + _loginLockout = new LoginLockout(_clock); + } + + [Fact] + public void RecordFailure_BelowTheLimit_DoesNotLockOut() + { + // Act + for (var i = 0; i < LoginLockout.MaxFailedLogins - 1; i++) + Assert.Null(_loginLockout.RecordFailure(IpAddress)); + + // Assert + Assert.False(_loginLockout.IsLockedOut(IpAddress)); + } + + [Fact] + public void RecordFailure_AtTheLimit_LocksOutForTheLockoutDuration() + { + // Act + DateTimeOffset? lockoutEnd = null; + for (var i = 0; i < LoginLockout.MaxFailedLogins; i++) + lockoutEnd = _loginLockout.RecordFailure(IpAddress); + + // Assert + Assert.Equal(_clock.UtcNow() + LoginLockout.LockoutDuration, lockoutEnd); + Assert.True(_loginLockout.IsLockedOut(IpAddress)); + } + + [Fact] + public void IsLockedOut_AfterTheLockoutDuration_IsFalse() + { + // Arrange + LockOut(); + + // Act + _clock.SetUtcNow(_clock.UtcNow() + LoginLockout.LockoutDuration); + + // Assert + Assert.False(_loginLockout.IsLockedOut(IpAddress)); + } + + [Fact] + public void RecordFailure_AfterTheFailuresExpire_StartsTheCountAgain() + { + // Arrange + for (var i = 0; i < LoginLockout.MaxFailedLogins - 1; i++) + _loginLockout.RecordFailure(IpAddress); + _clock.SetUtcNow(_clock.UtcNow() + LoginLockout.LockoutDuration); + + // Act + var lockoutEnd = _loginLockout.RecordFailure(IpAddress); + + // Assert + Assert.Null(lockoutEnd); + Assert.False(_loginLockout.IsLockedOut(IpAddress)); + } + + [Fact] + public void Reset_EndsTheLockout() + { + // Arrange + LockOut(); + + // Act + _loginLockout.Reset(IpAddress); + + // Assert + Assert.False(_loginLockout.IsLockedOut(IpAddress)); + } + + [Fact] + public void LockOut_DoesNotAffectOtherIpAddresses() + { + // Act + LockOut(); + + // Assert + Assert.False(_loginLockout.IsLockedOut("198.51.100.20")); + } + + void LockOut() + { + for (var i = 0; i < LoginLockout.MaxFailedLogins; i++) + _loginLockout.RecordFailure(IpAddress); + } +} diff --git a/source/CPDLCServer.Tests/Auth/Users/ChangePasswordCommandHandlerTests.cs b/source/CPDLCServer.Tests/Auth/Users/ChangePasswordCommandHandlerTests.cs new file mode 100644 index 0000000..30f1053 --- /dev/null +++ b/source/CPDLCServer.Tests/Auth/Users/ChangePasswordCommandHandlerTests.cs @@ -0,0 +1,59 @@ +using CPDLCServer.Auth.Users; +using CPDLCServer.Tests.Mocks; +using Microsoft.AspNetCore.Identity; +using Serilog.Core; + +namespace CPDLCServer.Tests.Auth.Users; + +public class ChangePasswordCommandHandlerTests +{ + const string CurrentPassword = "correct horse battery"; + const string NewPassword = "another long password"; + + readonly TestUserRepository _repository = new(); + readonly PasswordHasher _passwordHasher = new(); + readonly User _user; + + public ChangePasswordCommandHandlerTests() + { + _user = new User { Id = Guid.NewGuid(), Username = "admin" }; + _user.PasswordHash = _passwordHasher.HashPassword(_user, CurrentPassword); + _repository.Add(_user, CancellationToken.None); + } + + [Fact] + public async Task Handle_ChangesThePassword() + { + // Arrange + var handler = CreateHandler(); + + // Act + await handler.Handle(new ChangePasswordCommand(_user.Id, NewPassword), CancellationToken.None); + + // Assert + Assert.Equal(PasswordVerificationResult.Success, Verify(NewPassword)); + Assert.Equal(PasswordVerificationResult.Failed, Verify(CurrentPassword)); + } + + [Fact] + public async Task Handle_WithUnknownUser_Throws() + { + // Arrange + var handler = CreateHandler(); + + // Act & Assert + await Assert.ThrowsAsync(() => handler.Handle( + new ChangePasswordCommand(Guid.NewGuid(), NewPassword), + CancellationToken.None)); + } + + PasswordVerificationResult Verify(string password) + { + return _passwordHasher.VerifyHashedPassword(_user, _user.PasswordHash, password); + } + + ChangePasswordCommandHandler CreateHandler() + { + return new ChangePasswordCommandHandler(_repository, _passwordHasher, Logger.None); + } +} diff --git a/source/CPDLCServer.Tests/Auth/Users/CreateUserCommandHandlerTests.cs b/source/CPDLCServer.Tests/Auth/Users/CreateUserCommandHandlerTests.cs new file mode 100644 index 0000000..8225c9b --- /dev/null +++ b/source/CPDLCServer.Tests/Auth/Users/CreateUserCommandHandlerTests.cs @@ -0,0 +1,80 @@ +using CPDLCServer.Auth.Users; +using CPDLCServer.Setup; +using CPDLCServer.Tests.Mocks; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Serilog.Core; + +namespace CPDLCServer.Tests.Auth.Users; + +public class CreateUserCommandHandlerTests +{ + readonly TestUserRepository _repository = new(); + readonly PasswordHasher _passwordHasher = new(); + + [Fact] + public async Task Handle_CreatesAdminWithHashedPassword() + { + // Arrange + var handler = CreateHandler(CreateSetupState()); + + // Act + var id = await handler.Handle(new CreateUserCommand(" admin ", "correct horse battery"), CancellationToken.None); + + // Assert + var user = await _repository.FindByUsername("admin", CancellationToken.None); + Assert.NotNull(user); + Assert.Equal(id, user.Id); + Assert.NotEqual("correct horse battery", user.PasswordHash); + Assert.Equal( + PasswordVerificationResult.Success, + _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, "correct horse battery")); + } + + [Fact] + public async Task Handle_MarksAdminCreated() + { + // Arrange + var setupState = CreateSetupState(); + var handler = CreateHandler(setupState); + + // Act + await handler.Handle(new CreateUserCommand("admin", "correct horse battery"), CancellationToken.None); + + // Assert + Assert.True(setupState.IsConfigured); + } + + [Fact] + public async Task Handle_WhenAdminExists_Throws() + { + // Arrange + var handler = CreateHandler(CreateSetupState()); + await handler.Handle(new CreateUserCommand("admin", "correct horse battery"), CancellationToken.None); + + // Act & Assert + await Assert.ThrowsAsync(() => + handler.Handle(new CreateUserCommand("intruder", "another password"), CancellationToken.None)); + Assert.Null(await _repository.FindByUsername("intruder", CancellationToken.None)); + } + + CreateUserCommandHandler CreateHandler(SetupState setupState) + { + return new CreateUserCommandHandler( + _repository, + _passwordHasher, + setupState, + new TestClock(), + new TestUnitOfWork(), + Logger.None); + } + + SetupState CreateSetupState() + { + var services = new ServiceCollection(); + services.AddSingleton(_repository); + var serviceProvider = services.BuildServiceProvider(); + + return new SetupState(serviceProvider.GetRequiredService()); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/AircraftConnectionEstablishedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs similarity index 88% rename from source/CPDLCServer.Tests/Handlers/AircraftConnectionEstablishedNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs index 6031413..0c4670d 100644 --- a/source/CPDLCServer.Tests/Handlers/AircraftConnectionEstablishedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs @@ -1,14 +1,13 @@ using CPDLCServer.Contracts; -using CPDLCServer.Handlers; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Web; using CPDLCServer.Tests.Mocks; using Microsoft.AspNetCore.SignalR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class AircraftConnectionEstablishedNotificationHandlerTests { @@ -39,13 +38,13 @@ public async Task Handle_NotifiesAllConnectedControllers() var handler = new AircraftConnectionEstablishedNotificationHandler( controllerManager, hubContext, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionEstablished( "hoppies-ybbb", "YBBB", "UAL123", - CPDLCServer.Model.DataAuthorityState.NextDataAuthority); + CPDLCServer.Cpdlc.Connections.DataAuthorityState.NextDataAuthority); // Act await handler.Handle(notification, CancellationToken.None); @@ -78,13 +77,13 @@ public async Task Handle_DoesNotNotifyWhenNoControllersConnected() var handler = new AircraftConnectionEstablishedNotificationHandler( controllerManager, hubContext, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionEstablished( "hoppies-ybbb", "YBBB", "UAL123", - CPDLCServer.Model.DataAuthorityState.NextDataAuthority); + CPDLCServer.Cpdlc.Connections.DataAuthorityState.NextDataAuthority); // Act await handler.Handle(notification, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/AircraftConnectionLostNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs similarity index 94% rename from source/CPDLCServer.Tests/Handlers/AircraftConnectionLostNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs index d17bc96..6cab381 100644 --- a/source/CPDLCServer.Tests/Handlers/AircraftConnectionLostNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs @@ -1,13 +1,14 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Web; using CPDLCServer.Tests.Mocks; using Microsoft.AspNetCore.SignalR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class AircraftConnectionLostNotificationHandlerTests { @@ -19,7 +20,7 @@ public async Task Handle_RemovesAircraftFromTracking() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -38,7 +39,7 @@ public async Task Handle_RemovesAircraftFromTracking() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); @@ -60,7 +61,7 @@ public async Task Handle_CreatesDialogueWithErrorMessageAndNotifiesControllers() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller1 = new ControllerInfo( @@ -94,7 +95,7 @@ public async Task Handle_CreatesDialogueWithErrorMessageAndNotifiesControllers() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); @@ -147,7 +148,7 @@ public async Task Handle_DoesNotThrowWhenAircraftNotFound() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); @@ -166,7 +167,7 @@ public async Task Handle_DoesNotNotifyWhenNoControllersConnected() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -185,7 +186,7 @@ public async Task Handle_DoesNotNotifyWhenNoControllersConnected() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); @@ -211,7 +212,7 @@ public async Task Handle_AddsErrorMessageToExistingOpenDialogue() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -252,7 +253,7 @@ public async Task Handle_AddsErrorMessageToExistingOpenDialogue() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); @@ -280,7 +281,7 @@ public async Task Handle_ClosesOpenDialogue_SoItCanBeArchived() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -321,7 +322,7 @@ public async Task Handle_ClosesOpenDialogue_SoItCanBeArchived() messageIdProvider, publisher, clock, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionLost("hoppies-ybbb", "UAL123"); diff --git a/source/CPDLCServer.Tests/Handlers/AircraftConnectionTerminatedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs similarity index 92% rename from source/CPDLCServer.Tests/Handlers/AircraftConnectionTerminatedNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs index 921b33a..eef7153 100644 --- a/source/CPDLCServer.Tests/Handlers/AircraftConnectionTerminatedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs @@ -1,13 +1,12 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Web; using CPDLCServer.Tests.Mocks; using Microsoft.AspNetCore.SignalR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class AircraftConnectionTerminatedNotificationHandlerTests { @@ -38,7 +37,7 @@ public async Task Handle_NotifiesAllConnectedControllers() var handler = new AircraftConnectionTerminatedNotificationHandler( controllerManager, hubContext, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionTerminated("hoppies-ybbb", "YBBB", "UAL123"); @@ -70,7 +69,7 @@ public async Task Handle_DoesNotNotifyWhenNoControllersConnected() var handler = new AircraftConnectionTerminatedNotificationHandler( controllerManager, hubContext, - Logger.None); + new TestUnitOfWork(), Logger.None); var notification = new AircraftConnectionTerminated("hoppies-ybbb", "YBBB", "UAL123"); diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftRepositoryTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftRepositoryTests.cs new file mode 100644 index 0000000..a4831fe --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftRepositoryTests.cs @@ -0,0 +1,95 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.Cpdlc.Connections; + +public class AircraftRepositoryTests +{ + static readonly DateTimeOffset Start = new(2026, 10, 13, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task Find_ReturnsSavedConnection() + { + // Arrange + using var database = new TestDatabase(); + var connection = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); + connection.RequestLogon(Start); + connection.AcceptLogon(Start.AddSeconds(5)); + connection.PromoteToCurrentDataAuthority(); + connection.SetNextDataAuthority("YMMM", Start.AddHours(1)); + connection.SentNextDataAuthorityMessage(); + + await using (var dbContext = database.CreateDbContext()) + { + await new AircraftRepository(dbContext).Add(new("UAL123", "hoppies-ybbb"), connection, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using var readDbContext = database.CreateDbContext(); + var saved = await new AircraftRepository(readDbContext).Find(new("UAL123", "hoppies-ybbb"), CancellationToken.None); + + // Assert + Assert.NotNull(saved); + Assert.Equal("YBBB", saved.StationId); + Assert.Equal(DataAuthorityState.CurrentDataAuthority, saved.DataAuthorityState); + Assert.Equal(ConnectionState.Connected, saved.ConnectionState); + Assert.Equal(Start, saved.LogonRequested); + Assert.Equal(Start.AddSeconds(5), saved.LogonAccepted); + Assert.Equal(Start.AddSeconds(5), saved.LastSeen); + Assert.Equal("YMMM", saved.NextDataAuthority); + Assert.Equal(Start.AddHours(1), saved.ExpectedTransferTime); + Assert.True(saved.DidSentNextDataAuthorityMessage); + } + + [Fact] + public async Task Add_WhenConnectionExists_ReplacesConnection() + { + // Arrange + using var database = new TestDatabase(); + var first = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); + var second = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); + + await using (var dbContext = database.CreateDbContext()) + { + await new AircraftRepository(dbContext).Add(new("UAL123", "hoppies-ybbb"), first, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using (var dbContext = database.CreateDbContext()) + { + await new AircraftRepository(dbContext).Add(new("UAL123", "hoppies-ybbb"), second, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + await using var readDbContext = database.CreateDbContext(); + var connections = await new AircraftRepository(readDbContext).All(CancellationToken.None); + var connection = Assert.Single(connections); + Assert.Equal(DataAuthorityState.CurrentDataAuthority, connection.DataAuthorityState); + } + + [Fact] + public async Task Remove_InSameUnitOfWorkAsAdd_DoesNotSaveConnection() + { + // Arrange + using var database = new TestDatabase(); + var connection = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); + + // Act + bool removed; + await using (var dbContext = database.CreateDbContext()) + { + var repository = new AircraftRepository(dbContext); + await repository.Add(new("UAL123", "hoppies-ybbb"), connection, CancellationToken.None); + removed = await repository.Remove(new("UAL123", "hoppies-ybbb"), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + Assert.True(removed); + await using var readDbContext = database.CreateDbContext(); + Assert.Empty(await new AircraftRepository(readDbContext).All(CancellationToken.None)); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/CheckLostAircraftConnectionsRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandlerTests.cs similarity index 60% rename from source/CPDLCServer.Tests/Handlers/CheckLostAircraftConnectionsRequestHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandlerTests.cs index ca2f385..61761ff 100644 --- a/source/CPDLCServer.Tests/Handlers/CheckLostAircraftConnectionsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandlerTests.cs @@ -1,16 +1,87 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Infrastructure; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class CheckLostAircraftConnectionsRequestHandlerTests { + // The server has been online for longer than any timeout + static readonly ServerStartTime StartedLongAgo = new(DateTimeOffset.MinValue); + + [Fact] + public async Task Handle_WhenServerOnlineForLessThanTimeout_DoesNotPublishAircraftLost() + { + // Arrange - the aircraft was last seen long before the server started + var aircraftRepository = new TestAircraftRepository(); + var clock = new TestClock(); + var mediator = Substitute.For(); + + var lastSeen = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + clock.SetUtcNow(lastSeen); + + var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); + aircraft.RequestLogon(lastSeen); + aircraft.AcceptLogon(lastSeen); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); + + var timeout = TimeSpan.FromMinutes(15); + var serverStarted = lastSeen.AddHours(2); + var handler = new CheckLostAircraftConnectionsRequestHandler( + aircraftRepository, + clock, + new ServerStartTime(serverStarted), + mediator, + Logger.None); + + clock.SetUtcNow(serverStarted + timeout); + + // Act + await handler.Handle(new CheckLostAircraftConnectionsRequest(timeout), CancellationToken.None); + + // Assert + Assert.Empty(mediator.ReceivedCalls()); + } + + [Fact] + public async Task Handle_WhenServerOnlineForLongerThanTimeout_PublishesAircraftLost() + { + // Arrange - the aircraft was last seen long before the server started + var aircraftRepository = new TestAircraftRepository(); + var clock = new TestClock(); + var mediator = Substitute.For(); + + var lastSeen = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + clock.SetUtcNow(lastSeen); + + var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); + aircraft.RequestLogon(lastSeen); + aircraft.AcceptLogon(lastSeen); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); + + var timeout = TimeSpan.FromMinutes(15); + var serverStarted = lastSeen.AddHours(2); + var handler = new CheckLostAircraftConnectionsRequestHandler( + aircraftRepository, + clock, + new ServerStartTime(serverStarted), + mediator, + Logger.None); + + clock.SetUtcNow(serverStarted + timeout + TimeSpan.FromMinutes(1)); + + // Act + await handler.Handle(new CheckLostAircraftConnectionsRequest(timeout), CancellationToken.None); + + // Assert + await mediator.Received(1).Publish( + Arg.Is(n => n.AcarsConnectionId == "hoppies-ybbb" && n.Callsign == "UAL123"), + Arg.Any()); + } + [Fact] public async Task Handle_PublishesAircraftLostWhenConnectionTimedOut() { @@ -25,11 +96,12 @@ public async Task Handle_PublishesAircraftLostWhenConnectionTimedOut() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(initialTime); aircraft.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new CheckLostAircraftConnectionsRequestHandler( aircraftRepository, clock, + StartedLongAgo, mediator, Logger.None); @@ -45,7 +117,7 @@ public async Task Handle_PublishesAircraftLostWhenConnectionTimedOut() // Assert await mediator.Received(1).Publish( - Arg.Is(n => n.AcarsClientId == "hoppies-ybbb" && n.Callsign == "UAL123"), + Arg.Is(n => n.AcarsConnectionId == "hoppies-ybbb" && n.Callsign == "UAL123"), Arg.Any()); } @@ -63,11 +135,12 @@ public async Task Handle_DoesNotPublishAircraftLostWhenConnectionNotTimedOut() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(initialTime); aircraft.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new CheckLostAircraftConnectionsRequestHandler( aircraftRepository, clock, + StartedLongAgo, mediator, Logger.None); @@ -101,16 +174,17 @@ public async Task Handle_PublishesAircraftLostForEachTimedOutAircraft() var aircraft1 = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft1.RequestLogon(initialTime); aircraft1.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft1.Callsign, aircraft1.AcarsClientId), aircraft1, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft1.Callsign, aircraft1.AcarsConnectionId), aircraft1, CancellationToken.None); var aircraft2 = new AircraftConnection("QFA456", "hoppies-ymmm", "YMMM", DataAuthorityState.CurrentDataAuthority); aircraft2.RequestLogon(initialTime); aircraft2.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(aircraft2.Callsign, aircraft2.AcarsClientId), aircraft2, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(aircraft2.Callsign, aircraft2.AcarsConnectionId), aircraft2, CancellationToken.None); var handler = new CheckLostAircraftConnectionsRequestHandler( aircraftRepository, clock, + StartedLongAgo, mediator, Logger.None); @@ -126,11 +200,11 @@ public async Task Handle_PublishesAircraftLostForEachTimedOutAircraft() // Assert await mediator.Received(1).Publish( - Arg.Is(n => n.AcarsClientId == "hoppies-ybbb" && n.Callsign == "UAL123"), + Arg.Is(n => n.AcarsConnectionId == "hoppies-ybbb" && n.Callsign == "UAL123"), Arg.Any()); await mediator.Received(1).Publish( - Arg.Is(n => n.AcarsClientId == "hoppies-ymmm" && n.Callsign == "QFA456"), + Arg.Is(n => n.AcarsConnectionId == "hoppies-ymmm" && n.Callsign == "QFA456"), Arg.Any()); } @@ -149,7 +223,7 @@ public async Task Handle_OnlyPublishesForTimedOutAircraft() var oldAircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); oldAircraft.RequestLogon(initialTime); oldAircraft.AcceptLogon(initialTime); - await aircraftRepository.Add(new AircraftKey(oldAircraft.Callsign, oldAircraft.AcarsClientId), oldAircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(oldAircraft.Callsign, oldAircraft.AcarsConnectionId), oldAircraft, CancellationToken.None); // Advance time past the timeout var timeout = TimeSpan.FromMinutes(15); @@ -160,11 +234,12 @@ public async Task Handle_OnlyPublishesForTimedOutAircraft() var newAircraft = new AircraftConnection("QFA456", "hoppies-ymmm", "YMMM", DataAuthorityState.CurrentDataAuthority); newAircraft.RequestLogon(now); newAircraft.AcceptLogon(now); - await aircraftRepository.Add(new AircraftKey(newAircraft.Callsign, newAircraft.AcarsClientId), newAircraft, CancellationToken.None); + await aircraftRepository.Add(new AircraftKey(newAircraft.Callsign, newAircraft.AcarsConnectionId), newAircraft, CancellationToken.None); var handler = new CheckLostAircraftConnectionsRequestHandler( aircraftRepository, clock, + StartedLongAgo, mediator, Logger.None); diff --git a/source/CPDLCServer.Tests/Handlers/GetConnectedAircraftRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/GetConnectedAircraftRequestHandlerTests.cs similarity index 87% rename from source/CPDLCServer.Tests/Handlers/GetConnectedAircraftRequestHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/GetConnectedAircraftRequestHandlerTests.cs index 48e0a8b..132156a 100644 --- a/source/CPDLCServer.Tests/Handlers/GetConnectedAircraftRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/GetConnectedAircraftRequestHandlerTests.cs @@ -1,9 +1,7 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Tests.Mocks; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class GetConnectedAircraftRequestHandlerTests { @@ -22,7 +20,7 @@ public async Task Handle_ReturnsAllConnectedAircraft() DataAuthorityState.CurrentDataAuthority); aircraft1.RequestLogon(DateTimeOffset.UtcNow); aircraft1.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft1.Callsign, aircraft1.AcarsClientId), aircraft1, CancellationToken.None); + await aircraftManager.Add(new(aircraft1.Callsign, aircraft1.AcarsConnectionId), aircraft1, CancellationToken.None); var aircraft2 = new AircraftConnection( "QFA456", @@ -30,23 +28,23 @@ public async Task Handle_ReturnsAllConnectedAircraft() "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft2.RequestLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft2.Callsign, aircraft2.AcarsClientId), aircraft2, CancellationToken.None); + await aircraftManager.Add(new(aircraft2.Callsign, aircraft2.AcarsConnectionId), aircraft2, CancellationToken.None); - // Aircraft on different ACARS client - should also be returned + // Aircraft on different ACARS connection - should also be returned var aircraft3 = new AircraftConnection( "AAL789", "hoppies-ymmm", "YMMM", DataAuthorityState.CurrentDataAuthority); aircraft3.RequestLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft3.Callsign, aircraft3.AcarsClientId), aircraft3, CancellationToken.None); + await aircraftManager.Add(new(aircraft3.Callsign, aircraft3.AcarsConnectionId), aircraft3, CancellationToken.None); var query = new GetConnectedAircraftRequest(); // Act var result = await handler.Handle(query, CancellationToken.None); - // Assert - returns ALL aircraft regardless of ACARS client + // Assert - returns ALL aircraft regardless of ACARS connection Assert.NotNull(result); Assert.Equal(3, result.Aircraft.Length); Assert.Contains(result.Aircraft, a => a.Callsign == "UAL123"); @@ -85,7 +83,7 @@ public async Task Handle_IncludesAllConnectionState() DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(DateTimeOffset.UtcNow); aircraft.AcceptLogon(DateTimeOffset.UtcNow); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var query = new GetConnectedAircraftRequest(); diff --git a/source/CPDLCServer.Tests/Handlers/LogonCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs similarity index 72% rename from source/CPDLCServer.Tests/Handlers/LogonCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs index 3eb5c33..cd6a35b 100644 --- a/source/CPDLCServer.Tests/Handlers/LogonCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs @@ -1,12 +1,14 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class LogonCommandHandlerTests { @@ -18,10 +20,10 @@ public class LogonCommandHandlerTests DownlinkAlertType: AlertType.None, DownlinkContent: "REQUEST LOGON", DownlinkReceived: clock.UtcNow(), - AcarsClientId: "hoppies-ybbb"); + AcarsConnectionId: "hoppies-ybbb"); static LogonCommandHandler BuildHandler( - TestClientManager clientManager, + TestAcarsConnectionManager acarsConnectionManager, TestAircraftRepository aircraftRepository, TestControllerRepository controllerRepository, TestDialogueRepository dialogueRepository, @@ -29,13 +31,14 @@ static LogonCommandHandler BuildHandler( TestClock clock, IMediator mediator) => new( - clientManager, + acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator, + new TestUnitOfWork(), Logger.None); [Fact] @@ -43,7 +46,7 @@ public async Task Handle_NoATC_RejectsLogon() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -51,17 +54,17 @@ public async Task Handle_NoATC_RejectsLogon() var mediator = Substitute.For(); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); - // Assert - rejection uplink transmitted via the ACARS client - var client = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - Assert.Equal("LOGON REJECTED. NO ATS AVBL.", client.SentMessages[0].Content); - Assert.Equal("QFA1", client.SentMessages[0].Recipient); - Assert.Equal(1, client.SentMessages[0].MessageReference); + // Assert - rejection uplink transmitted via the ACARS connection + var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.SentMessages); + Assert.Equal("LOGON REJECTED. NO ATS AVBL.", acarsConnection.SentMessages[0].Content); + Assert.Equal("QFA1", acarsConnection.SentMessages[0].Recipient); + Assert.Equal(1, acarsConnection.SentMessages[0].MessageReference); } [Fact] @@ -69,7 +72,7 @@ public async Task Handle_NoATC_DoesNotTrackAircraft() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -77,7 +80,7 @@ public async Task Handle_NoATC_DoesNotTrackAircraft() var mediator = Substitute.For(); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); @@ -92,7 +95,7 @@ public async Task Handle_NewConnection_AcceptsLogon() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -108,17 +111,17 @@ public async Task Handle_NewConnection_AcceptsLogon() await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); // Assert - acceptance uplink transmitted - var client = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - Assert.Equal("LOGON ACCEPTED", client.SentMessages[0].Content); - Assert.Equal("QFA1", client.SentMessages[0].Recipient); - Assert.Equal(1, client.SentMessages[0].MessageReference); + var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.SentMessages); + Assert.Equal("LOGON ACCEPTED", acarsConnection.SentMessages[0].Content); + Assert.Equal("QFA1", acarsConnection.SentMessages[0].Recipient); + Assert.Equal(1, acarsConnection.SentMessages[0].MessageReference); } [Fact] @@ -126,7 +129,7 @@ public async Task Handle_NewConnection_TracksConnection() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -142,7 +145,7 @@ public async Task Handle_NewConnection_TracksConnection() await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); @@ -161,7 +164,7 @@ public async Task Handle_NewConnection_PersistsDialogueWithDownlinkAndUplink() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -177,7 +180,7 @@ public async Task Handle_NewConnection_PersistsDialogueWithDownlinkAndUplink() await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); @@ -204,7 +207,7 @@ public async Task Handle_ExistingConnection_AcceptsLogon_AndDoesNotDuplicateConn { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -225,19 +228,19 @@ public async Task Handle_ExistingConnection_AcceptsLogon_AndDoesNotDuplicateConn await aircraftRepository.Add(new("QFA1", "hoppies-ybbb"), existing, CancellationToken.None); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); // Assert - var client = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - Assert.Equal("LOGON ACCEPTED", client.SentMessages[0].Content); + var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.SentMessages); + Assert.Equal("LOGON ACCEPTED", acarsConnection.SentMessages[0].Content); var allTrackedAircraft = await aircraftRepository.All(CancellationToken.None); - Assert.Single(allTrackedAircraft); - Assert.Equal("QFA1", allTrackedAircraft.Single().Callsign); + Assert.Same(existing, Assert.Single(allTrackedAircraft)); + Assert.Equal(DataAuthorityState.CurrentDataAuthority, existing.DataAuthorityState); } [Fact] @@ -245,7 +248,7 @@ public async Task Handle_NotifiesATC() { // Arrange var clock = new TestClock(); - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var aircraftRepository = new TestAircraftRepository(); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -261,7 +264,7 @@ public async Task Handle_NotifiesATC() await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); - var handler = BuildHandler(clientManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); // Act await handler.Handle(command, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/SendConnectionRequestCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/SendConnectionRequestCommandHandlerTests.cs new file mode 100644 index 0000000..cb5092d --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/SendConnectionRequestCommandHandlerTests.cs @@ -0,0 +1,102 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Connections; + +public class SendConnectionRequestCommandHandlerTests +{ + [Fact] + public async Task Handle_SendsConnectionRequestUplink() + { + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var messageIdProvider = new TestMessageIdProvider(); + messageIdProvider.SetNextId(5); + var clock = new TestClock(); + + var handler = new SendConnectionRequestCommandHandler(acarsConnectionManager, messageIdProvider, clock, new TestUnitOfWork(), Logger.None); + + var command = new SendConnectionRequestCommand("UAL123", "YBBB"); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert + var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + var uplink = Assert.Single(acarsConnection.SentMessages); + Assert.Equal("UAL123", uplink.Recipient); + Assert.Equal("CONNECTION REQUESTED @YBBB@", uplink.Content); + Assert.Equal(5, uplink.MessageId); + Assert.Null(uplink.MessageReference); + Assert.Equal(CpdlcUplinkResponseType.NoResponse, uplink.ResponseType); + Assert.Equal(clock.UtcNow(), uplink.Sent); + } + + [Fact] + public async Task Handle_SendsUplinkViaConnectionForSelectedStation() + { + // The uplink must go through the ACARS connection of the selected ATSU, not another acarsConnection. + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var messageIdProvider = new TestMessageIdProvider(); + var clock = new TestClock(); + + var handler = new SendConnectionRequestCommandHandler(acarsConnectionManager, messageIdProvider, clock, new TestUnitOfWork(), Logger.None); + + var command = new SendConnectionRequestCommand("UAL123", "YMMM"); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert + var ymmmConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ymmm", CancellationToken.None); + var ybbbConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + + var uplink = Assert.Single(ymmmConnection.SentMessages); + Assert.Equal("CONNECTION REQUESTED @YMMM@", uplink.Content); + Assert.Empty(ybbbConnection.SentMessages); + } + + [Fact] + public async Task Handle_MatchesStationIdIgnoringCase() + { + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var messageIdProvider = new TestMessageIdProvider(); + var clock = new TestClock(); + + var handler = new SendConnectionRequestCommandHandler(acarsConnectionManager, messageIdProvider, clock, new TestUnitOfWork(), Logger.None); + + var command = new SendConnectionRequestCommand("UAL123", "ybbb"); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert + var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.SentMessages); + } + + [Fact] + public async Task Handle_ThrowsWhenNoConnectionForStation() + { + // Arrange + var acarsConnectionManager = new TestAcarsConnectionManager(); + var messageIdProvider = new TestMessageIdProvider(); + var clock = new TestClock(); + + var handler = new SendConnectionRequestCommandHandler(acarsConnectionManager, messageIdProvider, clock, new TestUnitOfWork(), Logger.None); + + var command = new SendConnectionRequestCommand("UAL123", "YPPP"); + + // Act & Assert + await Assert.ThrowsAnyAsync(() => handler.Handle(command, CancellationToken.None)); + + var ybbbConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + var ymmmConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ymmm", CancellationToken.None); + Assert.Empty(ybbbConnection.SentMessages); + Assert.Empty(ymmmConnection.SentMessages); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/TerminateConnectionHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionHandlerTests.cs similarity index 96% rename from source/CPDLCServer.Tests/Handlers/TerminateConnectionHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionHandlerTests.cs index b4bbba7..d6d626f 100644 --- a/source/CPDLCServer.Tests/Handlers/TerminateConnectionHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionHandlerTests.cs @@ -1,12 +1,12 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class TerminateConnectionHandlerTests { @@ -27,7 +27,7 @@ static async Task AddConnectedAircraft(TestAircraftRepositor var aircraft = new AircraftConnection(callsign, "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); return aircraft; } @@ -67,7 +67,7 @@ public async Task Handle_RemovesConnectionAndPublishesTerminatedNotification() await mediator.Received(1).Publish( Arg.Is(n => - n.AcarsClientId == "hoppies-ybbb" && + n.AcarsConnectionId == "hoppies-ybbb" && n.StationId == "YBBB" && n.Callsign == "UAL123"), Arg.Any()); diff --git a/source/CPDLCServer.Tests/Handlers/TerminateConnectionOnDialogueClosedHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandlerTests.cs similarity index 93% rename from source/CPDLCServer.Tests/Handlers/TerminateConnectionOnDialogueClosedHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandlerTests.cs index aafa77e..5817024 100644 --- a/source/CPDLCServer.Tests/Handlers/TerminateConnectionOnDialogueClosedHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandlerTests.cs @@ -1,12 +1,13 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class TerminateConnectionOnDialogueClosedHandlerTests { @@ -22,7 +23,7 @@ public async Task Handle_ClosedDialogueWithEndService_TerminatesConnection() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TerminateConnectionOnDialogueClosedHandler( aircraftRepository, @@ -51,7 +52,7 @@ await mediator.Received(1) .Send( Arg.Is(req => req.Callsign == "UAL123" && - req.AcarsClientId == "hoppies-ybbb"), + req.AcarsConnectionId == "hoppies-ybbb"), Arg.Any()); } @@ -67,7 +68,7 @@ public async Task Handle_OpenDialogueWithEndService_DoesNotTerminateConnection() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TerminateConnectionOnDialogueClosedHandler( aircraftRepository, @@ -110,7 +111,7 @@ public async Task Handle_ClosedDialogueWithoutEndService_DoesNotTerminateConnect var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TerminateConnectionOnDialogueClosedHandler( aircraftRepository, @@ -153,7 +154,7 @@ public async Task Handle_ClosedDialogueWithMultipleMessages_TerminatesWhenEndSer var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TerminateConnectionOnDialogueClosedHandler( aircraftRepository, @@ -204,7 +205,7 @@ await mediator.Received(1) .Send( Arg.Is(req => req.Callsign == "UAL123" && - req.AcarsClientId == "hoppies-ybbb"), + req.AcarsConnectionId == "hoppies-ybbb"), Arg.Any()); } @@ -259,7 +260,7 @@ public async Task Handle_AircraftConnectionNotCDA_DoesNotTerminate() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TerminateConnectionOnDialogueClosedHandler( aircraftRepository, diff --git a/source/CPDLCServer.Tests/Handlers/TransmitPendingNdaUplinksCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandlerTests.cs similarity index 88% rename from source/CPDLCServer.Tests/Handlers/TransmitPendingNdaUplinksCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandlerTests.cs index 5b94a78..8ad99b0 100644 --- a/source/CPDLCServer.Tests/Handlers/TransmitPendingNdaUplinksCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandlerTests.cs @@ -1,21 +1,18 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Settings; using CPDLCServer.Tests.Mocks; using MediatR; -using Microsoft.Extensions.Configuration; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class TransmitPendingNdaUplinksCommandHandlerTests { - static IConfiguration DefaultConfiguration() => - new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary { ["Handoff:NotificationLeadTime"] = "10" }) - .Build(); + static TestServerSettingsProvider DefaultSettings() => + new(new ServerSettings { HandoffNotificationLeadTimeMinutes = 10 }); static IAcarsStationRepository OnlineCallsigns(params string[] callsigns) { @@ -35,7 +32,7 @@ public async Task Handle_WhenNoNextDataAuthority_DoesNotSendMessage() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -43,7 +40,7 @@ public async Task Handle_WhenNoNextDataAuthority_DoesNotSendMessage() mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); @@ -65,7 +62,7 @@ public async Task Handle_WhenHandoffMessageAlreadySent_DoesNotSendMessage() aircraft.AcceptLogon(clock.UtcNow()); aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(5)); aircraft.SentNextDataAuthorityMessage(); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -73,7 +70,7 @@ public async Task Handle_WhenHandoffMessageAlreadySent_DoesNotSendMessage() mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); @@ -96,7 +93,7 @@ public async Task Handle_WhenOutsideNotificationWindow_DoesNotSendMessage() // Transfer is 20 minutes away, notification window is 10 minutes, too early to send aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(20)); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -104,7 +101,7 @@ public async Task Handle_WhenOutsideNotificationWindow_DoesNotSendMessage() mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); @@ -127,7 +124,7 @@ public async Task Handle_WhenNdaAtsuIsOffline_DoesNotSendMessage() // Transfer is 5 minutes away, within the notification window aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(5)); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -135,7 +132,7 @@ public async Task Handle_WhenNdaAtsuIsOffline_DoesNotSendMessage() mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); @@ -158,7 +155,7 @@ public async Task Handle_WhenWithinNotificationWindow_SendsNextDataAuthorityMess // Transfer is 5 minutes away, notification window is 10 minutes, within the window aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(5)); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -166,7 +163,7 @@ public async Task Handle_WhenWithinNotificationWindow_SendsNextDataAuthorityMess mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); @@ -195,7 +192,7 @@ public async Task Handle_WhenMessageSent_UpdatesAircraftConnection() // Transfer is 5 minutes away; notification window is 10 minutes → within window aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(5)); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new TransmitPendingNdaUplinksCommandHandler( aircraftRepository, @@ -203,7 +200,7 @@ public async Task Handle_WhenMessageSent_UpdatesAircraftConnection() mediator, clock, Logger.None, - DefaultConfiguration()); + DefaultSettings()); // Act await handler.Handle(new TransmitPendingNdaUplinksCommand(), CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Handlers/UpdateNextDataAuthorityCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandlerTests.cs similarity index 94% rename from source/CPDLCServer.Tests/Handlers/UpdateNextDataAuthorityCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandlerTests.cs index b987942..9a7fbf8 100644 --- a/source/CPDLCServer.Tests/Handlers/UpdateNextDataAuthorityCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandlerTests.cs @@ -1,10 +1,8 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Tests.Mocks; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Connections; public class UpdateNextDataAuthorityCommandHandlerTests { @@ -37,7 +35,7 @@ public async Task Handle_WhenSettingNextDataAuthority_UpdatesAircraftConnection( var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, @@ -72,7 +70,7 @@ public async Task Handle_WhenClearingNextDataAuthority_ClearsAircraftConnection( aircraft.AcceptLogon(clock.UtcNow()); aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(30)); aircraft.SentNextDataAuthorityMessage(); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, @@ -105,11 +103,11 @@ public async Task Handle_WhenMultipleAircraftWithSameCallsign_UpdatesCorrectOne( var aircraftYBBB = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraftYBBB.RequestLogon(clock.UtcNow()); aircraftYBBB.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraftYBBB.Callsign, aircraftYBBB.AcarsClientId), aircraftYBBB, CancellationToken.None); + await aircraftRepository.Add(new(aircraftYBBB.Callsign, aircraftYBBB.AcarsConnectionId), aircraftYBBB, CancellationToken.None); var aircraftYMMM = new AircraftConnection("UAL123", "hoppies-ymmm", "YMMM", DataAuthorityState.NextDataAuthority); aircraftYMMM.RequestLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraftYMMM.Callsign, aircraftYMMM.AcarsClientId), aircraftYMMM, CancellationToken.None); + await aircraftRepository.Add(new(aircraftYMMM.Callsign, aircraftYMMM.AcarsConnectionId), aircraftYMMM, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, @@ -145,7 +143,7 @@ public async Task Handle_WhenUpdatingExistingNextDataAuthority_ReplacesValues() aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(30)); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, @@ -179,7 +177,7 @@ public async Task Handle_WhenUpdatingAfterMessageSent_ClearsFlagToAllowNewMessag aircraft.AcceptLogon(clock.UtcNow()); aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(30)); aircraft.SentNextDataAuthorityMessage(); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, @@ -214,7 +212,7 @@ public async Task Handle_WhenOnlyTransferTimeChangesAfterMessageSent_KeepsFlag() aircraft.AcceptLogon(clock.UtcNow()); aircraft.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(30)); aircraft.SentNextDataAuthorityMessage(); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new UpdateNextDataAuthorityCommandHandler( aircraftRepository, diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandlerTests.cs new file mode 100644 index 0000000..c3fe365 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandlerTests.cs @@ -0,0 +1,152 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Dialogues; + +public class ArchiveCompletedDialoguesRequestHandlerTests +{ + [Fact] + public async Task Handle_ArchivesDialogue_WhenAllMessagesAcknowledgedAndDelayPassed() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create a closed dialogue with acknowledged message + var dialogue = new Dialogue("UAL123"); + dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.NoResponse, + AlertType.None, + "ROGER", + startTime); // NoResponse uplinks are self-closing and auto-acknowledged + await repository.Add(dialogue, CancellationToken.None); + + var handler = new ArchiveCompletedDialoguesRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond archive delay (10 seconds) + clock.SetUtcNow(startTime.AddSeconds(15)); + await handler.Handle(new ArchiveCompletedDialoguesRequest(), CancellationToken.None); + + // Assert + Assert.True(dialogue.IsArchived); + Assert.Single(publisher.PublishedNotifications); + var notification = Assert.IsType(publisher.PublishedNotifications[0]); + Assert.Equal(dialogue, notification.Dialogue); + } + + [Fact] + public async Task Handle_DoesNotArchive_WhenDelayNotPassed() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var dialogue = new Dialogue("UAL123"); + dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.NoResponse, + AlertType.None, + "ROGER", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new ArchiveCompletedDialoguesRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time but not enough (5 seconds < 10 second delay) + clock.SetUtcNow(startTime.AddSeconds(5)); + await handler.Handle(new ArchiveCompletedDialoguesRequest(), CancellationToken.None); + + // Assert + Assert.False(dialogue.IsArchived); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_IgnoresOpenDialogues() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create an open dialogue (requires response) + var dialogue = new Dialogue("UAL123"); + dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.WilcoUnable, + AlertType.None, + "CLIMB TO FL410", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new ArchiveCompletedDialoguesRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond archive delay + clock.SetUtcNow(startTime.AddSeconds(15)); + await handler.Handle(new ArchiveCompletedDialoguesRequest(), CancellationToken.None); + + // Assert - open dialogues should not be archived + Assert.False(dialogue.IsClosed); + Assert.False(dialogue.IsArchived); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_IgnoresDialoguesWithoutAcknowledgements() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create a downlink that's closed but not acknowledged + var dialogue = new Dialogue("UAL123"); + dialogue.AddDownlink( + 1, + null, + "UAL123", + CpdlcDownlinkResponseType.NoResponse, + AlertType.None, + "WILCO", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new ArchiveCompletedDialoguesRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond archive delay + clock.SetUtcNow(startTime.AddSeconds(15)); + await handler.Handle(new ArchiveCompletedDialoguesRequest(), CancellationToken.None); + + // Assert - unacknowledged dialogues should not be archived + Assert.True(dialogue.IsClosed); + Assert.False(dialogue.IsArchived); + Assert.Empty(publisher.PublishedNotifications); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/ArchiveDialogueCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveDialogueCommandHandlerTests.cs similarity index 96% rename from source/CPDLCServer.Tests/Handlers/ArchiveDialogueCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveDialogueCommandHandlerTests.cs index a2ab340..99fb760 100644 --- a/source/CPDLCServer.Tests/Handlers/ArchiveDialogueCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveDialogueCommandHandlerTests.cs @@ -1,10 +1,10 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Dialogues; public class ArchiveDialogueCommandHandlerTests { diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandlerTests.cs new file mode 100644 index 0000000..5ab96c7 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandlerTests.cs @@ -0,0 +1,258 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Dialogues; + +public class CheckMessageTimeoutsRequestHandlerTests +{ + [Fact] + public async Task Handle_MarksPilotLate_WhenUplinkTimesOut() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create an uplink that requires a response + var dialogue = new Dialogue("UAL123"); + var uplink = dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.WilcoUnable, + AlertType.None, + "CLIMB TO FL410", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond pilot late timeout (2 minutes) + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert + Assert.True(uplink.IsPilotLate); + Assert.Single(publisher.PublishedNotifications); + var notification = Assert.IsType(publisher.PublishedNotifications[0]); + Assert.Equal(dialogue, notification.Dialogue); + } + + [Fact] + public async Task Handle_DoesNotMarkPilotLate_WhenTimeoutNotReached() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var dialogue = new Dialogue("UAL123"); + var uplink = dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.WilcoUnable, + AlertType.None, + "CLIMB TO FL410", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time but not beyond timeout (1 minute < 2 minute timeout) + clock.SetUtcNow(startTime.AddMinutes(1)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert + Assert.False(uplink.IsPilotLate); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_IgnoresNoResponseUplinks() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create an uplink that doesn't require a response + var dialogue = new Dialogue("UAL123"); + var uplink = dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.NoResponse, + AlertType.None, + "ROGER", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond timeout + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert - should not be marked late since no response is needed + Assert.False(uplink.IsPilotLate); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_MarksControllerLate_WhenDownlinkTimesOut() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create a downlink that requires a response + var dialogue = new Dialogue("UAL123"); + var downlink = dialogue.AddDownlink( + 1, + null, + "UAL123", + CpdlcDownlinkResponseType.ResponseRequired, + AlertType.None, + "REQUEST CLIMB FL410", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond controller late timeout (2 minutes) + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert + Assert.True(downlink.IsControllerLate); + Assert.Single(publisher.PublishedNotifications); + var notification = Assert.IsType(publisher.PublishedNotifications[0]); + Assert.Equal(dialogue, notification.Dialogue); + } + + [Fact] + public async Task Handle_IgnoresClosedMessages() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var dialogue = new Dialogue("UAL123"); + var uplink = dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.WilcoUnable, + AlertType.None, + "CLIMB TO FL410", + startTime); + + // Close the message + uplink.Close(startTime); + + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond timeout + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert - closed messages should not be marked late + Assert.False(uplink.IsPilotLate); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_IgnoresClosedDialogues() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create a self-closing uplink (NoResponse) + var dialogue = new Dialogue("UAL123"); + dialogue.AddUplink( + 1, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.NoResponse, + AlertType.None, + "ROGER", + startTime); + await repository.Add(dialogue, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond timeout + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert - closed dialogues should be skipped + Assert.True(dialogue.IsClosed); + Assert.Empty(publisher.PublishedNotifications); + } + + [Fact] + public async Task Handle_HandlesMultipleDialogues() + { + // Arrange + var clock = new TestClock(); + var repository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + // Create multiple dialogues with different aircraft + var dialogue1 = new Dialogue("UAL123"); + var uplink1 = dialogue1.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB", startTime); + + var dialogue2 = new Dialogue("DAL456"); + var uplink2 = dialogue2.AddUplink(2, null, "DAL456", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "DESCEND", startTime); + + await repository.Add(dialogue1, CancellationToken.None); + await repository.Add(dialogue2, CancellationToken.None); + + var handler = new CheckMessageTimeoutsRequestHandler(repository, clock, publisher, Logger.None); + + // Act - advance time beyond timeout + clock.SetUtcNow(startTime.AddMinutes(3)); + await handler.Handle(new CheckMessageTimeoutsRequest(), CancellationToken.None); + + // Assert - both should be marked late + Assert.True(uplink1.IsPilotLate); + Assert.True(uplink2.IsPilotLate); + Assert.Equal(2, publisher.PublishedNotifications.Count); + } +} diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueRepositoryTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueRepositoryTests.cs new file mode 100644 index 0000000..e779a23 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueRepositoryTests.cs @@ -0,0 +1,208 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.Cpdlc.Dialogues; + +public class DialogueRepositoryTests +{ + static readonly DateTimeOffset Start = new(2026, 10, 13, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task FindById_ReturnsSavedDialogueWithMessagesInOrder() + { + // Arrange + using var database = new TestDatabase(); + var dialogue = new Dialogue("UAL123"); + dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", Start); + dialogue.AddUplink(1, 7, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "DESCEND TO FL350", Start.AddMinutes(1)); + dialogue.AddDownlink(8, 1, "UAL123", CpdlcDownlinkResponseType.NoResponse, AlertType.None, "WILCO", Start.AddMinutes(2)); + + await using (var dbContext = database.CreateDbContext()) + { + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using var readDbContext = database.CreateDbContext(); + var saved = await new DialogueRepository(readDbContext).FindById(dialogue.Id, CancellationToken.None); + + // Assert + Assert.NotNull(saved); + Assert.Equal("UAL123", saved.AircraftCallsign); + Assert.Equal(dialogue.Opened, saved.Opened); + Assert.Equal(dialogue.Closed, saved.Closed); + Assert.True(saved.IsClosed); + Assert.Equal([7, 1, 8], saved.Messages.Select(m => m.MessageId)); + + var request = Assert.IsType(saved.Messages[0]); + Assert.Equal("REQUEST DESCENT FL350", request.Content); + Assert.Equal(CpdlcDownlinkResponseType.ResponseRequired, request.ResponseType); + Assert.True(request.IsAcknowledged); + + var clearance = Assert.IsType(saved.Messages[1]); + Assert.Equal("DESCEND TO FL350", clearance.Content); + Assert.Equal("BN-TSN_FSS", clearance.SenderCallsign); + Assert.Equal(CpdlcUplinkResponseType.WilcoUnable, clearance.ResponseType); + Assert.Equal(7, clearance.MessageReference); + Assert.Equal(Start.AddMinutes(2), clearance.Closed); + } + + [Fact] + public async Task Add_MessageToSavedDialogue_SavesMessage() + { + // Arrange + using var database = new TestDatabase(); + var dialogue = new Dialogue("UAL123"); + dialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); + + await using (var dbContext = database.CreateDbContext()) + { + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using (var dbContext = database.CreateDbContext()) + { + var saved = await new DialogueRepository(dbContext).FindById(dialogue.Id, CancellationToken.None); + saved!.AddDownlink(5, 1, "UAL123", CpdlcDownlinkResponseType.NoResponse, AlertType.None, "WILCO", Start.AddMinutes(1)); + await dbContext.SaveChangesAsync(); + } + + // Assert + await using var readDbContext = database.CreateDbContext(); + var result = await new DialogueRepository(readDbContext).FindById(dialogue.Id, CancellationToken.None); + Assert.NotNull(result); + Assert.Equal(2, result.Messages.Count); + Assert.True(result.IsClosed); + } + + [Fact] + public async Task FindOpenDialogueByUplink_FindsDialogueAddedInSameUnitOfWork() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var repository = new DialogueRepository(dbContext); + + var dialogue = new Dialogue("UAL123"); + dialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); + await repository.Add(dialogue, CancellationToken.None); + + // Act + var result = await repository.FindOpenDialogueByUplink("UAL123", 1, CancellationToken.None); + + // Assert + Assert.Same(dialogue, result); + } + + [Fact] + public async Task FindOpen_ReturnsOnlyOpenDialogues() + { + // Arrange + using var database = new TestDatabase(); + var open = CreateOpenDialogue("UAL123", Start); + var closed = CreateClosedDialogue("QFA1", Start); + await AddAndSave(database, open, closed); + + // Act + await using var dbContext = database.CreateDbContext(); + var result = await new DialogueRepository(dbContext).FindOpen(CancellationToken.None); + + // Assert + Assert.Equal([open.Id], result.Select(d => d.Id)); + } + + [Fact] + public async Task FindClosedAndNotArchived_ReturnsOnlyClosedDialoguesThatAreNotArchived() + { + // Arrange + using var database = new TestDatabase(); + var open = CreateOpenDialogue("UAL123", Start); + var closed = CreateClosedDialogue("QFA1", Start); + var archived = CreateClosedDialogue("VOZ1", Start); + archived.Archive(Start.AddMinutes(1)); + await AddAndSave(database, open, closed, archived); + + // Act + await using var dbContext = database.CreateDbContext(); + var result = await new DialogueRepository(dbContext).FindClosedAndNotArchived(CancellationToken.None); + + // Assert + Assert.Equal([closed.Id], result.Select(d => d.Id)); + } + + [Fact] + public async Task FindOpenedBefore_ReturnsOnlyOlderDialogues() + { + // Arrange + using var database = new TestDatabase(); + var older = CreateOpenDialogue("UAL123", Start); + var newer = CreateOpenDialogue("QFA1", Start.AddHours(2)); + await AddAndSave(database, older, newer); + + // Act + await using var dbContext = database.CreateDbContext(); + var result = await new DialogueRepository(dbContext).FindOpenedBefore(Start.AddHours(1), CancellationToken.None); + + // Assert + Assert.Equal([older.Id], result.Select(d => d.Id)); + } + + [Fact] + public async Task Remove_DeletesDialogueAndMessages() + { + // Arrange + using var database = new TestDatabase(); + var dialogue = new Dialogue("UAL123"); + dialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); + + await using (var dbContext = database.CreateDbContext()) + { + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using (var dbContext = database.CreateDbContext()) + { + var repository = new DialogueRepository(dbContext); + var saved = await repository.FindById(dialogue.Id, CancellationToken.None); + await repository.Remove(saved!, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + await using var readDbContext = database.CreateDbContext(); + Assert.Empty(await new DialogueRepository(readDbContext).All(CancellationToken.None)); + Assert.Empty(readDbContext.Set()); + } + + static async Task AddAndSave(TestDatabase database, params Dialogue[] dialogues) + { + await using var dbContext = database.CreateDbContext(); + var repository = new DialogueRepository(dbContext); + + foreach (var dialogue in dialogues) + await repository.Add(dialogue, CancellationToken.None); + + await dbContext.SaveChangesAsync(); + } + + static Dialogue CreateOpenDialogue(string callsign, DateTimeOffset time) + { + var dialogue = new Dialogue(callsign); + dialogue.AddUplink(1, null, callsign, "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", time); + return dialogue; + } + + static Dialogue CreateClosedDialogue(string callsign, DateTimeOffset time) + { + var dialogue = new Dialogue(callsign); + dialogue.AddUplink(1, null, callsign, "BN-TSN_FSS", CpdlcUplinkResponseType.NoResponse, AlertType.None, "MONITOR BRISBANE CENTRE 128.6", time); + return dialogue; + } +} diff --git a/source/CPDLCServer.Tests/Model/DialogueTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueTests.cs similarity index 86% rename from source/CPDLCServer.Tests/Model/DialogueTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueTests.cs index 5fc2035..e03fb92 100644 --- a/source/CPDLCServer.Tests/Model/DialogueTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueTests.cs @@ -1,6 +1,8 @@ -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; -namespace CPDLCServer.Tests.Model; +namespace CPDLCServer.Tests.Cpdlc.Dialogues; public class DialogueTests { @@ -412,4 +414,37 @@ public void Dialogue_LogonRequestAndAcceptanceClosesImmediately() Assert.True(dialogue.IsArchived); // Dialogue is auto-archived with LOGON ACCEPTED Assert.Equal(logonAccepted.Sent, dialogue.Archived); } + + [Fact] + public void AddMessage_WithEarlierTime_IsPlacedByTime() + { + // Arrange + var time = new DateTimeOffset(2025, 1, 15, 10, 30, 0, TimeSpan.Zero); + var dialogue = new Dialogue("UAL123"); + dialogue.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB FL410", time); + dialogue.AddDownlink(3, null, "UAL123", CpdlcDownlinkResponseType.NoResponse, AlertType.None, "FREE TEXT", time.AddMinutes(2)); + + // Act + dialogue.AddDownlink(2, null, "UAL123", CpdlcDownlinkResponseType.NoResponse, AlertType.None, "FREE TEXT", time.AddMinutes(1)); + + // Assert + Assert.Equal([1, 2, 3], dialogue.Messages.Select(m => m.MessageId)); + Assert.Equal([0, 1, 2], dialogue.Messages.Select(m => m.Position)); + } + + [Fact] + public void AddMessage_WithEarlierTimeThanReferencedMessage_IsPlacedAfterReferencedMessage() + { + // Arrange - the reply has an earlier time than the request, for example because of a clock difference + var time = new DateTimeOffset(2025, 1, 15, 10, 30, 0, TimeSpan.Zero); + var dialogue = new Dialogue("UAL123"); + dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB FL410", time); + + // Act + dialogue.AddUplink(1, 7, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", time.AddSeconds(-5)); + + // Assert + Assert.Equal([7, 1], dialogue.Messages.Select(m => m.MessageId)); + Assert.Equal([0, 1], dialogue.Messages.Select(m => m.Position)); + } } diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandlerTests.cs new file mode 100644 index 0000000..62ed9db --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandlerTests.cs @@ -0,0 +1,36 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Dialogues; + +public class PurgeExpiredCpdlcDataRequestHandlerTests +{ + [Fact] + public async Task Handle_RemovesDialoguesOpenedMoreThan24HoursAgo() + { + // Arrange + var clock = new TestClock(); + var dialogueRepository = new TestDialogueRepository(); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var oldDialogue = new Dialogue("UAL123"); + oldDialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", startTime); + var newDialogue = new Dialogue("QFA1"); + newDialogue.AddUplink(1, null, "QFA1", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", startTime.AddHours(2)); + await dialogueRepository.Add(oldDialogue, CancellationToken.None); + await dialogueRepository.Add(newDialogue, CancellationToken.None); + + var handler = new PurgeExpiredCpdlcDataRequestHandler(dialogueRepository, clock, Logger.None); + + // Act - advance time beyond the purge timeout (24 hours) for the old dialogue only + clock.SetUtcNow(startTime.AddHours(25)); + await handler.Handle(new PurgeExpiredCpdlcDataRequest(), CancellationToken.None); + + // Assert + Assert.Equal([newDialogue], await dialogueRepository.All(CancellationToken.None)); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/AcknowledgeDownlinkCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandlerTests.cs similarity index 97% rename from source/CPDLCServer.Tests/Handlers/AcknowledgeDownlinkCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandlerTests.cs index 108b715..2ed656b 100644 --- a/source/CPDLCServer.Tests/Handlers/AcknowledgeDownlinkCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandlerTests.cs @@ -1,10 +1,9 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; using CPDLCServer.Tests.Mocks; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Downlinks; public class AcknowledgeDownlinkCommandHandlerTests { diff --git a/source/CPDLCServer.Tests/Handlers/DownlinkReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs similarity index 96% rename from source/CPDLCServer.Tests/Handlers/DownlinkReceivedNotificationHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs index 13708df..e09a6c1 100644 --- a/source/CPDLCServer.Tests/Handlers/DownlinkReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs @@ -1,14 +1,16 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Web; using CPDLCServer.Tests.Mocks; using MediatR; using Microsoft.AspNetCore.SignalR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Downlinks; public class DownlinkReceivedNotificationHandlerTests { @@ -26,6 +28,7 @@ static DownlinkReceivedNotificationHandler BuildHandler( controllerRepository, dialogueRepository, hubContext, + new TestUnitOfWork(), Logger.None); [Fact] @@ -37,7 +40,7 @@ public async Task Handle_PublishesDialogueChangedNotification() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller1 = new ControllerInfo( @@ -101,7 +104,7 @@ public async Task Handle_StillCreatesDialogueWhenNoControllersMatch() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -154,7 +157,7 @@ public async Task Handle_PromotesAircraftToCurrentDataAuthorityOnFirstDownlink() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -226,7 +229,7 @@ public async Task Handle_DoesNotPromoteToCurrentDataAuthority_WhenNotCurrentData var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -289,7 +292,7 @@ public async Task Handle_UpdatesLastSeen() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); aircraft.RequestLogon(logonTime); aircraft.AcceptLogon(logonTime); - await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerManager = new TestControllerRepository(); var controller = new ControllerInfo( @@ -345,7 +348,7 @@ public async Task Handle_CreatesNewDialogue_ForDownlinkWithNoReference() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -387,7 +390,7 @@ public async Task Handle_AppendsToExistingDialogue_ForDownlinkWithReference() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -444,7 +447,7 @@ public async Task Handle_FallsBackToNewDialogue_WhenNoOpenDialogueMatchesReferen var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -492,7 +495,7 @@ public async Task Handle_DoesNotAppendToClosedDialogue_WhenAircraftReusesMessage var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -550,7 +553,7 @@ public async Task Handle_LogoffMessage_TerminatesConnectionAndCreatesDialogue() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -572,7 +575,7 @@ public async Task Handle_LogoffMessage_TerminatesConnectionAndCreatesDialogue() // Assert - connection termination was requested await mediator.Received(1).Send( - Arg.Is(r => r.Callsign == "UAL123" && r.AcarsClientId == "hoppies-ybbb"), + Arg.Is(r => r.Callsign == "UAL123" && r.AcarsConnectionId == "hoppies-ybbb"), Arg.Any()); // Assert - logoff message still created a dialogue for the controller to see @@ -595,7 +598,7 @@ public async Task Handle_LogoffMessage_FromNextDataAuthority_DoesNotPromoteOrNot var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var controller = new ControllerInfo( @@ -636,7 +639,7 @@ await clientProxy.DidNotReceive().SendCoreAsync( // Assert - connection termination was requested await mediator.Received(1).Send( - Arg.Is(r => r.Callsign == "UAL123" && r.AcarsClientId == "hoppies-ybbb"), + Arg.Is(r => r.Callsign == "UAL123" && r.AcarsConnectionId == "hoppies-ybbb"), Arg.Any()); } @@ -651,7 +654,7 @@ public async Task Handle_LogoffMessage_PublishesDialogueBeforeTerminatingConnect var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var controllerRepository = new TestControllerRepository(); var dialogueRepository = new TestDialogueRepository(); @@ -708,14 +711,14 @@ public async Task Handle_LogonRequest_DispatchesLogonCommand() // Act await handler.Handle(notification, CancellationToken.None); - // Assert - LogonCommand dispatched with downlink primitives + AcarsClientId + // Assert - LogonCommand dispatched with downlink primitives + AcarsConnectionId await mediator.Received(1).Send( Arg.Is(c => c.DownlinkId == 1 && c.DownlinkMessageReference == null && c.Callsign == "QFA1" && c.DownlinkContent == "REQUEST LOGON" && - c.AcarsClientId == "hoppies-ybbb"), + c.AcarsConnectionId == "hoppies-ybbb"), Arg.Any()); // Notification handler must not have created a dialogue itself - LogonCommandHandler owns it. diff --git a/source/CPDLCServer.Tests/Handlers/AcknowledgeUplinkCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandlerTests.cs similarity index 98% rename from source/CPDLCServer.Tests/Handlers/AcknowledgeUplinkCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandlerTests.cs index d337c1e..349933e 100644 --- a/source/CPDLCServer.Tests/Handlers/AcknowledgeUplinkCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandlerTests.cs @@ -1,10 +1,10 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Uplinks; public class AcknowledgeUplinkCommandHandlerTests { diff --git a/source/CPDLCServer.Tests/Handlers/BeginDialogueCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/BeginDialogueCommandHandlerTests.cs similarity index 73% rename from source/CPDLCServer.Tests/Handlers/BeginDialogueCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Uplinks/BeginDialogueCommandHandlerTests.cs index ef57462..e82491b 100644 --- a/source/CPDLCServer.Tests/Handlers/BeginDialogueCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/BeginDialogueCommandHandlerTests.cs @@ -1,12 +1,12 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Uplinks; public class BeginDialogueCommandHandlerTests { @@ -14,7 +14,7 @@ public class BeginDialogueCommandHandlerTests public async Task Handle_CreatesNewDialogue() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -24,10 +24,10 @@ public async Task Handle_CreatesNewDialogue() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -47,7 +47,7 @@ public async Task Handle_UplinkHasNullMessageReference() { // A dialogue begun by the controller is never a reply - MessageReference must be null. // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -57,10 +57,10 @@ public async Task Handle_UplinkHasNullMessageReference() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -74,10 +74,10 @@ public async Task Handle_UplinkHasNullMessageReference() } [Fact] - public async Task Handle_SendsUplinkViaAcarsClient() + public async Task Handle_SendsUplinkViaAcarsConnection() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -87,10 +87,10 @@ public async Task Handle_SendsUplinkViaAcarsClient() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -98,17 +98,17 @@ public async Task Handle_SendsUplinkViaAcarsClient() await handler.Handle(command, CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - Assert.Equal("UAL123", client.SentMessages[0].Recipient); - Assert.Equal("CLIMB TO FL410", client.SentMessages[0].Content); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.SentMessages); + Assert.Equal("UAL123", acarsConnection.SentMessages[0].Recipient); + Assert.Equal("CLIMB TO FL410", acarsConnection.SentMessages[0].Content); } [Fact] public async Task Handle_PublishesDialogueChangedNotification() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -118,10 +118,10 @@ public async Task Handle_PublishesDialogueChangedNotification() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -136,7 +136,7 @@ public async Task Handle_PublishesDialogueChangedNotification() public async Task Handle_ThrowsWhenAircraftNotConnected() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -146,7 +146,7 @@ public async Task Handle_ThrowsWhenAircraftNotConnected() // No aircraft added var handler = new BeginDialogueCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); diff --git a/source/CPDLCServer.Tests/Services/MessageIdProviderTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/MessageIdProviderTests.cs similarity index 57% rename from source/CPDLCServer.Tests/Services/MessageIdProviderTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Uplinks/MessageIdProviderTests.cs index 7f0563c..80db06e 100644 --- a/source/CPDLCServer.Tests/Services/MessageIdProviderTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/MessageIdProviderTests.cs @@ -1,6 +1,7 @@ -using CPDLCServer.Services; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; -namespace CPDLCServer.Tests.Services; +namespace CPDLCServer.Tests.Cpdlc.Uplinks; public class MessageIdProviderTests { @@ -8,7 +9,9 @@ public class MessageIdProviderTests public async Task GetNextMessageId_FirstCall_ReturnsOne() { // Arrange - var provider = new MessageIdProvider(); + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var provider = new MessageIdProvider(dbContext); // Act var messageId = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); @@ -21,7 +24,9 @@ public async Task GetNextMessageId_FirstCall_ReturnsOne() public async Task GetNextMessageId_SequentialCalls_IncrementsForSamePair() { // Arrange - var provider = new MessageIdProvider(); + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var provider = new MessageIdProvider(dbContext); // Act var id1 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); @@ -38,7 +43,9 @@ public async Task GetNextMessageId_SequentialCalls_IncrementsForSamePair() public async Task GetNextMessageId_DifferentCallsigns_MaintainsSeparateSequences() { // Arrange - var provider = new MessageIdProvider(); + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var provider = new MessageIdProvider(dbContext); // Act var ual1 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); @@ -57,7 +64,9 @@ public async Task GetNextMessageId_DifferentCallsigns_MaintainsSeparateSequences public async Task GetNextMessageId_DifferentStations_MaintainsSeparateSequences() { // Arrange - var provider = new MessageIdProvider(); + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var provider = new MessageIdProvider(dbContext); // Act var ybbb1 = await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); @@ -71,4 +80,27 @@ public async Task GetNextMessageId_DifferentStations_MaintainsSeparateSequences( Assert.Equal(2, ybbb2); Assert.Equal(2, ymmm2); } + + [Fact] + public async Task GetNextMessageId_AfterRestart_ContinuesSequence() + { + // Arrange + using var database = new TestDatabase(); + + await using (var dbContext = database.CreateDbContext()) + { + var provider = new MessageIdProvider(dbContext); + await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using var newDbContext = database.CreateDbContext(); + var newProvider = new MessageIdProvider(newDbContext); + var messageId = await newProvider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + + // Assert + Assert.Equal(3, messageId); + } } diff --git a/source/CPDLCServer.Tests/Handlers/ReplyToDownlinkCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/ReplyToDownlinkCommandHandlerTests.cs similarity index 79% rename from source/CPDLCServer.Tests/Handlers/ReplyToDownlinkCommandHandlerTests.cs rename to source/CPDLCServer.Tests/Cpdlc/Uplinks/ReplyToDownlinkCommandHandlerTests.cs index 02336d8..5c33d9f 100644 --- a/source/CPDLCServer.Tests/Handlers/ReplyToDownlinkCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/ReplyToDownlinkCommandHandlerTests.cs @@ -1,12 +1,13 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.Cpdlc.Uplinks; public class ReplyToDownlinkCommandHandlerTests { @@ -17,7 +18,7 @@ public async Task Handle_AppendsUplinkToExistingDialogue_NotCreatingNew() // to the existing dialogue, not start a new one. // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -27,7 +28,7 @@ public async Task Handle_AppendsUplinkToExistingDialogue_NotCreatingNew() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var dialogue = new Dialogue("UAL123"); dialogue.AddDownlink( @@ -41,7 +42,7 @@ public async Task Handle_AppendsUplinkToExistingDialogue_NotCreatingNew() await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); var command = new ReplyToDownlinkCommand("BN-TSN_FSS", dialogue.Id, 7, CpdlcUplinkResponseType.WilcoUnable, "DESCEND FL350"); @@ -64,7 +65,7 @@ public async Task Handle_UplinkMessageReferenceMatchesDownlinkId() // The outgoing uplink must carry the downlink's MessageId as its MessageReference // so the aircraft knows which of its messages is being replied to. // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -74,14 +75,14 @@ public async Task Handle_UplinkMessageReferenceMatchesDownlinkId() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var dialogue = new Dialogue("UAL123"); dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", clock.UtcNow()); await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); // Act await handler.Handle( @@ -101,7 +102,7 @@ public async Task Handle_UsesDialogueId_WhenMultipleDialoguesHaveSameDownlinkMes // same MessageId. The fix uses DialogueId for unambiguous lookup. // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -111,7 +112,7 @@ public async Task Handle_UsesDialogueId_WhenMultipleDialoguesHaveSameDownlinkMes var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); // Both dialogues have a downlink with MessageId=1 (aircraft re-used the same ID) var dialogueA = new Dialogue("UAL123"); @@ -123,7 +124,7 @@ public async Task Handle_UsesDialogueId_WhenMultipleDialoguesHaveSameDownlinkMes await dialogueRepository.Add(dialogueB, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); // Controller explicitly replies to dialogueA await handler.Handle( @@ -136,10 +137,10 @@ await handler.Handle( } [Fact] - public async Task Handle_SendsUplinkViaAcarsClient() + public async Task Handle_SendsUplinkViaAcarsConnection() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -149,14 +150,14 @@ public async Task Handle_SendsUplinkViaAcarsClient() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var dialogue = new Dialogue("UAL123"); dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", clock.UtcNow()); await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); // Act await handler.Handle( @@ -164,18 +165,18 @@ await handler.Handle( CancellationToken.None); // Assert - var client = (TestAcarsClient) await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - Assert.Equal("UAL123", client.SentMessages[0].Recipient); - Assert.Equal("DESCEND FL350", client.SentMessages[0].Content); - Assert.Equal(7, client.SentMessages[0].MessageReference); + var acarsConnection = (TestAcarsConnection) await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Single(acarsConnection.SentMessages); + Assert.Equal("UAL123", acarsConnection.SentMessages[0].Recipient); + Assert.Equal("DESCEND FL350", acarsConnection.SentMessages[0].Content); + Assert.Equal(7, acarsConnection.SentMessages[0].MessageReference); } [Fact] public async Task Handle_PublishesDialogueChangedNotification() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -185,14 +186,14 @@ public async Task Handle_PublishesDialogueChangedNotification() var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); aircraft.RequestLogon(clock.UtcNow()); aircraft.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsClientId), aircraft, CancellationToken.None); + await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var dialogue = new Dialogue("UAL123"); dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", clock.UtcNow()); await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); // Act await handler.Handle( @@ -209,7 +210,7 @@ await mediator.Received(1).Publish( public async Task Handle_ThrowsWhenDialogueNotFound() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -217,7 +218,7 @@ public async Task Handle_ThrowsWhenDialogueNotFound() var aircraftRepository = new TestAircraftRepository(); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); // Act & Assert await Assert.ThrowsAsync(() => @@ -230,7 +231,7 @@ await Assert.ThrowsAsync(() => public async Task Handle_ThrowsWhenAircraftNotConnected() { // Arrange - var clientManager = new TestClientManager(); + var acarsConnectionManager = new TestAcarsConnectionManager(); var messageIdProvider = new TestMessageIdProvider(); var dialogueRepository = new TestDialogueRepository(); var mediator = Substitute.For(); @@ -243,7 +244,7 @@ public async Task Handle_ThrowsWhenAircraftNotConnected() await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, clientManager, messageIdProvider, dialogueRepository, mediator, clock, Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); // Act & Assert await Assert.ThrowsAsync(() => diff --git a/source/CPDLCServer.Tests/Handlers/SendConnectionRequestCommandHandlerTests.cs b/source/CPDLCServer.Tests/Handlers/SendConnectionRequestCommandHandlerTests.cs deleted file mode 100644 index d091993..0000000 --- a/source/CPDLCServer.Tests/Handlers/SendConnectionRequestCommandHandlerTests.cs +++ /dev/null @@ -1,103 +0,0 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Tests.Mocks; -using Serilog.Core; - -namespace CPDLCServer.Tests.Handlers; - -public class SendConnectionRequestCommandHandlerTests -{ - [Fact] - public async Task Handle_SendsConnectionRequestUplink() - { - // Arrange - var clientManager = new TestClientManager(); - var messageIdProvider = new TestMessageIdProvider(); - messageIdProvider.SetNextId(5); - var clock = new TestClock(); - - var handler = new SendConnectionRequestCommandHandler(clientManager, messageIdProvider, clock, Logger.None); - - var command = new SendConnectionRequestCommand("UAL123", "YBBB"); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - var client = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - var uplink = Assert.Single(client.SentMessages); - Assert.Equal("UAL123", uplink.Recipient); - Assert.Equal("CONNECTION REQUESTED @YBBB@", uplink.Content); - Assert.Equal(5, uplink.MessageId); - Assert.Null(uplink.MessageReference); - Assert.Equal(CpdlcUplinkResponseType.NoResponse, uplink.ResponseType); - Assert.Equal(clock.UtcNow(), uplink.Sent); - } - - [Fact] - public async Task Handle_SendsUplinkViaClientForSelectedStation() - { - // The uplink must go through the ACARS client of the selected ATSU, not another client. - // Arrange - var clientManager = new TestClientManager(); - var messageIdProvider = new TestMessageIdProvider(); - var clock = new TestClock(); - - var handler = new SendConnectionRequestCommandHandler(clientManager, messageIdProvider, clock, Logger.None); - - var command = new SendConnectionRequestCommand("UAL123", "YMMM"); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - var ymmmClient = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ymmm", CancellationToken.None); - var ybbbClient = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - - var uplink = Assert.Single(ymmmClient.SentMessages); - Assert.Equal("CONNECTION REQUESTED @YMMM@", uplink.Content); - Assert.Empty(ybbbClient.SentMessages); - } - - [Fact] - public async Task Handle_MatchesStationIdIgnoringCase() - { - // Arrange - var clientManager = new TestClientManager(); - var messageIdProvider = new TestMessageIdProvider(); - var clock = new TestClock(); - - var handler = new SendConnectionRequestCommandHandler(clientManager, messageIdProvider, clock, Logger.None); - - var command = new SendConnectionRequestCommand("UAL123", "ybbb"); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - var client = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - Assert.Single(client.SentMessages); - } - - [Fact] - public async Task Handle_ThrowsWhenNoClientForStation() - { - // Arrange - var clientManager = new TestClientManager(); - var messageIdProvider = new TestMessageIdProvider(); - var clock = new TestClock(); - - var handler = new SendConnectionRequestCommandHandler(clientManager, messageIdProvider, clock, Logger.None); - - var command = new SendConnectionRequestCommand("UAL123", "YPPP"); - - // Act & Assert - await Assert.ThrowsAnyAsync(() => handler.Handle(command, CancellationToken.None)); - - var ybbbClient = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ybbb", CancellationToken.None); - var ymmmClient = (TestAcarsClient)await clientManager.GetAcarsClient("hoppies-ymmm", CancellationToken.None); - Assert.Empty(ybbbClient.SentMessages); - Assert.Empty(ymmmClient.SentMessages); - } -} diff --git a/source/CPDLCServer.Tests/Logging/LogBufferTests.cs b/source/CPDLCServer.Tests/Logging/LogBufferTests.cs new file mode 100644 index 0000000..f065315 --- /dev/null +++ b/source/CPDLCServer.Tests/Logging/LogBufferTests.cs @@ -0,0 +1,105 @@ +using CPDLCServer.Logging; +using Serilog; +using Serilog.Events; + +namespace CPDLCServer.Tests.Logging; + +public class LogBufferTests +{ + [Fact] + public void Add_KeepsOnlyTheMostRecentEntries() + { + // Arrange + var logBuffer = new LogBuffer(capacity: 2); + + // Act + logBuffer.Add(CreateEntry("first")); + logBuffer.Add(CreateEntry("second")); + logBuffer.Add(CreateEntry("third")); + + // Assert + using var subscription = logBuffer.Subscribe(); + Assert.Equal(["second", "third"], subscription.RecentEntries.Select(e => e.Message)); + } + + [Fact] + public void Add_SetsIncreasingSequenceNumbers() + { + // Arrange + var logBuffer = new LogBuffer(); + + // Act + logBuffer.Add(CreateEntry("first")); + logBuffer.Add(CreateEntry("second")); + + // Assert + using var subscription = logBuffer.Subscribe(); + Assert.Equal([1L, 2L], subscription.RecentEntries.Select(e => e.Sequence)); + } + + [Fact] + public void Subscribe_ReceivesNewEntries() + { + // Arrange + var logBuffer = new LogBuffer(); + logBuffer.Add(CreateEntry("before")); + using var subscription = logBuffer.Subscribe(); + + // Act + logBuffer.Add(CreateEntry("after")); + + // Assert + Assert.Equal(["before"], subscription.RecentEntries.Select(e => e.Message)); + Assert.True(subscription.NewEntries.TryRead(out var entry)); + Assert.Equal("after", entry.Message); + Assert.False(subscription.NewEntries.TryRead(out _)); + } + + [Fact] + public void Dispose_StopsTheSubscription() + { + // Arrange + var logBuffer = new LogBuffer(); + var subscription = logBuffer.Subscribe(); + + // Act + subscription.Dispose(); + logBuffer.Add(CreateEntry("after")); + + // Assert + Assert.False(subscription.NewEntries.TryRead(out _)); + Assert.True(subscription.NewEntries.Completion.IsCompleted); + } + + [Fact] + public void Sink_WritesTheSameTextAsTheConsole() + { + // Arrange + var logBuffer = new LogBuffer(); + using var logger = new LoggerConfiguration() + .MinimumLevel.Verbose() + .WriteTo.Sink(new LogBufferSink(logBuffer)) + .CreateLogger(); + + // Act + logger.ForContext("Station", "YBBB").Warning("Aircraft {Callsign} not seen", "UAL123"); + logger.Error(new InvalidOperationException("Send failed"), "Error sending message"); + + // Assert + using var subscription = logBuffer.Subscribe(); + var warning = subscription.RecentEntries[0]; + Assert.Equal(nameof(LogEventLevel.Warning), warning.Level); + Assert.Equal("WRN", warning.LevelCode); + Assert.Equal("Aircraft UAL123 not seen", warning.Message); + Assert.Null(warning.Exception); + + var error = subscription.RecentEntries[1]; + Assert.Equal("ERR", error.LevelCode); + Assert.Contains("Send failed", error.Exception); + } + + static LogEntry CreateEntry(string message) + { + return new LogEntry(0, "12:00:00", "Information", "INF", message, null); + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestAcarsClient.cs b/source/CPDLCServer.Tests/Mocks/TestAcarsConnection.cs similarity index 90% rename from source/CPDLCServer.Tests/Mocks/TestAcarsClient.cs rename to source/CPDLCServer.Tests/Mocks/TestAcarsConnection.cs index de2d30e..dbec1db 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAcarsClient.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAcarsConnection.cs @@ -1,10 +1,12 @@ using System.Threading.Channels; -using CPDLCServer.Clients; -using CPDLCServer.Model; +using CPDLCServer.AcarsConnections; +using CPDLCServer.AdscContracts; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; namespace CPDLCServer.Tests.Mocks; -public class TestAcarsClient(string stationId) : IAcarsClient +public class TestAcarsConnection(string stationId) : IAcarsConnection { private readonly Channel _channel = Channel.CreateUnbounded(); private readonly Channel _adscChannel = Channel.CreateUnbounded(); diff --git a/source/CPDLCServer.Tests/Mocks/TestAcarsConnectionManager.cs b/source/CPDLCServer.Tests/Mocks/TestAcarsConnectionManager.cs new file mode 100644 index 0000000..66227b0 --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestAcarsConnectionManager.cs @@ -0,0 +1,117 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.AcarsConnections.ConnectionSettings; + +namespace CPDLCServer.Tests.Mocks; + +public class TestAcarsConnectionManager : IAcarsConnectionManager +{ + private readonly Dictionary _connections = new(); + private readonly Dictionary _configurations = new(); + + public TestAcarsConnectionManager() + { + AddConnection("hoppies-ybbb", new TestAcarsConnection("YBBB")); + AddConnection("hoppies-ymmm", new TestAcarsConnection("YMMM")); + AddConfiguration(CreateConfiguration("YBBB", 10)); + AddConfiguration(CreateConfiguration("YMMM", 20)); + } + + public void AddConnection(string acarsConnectionId, IAcarsConnection connection) + { + _connections[acarsConnectionId] = connection; + } + + public void AddConfiguration(HoppiesConfiguration configuration) + { + _configurations[configuration.StationIdentifier] = configuration; + } + + public static HoppiesConfiguration CreateConfiguration( + string stationId, + int defaultAdscReportingInterval, + int selectedAdscContractDuration = 60) + { + return new HoppiesConfiguration + { + Url = new Uri("http://test.hoppie.nl/acars"), + AuthenticationCode = "TEST123", + FlightSimulationNetwork = "VATSIM", + StationIdentifier = stationId, + DefaultAdscReportingInterval = defaultAdscReportingInterval, + SelectedAdscContractDuration = selectedAdscContractDuration + }; + } + + public Task GetAcarsConnection(string acarsConnectionId, CancellationToken cancellationToken) + { + if (!_connections.TryGetValue(acarsConnectionId, out var connection)) + { + throw new ConfigurationNotFoundException(acarsConnectionId); + } + return Task.FromResult(connection); + } + + public Task GetAcarsConnectionForStation(string stationId, CancellationToken cancellationToken) + { + var connection = _connections.Values.FirstOrDefault(c => c.StationId == stationId); + if (connection is null) + { + throw new Exception($"No ACARS connection found for station '{stationId}'"); + } + return Task.FromResult(connection); + } + + public Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken) + { + if (!_configurations.TryGetValue(stationId, out var configuration)) + { + throw new Exception($"No ACARS configuration found for station '{stationId}'"); + } + return Task.FromResult(configuration); + } + + public Task FindAcarsConnectionId(string stationId, CancellationToken cancellationToken) + { + var acarsConnectionId = _connections + .Where(c => string.Equals(c.Value.StationId, stationId, StringComparison.OrdinalIgnoreCase)) + .Select(c => c.Key) + .FirstOrDefault(); + + return Task.FromResult(acarsConnectionId); + } + + public bool ClientExists(string acarsConnectionId) + { + return _connections.ContainsKey(acarsConnectionId); + } + + // The calls to Start and Stop, in order + public List StartStopCalls { get; } = []; + public List StartedConnections { get; } = []; + public List StoppedConnections { get; } = []; + + public string[] GetAcarsConnectionIds() + { + return _connections.Keys.ToArray(); + } + + public bool IsRunning(Guid settingsId) + { + return StartedConnections.Any(s => s.Id == settingsId); + } + + public Task Start(AcarsConnectionSettings settings, CancellationToken cancellationToken) + { + StartStopCalls.Add($"Start {settings.Id}"); + StartedConnections.Add(settings); + return Task.CompletedTask; + } + + public Task Stop(Guid settingsId, CancellationToken cancellationToken) + { + StartStopCalls.Add($"Stop {settingsId}"); + StoppedConnections.Add(settingsId); + StartedConnections.RemoveAll(s => s.Id == settingsId); + return Task.CompletedTask; + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestAdscContractRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAdscContractRepository.cs index d7742f5..91dd5e1 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAdscContractRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAdscContractRepository.cs @@ -1,29 +1,29 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; namespace CPDLCServer.Tests.Mocks; public class TestAdscContractRepository : IAdscContractRepository { - private readonly InMemoryAdscContractRepository _inner = new(); + private readonly Dictionary _contracts = new(); public Task Add(AdscContractKey contractKey, AdscContract contract, CancellationToken cancellationToken) { - return _inner.Add(contractKey, contract, cancellationToken); + _contracts[contractKey] = contract; + return Task.CompletedTask; } public Task Find(AdscContractKey contractKey, CancellationToken cancellationToken) { - return _inner.Find(contractKey, cancellationToken); + return Task.FromResult(_contracts.GetValueOrDefault(contractKey)); } public Task All(CancellationToken cancellationToken) { - return _inner.All(cancellationToken); + return Task.FromResult(_contracts.Values.ToArray()); } public Task Remove(AdscContractKey contractKey, CancellationToken cancellationToken) { - return _inner.Remove(contractKey, cancellationToken); + return Task.FromResult(_contracts.Remove(contractKey)); } } diff --git a/source/CPDLCServer.Tests/Mocks/TestAdscMessageLogRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAdscMessageLogRepository.cs index 093e5b4..40cfabc 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAdscMessageLogRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAdscMessageLogRepository.cs @@ -1,5 +1,4 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts.MessageLog; namespace CPDLCServer.Tests.Mocks; diff --git a/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs index da963b2..8713f8d 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs @@ -1,29 +1,46 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts.Reports; namespace CPDLCServer.Tests.Mocks; public class TestAdscReportRepository : IAdscReportRepository { - private readonly InMemoryAdscReportRepository _inner = new(); + private readonly List _history = []; + private readonly Dictionary _latest = new(); public Task Add(AircraftAdscReport report, CancellationToken cancellationToken) { - return _inner.Add(report, cancellationToken); + _history.Add(report); + + if (_latest.TryGetValue(report.Callsign, out var latest)) + { + var replacesVatsimReport = report.Report.Source == AdscReportSource.Hoppie && + latest.Report.Source == AdscReportSource.VATSIM; + + if (!replacesVatsimReport && latest.Report.Timestamp > report.Report.Timestamp) + return Task.CompletedTask; + } + + _latest[report.Callsign] = report; + return Task.CompletedTask; } - public Task Find(string callsign, CancellationToken cancellationToken) + public Task FindLatest(string callsign, CancellationToken cancellationToken) { - return _inner.Find(callsign, cancellationToken); + return Task.FromResult(_latest.GetValueOrDefault(callsign)); } - public Task All(CancellationToken cancellationToken) + public Task AllLatest(CancellationToken cancellationToken) { - return _inner.All(cancellationToken); + return Task.FromResult(_latest.Values.ToArray()); } public Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken) { - return _inner.RemoveOlderThan(cutoff, cancellationToken); + _history.RemoveAll(r => r.Received < cutoff); + + foreach (var report in _latest.Values.Where(r => r.Received < cutoff).ToArray()) + _latest.Remove(report.Callsign); + + return Task.CompletedTask; } } diff --git a/source/CPDLCServer.Tests/Mocks/TestAircraftRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAircraftRepository.cs index 1c801d1..a210c88 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAircraftRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAircraftRepository.cs @@ -1,29 +1,29 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Connections; namespace CPDLCServer.Tests.Mocks; public class TestAircraftRepository : IAircraftRepository { - private readonly InMemoryAircraftRepository _inner = new(); + private readonly Dictionary _connections = new(); public Task Add(AircraftKey aircraftKey, AircraftConnection connection, CancellationToken cancellationToken) { - return _inner.Add(aircraftKey, connection, cancellationToken); + _connections[aircraftKey] = connection; + return Task.CompletedTask; } public Task Find(AircraftKey aircraftKey, CancellationToken cancellationToken) { - return _inner.Find(aircraftKey, cancellationToken); + return Task.FromResult(_connections.GetValueOrDefault(aircraftKey)); } public Task All(CancellationToken cancellationToken) { - return _inner.All(cancellationToken); + return Task.FromResult(_connections.Values.ToArray()); } public Task Remove(AircraftKey aircraftKey, CancellationToken cancellationToken) { - return _inner.Remove(aircraftKey, cancellationToken); + return Task.FromResult(_connections.Remove(aircraftKey)); } } diff --git a/source/CPDLCServer.Tests/Mocks/TestClientManager.cs b/source/CPDLCServer.Tests/Mocks/TestClientManager.cs deleted file mode 100644 index a2ac026..0000000 --- a/source/CPDLCServer.Tests/Mocks/TestClientManager.cs +++ /dev/null @@ -1,87 +0,0 @@ -using CPDLCServer.Clients; -using CPDLCServer.Exceptions; - -namespace CPDLCServer.Tests.Mocks; - -public class TestClientManager : IClientManager -{ - private readonly Dictionary _clients = new(); - private readonly Dictionary _configurations = new(); - - public TestClientManager() - { - AddClient("hoppies-ybbb", new TestAcarsClient("YBBB")); - AddClient("hoppies-ymmm", new TestAcarsClient("YMMM")); - AddConfiguration(CreateConfiguration("YBBB", 10)); - AddConfiguration(CreateConfiguration("YMMM", 20)); - } - - public void AddClient(string acarsClientId, IAcarsClient client) - { - _clients[acarsClientId] = client; - } - - public void AddConfiguration(HoppiesConfiguration configuration) - { - _configurations[configuration.StationIdentifier] = configuration; - } - - public static HoppiesConfiguration CreateConfiguration( - string stationId, - int defaultAdscReportingInterval, - int selectedAdscContractDuration = 60) - { - return new HoppiesConfiguration - { - Url = new Uri("http://test.hoppie.nl/acars"), - AuthenticationCode = "TEST123", - FlightSimulationNetwork = "VATSIM", - StationIdentifier = stationId, - DefaultAdscReportingInterval = defaultAdscReportingInterval, - SelectedAdscContractDuration = selectedAdscContractDuration - }; - } - - public Task GetAcarsClient(string acarsClientId, CancellationToken cancellationToken) - { - if (!_clients.TryGetValue(acarsClientId, out var client)) - { - throw new ConfigurationNotFoundException(acarsClientId); - } - return Task.FromResult(client); - } - - public Task GetAcarsClientForStation(string stationId, CancellationToken cancellationToken) - { - var client = _clients.Values.FirstOrDefault(c => c.StationId == stationId); - if (client is null) - { - throw new Exception($"No ACARS client found for station '{stationId}'"); - } - return Task.FromResult(client); - } - - public Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken) - { - if (!_configurations.TryGetValue(stationId, out var configuration)) - { - throw new Exception($"No ACARS configuration found for station '{stationId}'"); - } - return Task.FromResult(configuration); - } - - public Task FindAcarsClientId(string stationId, CancellationToken cancellationToken) - { - var acarsClientId = _clients - .Where(c => string.Equals(c.Value.StationId, stationId, StringComparison.OrdinalIgnoreCase)) - .Select(c => c.Key) - .FirstOrDefault(); - - return Task.FromResult(acarsClientId); - } - - public bool ClientExists(string acarsClientId) - { - return _clients.ContainsKey(acarsClientId); - } -} diff --git a/source/CPDLCServer.Tests/Mocks/TestControllerManager.cs b/source/CPDLCServer.Tests/Mocks/TestControllerManager.cs index aba052f..025820b 100644 --- a/source/CPDLCServer.Tests/Mocks/TestControllerManager.cs +++ b/source/CPDLCServer.Tests/Mocks/TestControllerManager.cs @@ -1,5 +1,4 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Controllers; namespace CPDLCServer.Tests.Mocks; diff --git a/source/CPDLCServer.Tests/Mocks/TestDatabase.cs b/source/CPDLCServer.Tests/Mocks/TestDatabase.cs new file mode 100644 index 0000000..fc878c6 --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestDatabase.cs @@ -0,0 +1,35 @@ +using CPDLCServer.Persistence; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Tests.Mocks; + +// An in-memory SQLite database. The database exists while the connection is open. +// Use a new context for each unit of work, so that the tests read the saved data and not the tracked entities. +public sealed class TestDatabase : IDisposable +{ + readonly SqliteConnection _connection; + + public TestDatabase() + { + _connection = new SqliteConnection("Data Source=:memory:"); + _connection.Open(); + + using var dbContext = CreateDbContext(); + dbContext.Database.EnsureCreated(); + } + + public CpdlcDbContext CreateDbContext() + { + var options = new DbContextOptionsBuilder() + .UseSqlite(_connection) + .Options; + + return new CpdlcDbContext(options); + } + + public void Dispose() + { + _connection.Dispose(); + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs b/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs index bd9f3a9..3aa8e9f 100644 --- a/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs @@ -1,15 +1,16 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; namespace CPDLCServer.Tests.Mocks; public class TestDialogueRepository : IDialogueRepository { - private readonly InMemoryDialogueRepository _inner = new(); + private readonly List _dialogues = []; public Task Add(Dialogue dialogue, CancellationToken cancellationToken) { - return _inner.Add(dialogue, cancellationToken); + _dialogues.Add(dialogue); + return Task.CompletedTask; } public Task FindOpenDialogueByUplink( @@ -17,25 +18,42 @@ public Task Add(Dialogue dialogue, CancellationToken cancellationToken) int uplinkMessageId, CancellationToken cancellationToken) { - return _inner.FindOpenDialogueByUplink( - aircraftCallsign, - uplinkMessageId, - cancellationToken); + var dialogue = _dialogues.FirstOrDefault(d => + d.AircraftCallsign == aircraftCallsign && + !d.IsClosed && + d.Messages.OfType().Any(m => m.MessageId == uplinkMessageId)); + + return Task.FromResult(dialogue); } public Task FindById(Guid id, CancellationToken cancellationToken) { - return _inner.FindById(id, cancellationToken); + return Task.FromResult(_dialogues.FirstOrDefault(d => d.Id == id)); } - public Task All(CancellationToken cancellationToken) + public Task FindOpen(CancellationToken cancellationToken) + { + return Task.FromResult(_dialogues.Where(d => !d.IsClosed).ToArray()); + } + + public Task FindClosedAndNotArchived(CancellationToken cancellationToken) { - return _inner.All(cancellationToken); + return Task.FromResult(_dialogues.Where(d => d.IsClosed && !d.IsArchived).ToArray()); } + public Task FindOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken) + { + return Task.FromResult(_dialogues.Where(d => d.Opened < cutoff).ToArray()); + } + + public Task All(CancellationToken cancellationToken) + { + return Task.FromResult(_dialogues.ToArray()); + } public Task Remove(Dialogue dialogue, CancellationToken cancellationToken) { - return _inner.Remove(dialogue, cancellationToken); + _dialogues.Remove(dialogue); + return Task.CompletedTask; } } diff --git a/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs b/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs index 84bd3ef..cec8d29 100644 --- a/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs +++ b/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs @@ -1,4 +1,4 @@ -using CPDLCServer.Services; +using CPDLCServer.Cpdlc.Uplinks; namespace CPDLCServer.Tests.Mocks; diff --git a/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs b/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs new file mode 100644 index 0000000..e70bb59 --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs @@ -0,0 +1,19 @@ +using CPDLCServer.Settings; + +namespace CPDLCServer.Tests.Mocks; + +public class TestServerSettingsProvider(ServerSettings settings) : IServerSettingsProvider +{ + ServerSettings _settings = settings; + + public Task Load(CancellationToken cancellationToken) + { + return Task.FromResult(_settings); + } + + public Task Save(ServerSettings settings, CancellationToken cancellationToken) + { + _settings = settings; + return Task.CompletedTask; + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestUnitOfWork.cs b/source/CPDLCServer.Tests/Mocks/TestUnitOfWork.cs new file mode 100644 index 0000000..8b565b9 --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestUnitOfWork.cs @@ -0,0 +1,12 @@ +using CPDLCServer.Persistence; + +namespace CPDLCServer.Tests.Mocks; + +// Runs each action immediately, so that the handler tests can check the messages after the handler returns +public class TestUnitOfWork : IUnitOfWork +{ + public void AfterCommit(Func action) + { + action(CancellationToken.None).GetAwaiter().GetResult(); + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestUserRepository.cs b/source/CPDLCServer.Tests/Mocks/TestUserRepository.cs new file mode 100644 index 0000000..cc46d21 --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestUserRepository.cs @@ -0,0 +1,34 @@ +using CPDLCServer.Auth.Users; + +namespace CPDLCServer.Tests.Mocks; + +public class TestUserRepository : IUserRepository +{ + private readonly List _users = []; + + public Task Add(User user, CancellationToken cancellationToken) + { + _users.Add(user); + return Task.CompletedTask; + } + + public Task FindByUsername(string username, CancellationToken cancellationToken) + { + return Task.FromResult(_users.FirstOrDefault(u => u.Username == username)); + } + + public Task FindById(Guid id, CancellationToken cancellationToken) + { + return Task.FromResult(_users.FirstOrDefault(u => u.Id == id)); + } + + public Task All(CancellationToken cancellationToken) + { + return Task.FromResult(_users.OrderBy(u => u.Username).ToArray()); + } + + public Task Any(CancellationToken cancellationToken) + { + return Task.FromResult(_users.Count > 0); + } +} diff --git a/source/CPDLCServer.Tests/Persistence/InMemoryAdscReportRepositoryTests.cs b/source/CPDLCServer.Tests/Persistence/InMemoryAdscReportRepositoryTests.cs deleted file mode 100644 index 0379004..0000000 --- a/source/CPDLCServer.Tests/Persistence/InMemoryAdscReportRepositoryTests.cs +++ /dev/null @@ -1,127 +0,0 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; - -namespace CPDLCServer.Tests.Persistence; - -public class InMemoryAdscReportRepositoryTests -{ - static readonly DateTimeOffset Start = new(2026, 10, 13, 12, 0, 0, TimeSpan.Zero); - - [Fact] - public async Task Add_KeepsLatestReportForEachAircraft() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var first = CreateReport("UAL123", "YBBB", 0); - var second = CreateReport("UAL123", "YBBB", 5); - var other = CreateReport("QFA1", "YBBB", 0); - - // Act - await repository.Add(first, CancellationToken.None); - await repository.Add(second, CancellationToken.None); - await repository.Add(other, CancellationToken.None); - - // Assert - var reports = await repository.All(CancellationToken.None); - Assert.Equal(2, reports.Length); - Assert.Contains(second, reports); - Assert.Contains(other, reports); - } - - [Fact] - public async Task Add_WhenReportIsOlder_KeepsNewerReport() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var newer = CreateReport("UAL123", "YBBB", 5); - var older = CreateReport("UAL123", "YMMM", 0); - - // Act - await repository.Add(newer, CancellationToken.None); - await repository.Add(older, CancellationToken.None); - - // Assert - Assert.Equal([newer], await repository.All(CancellationToken.None)); - } - - [Fact] - public async Task Add_WhenHoppieReportIsOlderThanVatsimReport_ReplacesVatsimReport() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var vatsimReport = CreateReport("UAL123", "YBBB", 5, AdscReportSource.VATSIM); - var hoppieReport = CreateReport("UAL123", "YBBB", 0); - - // Act - await repository.Add(vatsimReport, CancellationToken.None); - await repository.Add(hoppieReport, CancellationToken.None); - - // Assert - Assert.Equal([hoppieReport], await repository.All(CancellationToken.None)); - } - - [Fact] - public async Task Add_WhenVatsimReportIsOlderThanHoppieReport_KeepsHoppieReport() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var hoppieReport = CreateReport("UAL123", "YBBB", 5); - var vatsimReport = CreateReport("UAL123", "YBBB", 0, AdscReportSource.VATSIM); - - // Act - await repository.Add(hoppieReport, CancellationToken.None); - await repository.Add(vatsimReport, CancellationToken.None); - - // Assert - Assert.Equal([hoppieReport], await repository.All(CancellationToken.None)); - } - - [Fact] - public async Task Find_ReturnsLatestReportForAircraft() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var report = CreateReport("UAL123", "YBBB", 0); - await repository.Add(report, CancellationToken.None); - - // Act & Assert - Assert.Equal(report, await repository.Find("UAL123", CancellationToken.None)); - Assert.Null(await repository.Find("QFA1", CancellationToken.None)); - } - - [Fact] - public async Task RemoveOlderThan_RemovesOnlyOlderReports() - { - // Arrange - var repository = new InMemoryAdscReportRepository(); - var older = CreateReport("UAL123", "YBBB", 0); - var atCutoff = CreateReport("QFA1", "YBBB", 5); - var newer = CreateReport("VOZ1", "YBBB", 10); - await repository.Add(older, CancellationToken.None); - await repository.Add(atCutoff, CancellationToken.None); - await repository.Add(newer, CancellationToken.None); - - // Act - await repository.RemoveOlderThan(atCutoff.Received, CancellationToken.None); - - // Assert - var reports = await repository.All(CancellationToken.None); - Assert.Equal(2, reports.Length); - Assert.Contains(atCutoff, reports); - Assert.Contains(newer, reports); - } - - static AircraftAdscReport CreateReport( - string callsign, - string stationId, - int minutes, - AdscReportSource source = AdscReportSource.Hoppie) - { - var timestamp = Start.AddMinutes(minutes); - return new AircraftAdscReport( - callsign, - stationId, - new AdscReport(timestamp, -33.9461, 151.1772, 37000, source), - timestamp.AddSeconds(30)); - } -} diff --git a/source/CPDLCServer.Tests/Persistence/PostgreSqlConnectionStringTests.cs b/source/CPDLCServer.Tests/Persistence/PostgreSqlConnectionStringTests.cs new file mode 100644 index 0000000..39fb9f2 --- /dev/null +++ b/source/CPDLCServer.Tests/Persistence/PostgreSqlConnectionStringTests.cs @@ -0,0 +1,47 @@ +using CPDLCServer.Persistence; +using Npgsql; + +namespace CPDLCServer.Tests.Persistence; + +public class PostgreSqlConnectionStringTests +{ + [Fact] + public void Parse_WithUrl_ReturnsKeyValueConnectionString() + { + // Act + var connectionString = PostgreSqlConnectionString.Parse( + "postgresql://cpdlc:p%40ss%3Aword@db.example.com:25060/cpdlc?sslmode=require"); + + // Assert + var builder = new NpgsqlConnectionStringBuilder(connectionString); + Assert.Equal("db.example.com", builder.Host); + Assert.Equal(25060, builder.Port); + Assert.Equal("cpdlc", builder.Database); + Assert.Equal("cpdlc", builder.Username); + Assert.Equal("p@ss:word", builder.Password); + Assert.Equal(SslMode.Require, builder.SslMode); + } + + [Fact] + public void Parse_WithPostgresScheme_ReturnsKeyValueConnectionString() + { + // Act + var connectionString = PostgreSqlConnectionString.Parse("postgres://cpdlc:secret@localhost/cpdlc"); + + // Assert + var builder = new NpgsqlConnectionStringBuilder(connectionString); + Assert.Equal("localhost", builder.Host); + Assert.Equal("cpdlc", builder.Database); + Assert.Equal("secret", builder.Password); + } + + [Fact] + public void Parse_WithKeyValueConnectionString_ReturnsTheSameValue() + { + // Arrange + const string value = "Host=localhost;Database=cpdlc;Username=cpdlc;Password=secret"; + + // Act & Assert + Assert.Equal(value, PostgreSqlConnectionString.Parse(value)); + } +} diff --git a/source/CPDLCServer.Tests/Persistence/UnitOfWorkTests.cs b/source/CPDLCServer.Tests/Persistence/UnitOfWorkTests.cs new file mode 100644 index 0000000..6ca9a08 --- /dev/null +++ b/source/CPDLCServer.Tests/Persistence/UnitOfWorkTests.cs @@ -0,0 +1,105 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Persistence; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.Persistence; + +public class UnitOfWorkTests +{ + [Fact] + public async Task Commit_SavesChangesBeforeActions() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var unitOfWork = new UnitOfWork(dbContext); + + var dialogue = new Dialogue("UAL123"); + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + + var savedWhenActionRan = false; + unitOfWork.AfterCommit(async ct => + { + await using var readDbContext = database.CreateDbContext(); + savedWhenActionRan = await new DialogueRepository(readDbContext).FindById(dialogue.Id, ct) is not null; + }); + + // Act + await unitOfWork.Commit(CancellationToken.None); + + // Assert + Assert.True(savedWhenActionRan); + } + + [Fact] + public async Task AfterCommit_DoesNotRunActionBeforeCommit() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var unitOfWork = new UnitOfWork(dbContext); + + var actionRan = false; + + // Act + unitOfWork.AfterCommit(_ => + { + actionRan = true; + return Task.CompletedTask; + }); + + // Assert + Assert.False(actionRan); + } + + [Fact] + public async Task Commit_RunsActionsInOrder() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var unitOfWork = new UnitOfWork(dbContext); + + var order = new List(); + unitOfWork.AfterCommit(_ => + { + order.Add(1); + return Task.CompletedTask; + }); + unitOfWork.AfterCommit(_ => + { + order.Add(2); + return Task.CompletedTask; + }); + + // Act + await unitOfWork.Commit(CancellationToken.None); + + // Assert + Assert.Equal([1, 2], order); + } + + [Fact] + public async Task Commit_WhenActionFails_RunsOtherActionsThenThrows() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var unitOfWork = new UnitOfWork(dbContext); + + var secondActionRan = false; + unitOfWork.AfterCommit(_ => throw new InvalidOperationException("Send failed")); + unitOfWork.AfterCommit(_ => + { + secondActionRan = true; + return Task.CompletedTask; + }); + + // Act + var exception = await Assert.ThrowsAsync(() => unitOfWork.Commit(CancellationToken.None)); + + // Assert + Assert.True(secondActionRan); + Assert.IsType(Assert.Single(exception.InnerExceptions)); + } +} diff --git a/source/CPDLCServer.Tests/Security/MasterKeyEncryptionTests.cs b/source/CPDLCServer.Tests/Security/MasterKeyEncryptionTests.cs new file mode 100644 index 0000000..1ba382d --- /dev/null +++ b/source/CPDLCServer.Tests/Security/MasterKeyEncryptionTests.cs @@ -0,0 +1,54 @@ +using System.Security.Cryptography; +using CPDLCServer.Security; + +namespace CPDLCServer.Tests.Security; + +public class MasterKeyEncryptionTests +{ + [Fact] + public void Encrypt_ThenDecrypt_ReturnsThePlaintext() + { + // Arrange + var encryption = new MasterKeyEncryption(NewKey()); + + // Act + var encrypted = encryption.Encrypt("secret"); + + // Assert + Assert.NotEqual("secret", encrypted); + Assert.Equal("secret", encryption.Decrypt(encrypted)); + } + + [Fact] + public void Encrypt_SameValueTwice_GivesDifferentResults() + { + // Arrange + var encryption = new MasterKeyEncryption(NewKey()); + + // Act & Assert + Assert.NotEqual(encryption.Encrypt("secret"), encryption.Encrypt("secret")); + } + + [Fact] + public void Decrypt_WithDifferentKey_Throws() + { + // Arrange + var encrypted = new MasterKeyEncryption(NewKey()).Encrypt("secret"); + var otherEncryption = new MasterKeyEncryption(NewKey()); + + // Act & Assert + Assert.ThrowsAny(() => otherEncryption.Decrypt(encrypted)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("not-a-key")] + [InlineData("AAAAAAAAAAAAAAAAAAAAAA==")] + public void Constructor_WithMissingOrInvalidKey_Throws(string? masterKey) + { + Assert.Throws(() => new MasterKeyEncryption(masterKey!)); + } + + static string NewKey() => Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); +} diff --git a/source/CPDLCServer.Tests/Services/MessageMonitorServiceTests.cs b/source/CPDLCServer.Tests/Services/MessageMonitorServiceTests.cs deleted file mode 100644 index b207adc..0000000 --- a/source/CPDLCServer.Tests/Services/MessageMonitorServiceTests.cs +++ /dev/null @@ -1,482 +0,0 @@ -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Services; -using CPDLCServer.Tests.Mocks; -using Serilog.Core; - -namespace CPDLCServer.Tests.Services; - -public class MessageMonitorServiceTests -{ - [Fact] - public async Task CheckForTimeouts_MarksPilotLate_WhenUplinkTimesOut() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create an uplink that requires a response - var dialogue = new Dialogue("UAL123"); - var uplink = dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.WilcoUnable, - AlertType.None, - "CLIMB TO FL410", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond pilot late timeout (2 minutes) - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - Assert.True(uplink.IsPilotLate); - Assert.Single(publisher.PublishedNotifications); - var notification = Assert.IsType(publisher.PublishedNotifications[0]); - Assert.Equal(dialogue, notification.Dialogue); - } - - [Fact] - public async Task CheckForTimeouts_DoesNotMarkPilotLate_WhenTimeoutNotReached() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - var dialogue = new Dialogue("UAL123"); - var uplink = dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.WilcoUnable, - AlertType.None, - "CLIMB TO FL410", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time but not beyond timeout (1 minute < 2 minute timeout) - clock.SetUtcNow(startTime.AddMinutes(1)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - Assert.False(uplink.IsPilotLate); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task CheckForTimeouts_IgnoresNoResponseUplinks() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create an uplink that doesn't require a response - var dialogue = new Dialogue("UAL123"); - var uplink = dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.NoResponse, - AlertType.None, - "ROGER", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond timeout - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - should not be marked late since no response is needed - Assert.False(uplink.IsPilotLate); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task CheckForTimeouts_MarksControllerLate_WhenDownlinkTimesOut() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create a downlink that requires a response - var dialogue = new Dialogue("UAL123"); - var downlink = dialogue.AddDownlink( - 1, - null, - "UAL123", - CpdlcDownlinkResponseType.ResponseRequired, - AlertType.None, - "REQUEST CLIMB FL410", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond controller late timeout (2 minutes) - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - Assert.True(downlink.IsControllerLate); - Assert.Single(publisher.PublishedNotifications); - var notification = Assert.IsType(publisher.PublishedNotifications[0]); - Assert.Equal(dialogue, notification.Dialogue); - } - - [Fact] - public async Task CheckForTimeouts_IgnoresClosedMessages() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - var dialogue = new Dialogue("UAL123"); - var uplink = dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.WilcoUnable, - AlertType.None, - "CLIMB TO FL410", - startTime); - - // Close the message - uplink.Close(startTime); - - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond timeout - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - closed messages should not be marked late - Assert.False(uplink.IsPilotLate); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task CheckForTimeouts_IgnoresClosedDialogues() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create a self-closing uplink (NoResponse) - var dialogue = new Dialogue("UAL123"); - dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.NoResponse, - AlertType.None, - "ROGER", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond timeout - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - closed dialogues should be skipped - Assert.True(dialogue.IsClosed); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task ArchiveCompletedDialogues_ArchivesDialogue_WhenAllMessagesAcknowledgedAndDelayPassed() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create a closed dialogue with acknowledged message - var dialogue = new Dialogue("UAL123"); - dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.NoResponse, - AlertType.None, - "ROGER", - startTime); // NoResponse uplinks are self-closing and auto-acknowledged - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond archive delay (10 seconds) - clock.SetUtcNow(startTime.AddSeconds(15)); - await service.ArchiveCompletedDialogues(CancellationToken.None); - - // Assert - Assert.True(dialogue.IsArchived); - Assert.Single(publisher.PublishedNotifications); - var notification = Assert.IsType(publisher.PublishedNotifications[0]); - Assert.Equal(dialogue, notification.Dialogue); - } - - [Fact] - public async Task ArchiveCompletedDialogues_DoesNotArchive_WhenDelayNotPassed() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - var dialogue = new Dialogue("UAL123"); - dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.NoResponse, - AlertType.None, - "ROGER", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time but not enough (5 seconds < 10 second delay) - clock.SetUtcNow(startTime.AddSeconds(5)); - await service.ArchiveCompletedDialogues(CancellationToken.None); - - // Assert - Assert.False(dialogue.IsArchived); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task ArchiveCompletedDialogues_IgnoresOpenDialogues() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create an open dialogue (requires response) - var dialogue = new Dialogue("UAL123"); - dialogue.AddUplink( - 1, - null, - "UAL123", - "BN-TSN_FSS", - CpdlcUplinkResponseType.WilcoUnable, - AlertType.None, - "CLIMB TO FL410", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond archive delay - clock.SetUtcNow(startTime.AddSeconds(15)); - await service.ArchiveCompletedDialogues(CancellationToken.None); - - // Assert - open dialogues should not be archived - Assert.False(dialogue.IsClosed); - Assert.False(dialogue.IsArchived); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task ArchiveCompletedDialogues_IgnoresDialoguesWithoutAcknowledgements() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create a downlink that's closed but not acknowledged - var dialogue = new Dialogue("UAL123"); - dialogue.AddDownlink( - 1, - null, - "UAL123", - CpdlcDownlinkResponseType.NoResponse, - AlertType.None, - "WILCO", - startTime); - await repository.Add(dialogue, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond archive delay - clock.SetUtcNow(startTime.AddSeconds(15)); - await service.ArchiveCompletedDialogues(CancellationToken.None); - - // Assert - unacknowledged dialogues should not be archived - Assert.True(dialogue.IsClosed); - Assert.False(dialogue.IsArchived); - Assert.Empty(publisher.PublishedNotifications); - } - - [Fact] - public async Task CheckForTimeouts_HandlesMultipleDialogues() - { - // Arrange - var clock = new TestClock(); - var repository = new TestDialogueRepository(); - var publisher = new TestPublisher(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - // Create multiple dialogues with different aircraft - var dialogue1 = new Dialogue("UAL123"); - var uplink1 = dialogue1.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB", startTime); - - var dialogue2 = new Dialogue("DAL456"); - var uplink2 = dialogue2.AddUplink(2, null, "DAL456", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "DESCEND", startTime); - - await repository.Add(dialogue1, CancellationToken.None); - await repository.Add(dialogue2, CancellationToken.None); - - var service = new MessageMonitorService(repository, new TestAdscMessageLogRepository(), new TestAdscReportRepository(), clock, publisher, Logger.None); - - // Act - advance time beyond timeout - clock.SetUtcNow(startTime.AddMinutes(3)); - await service.CheckForTimeouts(CancellationToken.None); - - // Assert - both should be marked late - Assert.True(uplink1.IsPilotLate); - Assert.True(uplink2.IsPilotLate); - Assert.Equal(2, publisher.PublishedNotifications.Count); - } - - [Fact] - public async Task PurgeOldAdscMessages_RemovesMessagesOlderThan24Hours() - { - // Arrange - var clock = new TestClock(); - var adscMessageLogRepository = new TestAdscMessageLogRepository(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - var oldEntry = new AdscMessageLogEntry( - startTime, - "Hoppies/YBBB", - "YBBB", - "UAL123", - AdscMessageDirection.Uplink, - "REQUEST PERIODIC 1"); - var newEntry = new AdscMessageLogEntry( - startTime.AddHours(2), - "Hoppies/YBBB", - "YBBB", - "UAL123", - AdscMessageDirection.Uplink, - "REQUEST PERIODIC 2"); - await adscMessageLogRepository.Add(oldEntry, CancellationToken.None); - await adscMessageLogRepository.Add(newEntry, CancellationToken.None); - - var service = new MessageMonitorService( - new TestDialogueRepository(), - adscMessageLogRepository, - new TestAdscReportRepository(), - clock, - new TestPublisher(), - Logger.None); - - // Act - advance time beyond the purge timeout (24 hours) for the old entry only - clock.SetUtcNow(startTime.AddHours(25)); - await service.PurgeOldAdscMessages(CancellationToken.None); - - // Assert - Assert.Equal([newEntry], await adscMessageLogRepository.All(CancellationToken.None)); - } - - [Fact] - public async Task PurgeOldAdscReports_RemovesReportsOlderThan24Hours() - { - // Arrange - var clock = new TestClock(); - var adscReportRepository = new TestAdscReportRepository(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - var oldReport = new AircraftAdscReport( - "UAL123", - "YBBB", - new AdscReport(startTime, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie), - startTime); - var newReport = new AircraftAdscReport( - "QFA1", - "YBBB", - new AdscReport(startTime.AddHours(2), -33.9461, 151.1772, 37000, AdscReportSource.Hoppie), - startTime.AddHours(2)); - await adscReportRepository.Add(oldReport, CancellationToken.None); - await adscReportRepository.Add(newReport, CancellationToken.None); - - var service = new MessageMonitorService( - new TestDialogueRepository(), - new TestAdscMessageLogRepository(), - adscReportRepository, - clock, - new TestPublisher(), - Logger.None); - - // Act - advance time beyond the purge timeout (24 hours) for the old report only - clock.SetUtcNow(startTime.AddHours(25)); - await service.PurgeOldAdscReports(CancellationToken.None); - - // Assert - Assert.Equal([newReport], await adscReportRepository.All(CancellationToken.None)); - } -} diff --git a/source/CPDLCServer.Tests/Settings/ServerSettingsProviderTests.cs b/source/CPDLCServer.Tests/Settings/ServerSettingsProviderTests.cs new file mode 100644 index 0000000..6057f66 --- /dev/null +++ b/source/CPDLCServer.Tests/Settings/ServerSettingsProviderTests.cs @@ -0,0 +1,114 @@ +using CPDLCServer.Settings; +using CPDLCServer.Tests.Mocks; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Tests.Settings; + +public class ServerSettingsProviderTests +{ + [Fact] + public async Task SeedDefaults_WhenNoSettings_AddsDefaults() + { + // Arrange + using var database = new TestDatabase(); + + // Act + await Seed(database); + + // Assert + await using var dbContext = database.CreateDbContext(); + var settings = await new ServerSettingsProvider(dbContext).Load(CancellationToken.None); + Assert.Equal(new ServerSettings(), settings); + } + + [Fact] + public async Task SeedDefaults_WhenSettingsExist_DoesNotChangeThem() + { + // Arrange + using var database = new TestDatabase(); + await Seed(database); + await SaveAndCommit(database, new ServerSettings { AdscReportRetentionHours = 48 }); + + // Act + await Seed(database); + + // Assert + await using var dbContext = database.CreateDbContext(); + Assert.Equal(1, await dbContext.ServerSettings.CountAsync()); + var settings = await new ServerSettingsProvider(dbContext).Load(CancellationToken.None); + Assert.Equal(48, settings.AdscReportRetentionHours); + } + + [Fact] + public async Task Save_ThenCommit_ThenLoad_ReturnsSavedSettings() + { + // Arrange + using var database = new TestDatabase(); + await Seed(database); + var settings = new ServerSettings + { + ConnectivityCheckIntervalMinutes = 5, + AircraftConnectionTimeoutMinutes = 20, + VatsimStatusEnabled = true, + VatsimStatusUrl = new Uri("https://example.com/vatsim-data.json") + }; + + // Act + await SaveAndCommit(database, settings); + + // Assert + await using var dbContext = database.CreateDbContext(); + Assert.Equal(settings, await new ServerSettingsProvider(dbContext).Load(CancellationToken.None)); + } + + [Fact] + public async Task Save_WithoutCommit_DoesNotChangeTheDatabase() + { + // Arrange + using var database = new TestDatabase(); + await Seed(database); + + // Act + await using (var dbContext = database.CreateDbContext()) + { + await new ServerSettingsProvider(dbContext).Save( + new ServerSettings { AdscReportRetentionHours = 48 }, + CancellationToken.None); + } + + // Assert + await using var otherDbContext = database.CreateDbContext(); + var settings = await new ServerSettingsProvider(otherDbContext).Load(CancellationToken.None); + Assert.Equal(new ServerSettings().AdscReportRetentionHours, settings.AdscReportRetentionHours); + } + + [Fact] + public async Task Load_AfterSaveInTheSameScope_ReturnsTheUnsavedSettings() + { + // Arrange + using var database = new TestDatabase(); + await Seed(database); + await using var dbContext = database.CreateDbContext(); + var provider = new ServerSettingsProvider(dbContext); + + // Act + await provider.Save(new ServerSettings { AdscReportRetentionHours = 48 }, CancellationToken.None); + + // Assert + Assert.Equal(48, (await provider.Load(CancellationToken.None)).AdscReportRetentionHours); + } + + static async Task Seed(TestDatabase database) + { + await using var dbContext = database.CreateDbContext(); + await new ServerSettingsProvider(dbContext).SeedDefaults(CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + static async Task SaveAndCommit(TestDatabase database, ServerSettings settings) + { + await using var dbContext = database.CreateDbContext(); + await new ServerSettingsProvider(dbContext).Save(settings, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } +} diff --git a/source/CPDLCServer.Tests/Setup/SetupStateTests.cs b/source/CPDLCServer.Tests/Setup/SetupStateTests.cs new file mode 100644 index 0000000..9a5ccc4 --- /dev/null +++ b/source/CPDLCServer.Tests/Setup/SetupStateTests.cs @@ -0,0 +1,74 @@ +using CPDLCServer.Auth.Users; +using CPDLCServer.Setup; +using CPDLCServer.Tests.Mocks; +using Microsoft.Extensions.DependencyInjection; + +namespace CPDLCServer.Tests.Setup; + +public class SetupStateTests +{ + readonly TestUserRepository _userRepository = new(); + + [Fact] + public async Task Load_WhenNoUser_IsNotConfigured() + { + // Arrange + var setupState = CreateSetupState(); + + // Act + await setupState.Load(CancellationToken.None); + + // Assert + Assert.False(setupState.IsConfigured); + } + + [Fact] + public async Task Load_WhenUserExists_IsConfigured() + { + // Arrange + await _userRepository.Add(new User { Id = Guid.NewGuid(), Username = "admin" }, CancellationToken.None); + var setupState = CreateSetupState(); + + // Act + await setupState.Load(CancellationToken.None); + + // Assert + Assert.True(setupState.IsConfigured); + } + + [Fact] + public async Task MarkAdminCreated_CompletesTheSetup() + { + // Arrange + var setupState = CreateSetupState(); + await setupState.Load(CancellationToken.None); + + // Act + setupState.MarkAdminCreated(); + + // Assert + Assert.True(setupState.IsConfigured); + } + + [Fact] + public void IsValidSetupToken_AcceptsOnlyTheSetupToken() + { + // Arrange + var setupState = CreateSetupState(); + + // Act & Assert + Assert.True(setupState.IsValidSetupToken(setupState.SetupToken)); + Assert.False(setupState.IsValidSetupToken("wrong-token")); + Assert.False(setupState.IsValidSetupToken(null)); + Assert.False(setupState.IsValidSetupToken(string.Empty)); + } + + SetupState CreateSetupState() + { + var services = new ServiceCollection(); + services.AddSingleton(_userRepository); + var serviceProvider = services.BuildServiceProvider(); + + return new SetupState(serviceProvider.GetRequiredService()); + } +} diff --git a/source/CPDLCServer.Tests/Handlers/ProduceVatsimAdscReportsRequestHandlerTests.cs b/source/CPDLCServer.Tests/VatsimStatus/ProduceVatsimAdscReportsRequestHandlerTests.cs similarity index 97% rename from source/CPDLCServer.Tests/Handlers/ProduceVatsimAdscReportsRequestHandlerTests.cs rename to source/CPDLCServer.Tests/VatsimStatus/ProduceVatsimAdscReportsRequestHandlerTests.cs index ce04325..e20cba5 100644 --- a/source/CPDLCServer.Tests/Handlers/ProduceVatsimAdscReportsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/VatsimStatus/ProduceVatsimAdscReportsRequestHandlerTests.cs @@ -1,14 +1,13 @@ -using CPDLCServer.Handlers; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using CPDLCServer.Services; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Settings; +using CPDLCServer.VatsimStatus; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; using Serilog.Core; -namespace CPDLCServer.Tests.Handlers; +namespace CPDLCServer.Tests.VatsimStatus; public class ProduceVatsimAdscReportsRequestHandlerTests { @@ -273,7 +272,7 @@ [new VatsimPilot("UAL123", -33.9461, 151.1772, 37000, LastUpdated, isAdscEquippe contractRepository, reportRepository, pilotRepository, - new VatsimStatusConfiguration { Enabled = true, AllowNonEquippedAircraft = allowNonEquippedAircraft }, + new TestServerSettingsProvider(new ServerSettings { VatsimStatusEnabled = true, VatsimStatusAllowNonEquippedAircraft = allowNonEquippedAircraft }), clock, mediator, Logger.None); diff --git a/source/CPDLCServer.Tests/Model/VatsimPilotTests.cs b/source/CPDLCServer.Tests/VatsimStatus/VatsimPilotTests.cs similarity index 90% rename from source/CPDLCServer.Tests/Model/VatsimPilotTests.cs rename to source/CPDLCServer.Tests/VatsimStatus/VatsimPilotTests.cs index 2fc78e1..d06f76a 100644 --- a/source/CPDLCServer.Tests/Model/VatsimPilotTests.cs +++ b/source/CPDLCServer.Tests/VatsimStatus/VatsimPilotTests.cs @@ -1,6 +1,6 @@ -using CPDLCServer.Model; +using CPDLCServer.VatsimStatus; -namespace CPDLCServer.Tests.Model; +namespace CPDLCServer.Tests.VatsimStatus; public class VatsimPilotTests { diff --git a/source/CPDLCServer/AcarsConnections/AcarsConnectionManager.cs b/source/CPDLCServer/AcarsConnections/AcarsConnectionManager.cs new file mode 100644 index 0000000..6f2194f --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/AcarsConnectionManager.cs @@ -0,0 +1,412 @@ +using System.Collections.Concurrent; +using CPDLCServer.AcarsConnections.ConnectionSettings; +using CPDLCServer.AcarsConnections.Hoppie; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using CPDLCServer.Security; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.AcarsConnections; + +public interface IAcarsConnectionManager +{ + Task GetAcarsConnection(string acarsConnectionId, CancellationToken cancellationToken); + Task GetAcarsConnectionForStation(string stationId, CancellationToken cancellationToken); + Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken); + Task FindAcarsConnectionId(string stationId, CancellationToken cancellationToken); + + // The IDs of the connections that are running + string[] GetAcarsConnectionIds(); + bool IsRunning(Guid settingsId); + + // Connects to the upstream ACARS network + Task Start(AcarsConnectionSettings settings, CancellationToken cancellationToken); + + // Disconnects from the upstream ACARS network. Does nothing if the connection is not running. + Task Stop(Guid settingsId, CancellationToken cancellationToken); +} + +public class AcarsConnectionManager : BackgroundService, IAcarsConnectionManager +{ + readonly SemaphoreSlim _semaphoreSlim = new(1, 1); + readonly ConcurrentDictionary _connections = []; + readonly IServiceScopeFactory _serviceScopeFactory; + readonly MasterKeyEncryption _masterKeyEncryption; + readonly IClock _clock; + readonly IAdscMessageLogRepository _adscMessageLogRepository; + readonly ILogger _logger; + readonly IUnitOfWorkMediator _mediator; + + public AcarsConnectionManager( + IServiceScopeFactory serviceScopeFactory, + MasterKeyEncryption masterKeyEncryption, + IUnitOfWorkMediator mediator, + IClock clock, + IAdscMessageLogRepository adscMessageLogRepository, + ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _masterKeyEncryption = masterKeyEncryption; + _mediator = mediator; + _clock = clock; + _adscMessageLogRepository = adscMessageLogRepository; + _logger = logger.ForContext(); + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + var enabledSettings = await LoadEnabledSettings(stoppingToken); + _logger.Information("Starting ACARS connection manager with {Count} enabled connections", enabledSettings.Length); + + foreach (var settings in enabledSettings) + { + await StartWithRetry(settings, stoppingToken); + } + + _logger.Information("All ACARS connections initialized"); + + try + { + await Task.Delay(Timeout.Infinite, stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + _logger.Information("Stopping ACARS connection manager"); + } + } + + async Task LoadEnabledSettings(CancellationToken cancellationToken) + { + await using var scope = _serviceScopeFactory.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + return await dbContext.AcarsConnections + .AsNoTracking() + .Where(s => s.Enabled) + .ToArrayAsync(cancellationToken); + } + + async Task StartWithRetry(AcarsConnectionSettings settings, CancellationToken cancellationToken) + { + const int maxRetries = 5; + var retryDelay = TimeSpan.FromSeconds(1); + + for (var attempt = 0; attempt < maxRetries; attempt++) + { + try + { + await Start(settings, cancellationToken); + return; + } + catch (Exception ex) when (attempt < maxRetries - 1) + { + _logger.Warning( + ex, + "Failed to start ACARS connection for {StationId} (attempt {Attempt}/{MaxRetries}). Retrying in {Delay}", + settings.StationIdentifier, + attempt + 1, + maxRetries, + retryDelay); + + await Task.Delay(retryDelay, cancellationToken); + retryDelay *= 2; + } + catch (Exception ex) + { + _logger.Error( + ex, + "Failed to start ACARS connection for {StationId} after {MaxRetries} attempts. The connection will not be available", + settings.StationIdentifier, + maxRetries); + break; + } + } + } + + public async Task Start(AcarsConnectionSettings settings, CancellationToken cancellationToken) + { + using (await _semaphoreSlim.LockAsync(cancellationToken)) + { + var configuration = CreateConfiguration(settings); + if (_connections.ContainsKey(configuration.AcarsConnectionId)) + throw new InvalidOperationException($"ACARS connection {configuration.AcarsConnectionId} is already running"); + + var acarsConnectionHandle = await CreateAcarsConnection(settings.Id, configuration, cancellationToken); + _connections[configuration.AcarsConnectionId] = acarsConnectionHandle; + + _logger.Information("Started ACARS connection {AcarsConnectionId}", configuration.AcarsConnectionId); + } + } + + public async Task Stop(Guid settingsId, CancellationToken cancellationToken) + { + using (await _semaphoreSlim.LockAsync(cancellationToken)) + { + var (acarsConnectionId, acarsConnectionHandle) = _connections.FirstOrDefault(c => c.Value.SettingsId == settingsId); + if (acarsConnectionHandle is null) + return; + + _connections.TryRemove(acarsConnectionId, out _); + await acarsConnectionHandle.DisposeAsync(); + + _logger.Information("Stopped ACARS connection {AcarsConnectionId}", acarsConnectionId); + } + } + + public string[] GetAcarsConnectionIds() + { + return _connections.Keys.ToArray(); + } + + public bool IsRunning(Guid settingsId) + { + return _connections.Values.Any(h => h.SettingsId == settingsId); + } + + public Task GetAcarsConnection(string acarsConnectionId, CancellationToken cancellationToken) + { + if (!_connections.TryGetValue(acarsConnectionId, out var acarsConnectionHandle)) + { + throw new ConfigurationNotFoundException(acarsConnectionId); + } + + return Task.FromResult(acarsConnectionHandle.Connection); + } + + public Task GetAcarsConnectionForStation(string stationId, CancellationToken cancellationToken) + { + var acarsConnectionHandle = _connections.Values.FirstOrDefault(h => h.Connection.StationId == stationId); + if (acarsConnectionHandle is null) + { + throw new Exception($"No ACARS connection found for station '{stationId}'"); + } + + return Task.FromResult(acarsConnectionHandle.Connection); + } + + public Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken) + { + var acarsConnectionHandle = _connections.Values.FirstOrDefault(h => h.Connection.StationId == stationId); + if (acarsConnectionHandle is null) + { + throw new Exception($"No ACARS configuration found for station '{stationId}'"); + } + + return Task.FromResult(acarsConnectionHandle.Configuration); + } + + public Task FindAcarsConnectionId(string stationId, CancellationToken cancellationToken) + { + var acarsConnectionId = _connections + .Where(c => string.Equals(c.Value.Connection.StationId, stationId, StringComparison.OrdinalIgnoreCase)) + .Select(c => c.Key) + .FirstOrDefault(); + + return Task.FromResult(acarsConnectionId); + } + + AcarsConfiguration CreateConfiguration(AcarsConnectionSettings settings) + { + return settings.Type switch + { + AcarsNetworkType.Hoppie => new HoppiesConfiguration + { + Url = settings.Url, + AuthenticationCode = _masterKeyEncryption.Decrypt(settings.EncryptedAuthenticationCode), + FlightSimulationNetwork = settings.FlightSimulationNetwork, + StationIdentifier = settings.StationIdentifier, + DefaultAdscReportingInterval = settings.DefaultAdscReportingInterval, + SelectedAdscContractDuration = settings.SelectedAdscContractDuration + }, + _ => throw new NotSupportedException($"ACARS network type {settings.Type} is not supported") + }; + } + + async Task CreateAcarsConnection( + Guid settingsId, + AcarsConfiguration configuration, + CancellationToken cancellationToken) + { + var acarsConnectionId = configuration.AcarsConnectionId; + + IAcarsConnection acarsConnection = configuration switch + { + HoppiesConfiguration hoppieConfig => CreateHoppieConnection(hoppieConfig), + _ => throw new NotSupportedException($"ACARS configuration type {configuration.GetType().Name} is not supported") + }; + + var stationId = acarsConnection.StationId; + + var subscribeTaskCancellationSource = new CancellationTokenSource(); + var subscribeTask = Task.WhenAll( + Subscribe( + acarsConnectionId, + stationId, + acarsConnection, + _mediator, + subscribeTaskCancellationSource.Token), + SubscribeAdsc( + acarsConnectionId, + stationId, + acarsConnection, + _mediator, + subscribeTaskCancellationSource.Token)); + + var acarsConnectionHandle = new AcarsConnectionHandle( + settingsId, + configuration, + acarsConnection, + subscribeTask, + subscribeTaskCancellationSource); + + await acarsConnection.Connect(cancellationToken); + + _logger.Information("Connected to ACARS connection {AcarsConnectionId}", acarsConnectionId); + + return acarsConnectionHandle; + } + + HoppieAcarsConnection CreateHoppieConnection(HoppiesConfiguration configuration) + { + var httpClient = new HttpClient(); + httpClient.BaseAddress = configuration.Url; + + return new HoppieAcarsConnection( + configuration, + httpClient, + _clock, + _adscMessageLogRepository, + _logger.ForContext()); + } + + async Task Subscribe(string acarsConnectionId, string stationId, IAcarsConnection acarsConnection, IUnitOfWorkMediator mediator, CancellationToken cancellationToken) + { + var subscriptionLogger = _logger.ForContext("AcarsConnectionId", acarsConnectionId); + + try + { + await foreach (var downlinkMessage in acarsConnection.MessageReader.ReadAllAsync(cancellationToken)) + { + // TODO: Make this configurable + // Linked to the subscription, so that a stopped connection does not wait for the timeout + using var publishTimeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + publishTimeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10)); + + try + { + await mediator.Publish( + new DownlinkReceivedNotification( + acarsConnectionId, + stationId, + downlinkMessage), + publishTimeoutCancellationTokenSource.Token); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + subscriptionLogger.Information("Subscription canceled"); + return; + } + catch (OperationCanceledException) when (publishTimeoutCancellationTokenSource.Token.IsCancellationRequested) + { + subscriptionLogger.Warning("Timeout handling downlink {Downlink}", downlinkMessage); + } + catch (Exception ex) + { + subscriptionLogger.Error(ex, "Failed to relay {MessageType}", downlinkMessage.GetType()); + } + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + subscriptionLogger.Information("Subscription canceled"); + } + } + + async Task SubscribeAdsc(string acarsConnectionId, string stationId, IAcarsConnection acarsConnection, IUnitOfWorkMediator mediator, CancellationToken cancellationToken) + { + var subscriptionLogger = _logger.ForContext("AcarsConnectionId", acarsConnectionId); + + try + { + await foreach (var adscMessage in acarsConnection.AdscMessageReader.ReadAllAsync(cancellationToken)) + { + // TODO: Make this configurable + // Linked to the subscription, so that a stopped connection does not wait for the timeout + using var publishTimeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + publishTimeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10)); + + try + { + await mediator.Publish( + new AdscMessageReceivedNotification( + acarsConnectionId, + stationId, + adscMessage), + publishTimeoutCancellationTokenSource.Token); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + subscriptionLogger.Information("ADS-C subscription canceled"); + return; + } + catch (OperationCanceledException) when (publishTimeoutCancellationTokenSource.Token.IsCancellationRequested) + { + subscriptionLogger.Warning("Timeout handling ADS-C message {AdscMessage}", adscMessage); + } + catch (Exception ex) + { + subscriptionLogger.Error(ex, "Failed to relay {MessageType}", adscMessage.GetType()); + } + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + subscriptionLogger.Information("ADS-C subscription canceled"); + } + } + + record AcarsConnectionHandle( + Guid SettingsId, + AcarsConfiguration Configuration, + IAcarsConnection Connection, + Task SubscribeTask, + CancellationTokenSource SubscribeCancellationTokenSource) : IAsyncDisposable + { + public async ValueTask DisposeAsync() + { + await Connection.DisposeAsync(); + + await SubscribeCancellationTokenSource.CancelAsync(); + + try + { + await SubscribeTask; + } + catch (OperationCanceledException) + { + // Expected during shutdown + } + + SubscribeCancellationTokenSource.Dispose(); + SubscribeTask.Dispose(); + } + } + + public override async Task StopAsync(CancellationToken cancellationToken) + { + _logger.Information("Stopping ACARS connection manager and disposing all connections"); + + await base.StopAsync(cancellationToken); + + foreach (var (_, connectionHandle) in _connections) + { + await connectionHandle.DisposeAsync(); + } + + _connections.Clear(); + _semaphoreSlim.Dispose(); + } +} diff --git a/source/CPDLCServer/AcarsConnections/AcarsConnectionsServiceCollectionExtensions.cs b/source/CPDLCServer/AcarsConnections/AcarsConnectionsServiceCollectionExtensions.cs new file mode 100644 index 0000000..0418fea --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/AcarsConnectionsServiceCollectionExtensions.cs @@ -0,0 +1,18 @@ +using CPDLCServer.AcarsConnections.Stations; + +namespace CPDLCServer.AcarsConnections; + +public static class AcarsConnectionsServiceCollectionExtensions +{ + public static IServiceCollection AddAcarsConnections(this IServiceCollection services) + { + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddHostedService(sp => sp.GetRequiredService()); + + services.AddSingleton(); + services.AddHostedService(); + + return services; + } +} diff --git a/source/CPDLCServer/AcarsConnections/ConfigurationNotFoundException.cs b/source/CPDLCServer/AcarsConnections/ConfigurationNotFoundException.cs new file mode 100644 index 0000000..e4671ed --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConfigurationNotFoundException.cs @@ -0,0 +1,4 @@ +namespace CPDLCServer.AcarsConnections; + +public sealed class ConfigurationNotFoundException(string acarsConnectionId) + : Exception($"No ACARS configuration found for ACARS connection ID '{acarsConnectionId}'"); \ No newline at end of file diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettings.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettings.cs new file mode 100644 index 0000000..e5ba86f --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettings.cs @@ -0,0 +1,48 @@ +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public enum AcarsNetworkType +{ + Hoppie +} + +// The settings of an ACARS connection. The initial values are the default values. +// The settings page binds its form to this type, so the form cannot set the ID or the encrypted authentication code. +public class AcarsConnectionSettings +{ + [BindNever] + public Guid Id { get; init; } = Guid.NewGuid(); + + public AcarsNetworkType Type { get; set; } = AcarsNetworkType.Hoppie; + + // The server starts only the enabled connections + public bool Enabled { get; set; } = true; + + [Required] + [RegularExpression("^[A-Za-z0-9]+$", ErrorMessage = "Use only letters and digits.")] + public string StationIdentifier { get; set; } = string.Empty; + + [Required] + public string FlightSimulationNetwork { get; set; } = "VATSIM"; + + [Required] + public Uri Url { get; set; } = new("http://www.hoppie.nl/acars/system/connect.html"); + + // Encrypted with the master key. Use MasterKeyEncryption to decrypt it. The plain code is not kept. + [BindNever] + [ValidateNever] + public string EncryptedAuthenticationCode { get; set; } = string.Empty; + + [Range(1, int.MaxValue)] + public int DefaultAdscReportingInterval { get; set; } = 10; + + [Range(1, int.MaxValue)] + public int SelectedAdscContractDuration { get; set; } = 60; + + // Free text for the users. The server does not use it. + [StringLength(2000)] + public string? Notes { get; set; } +} diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettingsConfiguration.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettingsConfiguration.cs new file mode 100644 index 0000000..796fffa --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettingsConfiguration.cs @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public class AcarsConnectionSettingsConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("AcarsConnections"); + + builder.HasKey(c => c.Id); + builder.Property(c => c.Id).ValueGeneratedNever(); + + builder.Property(c => c.Type).HasConversion(); + builder.Property(c => c.Url).HasConversion(); + + // The ACARS connection ID comes from the station identifier, so only one connection can use a station identifier + builder.HasIndex(c => c.StationIdentifier).IsUnique(); + } +} diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommand.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommand.cs new file mode 100644 index 0000000..87c734e --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +// The authentication code is plain text. The handler encrypts it. +public record CreateAcarsConnectionCommand(AcarsConnectionSettings Settings, string? AuthenticationCode) : IRequest; diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommandHandler.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommandHandler.cs new file mode 100644 index 0000000..26a2887 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommandHandler.cs @@ -0,0 +1,33 @@ +using CPDLCServer.Persistence; +using CPDLCServer.Security; +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public class CreateAcarsConnectionCommandHandler( + CpdlcDbContext dbContext, + MasterKeyEncryption masterKeyEncryption, + IAcarsConnectionManager acarsConnectionManager, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public Task Handle(CreateAcarsConnectionCommand request, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.AuthenticationCode)) + throw new ArgumentException("An authentication code is required for a new ACARS connection"); + + var settings = request.Settings; + settings.StationIdentifier = settings.StationIdentifier.ToUpperInvariant(); + settings.EncryptedAuthenticationCode = masterKeyEncryption.Encrypt(request.AuthenticationCode); + + dbContext.AcarsConnections.Add(settings); + + logger.Information("ACARS connection for {StationId} created", settings.StationIdentifier); + + if (settings.Enabled) + unitOfWork.AfterCommit(ct => acarsConnectionManager.Start(settings, ct)); + + return Task.FromResult(settings.Id); + } +} diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommand.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommand.cs new file mode 100644 index 0000000..b24e165 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public record DeleteAcarsConnectionCommand(Guid Id) : IRequest; diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommandHandler.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommandHandler.cs new file mode 100644 index 0000000..b6548a3 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/DeleteAcarsConnectionCommandHandler.cs @@ -0,0 +1,28 @@ +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public class DeleteAcarsConnectionCommandHandler( + CpdlcDbContext dbContext, + IAcarsConnectionManager acarsConnectionManager, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(DeleteAcarsConnectionCommand request, CancellationToken cancellationToken) + { + var settings = await dbContext.AcarsConnections.FindAsync([request.Id], cancellationToken); + if (settings is null) + { + logger.Warning("ACARS connection {Id} not found for deletion", request.Id); + return; + } + + dbContext.AcarsConnections.Remove(settings); + + logger.Information("ACARS connection for {StationId} deleted", settings.StationIdentifier); + + unitOfWork.AfterCommit(ct => acarsConnectionManager.Stop(request.Id, ct)); + } +} diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommand.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommand.cs new file mode 100644 index 0000000..00e360d --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +// The authentication code is plain text. An empty value keeps the current authentication code. +public record UpdateAcarsConnectionCommand(Guid Id, AcarsConnectionSettings Settings, string? AuthenticationCode) : IRequest; diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommandHandler.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommandHandler.cs new file mode 100644 index 0000000..21782b6 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommandHandler.cs @@ -0,0 +1,45 @@ +using CPDLCServer.Persistence; +using CPDLCServer.Security; +using MediatR; + +namespace CPDLCServer.AcarsConnections.ConnectionSettings; + +public class UpdateAcarsConnectionCommandHandler( + CpdlcDbContext dbContext, + MasterKeyEncryption masterKeyEncryption, + IAcarsConnectionManager acarsConnectionManager, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(UpdateAcarsConnectionCommand request, CancellationToken cancellationToken) + { + var settings = await dbContext.AcarsConnections.FindAsync([request.Id], cancellationToken); + if (settings is null) + throw new InvalidOperationException($"ACARS connection {request.Id} not found"); + + var changes = request.Settings; + settings.Type = changes.Type; + settings.Enabled = changes.Enabled; + settings.StationIdentifier = changes.StationIdentifier.ToUpperInvariant(); + settings.FlightSimulationNetwork = changes.FlightSimulationNetwork; + settings.Url = changes.Url; + settings.DefaultAdscReportingInterval = changes.DefaultAdscReportingInterval; + settings.SelectedAdscContractDuration = changes.SelectedAdscContractDuration; + settings.Notes = changes.Notes; + + if (!string.IsNullOrWhiteSpace(request.AuthenticationCode)) + settings.EncryptedAuthenticationCode = masterKeyEncryption.Encrypt(request.AuthenticationCode); + + logger.Information("ACARS connection for {StationId} updated", settings.StationIdentifier); + + // Start the connection again, so that it uses the new settings + unitOfWork.AfterCommit(async ct => + { + await acarsConnectionManager.Stop(settings.Id, ct); + + if (settings.Enabled) + await acarsConnectionManager.Start(settings, ct); + }); + } +} diff --git a/source/CPDLCServer/Messages/GetAtsuSettingsRequest.cs b/source/CPDLCServer/AcarsConnections/GetAtsuSettingsRequest.cs similarity index 76% rename from source/CPDLCServer/Messages/GetAtsuSettingsRequest.cs rename to source/CPDLCServer/AcarsConnections/GetAtsuSettingsRequest.cs index 2165019..536ccc4 100644 --- a/source/CPDLCServer/Messages/GetAtsuSettingsRequest.cs +++ b/source/CPDLCServer/AcarsConnections/GetAtsuSettingsRequest.cs @@ -1,6 +1,6 @@ using CPDLCServer.Contracts; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AcarsConnections; public record GetAtsuSettingsRequest(string StationId) : IRequest; diff --git a/source/CPDLCServer/Handlers/GetAtsuSettingsRequestHandler.cs b/source/CPDLCServer/AcarsConnections/GetAtsuSettingsRequestHandler.cs similarity index 58% rename from source/CPDLCServer/Handlers/GetAtsuSettingsRequestHandler.cs rename to source/CPDLCServer/AcarsConnections/GetAtsuSettingsRequestHandler.cs index 12f0f6d..4bd7db5 100644 --- a/source/CPDLCServer/Handlers/GetAtsuSettingsRequestHandler.cs +++ b/source/CPDLCServer/AcarsConnections/GetAtsuSettingsRequestHandler.cs @@ -1,16 +1,14 @@ -using CPDLCServer.Clients; using CPDLCServer.Contracts; -using CPDLCServer.Messages; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AcarsConnections; -public class GetAtsuSettingsRequestHandler(IClientManager clientManager) +public class GetAtsuSettingsRequestHandler(IAcarsConnectionManager acarsConnectionManager) : IRequestHandler { public async Task Handle(GetAtsuSettingsRequest request, CancellationToken cancellationToken) { - var configuration = await clientManager.GetConfigurationForStation(request.StationId, cancellationToken); + var configuration = await acarsConnectionManager.GetConfigurationForStation(request.StationId, cancellationToken); return new AtsuSettingsDto( request.StationId, diff --git a/source/CPDLCServer/Clients/HoppieAcarsClient.cs b/source/CPDLCServer/AcarsConnections/Hoppie/HoppieAcarsConnection.cs similarity index 95% rename from source/CPDLCServer/Clients/HoppieAcarsClient.cs rename to source/CPDLCServer/AcarsConnections/Hoppie/HoppieAcarsConnection.cs index ae2c0d9..1f260c7 100644 --- a/source/CPDLCServer/Clients/HoppieAcarsClient.cs +++ b/source/CPDLCServer/AcarsConnections/Hoppie/HoppieAcarsConnection.cs @@ -1,624 +1,627 @@ -using System.Globalization; -using System.Threading.Channels; -using CPDLCServer.Exceptions; -using CPDLCServer.Infrastructure; -using CPDLCServer.Model; -using CPDLCServer.Persistence; - -namespace CPDLCServer.Clients; - -// TODO: Accept encoded messages via the API (i.e. UMxxx), translate from within the client. - -public class HoppieAcarsClient : IAcarsClient -{ - readonly Dictionary _uplinkMessageTranslations = new() - { - { "END SERVICE", "LOGOFF" } - }; - - readonly HoppiesConfiguration _configuration; - readonly HttpClient _httpClient; - readonly IClock _clock; - readonly IAdscMessageLogRepository _adscMessageLogRepository; - readonly ILogger _logger; - - readonly Channel _messageChannel = Channel.CreateUnbounded(); - readonly Channel _adscMessageChannel = Channel.CreateUnbounded(); - readonly Random _random = Random.Shared; - - CancellationTokenSource? _pollCancellationTokenSource; - Task? _pollTask; - DateTimeOffset? _lastSendTime; - - bool _disposed; - - public ChannelReader MessageReader => _messageChannel.Reader; - public ChannelReader AdscMessageReader => _adscMessageChannel.Reader; - public string StationId => _configuration.StationIdentifier; - - public HoppieAcarsClient(HoppiesConfiguration configuration, HttpClient httpClient, IClock clock, IAdscMessageLogRepository adscMessageLogRepository, ILogger logger) - { - _configuration = configuration; - _httpClient = httpClient; - _httpClient.Timeout = TimeSpan.FromSeconds(15); - _clock = clock; - _adscMessageLogRepository = adscMessageLogRepository; - _logger = logger.ForContext("ClientId", _configuration.ClientId); - } - - public Task Connect(CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - _pollCancellationTokenSource = new CancellationTokenSource(); - _pollTask = Poll(_pollCancellationTokenSource.Token); - - _logger.Information("Connected to Hoppies ACARS network"); - - return Task.CompletedTask; - } - - public async Task Send(UplinkMessage message, CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - var packet = SerializeCpdlcMessage(message); - await SendPacket(message.Recipient, "cpdlc", packet, cancellationToken); - } - - public async Task RequestPeriodicAdscContract(string callsign, TimeSpan reportingInterval, CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - var reportingIntervalSeconds = (int)reportingInterval.TotalSeconds; - if (reportingIntervalSeconds <= 0) - throw new ArgumentOutOfRangeException(nameof(reportingInterval), reportingInterval, "Reporting interval must be one second or more"); - - await SendAdscPacket(callsign, $"REQUEST PERIODIC {reportingIntervalSeconds}", cancellationToken); - } - - // Hoppie has no separate demand contract. A periodic request with an interval of zero asks for one report. - public async Task RequestAdscDemandReport(string callsign, CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - await SendAdscPacket(callsign, "REQUEST PERIODIC 0", cancellationToken); - } - - public async Task CancelAdscContract(string callsign, CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - await SendAdscPacket(callsign, "REQUEST CANCEL", cancellationToken); - } - - async Task SendAdscPacket(string callsign, string packet, CancellationToken cancellationToken) - { - await SendPacket(callsign, "ads-c", packet, cancellationToken); - await LogAdscPacket(callsign, AdscMessageDirection.Uplink, packet, cancellationToken); - } - - async Task LogAdscPacket(string callsign, AdscMessageDirection direction, string packet, CancellationToken cancellationToken) - { - var entry = new AdscMessageLogEntry( - _clock.UtcNow(), - _configuration.ClientId, - _configuration.StationIdentifier, - callsign, - direction, - packet); - await _adscMessageLogRepository.Add(entry, cancellationToken); - } - - async Task SendPacket(string to, string messageType, string packet, CancellationToken cancellationToken) - { - var parameters = new Dictionary - { - ["logon"] = _configuration.AuthenticationCode, - ["network"] = _configuration.FlightSimulationNetwork, - ["from"] = _configuration.StationIdentifier, - ["to"] = to, - ["type"] = messageType - }; - - if (!string.IsNullOrEmpty(packet)) - parameters["packet"] = packet; - - var content = new FormUrlEncodedContent(parameters); - - try - { - _logger.Verbose("Sending {MessageType} to {Recipient} with packet {Packet}", messageType, to, packet); - var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); - response.EnsureSuccessStatusCode(); - - var responseText = await response.Content.ReadAsStringAsync(cancellationToken); - _logger.Verbose("Send response: {Response}", responseText); - - _lastSendTime = _clock.UtcNow(); - } - catch (HttpRequestException ex) - { - _logger.Error(ex, "Failed to send message"); - throw; - } - catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) - { - _logger.Warning("Send request timed out, skipping"); - } - } - - public async Task ListConnections(CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - var parameters = new Dictionary - { - ["logon"] = _configuration.AuthenticationCode, - ["from"] = _configuration.StationIdentifier, - ["to"] = "SERVER", - ["type"] = "ping", - ["packet"] = "ALL-CALLSIGNS" - }; - - var content = new FormUrlEncodedContent(parameters); - - try - { - _logger.Verbose("Listing connections"); - var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); - response.EnsureSuccessStatusCode(); - - var responseText = await response.Content.ReadAsStringAsync(cancellationToken); - _logger.Verbose("ListConnections response: {Response}", responseText); - - // Parse the response to extract callsigns - if (string.IsNullOrWhiteSpace(responseText)) - return Array.Empty(); - - // Strip "ok" prefix if present - if (responseText.StartsWith("ok", StringComparison.OrdinalIgnoreCase)) - { - responseText = responseText[2..].TrimStart(); - } - - if (string.IsNullOrWhiteSpace(responseText)) - return Array.Empty(); - - // Strip curly braces if present - if (responseText.StartsWith('{') && responseText.EndsWith('}')) - { - responseText = responseText[1..^1].Trim(); - } - - if (string.IsNullOrWhiteSpace(responseText)) - return Array.Empty(); - - // The response contains space-separated callsigns - var callsigns = responseText - .Split(' ', StringSplitOptions.RemoveEmptyEntries) - .Where(s => !string.IsNullOrWhiteSpace(s)) - .ToArray(); - - _logger.Information("Found {Count} active connections", callsigns.Length); - return callsigns; - } - catch (HttpRequestException ex) - { - _logger.Error(ex, "Failed to list connections"); - throw; - } - catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) - { - _logger.Warning("ListConnections request timed out"); - return Array.Empty(); - } - } - - public async Task Disconnect(CancellationToken cancellationToken) - { - if (_disposed) - throw new ObjectDisposedException(nameof(HoppieAcarsClient)); - - if (_pollCancellationTokenSource is not null) - await _pollCancellationTokenSource.CancelAsync(); - - if (_pollTask is not null) - await _pollTask; - - _logger.Information("Disconnected from Hoppies ACARS network"); - } - - async Task Poll(CancellationToken cancellationToken) - { - try - { - while (!cancellationToken.IsCancellationRequested) - { - try - { - _logger.Verbose("Polling for messages"); - - var parameters = new Dictionary - { - ["logon"] = _configuration.AuthenticationCode, - ["from"] = _configuration.StationIdentifier, - ["to"] = "SERVER", - ["type"] = "poll" - }; - - var content = new FormUrlEncodedContent(parameters); - var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); - response.EnsureSuccessStatusCode(); - - var responseText = await response.Content.ReadAsStringAsync(cancellationToken); - - _logger.Verbose("Poll response: {Response}", responseText); - - if (!string.IsNullOrWhiteSpace(responseText) && responseText != "ok") - { - await ParseAndPublishDownlinkMessages(responseText, cancellationToken); - } - } - catch (HttpRequestException ex) - { - _logger.Error(ex, "Poll request failed"); - } - catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) - { - _logger.Warning("Poll request timed out, skipping this attempt"); - } - catch (Exception ex) - { - _logger.Error(ex, "Unhandled exception when polling messages"); - } - - var pollInterval = GetPollInterval(); - _logger.Verbose("Poll completed, waiting {PollInterval}", pollInterval); - await Task.Delay(pollInterval, cancellationToken); - } - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - _logger.Information("Stopping poll task"); - } - catch (Exception ex) - { - _logger.Fatal(ex, "Unhandled exception when polling messages"); - } - } - - async Task ParseAndPublishDownlinkMessages(string responseText, CancellationToken cancellationToken) - { - try - { - if (responseText.StartsWith("ok", StringComparison.OrdinalIgnoreCase)) - { - responseText = responseText[2..].TrimStart(); - } - - if (string.IsNullOrWhiteSpace(responseText)) - return; - - if (responseText.StartsWith("error", StringComparison.OrdinalIgnoreCase)) - { - _logger.Warning("Hoppie server error: {Error}", responseText); - return; - } - - var messages = ExtractMessages(responseText); - - _logger.Verbose("Extracted {Count} messages", messages.Count); - - foreach (var messageText in messages) - { - _logger.Verbose("Extracted: {Message}", messageText); - var (from, type, packet) = ParseMessage(messageText); - - switch (type.ToLowerInvariant()) - { - case "cpdlc": - var downlink = ParseCpdlcDownlink(from, packet); - _logger.Information("Received {MessageType} from {From}", type, from); - _messageChannel.Writer.TryWrite(downlink); - break; - - case "ads-c": - // Log the packet before it is parsed, so that packets that cannot be parsed are also in the log - await LogAdscPacket(from, AdscMessageDirection.Downlink, packet, cancellationToken); - - var adscMessage = ParseAdscDownlink(from, packet); - if (adscMessage is null) - break; - - _logger.Information("Received {MessageType} from {From}", type, from); - _adscMessageChannel.Writer.TryWrite(adscMessage); - break; - - default: - _logger.Information("Unsupported message type: {Type}", type); - break; - } - } - } - catch (Exception ex) - { - throw new MessageParseException("Failed to parse downlink messages", ex); - } - } - - static List ExtractMessages(string responseText) - { - var messages = new List(); - var depth = 0; - var currentMessage = new System.Text.StringBuilder(); - - for (var i = 0; i < responseText.Length; i++) - { - var c = responseText[i]; - - if (c == '{') - { - depth++; - if (depth == 1) - continue; - } - else if (c == '}') - { - depth--; - if (depth == 0) - { - messages.Add(currentMessage.ToString()); - currentMessage.Clear(); - continue; - } - } - - if (depth > 0) - { - currentMessage.Append(c); - } - } - - return messages; - } - - static (string from, string type, string packet) ParseMessage(string messageText) - { - var firstBraceIndex = messageText.IndexOf('{'); - if (firstBraceIndex == -1) - { - var parts = messageText.Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (parts.Length < 2) - throw new Exception($"Invalid message format: {messageText}"); - - return (parts[0], parts[1], parts.Length > 2 ? string.Join(" ", parts[2..]) : string.Empty); - } - - var headerParts = messageText[..firstBraceIndex].Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (headerParts.Length < 2) - throw new Exception($"Invalid message format: {messageText}"); - - var packet = messageText[(firstBraceIndex + 1)..]; - if (packet.EndsWith('}')) - packet = packet[..^1]; - - return (headerParts[0], headerParts[1], packet); - } - - ReceivedDownlink ParseCpdlcDownlink(string from, string packet) - { - if (packet.StartsWith("/DATA1/", StringComparison.OrdinalIgnoreCase)) - return ParseData1Downlink(from, packet); - - var parts = packet.Split('/', 6); - if (parts.Length != 6) - throw new MessageParseException($"Invalid CPDLC packet: Expected 6 components, got {parts.Length}: \"{packet}\""); - - var messageId = !string.IsNullOrEmpty(parts[2]) ? int.Parse(parts[2]) : -1; - int? replyToId = !string.IsNullOrEmpty(parts[3]) ? int.Parse(parts[3]) : null; - var responseType = parts[4] switch - { - "N" => CpdlcDownlinkResponseType.NoResponse, - "Y" => CpdlcDownlinkResponseType.ResponseRequired, - _ => throw new NotSupportedException($"Unsupported CPDLC downlink response type: {parts[4]}") - }; - - var content = parts[5]; - - return new ReceivedDownlink( - messageId, - replyToId, - from, - responseType, - AlertType.None, - content, - _clock.UtcNow()); - } - - // Some aircraft (for example, PMDG) send position reports in this format: - // /DATA1/*/*/*/*/FL380/*/0.84/ - // - // OVER MEPAB AT 0501Z, FL380, - // ESTIMATING ISTEM AT 0533Z, - // ... - // The first line is a header. The lines after the header contain the text of the report. - ReceivedDownlink ParseData1Downlink(string from, string packet) - { - var lines = packet.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - var content = lines.Length > 1 - ? string.Join(" ", lines[1..]) - : packet; - - return new ReceivedDownlink( - -1, - null, - from, - CpdlcDownlinkResponseType.NoResponse, - AlertType.None, - content, - _clock.UtcNow()); - } - - // Packet formats: - // REPORT [] - // REJECT - ReceivedAdscMessage? ParseAdscDownlink(string from, string packet) - { - var parts = packet.Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (parts.Length == 0) - throw new MessageParseException("Invalid ADS-C packet: Packet is empty"); - - switch (parts[0]) - { - case "REJECT": - return new ReceivedAdscRejection(from, _clock.UtcNow()); - - case "REPORT": - if (parts.Length < 6) - throw new MessageParseException($"Invalid ADS-C report: Expected 6 or more components, got {parts.Length}: \"{packet}\""); - - if (!TryParseCoordinate(parts[3], 'N', 'S', 90, out var latitude) || - !TryParseCoordinate(parts[4], 'E', 'W', 180, out var longitude)) - { - _logger.Warning("Ignoring ADS-C report from {From}: Cannot read the position: \"{Packet}\"", from, packet); - return null; - } - - // Aircraft do not agree on the format of the optional groups, so ignore them - var report = new AdscReport( - ParseAdscTimestamp(parts[2]), - latitude, - longitude, - ParseAdscAltitude(parts[5]), - AdscReportSource.Hoppie); - - return new ReceivedAdscReport(from, report, _clock.UtcNow()); - - default: - throw new MessageParseException($"Unsupported ADS-C packet: \"{packet}\""); - } - } - - // Aircraft send coordinates in different formats. - // For example, a latitude can be "-33.9461", "S33.9461", or "33.9461S". - static bool TryParseCoordinate(string text, char positiveHemisphere, char negativeHemisphere, double maximum, out double coordinate) - { - coordinate = 0; - - var number = text.ToUpperInvariant(); - var sign = 1; - if (number.Length > 1 && (number[0] == positiveHemisphere || number[0] == negativeHemisphere)) - { - sign = number[0] == negativeHemisphere ? -1 : 1; - number = number[1..]; - } - else if (number.Length > 1 && (number[^1] == positiveHemisphere || number[^1] == negativeHemisphere)) - { - sign = number[^1] == negativeHemisphere ? -1 : 1; - number = number[..^1]; - } - - if (!double.TryParse(number, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value)) - return false; - - coordinate = sign * value; - return Math.Abs(coordinate) <= maximum; - } - - // Some aircraft send the altitude in feet, and some send it in hundreds of feet. - // Below 10,000, the altitude is in hundreds of feet. - static int ParseAdscAltitude(string text) - { - var altitude = int.Parse(text, CultureInfo.InvariantCulture); - return altitude < 10_000 ? altitude * 100 : altitude; - } - - // The report time has the day of the month, the hour, and the minute (ddHHmm) in UTC. - // Use the current month, or the previous month if the day is in the future. - DateTimeOffset ParseAdscTimestamp(string text) - { - if (text.Length != 6) - throw new MessageParseException($"Invalid ADS-C report time: \"{text}\""); - - var day = int.Parse(text[..2], CultureInfo.InvariantCulture); - var hour = int.Parse(text[2..4], CultureInfo.InvariantCulture); - var minute = int.Parse(text[4..], CultureInfo.InvariantCulture); - - var now = _clock.UtcNow(); - var month = new DateTimeOffset(now.Year, now.Month, 1, 0, 0, 0, TimeSpan.Zero); - if (day > now.Day) - month = month.AddMonths(-1); - - return month.AddDays(day - 1).AddHours(hour).AddMinutes(minute); - } - - TimeSpan GetPollInterval() - { - if (_lastSendTime.HasValue) - { - var timeSinceLastSend = _clock.UtcNow() - _lastSendTime.Value; - if (timeSinceLastSend < TimeSpan.FromMinutes(1)) - { - return TimeSpan.FromSeconds(20); - } - } - - return TimeSpan.FromSeconds(_random.Next(45, 76)); - } - - string SerializeCpdlcMessage(UplinkMessage uplinkMessage) - { - var responseType = uplinkMessage.ResponseType switch - { - CpdlcUplinkResponseType.NoResponse => "NE", - CpdlcUplinkResponseType.WilcoUnable => "WU", - CpdlcUplinkResponseType.AffirmativeNegative => "AN", - CpdlcUplinkResponseType.Roger => "R", - _ => throw new ArgumentException($"Unexpected CpdlcResponseType: {uplinkMessage.ResponseType}") - }; - - var replyToId = uplinkMessage.MessageReference is not null - ? uplinkMessage.MessageReference.ToString() - : string.Empty; - - var content = GetTranslatedContent(uplinkMessage); - - return $"/data2/{uplinkMessage.MessageId}/{replyToId}/{responseType}/{content}"; - } - - string GetTranslatedContent(UplinkMessage uplinkMessage) - { - var translatedContent = uplinkMessage.Content; - foreach (var uplinkMessageTranslation in _uplinkMessageTranslations) - { - translatedContent = translatedContent.Replace(uplinkMessageTranslation.Key, uplinkMessageTranslation.Value); - } - - return translatedContent; - } - - public async ValueTask DisposeAsync() - { - if (_disposed) - return; - - await Disconnect(CancellationToken.None); - - if (_pollTask is not null) - _pollTask.Dispose(); - - if (_pollCancellationTokenSource is not null) - _pollCancellationTokenSource.Dispose(); - - _httpClient.Dispose(); - - _disposed = true; - } -} +using System.Globalization; +using System.Threading.Channels; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Infrastructure; + +namespace CPDLCServer.AcarsConnections.Hoppie; + +// TODO: Accept encoded messages via the API (i.e. UMxxx), translate from within the connection. + +public class HoppieAcarsConnection : IAcarsConnection +{ + readonly Dictionary _uplinkMessageTranslations = new() + { + { "END SERVICE", "LOGOFF" } + }; + + readonly HoppiesConfiguration _configuration; + readonly HttpClient _httpClient; + readonly IClock _clock; + readonly IAdscMessageLogRepository _adscMessageLogRepository; + readonly ILogger _logger; + + readonly Channel _messageChannel = Channel.CreateUnbounded(); + readonly Channel _adscMessageChannel = Channel.CreateUnbounded(); + readonly Random _random = Random.Shared; + + CancellationTokenSource? _pollCancellationTokenSource; + Task? _pollTask; + DateTimeOffset? _lastSendTime; + + bool _disposed; + + public ChannelReader MessageReader => _messageChannel.Reader; + public ChannelReader AdscMessageReader => _adscMessageChannel.Reader; + public string StationId => _configuration.StationIdentifier; + + public HoppieAcarsConnection(HoppiesConfiguration configuration, HttpClient httpClient, IClock clock, IAdscMessageLogRepository adscMessageLogRepository, ILogger logger) + { + _configuration = configuration; + _httpClient = httpClient; + _httpClient.Timeout = TimeSpan.FromSeconds(15); + _clock = clock; + _adscMessageLogRepository = adscMessageLogRepository; + _logger = logger.ForContext("AcarsConnectionId", _configuration.AcarsConnectionId); + } + + public Task Connect(CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + _pollCancellationTokenSource = new CancellationTokenSource(); + _pollTask = Poll(_pollCancellationTokenSource.Token); + + _logger.Information("Connected to Hoppies ACARS network"); + + return Task.CompletedTask; + } + + public async Task Send(UplinkMessage message, CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + var packet = SerializeCpdlcMessage(message); + await SendPacket(message.Recipient, "cpdlc", packet, cancellationToken); + } + + public async Task RequestPeriodicAdscContract(string callsign, TimeSpan reportingInterval, CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + var reportingIntervalSeconds = (int)reportingInterval.TotalSeconds; + if (reportingIntervalSeconds <= 0) + throw new ArgumentOutOfRangeException(nameof(reportingInterval), reportingInterval, "Reporting interval must be one second or more"); + + await SendAdscPacket(callsign, $"REQUEST PERIODIC {reportingIntervalSeconds}", cancellationToken); + } + + // Hoppie has no separate demand contract. A periodic request with an interval of zero asks for one report. + public async Task RequestAdscDemandReport(string callsign, CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + await SendAdscPacket(callsign, "REQUEST PERIODIC 0", cancellationToken); + } + + public async Task CancelAdscContract(string callsign, CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + await SendAdscPacket(callsign, "REQUEST CANCEL", cancellationToken); + } + + async Task SendAdscPacket(string callsign, string packet, CancellationToken cancellationToken) + { + await SendPacket(callsign, "ads-c", packet, cancellationToken); + await LogAdscPacket(callsign, AdscMessageDirection.Uplink, packet, cancellationToken); + } + + async Task LogAdscPacket(string callsign, AdscMessageDirection direction, string packet, CancellationToken cancellationToken) + { + var entry = new AdscMessageLogEntry( + _clock.UtcNow(), + _configuration.AcarsConnectionId, + _configuration.StationIdentifier, + callsign, + direction, + packet); + await _adscMessageLogRepository.Add(entry, cancellationToken); + } + + async Task SendPacket(string to, string messageType, string packet, CancellationToken cancellationToken) + { + var parameters = new Dictionary + { + ["logon"] = _configuration.AuthenticationCode, + ["network"] = _configuration.FlightSimulationNetwork, + ["from"] = _configuration.StationIdentifier, + ["to"] = to, + ["type"] = messageType + }; + + if (!string.IsNullOrEmpty(packet)) + parameters["packet"] = packet; + + var content = new FormUrlEncodedContent(parameters); + + try + { + _logger.Verbose("Sending {MessageType} to {Recipient} with packet {Packet}", messageType, to, packet); + var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); + response.EnsureSuccessStatusCode(); + + var responseText = await response.Content.ReadAsStringAsync(cancellationToken); + _logger.Verbose("Send response: {Response}", responseText); + + _lastSendTime = _clock.UtcNow(); + } + catch (HttpRequestException ex) + { + _logger.Error(ex, "Failed to send message"); + throw; + } + catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) + { + _logger.Warning("Send request timed out, skipping"); + } + } + + public async Task ListConnections(CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + var parameters = new Dictionary + { + ["logon"] = _configuration.AuthenticationCode, + ["from"] = _configuration.StationIdentifier, + ["to"] = "SERVER", + ["type"] = "ping", + ["packet"] = "ALL-CALLSIGNS" + }; + + var content = new FormUrlEncodedContent(parameters); + + try + { + _logger.Verbose("Listing connections"); + var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); + response.EnsureSuccessStatusCode(); + + var responseText = await response.Content.ReadAsStringAsync(cancellationToken); + _logger.Verbose("ListConnections response: {Response}", responseText); + + // Parse the response to extract callsigns + if (string.IsNullOrWhiteSpace(responseText)) + return Array.Empty(); + + // Strip "ok" prefix if present + if (responseText.StartsWith("ok", StringComparison.OrdinalIgnoreCase)) + { + responseText = responseText[2..].TrimStart(); + } + + if (string.IsNullOrWhiteSpace(responseText)) + return Array.Empty(); + + // Strip curly braces if present + if (responseText.StartsWith('{') && responseText.EndsWith('}')) + { + responseText = responseText[1..^1].Trim(); + } + + if (string.IsNullOrWhiteSpace(responseText)) + return Array.Empty(); + + // The response contains space-separated callsigns + var callsigns = responseText + .Split(' ', StringSplitOptions.RemoveEmptyEntries) + .Where(s => !string.IsNullOrWhiteSpace(s)) + .ToArray(); + + _logger.Information("Found {Count} active connections", callsigns.Length); + return callsigns; + } + catch (HttpRequestException ex) + { + _logger.Error(ex, "Failed to list connections"); + throw; + } + catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) + { + _logger.Warning("ListConnections request timed out"); + return Array.Empty(); + } + } + + public async Task Disconnect(CancellationToken cancellationToken) + { + if (_disposed) + throw new ObjectDisposedException(nameof(HoppieAcarsConnection)); + + if (_pollCancellationTokenSource is not null) + await _pollCancellationTokenSource.CancelAsync(); + + if (_pollTask is not null) + await _pollTask; + + _logger.Information("Disconnected from Hoppies ACARS network"); + } + + async Task Poll(CancellationToken cancellationToken) + { + try + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + _logger.Verbose("Polling for messages"); + + var parameters = new Dictionary + { + ["logon"] = _configuration.AuthenticationCode, + ["from"] = _configuration.StationIdentifier, + ["to"] = "SERVER", + ["type"] = "poll" + }; + + var content = new FormUrlEncodedContent(parameters); + var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); + response.EnsureSuccessStatusCode(); + + var responseText = await response.Content.ReadAsStringAsync(cancellationToken); + + _logger.Verbose("Poll response: {Response}", responseText); + + if (!string.IsNullOrWhiteSpace(responseText) && responseText != "ok") + { + await ParseAndPublishDownlinkMessages(responseText, cancellationToken); + } + } + catch (HttpRequestException ex) + { + _logger.Error(ex, "Poll request failed"); + } + catch (TaskCanceledException ex) when (ex.CancellationToken != cancellationToken) + { + _logger.Warning("Poll request timed out, skipping this attempt"); + } + catch (Exception ex) + { + _logger.Error(ex, "Unhandled exception when polling messages"); + } + + var pollInterval = GetPollInterval(); + _logger.Verbose("Poll completed, waiting {PollInterval}", pollInterval); + await Task.Delay(pollInterval, cancellationToken); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + _logger.Information("Stopping poll task"); + } + catch (Exception ex) + { + _logger.Fatal(ex, "Unhandled exception when polling messages"); + } + } + + async Task ParseAndPublishDownlinkMessages(string responseText, CancellationToken cancellationToken) + { + try + { + if (responseText.StartsWith("ok", StringComparison.OrdinalIgnoreCase)) + { + responseText = responseText[2..].TrimStart(); + } + + if (string.IsNullOrWhiteSpace(responseText)) + return; + + if (responseText.StartsWith("error", StringComparison.OrdinalIgnoreCase)) + { + _logger.Warning("Hoppie server error: {Error}", responseText); + return; + } + + var messages = ExtractMessages(responseText); + + _logger.Verbose("Extracted {Count} messages", messages.Count); + + foreach (var messageText in messages) + { + _logger.Verbose("Extracted: {Message}", messageText); + var (from, type, packet) = ParseMessage(messageText); + + switch (type.ToLowerInvariant()) + { + case "cpdlc": + var downlink = ParseCpdlcDownlink(from, packet); + _logger.Information("Received {MessageType} from {From}", type, from); + _messageChannel.Writer.TryWrite(downlink); + break; + + case "ads-c": + // Log the packet before it is parsed, so that packets that cannot be parsed are also in the log + await LogAdscPacket(from, AdscMessageDirection.Downlink, packet, cancellationToken); + + var adscMessage = ParseAdscDownlink(from, packet); + if (adscMessage is null) + break; + + _logger.Information("Received {MessageType} from {From}", type, from); + _adscMessageChannel.Writer.TryWrite(adscMessage); + break; + + default: + _logger.Information("Unsupported message type: {Type}", type); + break; + } + } + } + catch (Exception ex) + { + throw new MessageParseException("Failed to parse downlink messages", ex); + } + } + + static List ExtractMessages(string responseText) + { + var messages = new List(); + var depth = 0; + var currentMessage = new System.Text.StringBuilder(); + + for (var i = 0; i < responseText.Length; i++) + { + var c = responseText[i]; + + if (c == '{') + { + depth++; + if (depth == 1) + continue; + } + else if (c == '}') + { + depth--; + if (depth == 0) + { + messages.Add(currentMessage.ToString()); + currentMessage.Clear(); + continue; + } + } + + if (depth > 0) + { + currentMessage.Append(c); + } + } + + return messages; + } + + static (string from, string type, string packet) ParseMessage(string messageText) + { + var firstBraceIndex = messageText.IndexOf('{'); + if (firstBraceIndex == -1) + { + var parts = messageText.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length < 2) + throw new Exception($"Invalid message format: {messageText}"); + + return (parts[0], parts[1], parts.Length > 2 ? string.Join(" ", parts[2..]) : string.Empty); + } + + var headerParts = messageText[..firstBraceIndex].Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (headerParts.Length < 2) + throw new Exception($"Invalid message format: {messageText}"); + + var packet = messageText[(firstBraceIndex + 1)..]; + if (packet.EndsWith('}')) + packet = packet[..^1]; + + return (headerParts[0], headerParts[1], packet); + } + + ReceivedDownlink ParseCpdlcDownlink(string from, string packet) + { + if (packet.StartsWith("/DATA1/", StringComparison.OrdinalIgnoreCase)) + return ParseData1Downlink(from, packet); + + var parts = packet.Split('/', 6); + if (parts.Length != 6) + throw new MessageParseException($"Invalid CPDLC packet: Expected 6 components, got {parts.Length}: \"{packet}\""); + + var messageId = !string.IsNullOrEmpty(parts[2]) ? int.Parse(parts[2]) : -1; + int? replyToId = !string.IsNullOrEmpty(parts[3]) ? int.Parse(parts[3]) : null; + var responseType = parts[4] switch + { + "N" => CpdlcDownlinkResponseType.NoResponse, + "Y" => CpdlcDownlinkResponseType.ResponseRequired, + _ => throw new NotSupportedException($"Unsupported CPDLC downlink response type: {parts[4]}") + }; + + var content = parts[5]; + + return new ReceivedDownlink( + messageId, + replyToId, + from, + responseType, + AlertType.None, + content, + _clock.UtcNow()); + } + + // Some aircraft (for example, PMDG) send position reports in this format: + // /DATA1/*/*/*/*/FL380/*/0.84/ + // + // OVER MEPAB AT 0501Z, FL380, + // ESTIMATING ISTEM AT 0533Z, + // ... + // The first line is a header. The lines after the header contain the text of the report. + ReceivedDownlink ParseData1Downlink(string from, string packet) + { + var lines = packet.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var content = lines.Length > 1 + ? string.Join(" ", lines[1..]) + : packet; + + return new ReceivedDownlink( + -1, + null, + from, + CpdlcDownlinkResponseType.NoResponse, + AlertType.None, + content, + _clock.UtcNow()); + } + + // Packet formats: + // REPORT [] + // REJECT + ReceivedAdscMessage? ParseAdscDownlink(string from, string packet) + { + var parts = packet.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0) + throw new MessageParseException("Invalid ADS-C packet: Packet is empty"); + + switch (parts[0]) + { + case "REJECT": + return new ReceivedAdscRejection(from, _clock.UtcNow()); + + case "REPORT": + if (parts.Length < 6) + throw new MessageParseException($"Invalid ADS-C report: Expected 6 or more components, got {parts.Length}: \"{packet}\""); + + if (!TryParseCoordinate(parts[3], 'N', 'S', 90, out var latitude) || + !TryParseCoordinate(parts[4], 'E', 'W', 180, out var longitude)) + { + _logger.Warning("Ignoring ADS-C report from {From}: Cannot read the position: \"{Packet}\"", from, packet); + return null; + } + + // Aircraft do not agree on the format of the optional groups, so ignore them + var report = new AdscReport( + ParseAdscTimestamp(parts[2]), + latitude, + longitude, + ParseAdscAltitude(parts[5]), + AdscReportSource.Hoppie); + + return new ReceivedAdscReport(from, report, _clock.UtcNow()); + + default: + throw new MessageParseException($"Unsupported ADS-C packet: \"{packet}\""); + } + } + + // Aircraft send coordinates in different formats. + // For example, a latitude can be "-33.9461", "S33.9461", or "33.9461S". + static bool TryParseCoordinate(string text, char positiveHemisphere, char negativeHemisphere, double maximum, out double coordinate) + { + coordinate = 0; + + var number = text.ToUpperInvariant(); + var sign = 1; + if (number.Length > 1 && (number[0] == positiveHemisphere || number[0] == negativeHemisphere)) + { + sign = number[0] == negativeHemisphere ? -1 : 1; + number = number[1..]; + } + else if (number.Length > 1 && (number[^1] == positiveHemisphere || number[^1] == negativeHemisphere)) + { + sign = number[^1] == negativeHemisphere ? -1 : 1; + number = number[..^1]; + } + + if (!double.TryParse(number, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value)) + return false; + + coordinate = sign * value; + return Math.Abs(coordinate) <= maximum; + } + + // Some aircraft send the altitude in feet, and some send it in hundreds of feet. + // Below 10,000, the altitude is in hundreds of feet. + static int ParseAdscAltitude(string text) + { + var altitude = int.Parse(text, CultureInfo.InvariantCulture); + return altitude < 10_000 ? altitude * 100 : altitude; + } + + // The report time has the day of the month, the hour, and the minute (ddHHmm) in UTC. + // Use the current month, or the previous month if the day is in the future. + DateTimeOffset ParseAdscTimestamp(string text) + { + if (text.Length != 6) + throw new MessageParseException($"Invalid ADS-C report time: \"{text}\""); + + var day = int.Parse(text[..2], CultureInfo.InvariantCulture); + var hour = int.Parse(text[2..4], CultureInfo.InvariantCulture); + var minute = int.Parse(text[4..], CultureInfo.InvariantCulture); + + var now = _clock.UtcNow(); + var month = new DateTimeOffset(now.Year, now.Month, 1, 0, 0, 0, TimeSpan.Zero); + if (day > now.Day) + month = month.AddMonths(-1); + + return month.AddDays(day - 1).AddHours(hour).AddMinutes(minute); + } + + TimeSpan GetPollInterval() + { + if (_lastSendTime.HasValue) + { + var timeSinceLastSend = _clock.UtcNow() - _lastSendTime.Value; + if (timeSinceLastSend < TimeSpan.FromMinutes(1)) + { + return TimeSpan.FromSeconds(20); + } + } + + return TimeSpan.FromSeconds(_random.Next(45, 76)); + } + + string SerializeCpdlcMessage(UplinkMessage uplinkMessage) + { + var responseType = uplinkMessage.ResponseType switch + { + CpdlcUplinkResponseType.NoResponse => "NE", + CpdlcUplinkResponseType.WilcoUnable => "WU", + CpdlcUplinkResponseType.AffirmativeNegative => "AN", + CpdlcUplinkResponseType.Roger => "R", + _ => throw new ArgumentException($"Unexpected CpdlcResponseType: {uplinkMessage.ResponseType}") + }; + + var replyToId = uplinkMessage.MessageReference is not null + ? uplinkMessage.MessageReference.ToString() + : string.Empty; + + var content = GetTranslatedContent(uplinkMessage); + + return $"/data2/{uplinkMessage.MessageId}/{replyToId}/{responseType}/{content}"; + } + + string GetTranslatedContent(UplinkMessage uplinkMessage) + { + var translatedContent = uplinkMessage.Content; + foreach (var uplinkMessageTranslation in _uplinkMessageTranslations) + { + translatedContent = translatedContent.Replace(uplinkMessageTranslation.Key, uplinkMessageTranslation.Value); + } + + return translatedContent; + } + + public async ValueTask DisposeAsync() + { + if (_disposed) + return; + + await Disconnect(CancellationToken.None); + + if (_pollTask is not null) + _pollTask.Dispose(); + + if (_pollCancellationTokenSource is not null) + _pollCancellationTokenSource.Dispose(); + + _httpClient.Dispose(); + + _disposed = true; + } +} diff --git a/source/CPDLCServer/Exceptions/MessageParseException.cs b/source/CPDLCServer/AcarsConnections/Hoppie/MessageParseException.cs similarity index 72% rename from source/CPDLCServer/Exceptions/MessageParseException.cs rename to source/CPDLCServer/AcarsConnections/Hoppie/MessageParseException.cs index c4f9953..a164c2a 100644 --- a/source/CPDLCServer/Exceptions/MessageParseException.cs +++ b/source/CPDLCServer/AcarsConnections/Hoppie/MessageParseException.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Exceptions; +namespace CPDLCServer.AcarsConnections.Hoppie; public class MessageParseException(string message, Exception? innerException = null) : Exception(message, innerException); \ No newline at end of file diff --git a/source/CPDLCServer/Clients/HoppiesConfiguration.cs b/source/CPDLCServer/AcarsConnections/HoppiesConfiguration.cs similarity index 83% rename from source/CPDLCServer/Clients/HoppiesConfiguration.cs rename to source/CPDLCServer/AcarsConnections/HoppiesConfiguration.cs index 1acccdc..de2e611 100644 --- a/source/CPDLCServer/Clients/HoppiesConfiguration.cs +++ b/source/CPDLCServer/AcarsConnections/HoppiesConfiguration.cs @@ -1,12 +1,12 @@ using System.Text.Json.Serialization; -namespace CPDLCServer.Clients; +namespace CPDLCServer.AcarsConnections; [JsonPolymorphic(TypeDiscriminatorPropertyName = "Type")] [JsonDerivedType(typeof(HoppiesConfiguration), "Hoppie")] public abstract class AcarsConfiguration { - public abstract string ClientId { get; } + public abstract string AcarsConnectionId { get; } // The reporting interval in minutes for the ADS-C contract that is requested when an aircraft logs on with CPDLC public int DefaultAdscReportingInterval { get; init; } = 10; @@ -17,7 +17,7 @@ public abstract class AcarsConfiguration public class HoppiesConfiguration : AcarsConfiguration { - public override string ClientId => $"Hoppies/{StationIdentifier}"; + public override string AcarsConnectionId => $"Hoppies/{StationIdentifier}"; public required Uri Url { get; init; } public required string AuthenticationCode { get; init; } diff --git a/source/CPDLCServer/Clients/IAcarsClient.cs b/source/CPDLCServer/AcarsConnections/IAcarsConnection.cs similarity index 79% rename from source/CPDLCServer/Clients/IAcarsClient.cs rename to source/CPDLCServer/AcarsConnections/IAcarsConnection.cs index 5cff89a..6d112b6 100644 --- a/source/CPDLCServer/Clients/IAcarsClient.cs +++ b/source/CPDLCServer/AcarsConnections/IAcarsConnection.cs @@ -1,10 +1,12 @@ using System.Threading.Channels; using CPDLCServer.Contracts; -using CPDLCServer.Model; +using CPDLCServer.AdscContracts; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; -namespace CPDLCServer.Clients; +namespace CPDLCServer.AcarsConnections; -public interface IAcarsClient : IAsyncDisposable +public interface IAcarsConnection : IAsyncDisposable { ChannelReader MessageReader { get; } ChannelReader AdscMessageReader { get; } diff --git a/source/CPDLCServer/Services/AcarsConnectivityCheckService.cs b/source/CPDLCServer/AcarsConnections/Stations/AcarsConnectivityCheckService.cs similarity index 66% rename from source/CPDLCServer/Services/AcarsConnectivityCheckService.cs rename to source/CPDLCServer/AcarsConnections/Stations/AcarsConnectivityCheckService.cs index bc4ecb5..c5e53ee 100644 --- a/source/CPDLCServer/Services/AcarsConnectivityCheckService.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/AcarsConnectivityCheckService.cs @@ -1,53 +1,31 @@ -using CPDLCServer.Clients; -using CPDLCServer.Exceptions; -using CPDLCServer.Messages; -using MediatR; +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; -namespace CPDLCServer.Services; +namespace CPDLCServer.AcarsConnections.Stations; public class AcarsConnectivityCheckService : IHostedService, IDisposable { - readonly TimeSpan _checkInterval; #if DEBUG readonly TimeSpan _errorInterval = TimeSpan.FromSeconds(5); #else readonly TimeSpan _errorInterval = TimeSpan.FromMinutes(5); #endif - readonly AcarsConfiguration[] _acarsConfigurations; - readonly IMediator _mediator; + readonly IAcarsConnectionManager _acarsConnectionManager; + readonly IUnitOfWorkMediator _mediator; readonly ILogger _logger; CancellationTokenSource? _cancellationTokenSource; Task? _task; - public AcarsConnectivityCheckService(IConfiguration configuration, IMediator mediator, ILogger logger) + public AcarsConnectivityCheckService( + IAcarsConnectionManager acarsConnectionManager, + IUnitOfWorkMediator mediator, + ILogger logger) { + _acarsConnectionManager = acarsConnectionManager; _mediator = mediator; _logger = logger.ForContext(); - - var checkIntervalMinutes = configuration.GetValue("ConnectivityCheckIntervalMinutes", 15); - _checkInterval = TimeSpan.FromMinutes(checkIntervalMinutes); - - var acarsConfigurationSection = configuration.GetSection("Acars"); - var configurationList = new List(); - - foreach (var section in acarsConfigurationSection.GetChildren()) - { - var type = section["Type"]; - var config = type switch - { - "Hoppie" => section.Get(), - _ => throw new NotSupportedException($"ACARS configuration type '{type}' is not supported") - }; - - if (config is not null) - { - configurationList.Add(config); - } - } - - _acarsConfigurations = configurationList.ToArray(); } public Task StartAsync(CancellationToken cancellationToken) @@ -85,17 +63,28 @@ async Task DoWork(CancellationToken stoppingToken) { _logger.Debug("Checking aircraft connectivity"); - foreach (var acarsConfiguration in _acarsConfigurations) + // The connections can start and stop while the server is running, so get them each time + var acarsConnectionIds = _acarsConnectionManager.GetAcarsConnectionIds(); + if (acarsConnectionIds.Length == 0) + { + _logger.Debug("No ACARS connections are running, retrying"); + await Task.Delay(_errorInterval, stoppingToken); + continue; + } + + foreach (var acarsConnectionId in acarsConnectionIds) { using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); await _mediator.Send( - new RefreshAcarsCallsignsRequest(acarsConfiguration.ClientId), + new RefreshAcarsCallsignsRequest(acarsConnectionId), timeoutCts.Token); } - await Task.Delay(_checkInterval, stoppingToken); + var settings = await _mediator.Send(new GetServerSettingsRequest(), stoppingToken); + var checkInterval = TimeSpan.FromMinutes(settings.ConnectivityCheckIntervalMinutes); + await Task.Delay(checkInterval, stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { @@ -103,7 +92,7 @@ await _mediator.Send( } catch (ConfigurationNotFoundException) { - _logger.Debug("ACARS client not yet available, retrying"); + _logger.Debug("ACARS connection not yet available, retrying"); await Task.Delay(_errorInterval, stoppingToken); } catch (Exception ex) diff --git a/source/CPDLCServer/Messages/AcarsStationsChangedNotification.cs b/source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotification.cs similarity index 67% rename from source/CPDLCServer/Messages/AcarsStationsChangedNotification.cs rename to source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotification.cs index 0b063a6..12d6645 100644 --- a/source/CPDLCServer/Messages/AcarsStationsChangedNotification.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotification.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AcarsConnections.Stations; public record AcarsStationsChangedNotification(string[] Callsigns) : INotification; diff --git a/source/CPDLCServer/Handlers/AcarsStationsChangedNotificationHandler.cs b/source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotificationHandler.cs similarity index 55% rename from source/CPDLCServer/Handlers/AcarsStationsChangedNotificationHandler.cs rename to source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotificationHandler.cs index 3298576..3199914 100644 --- a/source/CPDLCServer/Handlers/AcarsStationsChangedNotificationHandler.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/AcarsStationsChangedNotificationHandler.cs @@ -1,22 +1,25 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; +using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AcarsConnections.Stations; public class AcarsStationsChangedNotificationHandler( IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { - public async Task Handle(AcarsStationsChangedNotification notification, CancellationToken cancellationToken) + public Task Handle(AcarsStationsChangedNotification notification, CancellationToken cancellationToken) { logger.Information("Broadcasting ACARS connected callsigns update ({Count} callsigns)", notification.Callsigns.Length); - await hubContext.Clients.All.SendAsync( + unitOfWork.AfterCommit(ct => hubContext.Clients.All.SendAsync( "AcarsStationsUpdated", notification.Callsigns, - cancellationToken); + ct)); + + return Task.CompletedTask; } } diff --git a/source/CPDLCServer/Persistence/IAcarsStationRepository.cs b/source/CPDLCServer/AcarsConnections/Stations/IAcarsStationRepository.cs similarity index 79% rename from source/CPDLCServer/Persistence/IAcarsStationRepository.cs rename to source/CPDLCServer/AcarsConnections/Stations/IAcarsStationRepository.cs index 7c3e5f1..268ef0a 100644 --- a/source/CPDLCServer/Persistence/IAcarsStationRepository.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/IAcarsStationRepository.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Persistence; +namespace CPDLCServer.AcarsConnections.Stations; public interface IAcarsStationRepository { diff --git a/source/CPDLCServer/Persistence/InMemoryAcarsStationRepository.cs b/source/CPDLCServer/AcarsConnections/Stations/InMemoryAcarsStationRepository.cs similarity index 92% rename from source/CPDLCServer/Persistence/InMemoryAcarsStationRepository.cs rename to source/CPDLCServer/AcarsConnections/Stations/InMemoryAcarsStationRepository.cs index 5d05695..3a4b1a9 100644 --- a/source/CPDLCServer/Persistence/InMemoryAcarsStationRepository.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/InMemoryAcarsStationRepository.cs @@ -1,6 +1,6 @@ -using CPDLCServer.Extensions; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Persistence; +namespace CPDLCServer.AcarsConnections.Stations; public class InMemoryAcarsStationRepository : IAcarsStationRepository { diff --git a/source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequest.cs b/source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequest.cs new file mode 100644 index 0000000..50c088c --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.AcarsConnections.Stations; + +public record RefreshAcarsCallsignsRequest(string AcarsConnectionId) : IRequest; diff --git a/source/CPDLCServer/Handlers/RefreshAcarsCallsignsRequestHandler.cs b/source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandler.cs similarity index 76% rename from source/CPDLCServer/Handlers/RefreshAcarsCallsignsRequestHandler.cs rename to source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandler.cs index 0738375..74308c9 100644 --- a/source/CPDLCServer/Handlers/RefreshAcarsCallsignsRequestHandler.cs +++ b/source/CPDLCServer/AcarsConnections/Stations/RefreshAcarsCallsignsRequestHandler.cs @@ -1,13 +1,11 @@ -using CPDLCServer.Clients; +using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AcarsConnections.Stations; public class RefreshAcarsCallsignsRequestHandler( - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IAircraftRepository aircraftRepository, IAcarsStationRepository acarsConnectedCallsignsRepository, IMediator mediator, @@ -16,8 +14,8 @@ public class RefreshAcarsCallsignsRequestHandler( { public async Task Handle(RefreshAcarsCallsignsRequest request, CancellationToken cancellationToken) { - var client = await clientManager.GetAcarsClient(request.AcarsClientId, cancellationToken); - var activeConnections = await client.ListConnections(cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(request.AcarsConnectionId, cancellationToken); + var activeConnections = await acarsConnection.ListConnections(cancellationToken); // Update the repository and broadcast if changed var changed = await acarsConnectedCallsignsRepository.Update(activeConnections, cancellationToken); @@ -32,7 +30,7 @@ await mediator.Publish( // Update last seen for tracked connections var trackedConnections = await aircraftRepository.All(cancellationToken); var matchingConnections = trackedConnections - .Where(c => c.AcarsClientId == request.AcarsClientId) + .Where(c => c.AcarsConnectionId == request.AcarsConnectionId) .Where(c => activeConnections.Contains(c.Callsign)); var now = clock.UtcNow(); diff --git a/source/CPDLCServer/Model/AdscContract.cs b/source/CPDLCServer/AdscContracts/AdscContract.cs similarity index 97% rename from source/CPDLCServer/Model/AdscContract.cs rename to source/CPDLCServer/AdscContracts/AdscContract.cs index 401193e..53a84a8 100644 --- a/source/CPDLCServer/Model/AdscContract.cs +++ b/source/CPDLCServer/AdscContracts/AdscContract.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.AdscContracts; /// /// The ADS-C requests that an ATSU sent to an aircraft. @@ -11,7 +11,7 @@ namespace CPDLCServer.Model; /// public class AdscContract(string callsign, string stationId) { - // The ACARS clients poll for messages every 20 to 75 seconds. A shorter interval gives no more data. + // The ACARS connections poll for messages every 20 to 75 seconds. A shorter interval gives no more data. public static readonly TimeSpan MinimumReportingInterval = TimeSpan.FromSeconds(60); public string Callsign { get; } = callsign; diff --git a/source/CPDLCServer/Messages/AdscContractChangedNotification.cs b/source/CPDLCServer/AdscContracts/AdscContractChangedNotification.cs similarity index 64% rename from source/CPDLCServer/Messages/AdscContractChangedNotification.cs rename to source/CPDLCServer/AdscContracts/AdscContractChangedNotification.cs index bd3abdf..3f7efbe 100644 --- a/source/CPDLCServer/Messages/AdscContractChangedNotification.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractChangedNotification.cs @@ -1,6 +1,5 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record AdscContractChangedNotification(AdscContract Contract) : INotification; diff --git a/source/CPDLCServer/Handlers/AdscContractChangedNotificationHandler.cs b/source/CPDLCServer/AdscContracts/AdscContractChangedNotificationHandler.cs similarity index 77% rename from source/CPDLCServer/Handlers/AdscContractChangedNotificationHandler.cs rename to source/CPDLCServer/AdscContracts/AdscContractChangedNotificationHandler.cs index 0691adc..e0a2ae4 100644 --- a/source/CPDLCServer/Handlers/AdscContractChangedNotificationHandler.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractChangedNotificationHandler.cs @@ -1,15 +1,15 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class AdscContractChangedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -26,9 +26,10 @@ public async Task Handle(AdscContractChangedNotification notification, Cancellat return; } - await hubContext.Clients + var contractDto = AdscContractConverter.ToDto(contract); + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("AdscContractUpdated", AdscContractConverter.ToDto(contract), cancellationToken); + .SendAsync("AdscContractUpdated", contractDto, ct)); logger.Information( "Notified {ControllerCount} controller(s) about ADS-C contract change for {Callsign}", diff --git a/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs b/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs new file mode 100644 index 0000000..b9addff --- /dev/null +++ b/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.AdscContracts; + +public class AdscContractConfiguration : IEntityTypeConfiguration +{ + public const string IdProperty = "Id"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("AdscContracts"); + + // The domain model has no ID, so the key is a shadow property + builder.Property(IdProperty); + builder.HasKey(IdProperty); + + builder.Property(c => c.Callsign); + builder.Property(c => c.StationId); + builder.Property(c => c.ReportingInterval); + builder.Property(c => c.DefaultContractState); + builder.Property(c => c.SelectedReportingInterval); + builder.Property(c => c.SelectedContractState); + builder.Property(c => c.SelectedContractEnds); + builder.Property(c => c.DemandContractState); + builder.Property(c => c.LastActivity); + + builder.HasIndex(c => new { c.Callsign, c.StationId }); + } +} diff --git a/source/CPDLCServer/Model/AdscContractConverter.cs b/source/CPDLCServer/AdscContracts/AdscContractConverter.cs similarity index 82% rename from source/CPDLCServer/Model/AdscContractConverter.cs rename to source/CPDLCServer/AdscContracts/AdscContractConverter.cs index 95562a1..9191757 100644 --- a/source/CPDLCServer/Model/AdscContractConverter.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractConverter.cs @@ -1,6 +1,7 @@ +using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Contracts; -namespace CPDLCServer.Model; +namespace CPDLCServer.AdscContracts; public static class AdscContractConverter { @@ -30,12 +31,12 @@ public static AdscReportDto ToDto(string callsign, string stationId, AdscReport ToDto(report.Source)); } - static Contracts.AdscReportSource ToDto(AdscReportSource source) + static Contracts.AdscReportSource ToDto(Reports.AdscReportSource source) { return source switch { - AdscReportSource.Hoppie => Contracts.AdscReportSource.Hoppie, - AdscReportSource.VATSIM => Contracts.AdscReportSource.VATSIM, + Reports.AdscReportSource.Hoppie => Contracts.AdscReportSource.Hoppie, + Reports.AdscReportSource.VATSIM => Contracts.AdscReportSource.VATSIM, _ => throw new ArgumentException($"Unknown ADS-C report source: {source}") }; } diff --git a/source/CPDLCServer/Services/AdscContractExpiryService.cs b/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs similarity index 76% rename from source/CPDLCServer/Services/AdscContractExpiryService.cs rename to source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs index d03f0e9..4a6299f 100644 --- a/source/CPDLCServer/Services/AdscContractExpiryService.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs @@ -1,25 +1,22 @@ -using CPDLCServer.Messages; -using MediatR; +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; -namespace CPDLCServer.Services; +namespace CPDLCServer.AdscContracts; public class AdscContractExpiryService : IHostedService, IDisposable { readonly TimeSpan _checkInterval = TimeSpan.FromMinutes(1); - readonly TimeSpan _contractTimeout; - readonly IMediator _mediator; + readonly IUnitOfWorkMediator _mediator; readonly ILogger _logger; CancellationTokenSource? _cancellationTokenSource; Task? _task; - public AdscContractExpiryService(IConfiguration configuration, IMediator mediator, ILogger logger) + public AdscContractExpiryService(IUnitOfWorkMediator mediator, ILogger logger) { _mediator = mediator; _logger = logger.ForContext(); - - _contractTimeout = configuration.GetValue("AdscContractTimeout", TimeSpan.FromMinutes(120)); } public Task StartAsync(CancellationToken cancellationToken) @@ -55,12 +52,17 @@ async Task DoWork(CancellationToken stoppingToken) { try { - _logger.Debug("Checking for ended ADS-C contracts"); + _logger.Debug("Checking for ended ADS-C contracts and expired ADS-C data"); using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); - await _mediator.Send(new EndExpiredAdscContractsRequest(_contractTimeout), timeoutCts.Token); + var settings = await _mediator.Send(new GetServerSettingsRequest(), timeoutCts.Token); + var contractTimeout = TimeSpan.FromMinutes(settings.AdscContractTimeoutMinutes); + await _mediator.Send(new EndExpiredAdscContractsRequest(contractTimeout), timeoutCts.Token); + + var adscReportRetention = TimeSpan.FromHours(settings.AdscReportRetentionHours); + await _mediator.Send(new PurgeExpiredAdscDataRequest(adscReportRetention), timeoutCts.Token); await Task.Delay(_checkInterval, stoppingToken); } @@ -70,7 +72,7 @@ async Task DoWork(CancellationToken stoppingToken) } catch (Exception ex) { - _logger.Error(ex, "Error checking for ended ADS-C contracts"); + _logger.Error(ex, "Error checking for ended ADS-C contracts and expired ADS-C data"); await Task.Delay(_checkInterval, stoppingToken); } } diff --git a/source/CPDLCServer/Messages/AdscContractRemovedNotification.cs b/source/CPDLCServer/AdscContracts/AdscContractRemovedNotification.cs similarity index 75% rename from source/CPDLCServer/Messages/AdscContractRemovedNotification.cs rename to source/CPDLCServer/AdscContracts/AdscContractRemovedNotification.cs index 5332347..5625da2 100644 --- a/source/CPDLCServer/Messages/AdscContractRemovedNotification.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractRemovedNotification.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record AdscContractRemovedNotification(string Callsign, string StationId) : INotification; diff --git a/source/CPDLCServer/Handlers/AdscContractRemovedNotificationHandler.cs b/source/CPDLCServer/AdscContracts/AdscContractRemovedNotificationHandler.cs similarity index 83% rename from source/CPDLCServer/Handlers/AdscContractRemovedNotificationHandler.cs rename to source/CPDLCServer/AdscContracts/AdscContractRemovedNotificationHandler.cs index e03a5f9..57d63a2 100644 --- a/source/CPDLCServer/Handlers/AdscContractRemovedNotificationHandler.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractRemovedNotificationHandler.cs @@ -1,14 +1,15 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; +using CPDLCServer.Controllers; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class AdscContractRemovedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -23,9 +24,9 @@ public async Task Handle(AdscContractRemovedNotification notification, Cancellat return; } - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("AdscContractRemoved", notification.Callsign, notification.StationId, cancellationToken); + .SendAsync("AdscContractRemoved", notification.Callsign, notification.StationId, ct)); logger.Information( "Notified {ControllerCount} controller(s) about removed ADS-C contract for {Callsign}", diff --git a/source/CPDLCServer/AdscContracts/AdscContractRepository.cs b/source/CPDLCServer/AdscContracts/AdscContractRepository.cs new file mode 100644 index 0000000..2c5c082 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/AdscContractRepository.cs @@ -0,0 +1,46 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.AdscContracts; + +// The changes are saved when the unit of work is committed. +// Queries load the rows into the context, then read the local entities, so that the results include entities that are +// added in the unit of work and exclude entities that are removed in it. +public class AdscContractRepository(CpdlcDbContext dbContext) : IAdscContractRepository +{ + public async Task Add(AdscContractKey contractKey, AdscContract contract, CancellationToken cancellationToken) + { + // A new contract replaces the contract with the same key + var existing = await Find(contractKey, cancellationToken); + if (existing is not null) + dbContext.AdscContracts.Remove(existing); + + dbContext.AdscContracts.Add(contract); + } + + public async Task Find(AdscContractKey contractKey, CancellationToken cancellationToken) + { + await dbContext.AdscContracts + .Where(c => c.Callsign == contractKey.Callsign && c.StationId == contractKey.StationId) + .LoadAsync(cancellationToken); + + return dbContext.AdscContracts.Local + .FirstOrDefault(c => c.Callsign == contractKey.Callsign && c.StationId == contractKey.StationId); + } + + public async Task All(CancellationToken cancellationToken) + { + await dbContext.AdscContracts.LoadAsync(cancellationToken); + return dbContext.AdscContracts.Local.ToArray(); + } + + public async Task Remove(AdscContractKey contractKey, CancellationToken cancellationToken) + { + var contract = await Find(contractKey, cancellationToken); + if (contract is null) + return false; + + dbContext.AdscContracts.Remove(contract); + return true; + } +} diff --git a/source/CPDLCServer/Model/AdscContractState.cs b/source/CPDLCServer/AdscContracts/AdscContractState.cs similarity index 81% rename from source/CPDLCServer/Model/AdscContractState.cs rename to source/CPDLCServer/AdscContracts/AdscContractState.cs index 38abd2c..58fc6d1 100644 --- a/source/CPDLCServer/Model/AdscContractState.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractState.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.AdscContracts; // The aircraft does not acknowledge a request. The first report after the request accepts it. public enum AdscContractState diff --git a/source/CPDLCServer/AdscContracts/AdscContractsServiceCollectionExtensions.cs b/source/CPDLCServer/AdscContracts/AdscContractsServiceCollectionExtensions.cs new file mode 100644 index 0000000..a0f9c53 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/AdscContractsServiceCollectionExtensions.cs @@ -0,0 +1,18 @@ +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.AdscContracts.Reports; + +namespace CPDLCServer.AdscContracts; + +public static class AdscContractsServiceCollectionExtensions +{ + public static IServiceCollection AddAdscContracts(this IServiceCollection services) + { + services.AddScoped(); + services.AddHostedService(); + + services.AddScoped(); + services.AddSingleton(); + + return services; + } +} diff --git a/source/CPDLCServer/Messages/AdscMessageReceivedNotification.cs b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotification.cs similarity index 62% rename from source/CPDLCServer/Messages/AdscMessageReceivedNotification.cs rename to source/CPDLCServer/AdscContracts/AdscMessageReceivedNotification.cs index 42243cd..3311b12 100644 --- a/source/CPDLCServer/Messages/AdscMessageReceivedNotification.cs +++ b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotification.cs @@ -1,10 +1,9 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record AdscMessageReceivedNotification( - string AcarsClientId, + string AcarsConnectionId, string StationId, ReceivedAdscMessage Message) : INotification; diff --git a/source/CPDLCServer/Handlers/AdscMessageReceivedNotificationHandler.cs b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs similarity index 96% rename from source/CPDLCServer/Handlers/AdscMessageReceivedNotificationHandler.cs rename to source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs index d315bbb..03991b8 100644 --- a/source/CPDLCServer/Handlers/AdscMessageReceivedNotificationHandler.cs +++ b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs @@ -1,9 +1,7 @@ -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts.Reports; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class AdscMessageReceivedNotificationHandler( IAdscContractRepository adscContractRepository, diff --git a/source/CPDLCServer/Messages/CancelAdscContractCommand.cs b/source/CPDLCServer/AdscContracts/CancelAdscContractCommand.cs similarity index 75% rename from source/CPDLCServer/Messages/CancelAdscContractCommand.cs rename to source/CPDLCServer/AdscContracts/CancelAdscContractCommand.cs index c066148..3de2af3 100644 --- a/source/CPDLCServer/Messages/CancelAdscContractCommand.cs +++ b/source/CPDLCServer/AdscContracts/CancelAdscContractCommand.cs @@ -1,6 +1,6 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record CancelAdscContractCommand( string StationId, diff --git a/source/CPDLCServer/Handlers/CancelAdscContractCommandHandler.cs b/source/CPDLCServer/AdscContracts/CancelAdscContractCommandHandler.cs similarity index 75% rename from source/CPDLCServer/Handlers/CancelAdscContractCommandHandler.cs rename to source/CPDLCServer/AdscContracts/CancelAdscContractCommandHandler.cs index 0d10970..2d6c74f 100644 --- a/source/CPDLCServer/Handlers/CancelAdscContractCommandHandler.cs +++ b/source/CPDLCServer/AdscContracts/CancelAdscContractCommandHandler.cs @@ -1,14 +1,14 @@ -using CPDLCServer.Clients; -using CPDLCServer.Messages; +using CPDLCServer.AcarsConnections; using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class CancelAdscContractCommandHandler( - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, + IUnitOfWork unitOfWork, ILogger logger) : IRequestHandler { @@ -30,8 +30,8 @@ public async Task Handle(CancelAdscContractCommand request, CancellationToken ca request.Callsign, request.StationId); - var client = await clientManager.GetAcarsClientForStation(request.StationId, cancellationToken); - await client.CancelAdscContract(request.Callsign, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnectionForStation(request.StationId, cancellationToken); + unitOfWork.AfterCommit(ct => acarsConnection.CancelAdscContract(request.Callsign, ct)); await adscContractRepository.Remove(contractKey, cancellationToken); diff --git a/source/CPDLCServer/Handlers/CancelAdscContractOnConnectionEndedHandler.cs b/source/CPDLCServer/AdscContracts/CancelAdscContractOnConnectionEndedHandler.cs similarity index 78% rename from source/CPDLCServer/Handlers/CancelAdscContractOnConnectionEndedHandler.cs rename to source/CPDLCServer/AdscContracts/CancelAdscContractOnConnectionEndedHandler.cs index b05be1c..af4a5cb 100644 --- a/source/CPDLCServer/Handlers/CancelAdscContractOnConnectionEndedHandler.cs +++ b/source/CPDLCServer/AdscContracts/CancelAdscContractOnConnectionEndedHandler.cs @@ -1,12 +1,11 @@ -using CPDLCServer.Clients; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Connections; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class CancelAdscContractOnConnectionEndedHandler( - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, ILogger logger) @@ -19,8 +18,8 @@ public async Task Handle(AircraftConnectionTerminated notification, Cancellation public async Task Handle(AircraftConnectionLost notification, CancellationToken cancellationToken) { - var client = await clientManager.GetAcarsClient(notification.AcarsClientId, cancellationToken); - await CancelContract(notification.Callsign, client.StationId, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(notification.AcarsConnectionId, cancellationToken); + await CancelContract(notification.Callsign, acarsConnection.StationId, cancellationToken); } async Task CancelContract(string callsign, string stationId, CancellationToken cancellationToken) diff --git a/source/CPDLCServer/Messages/EndExpiredAdscContractsRequest.cs b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequest.cs similarity index 72% rename from source/CPDLCServer/Messages/EndExpiredAdscContractsRequest.cs rename to source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequest.cs index 4f4eada..1d6e199 100644 --- a/source/CPDLCServer/Messages/EndExpiredAdscContractsRequest.cs +++ b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequest.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record EndExpiredAdscContractsRequest(TimeSpan ContractTimeout) : IRequest; diff --git a/source/CPDLCServer/Handlers/EndExpiredAdscContractsRequestHandler.cs b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequestHandler.cs similarity index 72% rename from source/CPDLCServer/Handlers/EndExpiredAdscContractsRequestHandler.cs rename to source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequestHandler.cs index dc8f76c..3c75324 100644 --- a/source/CPDLCServer/Handlers/EndExpiredAdscContractsRequestHandler.cs +++ b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequestHandler.cs @@ -1,17 +1,17 @@ -using CPDLCServer.Clients; +using CPDLCServer.AcarsConnections; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class EndExpiredAdscContractsRequestHandler( - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IClock clock, + ServerStartTime serverStartTime, IMediator mediator, + IUnitOfWork unitOfWork, ILogger logger) : IRequestHandler { @@ -20,9 +20,12 @@ public async Task Handle(EndExpiredAdscContractsRequest request, CancellationTok var contracts = await adscContractRepository.All(cancellationToken); var now = clock.UtcNow(); + // The last activity times do not change while the server is stopped + var canApplyContractTimeout = now - serverStartTime.Started > request.ContractTimeout; + foreach (var contract in contracts) { - if (now - contract.LastActivity > request.ContractTimeout) + if (canApplyContractTimeout && now - contract.LastActivity > request.ContractTimeout) { // A failure for one aircraft must not stop the other aircraft try @@ -77,19 +80,22 @@ async Task CancelInactiveContract(AdscContract contract, CancellationToken cance // The aircraft is possibly not on the ACARS network any more. // Remove the contract, even if the ACARS network cannot cancel it. - try - { - var client = await clientManager.GetAcarsClientForStation(contract.StationId, cancellationToken); - await client.CancelAdscContract(contract.Callsign, cancellationToken); - } - catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + unitOfWork.AfterCommit(async ct => { - logger.Warning( - ex, - "Failed to cancel ADS-C contract with {Callsign} for {StationId} on the ACARS network", - contract.Callsign, - contract.StationId); - } + try + { + var acarsConnection = await acarsConnectionManager.GetAcarsConnectionForStation(contract.StationId, ct); + await acarsConnection.CancelAdscContract(contract.Callsign, ct); + } + catch (Exception ex) when (!ct.IsCancellationRequested) + { + logger.Warning( + ex, + "Failed to cancel ADS-C contract with {Callsign} for {StationId} on the ACARS network", + contract.Callsign, + contract.StationId); + } + }); await adscContractRepository.Remove(new AdscContractKey(contract.Callsign, contract.StationId), cancellationToken); diff --git a/source/CPDLCServer/Messages/GetAdscContractsRequest.cs b/source/CPDLCServer/AdscContracts/GetAdscContractsRequest.cs similarity index 83% rename from source/CPDLCServer/Messages/GetAdscContractsRequest.cs rename to source/CPDLCServer/AdscContracts/GetAdscContractsRequest.cs index f8d90f7..dc33dcf 100644 --- a/source/CPDLCServer/Messages/GetAdscContractsRequest.cs +++ b/source/CPDLCServer/AdscContracts/GetAdscContractsRequest.cs @@ -1,7 +1,7 @@ using CPDLCServer.Contracts; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record GetAdscContractsRequest : IRequest; diff --git a/source/CPDLCServer/Handlers/GetAdscContractsRequestHandler.cs b/source/CPDLCServer/AdscContracts/GetAdscContractsRequestHandler.cs similarity index 83% rename from source/CPDLCServer/Handlers/GetAdscContractsRequestHandler.cs rename to source/CPDLCServer/AdscContracts/GetAdscContractsRequestHandler.cs index 454e9f6..f149ce7 100644 --- a/source/CPDLCServer/Handlers/GetAdscContractsRequestHandler.cs +++ b/source/CPDLCServer/AdscContracts/GetAdscContractsRequestHandler.cs @@ -1,9 +1,6 @@ -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class GetAdscContractsRequestHandler(IAdscContractRepository adscContractRepository) : IRequestHandler diff --git a/source/CPDLCServer/Persistence/IAdscContractRepository.cs b/source/CPDLCServer/AdscContracts/IAdscContractRepository.cs similarity index 88% rename from source/CPDLCServer/Persistence/IAdscContractRepository.cs rename to source/CPDLCServer/AdscContracts/IAdscContractRepository.cs index fddd90c..233537c 100644 --- a/source/CPDLCServer/Persistence/IAdscContractRepository.cs +++ b/source/CPDLCServer/AdscContracts/IAdscContractRepository.cs @@ -1,6 +1,4 @@ -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; +namespace CPDLCServer.AdscContracts; public interface IAdscContractRepository { diff --git a/source/CPDLCServer/Model/AdscMessageLogEntry.cs b/source/CPDLCServer/AdscContracts/MessageLog/AdscMessageLogEntry.cs similarity index 79% rename from source/CPDLCServer/Model/AdscMessageLogEntry.cs rename to source/CPDLCServer/AdscContracts/MessageLog/AdscMessageLogEntry.cs index 36568a4..7295163 100644 --- a/source/CPDLCServer/Model/AdscMessageLogEntry.cs +++ b/source/CPDLCServer/AdscContracts/MessageLog/AdscMessageLogEntry.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.AdscContracts.MessageLog; public enum AdscMessageDirection { @@ -9,7 +9,7 @@ public enum AdscMessageDirection // An ADS-C packet as it was sent to or received from the ACARS network public record AdscMessageLogEntry( DateTimeOffset Time, - string AcarsClientId, + string AcarsConnectionId, string StationId, string Callsign, AdscMessageDirection Direction, diff --git a/source/CPDLCServer/Persistence/IAdscMessageLogRepository.cs b/source/CPDLCServer/AdscContracts/MessageLog/IAdscMessageLogRepository.cs similarity index 83% rename from source/CPDLCServer/Persistence/IAdscMessageLogRepository.cs rename to source/CPDLCServer/AdscContracts/MessageLog/IAdscMessageLogRepository.cs index e7848d3..acc640c 100644 --- a/source/CPDLCServer/Persistence/IAdscMessageLogRepository.cs +++ b/source/CPDLCServer/AdscContracts/MessageLog/IAdscMessageLogRepository.cs @@ -1,6 +1,4 @@ -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; +namespace CPDLCServer.AdscContracts.MessageLog; public interface IAdscMessageLogRepository { diff --git a/source/CPDLCServer/Persistence/InMemoryAdscMessageLogRepository.cs b/source/CPDLCServer/AdscContracts/MessageLog/InMemoryAdscMessageLogRepository.cs similarity index 93% rename from source/CPDLCServer/Persistence/InMemoryAdscMessageLogRepository.cs rename to source/CPDLCServer/AdscContracts/MessageLog/InMemoryAdscMessageLogRepository.cs index dd749a2..51eadbd 100644 --- a/source/CPDLCServer/Persistence/InMemoryAdscMessageLogRepository.cs +++ b/source/CPDLCServer/AdscContracts/MessageLog/InMemoryAdscMessageLogRepository.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Persistence; +namespace CPDLCServer.AdscContracts.MessageLog; public class InMemoryAdscMessageLogRepository : IAdscMessageLogRepository { diff --git a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequest.cs b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequest.cs new file mode 100644 index 0000000..baad90c --- /dev/null +++ b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.AdscContracts; + +public record PurgeExpiredAdscDataRequest(TimeSpan AdscReportRetention) : IRequest; diff --git a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs new file mode 100644 index 0000000..342c55c --- /dev/null +++ b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs @@ -0,0 +1,23 @@ +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.AdscContracts; + +public class PurgeExpiredAdscDataRequestHandler( + IAdscMessageLogRepository adscMessageLogRepository, + IAdscReportRepository adscReportRepository, + IClock clock) + : IRequestHandler +{ + readonly TimeSpan _messageLogRetention = TimeSpan.FromHours(24); + + public async Task Handle(PurgeExpiredAdscDataRequest request, CancellationToken cancellationToken) + { + var now = clock.UtcNow(); + + await adscMessageLogRepository.RemoveOlderThan(now - _messageLogRetention, cancellationToken); + await adscReportRepository.RemoveOlderThan(now - request.AdscReportRetention, cancellationToken); + } +} diff --git a/source/CPDLCServer/Model/ReceivedAdscMessage.cs b/source/CPDLCServer/AdscContracts/ReceivedAdscMessage.cs similarity index 87% rename from source/CPDLCServer/Model/ReceivedAdscMessage.cs rename to source/CPDLCServer/AdscContracts/ReceivedAdscMessage.cs index fb90cc5..c20beff 100644 --- a/source/CPDLCServer/Model/ReceivedAdscMessage.cs +++ b/source/CPDLCServer/AdscContracts/ReceivedAdscMessage.cs @@ -1,4 +1,5 @@ -namespace CPDLCServer.Model; +using CPDLCServer.AdscContracts.Reports; +namespace CPDLCServer.AdscContracts; // Raw ADS-C data as parsed from an ACARS packet, before being assigned to a contract. public abstract record ReceivedAdscMessage(string Sender, DateTimeOffset Received); diff --git a/source/CPDLCServer/Model/AdscReport.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReport.cs similarity index 80% rename from source/CPDLCServer/Model/AdscReport.cs rename to source/CPDLCServer/AdscContracts/Reports/AdscReport.cs index 1f1d216..e559aaa 100644 --- a/source/CPDLCServer/Model/AdscReport.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReport.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.AdscContracts.Reports; // ADS-C basic group. Altitude is in feet. public record AdscReport( diff --git a/source/CPDLCServer/Messages/AdscReportReceivedNotification.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotification.cs similarity index 75% rename from source/CPDLCServer/Messages/AdscReportReceivedNotification.cs rename to source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotification.cs index 6770cdc..a7ffc8f 100644 --- a/source/CPDLCServer/Messages/AdscReportReceivedNotification.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotification.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts.Reports; public record AdscReportReceivedNotification( string Callsign, diff --git a/source/CPDLCServer/Handlers/AdscReportReceivedNotificationHandler.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotificationHandler.cs similarity index 86% rename from source/CPDLCServer/Handlers/AdscReportReceivedNotificationHandler.cs rename to source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotificationHandler.cs index e1a41f3..32e0a31 100644 --- a/source/CPDLCServer/Handlers/AdscReportReceivedNotificationHandler.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportReceivedNotificationHandler.cs @@ -1,16 +1,16 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts.Reports; public class AdscReportReceivedNotificationHandler( IAdscReportRepository adscReportRepository, IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -36,9 +36,9 @@ await adscReportRepository.Add( notification.Report, notification.Received); - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("AdscReportReceived", reportDto, cancellationToken); + .SendAsync("AdscReportReceived", reportDto, ct)); logger.Information( "Notified {ControllerCount} controller(s) about ADS-C report from {Callsign}", diff --git a/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs new file mode 100644 index 0000000..44613b2 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs @@ -0,0 +1,70 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.AdscContracts.Reports; + +// The changes are saved when the unit of work is committed. +// Queries load the rows into the context, then read the local entities, so that the results include entities that are +// added in the unit of work and exclude entities that are removed in it. +public class AdscReportRepository(CpdlcDbContext dbContext) : IAdscReportRepository +{ + public async Task Add(AircraftAdscReport report, CancellationToken cancellationToken) + { + var latest = await FindLatest(report.Callsign, cancellationToken); + + var isLatest = latest is null || ReplacesLatest(report, latest); + if (isLatest && latest is not null) + SetIsLatest(latest, false); + + dbContext.AdscReports.Add(report); + SetIsLatest(report, isLatest); + } + + public async Task FindLatest(string callsign, CancellationToken cancellationToken) + { + await dbContext.AdscReports + .Where(r => r.Callsign == callsign && EF.Property(r, AircraftAdscReportConfiguration.IsLatestProperty)) + .LoadAsync(cancellationToken); + + return dbContext.AdscReports.Local.FirstOrDefault(r => r.Callsign == callsign && IsLatest(r)); + } + + public async Task AllLatest(CancellationToken cancellationToken) + { + await dbContext.AdscReports + .Where(r => EF.Property(r, AircraftAdscReportConfiguration.IsLatestProperty)) + .LoadAsync(cancellationToken); + + return dbContext.AdscReports.Local.Where(IsLatest).ToArray(); + } + + public async Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken) + { + await dbContext.AdscReports + .Where(r => r.Received < cutoff) + .LoadAsync(cancellationToken); + + var oldReports = dbContext.AdscReports.Local.Where(r => r.Received < cutoff).ToArray(); + dbContext.AdscReports.RemoveRange(oldReports); + } + + static bool ReplacesLatest(AircraftAdscReport report, AircraftAdscReport latest) + { + // A report from Hoppie always replaces a report from VATSIM + if (report.Report.Source == AdscReportSource.Hoppie && latest.Report.Source == AdscReportSource.VATSIM) + return true; + + // An aircraft can report to more than one ATSU, so reports can arrive out of order + return report.Report.Timestamp >= latest.Report.Timestamp; + } + + bool IsLatest(AircraftAdscReport report) + { + return dbContext.Entry(report).Property(AircraftAdscReportConfiguration.IsLatestProperty).CurrentValue; + } + + void SetIsLatest(AircraftAdscReport report, bool isLatest) + { + dbContext.Entry(report).Property(AircraftAdscReportConfiguration.IsLatestProperty).CurrentValue = isLatest; + } +} diff --git a/source/CPDLCServer/Model/AdscReportSource.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportSource.cs similarity index 83% rename from source/CPDLCServer/Model/AdscReportSource.cs rename to source/CPDLCServer/AdscContracts/Reports/AdscReportSource.cs index 5172ea6..e415cfa 100644 --- a/source/CPDLCServer/Model/AdscReportSource.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportSource.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.AdscContracts.Reports; // The system that supplied the ADS-C report public enum AdscReportSource diff --git a/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReport.cs b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReport.cs new file mode 100644 index 0000000..6700223 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReport.cs @@ -0,0 +1,14 @@ +namespace CPDLCServer.AdscContracts.Reports; + +// An ADS-C report from an aircraft, and the ATSU that received it +public record AircraftAdscReport( + string Callsign, + string StationId, + AdscReport Report, + DateTimeOffset Received) +{ + // EF Core uses this constructor, because it cannot give the Report to the primary constructor + private AircraftAdscReport() : this(null!, null!, null!, default) + { + } +} diff --git a/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs new file mode 100644 index 0000000..016b11a --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.AdscContracts.Reports; + +public class AircraftAdscReportConfiguration : IEntityTypeConfiguration +{ + public const string IdProperty = "Id"; + + // True for the report that is the latest report of the aircraft + public const string IsLatestProperty = "IsLatest"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("AdscReports"); + + // The domain model has no ID, so the key is a shadow property + builder.Property(IdProperty); + builder.HasKey(IdProperty); + + builder.Property(IsLatestProperty); + + builder.Property(r => r.Callsign); + builder.Property(r => r.StationId); + builder.Property(r => r.Received); + + builder.ComplexProperty(r => r.Report, report => + { + report.Property(r => r.Timestamp).HasColumnName("Timestamp"); + report.Property(r => r.Latitude).HasColumnName("Latitude"); + report.Property(r => r.Longitude).HasColumnName("Longitude"); + report.Property(r => r.Altitude).HasColumnName("Altitude"); + report.Property(r => r.Source).HasColumnName("Source"); + }); + + builder.HasIndex(r => r.Callsign); + builder.HasIndex(r => r.Received); + } +} diff --git a/source/CPDLCServer/Messages/GetAdscReportsRequest.cs b/source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequest.cs similarity index 79% rename from source/CPDLCServer/Messages/GetAdscReportsRequest.cs rename to source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequest.cs index 29a3dfb..cc886bc 100644 --- a/source/CPDLCServer/Messages/GetAdscReportsRequest.cs +++ b/source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequest.cs @@ -1,7 +1,7 @@ using CPDLCServer.Contracts; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts.Reports; public record GetAdscReportsRequest : IRequest; diff --git a/source/CPDLCServer/Handlers/GetAdscReportsRequestHandler.cs b/source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequestHandler.cs similarity index 73% rename from source/CPDLCServer/Handlers/GetAdscReportsRequestHandler.cs rename to source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequestHandler.cs index 78dc784..0b618e7 100644 --- a/source/CPDLCServer/Handlers/GetAdscReportsRequestHandler.cs +++ b/source/CPDLCServer/AdscContracts/Reports/GetAdscReportsRequestHandler.cs @@ -1,9 +1,6 @@ -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts.Reports; public class GetAdscReportsRequestHandler(IAdscReportRepository adscReportRepository) : IRequestHandler @@ -12,7 +9,7 @@ public async Task Handle( GetAdscReportsRequest request, CancellationToken cancellationToken) { - var reports = await adscReportRepository.All(cancellationToken); + var reports = await adscReportRepository.AllLatest(cancellationToken); var reportDtos = reports .Select(r => AdscContractConverter.ToDto(r.Callsign, r.StationId, r.Report, r.Received)) .ToArray(); diff --git a/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs b/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs new file mode 100644 index 0000000..58989a3 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs @@ -0,0 +1,14 @@ +namespace CPDLCServer.AdscContracts.Reports; + +// Holds the history of ADS-C reports, and the latest report for each aircraft +public interface IAdscReportRepository +{ + // Adds the report to the history. + // The report becomes the latest report, unless the repository has a newer report for the same aircraft. + // A report from Hoppie always replaces a report from VATSIM as the latest report. + Task Add(AircraftAdscReport report, CancellationToken cancellationToken); + Task FindLatest(string callsign, CancellationToken cancellationToken); + Task AllLatest(CancellationToken cancellationToken); + + Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken); +} diff --git a/source/CPDLCServer/Messages/RequestAdscDemandReportCommand.cs b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommand.cs similarity index 73% rename from source/CPDLCServer/Messages/RequestAdscDemandReportCommand.cs rename to source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommand.cs index 47f0f4e..089085c 100644 --- a/source/CPDLCServer/Messages/RequestAdscDemandReportCommand.cs +++ b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommand.cs @@ -1,6 +1,6 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts.Reports; public record RequestAdscDemandReportCommand( string StationId, diff --git a/source/CPDLCServer/Handlers/RequestAdscDemandReportCommandHandler.cs b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs similarity index 77% rename from source/CPDLCServer/Handlers/RequestAdscDemandReportCommandHandler.cs rename to source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs index 9cb51c8..85642c4 100644 --- a/source/CPDLCServer/Handlers/RequestAdscDemandReportCommandHandler.cs +++ b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs @@ -1,17 +1,16 @@ -using CPDLCServer.Clients; +using CPDLCServer.AcarsConnections; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts.Reports; public class RequestAdscDemandReportCommandHandler( - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, IClock clock, + IUnitOfWork unitOfWork, ILogger logger) : IRequestHandler { @@ -22,8 +21,8 @@ public async Task Handle(RequestAdscDemandReportCommand request, CancellationTok request.Callsign, request.StationId); - var client = await clientManager.GetAcarsClientForStation(request.StationId, cancellationToken); - await client.RequestAdscDemandReport(request.Callsign, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnectionForStation(request.StationId, cancellationToken); + unitOfWork.AfterCommit(ct => acarsConnection.RequestAdscDemandReport(request.Callsign, ct)); // A demand report does not change the periodic contract. // Without a contract, the report would be ignored, so add a contract with only the demand request. diff --git a/source/CPDLCServer/Handlers/RequestAdscContractOnConnectionEstablishedHandler.cs b/source/CPDLCServer/AdscContracts/RequestAdscContractOnConnectionEstablishedHandler.cs similarity index 94% rename from source/CPDLCServer/Handlers/RequestAdscContractOnConnectionEstablishedHandler.cs rename to source/CPDLCServer/AdscContracts/RequestAdscContractOnConnectionEstablishedHandler.cs index 7239dd9..d01fa9f 100644 --- a/source/CPDLCServer/Handlers/RequestAdscContractOnConnectionEstablishedHandler.cs +++ b/source/CPDLCServer/AdscContracts/RequestAdscContractOnConnectionEstablishedHandler.cs @@ -1,8 +1,7 @@ -using CPDLCServer.Messages; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Connections; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class RequestAdscContractOnConnectionEstablishedHandler( IAdscContractRepository adscContractRepository, diff --git a/source/CPDLCServer/Messages/RequestDefaultAdscContractCommand.cs b/source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommand.cs similarity index 77% rename from source/CPDLCServer/Messages/RequestDefaultAdscContractCommand.cs rename to source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommand.cs index e6fe1ff..2ee14cf 100644 --- a/source/CPDLCServer/Messages/RequestDefaultAdscContractCommand.cs +++ b/source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommand.cs @@ -1,6 +1,6 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record RequestDefaultAdscContractCommand( string StationId, diff --git a/source/CPDLCServer/Handlers/RequestDefaultAdscContractCommandHandler.cs b/source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommandHandler.cs similarity index 72% rename from source/CPDLCServer/Handlers/RequestDefaultAdscContractCommandHandler.cs rename to source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommandHandler.cs index ecc4f8f..9f60f7e 100644 --- a/source/CPDLCServer/Handlers/RequestDefaultAdscContractCommandHandler.cs +++ b/source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommandHandler.cs @@ -1,23 +1,22 @@ -using CPDLCServer.Clients; +using CPDLCServer.AcarsConnections; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class RequestDefaultAdscContractCommandHandler( - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, IClock clock, + IUnitOfWork unitOfWork, ILogger logger) : IRequestHandler { public async Task Handle(RequestDefaultAdscContractCommand request, CancellationToken cancellationToken) { - var configuration = await clientManager.GetConfigurationForStation(request.StationId, cancellationToken); + var configuration = await acarsConnectionManager.GetConfigurationForStation(request.StationId, cancellationToken); var reportingInterval = TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval); logger.Information( @@ -26,8 +25,8 @@ public async Task Handle(RequestDefaultAdscContractCommand request, Cancellation request.StationId, reportingInterval); - var client = await clientManager.GetAcarsClientForStation(request.StationId, cancellationToken); - await client.RequestPeriodicAdscContract(request.Callsign, reportingInterval, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnectionForStation(request.StationId, cancellationToken); + unitOfWork.AfterCommit(ct => acarsConnection.RequestPeriodicAdscContract(request.Callsign, reportingInterval, ct)); var contractKey = new AdscContractKey(request.Callsign, request.StationId); var contract = await adscContractRepository.Find(contractKey, cancellationToken); diff --git a/source/CPDLCServer/Messages/RequestSelectedAdscContractCommand.cs b/source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommand.cs similarity index 81% rename from source/CPDLCServer/Messages/RequestSelectedAdscContractCommand.cs rename to source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommand.cs index 02f6a47..0bce216 100644 --- a/source/CPDLCServer/Messages/RequestSelectedAdscContractCommand.cs +++ b/source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommand.cs @@ -1,6 +1,6 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.AdscContracts; public record RequestSelectedAdscContractCommand( string StationId, diff --git a/source/CPDLCServer/Handlers/RequestSelectedAdscContractCommandHandler.cs b/source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommandHandler.cs similarity index 77% rename from source/CPDLCServer/Handlers/RequestSelectedAdscContractCommandHandler.cs rename to source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommandHandler.cs index 94ce6c4..48eb81e 100644 --- a/source/CPDLCServer/Handlers/RequestSelectedAdscContractCommandHandler.cs +++ b/source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommandHandler.cs @@ -1,17 +1,16 @@ -using CPDLCServer.Clients; +using CPDLCServer.AcarsConnections; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.AdscContracts; public class RequestSelectedAdscContractCommandHandler( - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, IClock clock, + IUnitOfWork unitOfWork, ILogger logger) : IRequestHandler { @@ -29,11 +28,11 @@ public async Task Handle(RequestSelectedAdscContractCommand request, Cancellatio request.StationId, request.ReportingInterval); - var client = await clientManager.GetAcarsClientForStation(request.StationId, cancellationToken); - await client.RequestPeriodicAdscContract(request.Callsign, request.ReportingInterval, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnectionForStation(request.StationId, cancellationToken); + unitOfWork.AfterCommit(ct => acarsConnection.RequestPeriodicAdscContract(request.Callsign, request.ReportingInterval, ct)); // The selected contract ends at a fixed time after the request is sent - var configuration = await clientManager.GetConfigurationForStation(request.StationId, cancellationToken); + var configuration = await acarsConnectionManager.GetConfigurationForStation(request.StationId, cancellationToken); var ends = clock.UtcNow() + TimeSpan.FromMinutes(configuration.SelectedAdscContractDuration); var contractKey = new AdscContractKey(request.Callsign, request.StationId); diff --git a/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs b/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs new file mode 100644 index 0000000..7bea987 --- /dev/null +++ b/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs @@ -0,0 +1,39 @@ +using CPDLCServer.Auth.Login; +using CPDLCServer.Auth.Users; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Identity; + +namespace CPDLCServer.Auth; + +public static class AuthServiceCollectionExtensions +{ + public static IServiceCollection AddAuth(this IServiceCollection services) + { + services.AddScoped(); + services.AddSingleton, PasswordHasher>(); + + // Keep the keys of the login cookies only in memory, so that no key is on the disk. + // After a restart, the user must log in again. + services.AddSingleton(); + + services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) + .AddCookie(options => + { + options.LoginPath = "/login"; + options.LogoutPath = "/logout"; + options.AccessDeniedPath = "/login"; + options.Cookie.Name = "cpdlc-admin"; + options.Cookie.HttpOnly = true; + options.Cookie.SameSite = SameSiteMode.Strict; + options.ExpireTimeSpan = TimeSpan.FromHours(8); + options.SlidingExpiration = true; + }); + services.AddAuthorization(); + + services.AddSingleton(); + services.AddRateLimiter(PasswordRateLimit.Configure); + + return services; + } +} diff --git a/source/CPDLCServer/Auth/Login/AdminAuthentication.cs b/source/CPDLCServer/Auth/Login/AdminAuthentication.cs new file mode 100644 index 0000000..6738d37 --- /dev/null +++ b/source/CPDLCServer/Auth/Login/AdminAuthentication.cs @@ -0,0 +1,25 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; + +namespace CPDLCServer.Auth.Login; + +public static class AdminAuthentication +{ + public static Task SignIn(HttpContext httpContext, Guid userId, string username) + { + var identity = new ClaimsIdentity( + [ + new Claim(ClaimTypes.NameIdentifier, userId.ToString()), + new Claim(ClaimTypes.Name, username) + ], + CookieAuthenticationDefaults.AuthenticationScheme); + + return httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); + } + + public static Task SignOut(HttpContext httpContext) + { + return httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + } +} diff --git a/source/CPDLCServer/Auth/Login/ClientIpAddress.cs b/source/CPDLCServer/Auth/Login/ClientIpAddress.cs new file mode 100644 index 0000000..d6c5cc0 --- /dev/null +++ b/source/CPDLCServer/Auth/Login/ClientIpAddress.cs @@ -0,0 +1,36 @@ +using System.Net; + +namespace CPDLCServer.Auth.Login; + +/// +/// Gives the IP address of the client. +/// Behind a proxy, the connection comes from the proxy, so the IP address of the client comes from a header that the proxy adds. +/// A client can also send these headers. Thus a client that connects without the proxy can choose its IP address. +/// +public static class ClientIpAddress +{ + // The first header that contains a valid IP address is used + static readonly string[] Headers = + [ + "do-connecting-ip", // DigitalOcean App Platform + "cf-connecting-ip", // Cloudflare + "true-client-ip", // Akamai, Cloudflare Enterprise + "x-real-ip", // nginx + "x-forwarded-for" // Most proxies. The first address is the client. + ]; + + public static string Get(HttpContext httpContext) + { + foreach (var header in Headers) + { + if (!httpContext.Request.Headers.TryGetValue(header, out var stringValues)) + continue; + + var firstAddress = stringValues.ToString().Split(',')[0].Trim(); + if (IPAddress.TryParse(firstAddress, out var address)) + return address.ToString(); + } + + return httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown"; + } +} diff --git a/source/CPDLCServer/Auth/Login/LoginCommand.cs b/source/CPDLCServer/Auth/Login/LoginCommand.cs new file mode 100644 index 0000000..ea0d6b7 --- /dev/null +++ b/source/CPDLCServer/Auth/Login/LoginCommand.cs @@ -0,0 +1,8 @@ +using MediatR; + +namespace CPDLCServer.Auth.Login; + +// Returns null when the login fails +public record LoginCommand(string Username, string Password, string IpAddress) : IRequest; + +public record LoginResult(Guid UserId, string Username); diff --git a/source/CPDLCServer/Auth/Login/LoginCommandHandler.cs b/source/CPDLCServer/Auth/Login/LoginCommandHandler.cs new file mode 100644 index 0000000..e1c195b --- /dev/null +++ b/source/CPDLCServer/Auth/Login/LoginCommandHandler.cs @@ -0,0 +1,50 @@ +using CPDLCServer.Auth.Users; +using MediatR; +using Microsoft.AspNetCore.Identity; + +namespace CPDLCServer.Auth.Login; + +// Checks the password of a user. +// After too many failed logins from an IP address, the login is locked for that IP address. +public class LoginCommandHandler( + IUserRepository userRepository, + IPasswordHasher passwordHasher, + LoginLockout loginLockout, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(LoginCommand request, CancellationToken cancellationToken) + { + // Do not check the password during the lockout, so that a person cannot continue to try passwords + if (loginLockout.IsLockedOut(request.IpAddress)) + { + logger.Warning("Failed login for {Username} from {IpAddress}: the IP address is locked out", request.Username, request.IpAddress); + return null; + } + + var user = await userRepository.FindByUsername(request.Username.Trim(), cancellationToken); + var result = user is null + ? PasswordVerificationResult.Failed + : passwordHasher.VerifyHashedPassword(user, user.PasswordHash, request.Password); + + if (user is null || result == PasswordVerificationResult.Failed) + { + var lockoutEnd = loginLockout.RecordFailure(request.IpAddress); + if (lockoutEnd is not null) + logger.Warning("Failed login for {Username} from {IpAddress}: the IP address is locked out until {LockoutEnd}", request.Username, request.IpAddress, lockoutEnd); + else + logger.Warning("Failed login for {Username} from {IpAddress}", request.Username, request.IpAddress); + + return null; + } + + loginLockout.Reset(request.IpAddress); + + // The hash was made with older settings. Make it again with the current settings. + if (result == PasswordVerificationResult.SuccessRehashNeeded) + user.PasswordHash = passwordHasher.HashPassword(user, request.Password); + + logger.Information("User {Username} logged in from {IpAddress}", user.Username, request.IpAddress); + return new LoginResult(user.Id, user.Username); + } +} diff --git a/source/CPDLCServer/Auth/Login/LoginLockout.cs b/source/CPDLCServer/Auth/Login/LoginLockout.cs new file mode 100644 index 0000000..f3aaef2 --- /dev/null +++ b/source/CPDLCServer/Auth/Login/LoginLockout.cs @@ -0,0 +1,79 @@ +using CPDLCServer.Infrastructure; + +namespace CPDLCServer.Auth.Login; + +// Locks the login for an IP address after too many failed logins. +// The failed logins are kept only in memory, so a restart clears them. +public class LoginLockout(IClock clock) +{ + public const int MaxFailedLogins = 5; + public static readonly TimeSpan LockoutDuration = TimeSpan.FromMinutes(15); + + readonly Lock _lock = new(); + readonly Dictionary _failedLogins = new(); + + public bool IsLockedOut(string ipAddress) + { + lock (_lock) + { + var now = clock.UtcNow(); + RemoveExpired(now); + + return _failedLogins.TryGetValue(ipAddress, out var failedLogins) && failedLogins.LockoutEnd > now; + } + } + + // Returns the end of the lockout when this failure locks the IP address + public DateTimeOffset? RecordFailure(string ipAddress) + { + lock (_lock) + { + var now = clock.UtcNow(); + RemoveExpired(now); + + if (!_failedLogins.TryGetValue(ipAddress, out var failedLogins)) + { + failedLogins = new FailedLogins(); + _failedLogins[ipAddress] = failedLogins; + } + + failedLogins.Count++; + failedLogins.LastFailure = now; + + if (failedLogins.Count < MaxFailedLogins) + return null; + + failedLogins.Count = 0; + failedLogins.LockoutEnd = now + LockoutDuration; + return failedLogins.LockoutEnd; + } + } + + public void Reset(string ipAddress) + { + lock (_lock) + { + _failedLogins.Remove(ipAddress); + } + } + + // The failed logins of an IP address expire after the lockout duration without a new failure. + // This also ends a lockout, because a lockout starts at a failure. + void RemoveExpired(DateTimeOffset now) + { + var expired = _failedLogins + .Where(pair => pair.Value.LastFailure + LockoutDuration <= now) + .Select(pair => pair.Key) + .ToList(); + + foreach (var ipAddress in expired) + _failedLogins.Remove(ipAddress); + } + + class FailedLogins + { + public int Count { get; set; } + public DateTimeOffset LastFailure { get; set; } + public DateTimeOffset? LockoutEnd { get; set; } + } +} diff --git a/source/CPDLCServer/Auth/Login/PasswordRateLimit.cs b/source/CPDLCServer/Auth/Login/PasswordRateLimit.cs new file mode 100644 index 0000000..9cf74e3 --- /dev/null +++ b/source/CPDLCServer/Auth/Login/PasswordRateLimit.cs @@ -0,0 +1,39 @@ +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.RateLimiting; + +namespace CPDLCServer.Auth.Login; + +/// +/// Limits the number of password attempts from one IP address, so that a person cannot quickly try many passwords. +/// +public static class PasswordRateLimit +{ + public const string PolicyName = "password"; + + const int PermitLimit = 10; + static readonly TimeSpan Window = TimeSpan.FromMinutes(1); + + public static void Configure(RateLimiterOptions options) + { + options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + options.OnRejected = (context, cancellationToken) => + new ValueTask(context.HttpContext.Response.WriteAsync( + "Too many attempts. Wait one minute, then try again.", + cancellationToken)); + + options.AddPolicy(PolicyName, httpContext => + { + // Only a form post sends a password. Do not limit the page itself. + if (!HttpMethods.IsPost(httpContext.Request.Method)) + return RateLimitPartition.GetNoLimiter(string.Empty); + + var address = ClientIpAddress.Get(httpContext); + return RateLimitPartition.GetFixedWindowLimiter(address, _ => new FixedWindowRateLimiterOptions + { + PermitLimit = PermitLimit, + Window = Window, + QueueLimit = 0 + }); + }); + } +} diff --git a/source/CPDLCServer/Auth/Users/ChangePasswordCommand.cs b/source/CPDLCServer/Auth/Users/ChangePasswordCommand.cs new file mode 100644 index 0000000..02559df --- /dev/null +++ b/source/CPDLCServer/Auth/Users/ChangePasswordCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Auth.Users; + +public record ChangePasswordCommand(Guid UserId, string NewPassword) : IRequest; diff --git a/source/CPDLCServer/Auth/Users/ChangePasswordCommandHandler.cs b/source/CPDLCServer/Auth/Users/ChangePasswordCommandHandler.cs new file mode 100644 index 0000000..12d756a --- /dev/null +++ b/source/CPDLCServer/Auth/Users/ChangePasswordCommandHandler.cs @@ -0,0 +1,21 @@ +using MediatR; +using Microsoft.AspNetCore.Identity; + +namespace CPDLCServer.Auth.Users; + +public class ChangePasswordCommandHandler( + IUserRepository userRepository, + IPasswordHasher passwordHasher, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(ChangePasswordCommand request, CancellationToken cancellationToken) + { + var user = await userRepository.FindById(request.UserId, cancellationToken); + if (user is null) + throw new InvalidOperationException($"User {request.UserId} does not exist"); + + user.PasswordHash = passwordHasher.HashPassword(user, request.NewPassword); + logger.Information("The password of user {Username} was changed", user.Username); + } +} diff --git a/source/CPDLCServer/Auth/Users/CreateUserCommand.cs b/source/CPDLCServer/Auth/Users/CreateUserCommand.cs new file mode 100644 index 0000000..bf76ec6 --- /dev/null +++ b/source/CPDLCServer/Auth/Users/CreateUserCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Auth.Users; + +public record CreateUserCommand(string Username, string Password) : IRequest; diff --git a/source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs b/source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs new file mode 100644 index 0000000..08b17e9 --- /dev/null +++ b/source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs @@ -0,0 +1,43 @@ +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using CPDLCServer.Setup; +using MediatR; +using Microsoft.AspNetCore.Identity; + +namespace CPDLCServer.Auth.Users; + +// The setup creates the first user +public class CreateUserCommandHandler( + IUserRepository userRepository, + IPasswordHasher passwordHasher, + SetupState setupState, + IClock clock, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(CreateUserCommand request, CancellationToken cancellationToken) + { + if (await userRepository.Any(cancellationToken)) + throw new InvalidOperationException("A user already exists"); + + var user = new User + { + Id = Guid.NewGuid(), + Username = request.Username.Trim(), + Created = clock.UtcNow() + }; + user.PasswordHash = passwordHasher.HashPassword(user, request.Password); + + await userRepository.Add(user, cancellationToken); + + unitOfWork.AfterCommit(_ => + { + setupState.MarkAdminCreated(); + logger.Information("User {Username} created", user.Username); + return Task.CompletedTask; + }); + + return user.Id; + } +} diff --git a/source/CPDLCServer/Auth/Users/IUserRepository.cs b/source/CPDLCServer/Auth/Users/IUserRepository.cs new file mode 100644 index 0000000..635cee1 --- /dev/null +++ b/source/CPDLCServer/Auth/Users/IUserRepository.cs @@ -0,0 +1,10 @@ +namespace CPDLCServer.Auth.Users; + +public interface IUserRepository +{ + Task Add(User user, CancellationToken cancellationToken); + Task FindByUsername(string username, CancellationToken cancellationToken); + Task FindById(Guid id, CancellationToken cancellationToken); + Task All(CancellationToken cancellationToken); + Task Any(CancellationToken cancellationToken); +} diff --git a/source/CPDLCServer/Auth/Users/User.cs b/source/CPDLCServer/Auth/Users/User.cs new file mode 100644 index 0000000..ee630a1 --- /dev/null +++ b/source/CPDLCServer/Auth/Users/User.cs @@ -0,0 +1,10 @@ +namespace CPDLCServer.Auth.Users; + +// A user that can open the restricted pages of the dashboard +public class User +{ + public Guid Id { get; init; } + public string Username { get; init; } = string.Empty; + public string PasswordHash { get; set; } = string.Empty; + public DateTimeOffset Created { get; init; } +} diff --git a/source/CPDLCServer/Auth/Users/UserConfiguration.cs b/source/CPDLCServer/Auth/Users/UserConfiguration.cs new file mode 100644 index 0000000..ffb8a10 --- /dev/null +++ b/source/CPDLCServer/Auth/Users/UserConfiguration.cs @@ -0,0 +1,17 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Auth.Users; + +public class UserConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Users"); + + builder.HasKey(u => u.Id); + builder.Property(u => u.Id).ValueGeneratedNever(); + + builder.HasIndex(u => u.Username).IsUnique(); + } +} diff --git a/source/CPDLCServer/Auth/Users/UserRepository.cs b/source/CPDLCServer/Auth/Users/UserRepository.cs new file mode 100644 index 0000000..8b25a7c --- /dev/null +++ b/source/CPDLCServer/Auth/Users/UserRepository.cs @@ -0,0 +1,42 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Auth.Users; + +// The changes are saved when the unit of work is committed. +// Queries load the rows into the context, then read the local entities, so that the results include entities that are +// added in the unit of work and exclude entities that are removed in it. +public class UserRepository(CpdlcDbContext dbContext) : IUserRepository +{ + public Task Add(User user, CancellationToken cancellationToken) + { + dbContext.Users.Add(user); + return Task.CompletedTask; + } + + public async Task FindByUsername(string username, CancellationToken cancellationToken) + { + await dbContext.Users + .Where(u => u.Username == username) + .LoadAsync(cancellationToken); + + return dbContext.Users.Local.FirstOrDefault(u => u.Username == username); + } + + public async Task FindById(Guid id, CancellationToken cancellationToken) + { + return await dbContext.Users.FindAsync([id], cancellationToken); + } + + public async Task All(CancellationToken cancellationToken) + { + await dbContext.Users.LoadAsync(cancellationToken); + return dbContext.Users.Local.OrderBy(u => u.Username).ToArray(); + } + + public async Task Any(CancellationToken cancellationToken) + { + await dbContext.Users.LoadAsync(cancellationToken); + return dbContext.Users.Local.Count > 0; + } +} diff --git a/source/CPDLCServer/CPDLCServer.csproj b/source/CPDLCServer/CPDLCServer.csproj index b2f4533..f43dbd9 100644 --- a/source/CPDLCServer/CPDLCServer.csproj +++ b/source/CPDLCServer/CPDLCServer.csproj @@ -6,6 +6,8 @@ enable Linux false + + false @@ -13,19 +15,20 @@ - + - - - - - - - + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive all - + @@ -39,14 +42,6 @@ - - - - - - - - <_ContentIncludedByDefault Remove="Pages\Dashboard\Connections\Index.cshtml" /> <_ContentIncludedByDefault Remove="Pages\Dashboard\Dialogue\Index.cshtml" /> diff --git a/source/CPDLCServer/Clients/ClientManager.cs b/source/CPDLCServer/Clients/ClientManager.cs deleted file mode 100644 index cf99337..0000000 --- a/source/CPDLCServer/Clients/ClientManager.cs +++ /dev/null @@ -1,353 +0,0 @@ -using CPDLCServer.Exceptions; -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; - -namespace CPDLCServer.Clients; - -public interface IClientManager -{ - Task GetAcarsClient(string acarsClientId, CancellationToken cancellationToken); - Task GetAcarsClientForStation(string stationId, CancellationToken cancellationToken); - Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken); - Task FindAcarsClientId(string stationId, CancellationToken cancellationToken); -} - -public class ClientManager : BackgroundService, IClientManager -{ - readonly AcarsConfiguration[] _acarsConfigurations; - readonly SemaphoreSlim _semaphoreSlim = new(1, 1); - readonly Dictionary _clients = []; - readonly IClock _clock; - readonly IAdscMessageLogRepository _adscMessageLogRepository; - readonly ILogger _logger; - readonly IMediator _mediator; - - public ClientManager( - IConfiguration configuration, - IMediator mediator, - IClock clock, - IAdscMessageLogRepository adscMessageLogRepository, - ILogger logger) - { - var acarsConfigurationSection = configuration.GetSection("Acars"); - var configurationList = new List(); - - foreach (var section in acarsConfigurationSection.GetChildren()) - { - var type = section["Type"]; - var config = type switch - { - "Hoppie" => section.Get(), - _ => throw new NotSupportedException($"ACARS configuration type '{type}' is not supported") - }; - - if (config is not null) - { - if (TimeSpan.FromMinutes(config.DefaultAdscReportingInterval) < AdscContract.MinimumReportingInterval) - throw new Exception( - $"DefaultAdscReportingInterval for ACARS client '{config.ClientId}' must be {AdscContract.MinimumReportingInterval.TotalMinutes} minutes or more"); - - configurationList.Add(config); - } - } - - _acarsConfigurations = configurationList.ToArray(); - - _mediator = mediator; - _clock = clock; - _adscMessageLogRepository = adscMessageLogRepository; - _logger = logger.ForContext(); - } - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - _logger.Information("Starting ACARS client manager with {Count} configurations", _acarsConfigurations.Length); - - foreach (var config in _acarsConfigurations) - { - await CreateClientWithRetry(config.ClientId, stoppingToken); - } - - _logger.Information("All ACARS clients initialized"); - - try - { - await Task.Delay(Timeout.Infinite, stoppingToken); - } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { - _logger.Information("Stopping ACARS client manager"); - } - } - - async Task CreateClientWithRetry(string acarsClientId, CancellationToken cancellationToken) - { - const int maxRetries = 5; - var retryDelay = TimeSpan.FromSeconds(1); - - for (var attempt = 0; attempt < maxRetries; attempt++) - { - try - { - var acarsClientHandle = await CreateAcarsClient(acarsClientId, cancellationToken); - _clients.Add(acarsClientId, acarsClientHandle); - - _logger.Information("Created ACARS client {ClientId}", acarsClientId); - - return; - } - catch (Exception ex) when (attempt < maxRetries - 1) - { - _logger.Warning( - ex, - "Failed to create ACARS client {ClientId} (attempt {Attempt}/{MaxRetries}). Retrying in {Delay}", - acarsClientId, - attempt + 1, - maxRetries, - retryDelay); - - await Task.Delay(retryDelay, cancellationToken); - retryDelay *= 2; - } - catch (Exception ex) - { - _logger.Error( - ex, - "Failed to create ACARS client {ClientId} after {MaxRetries} attempts. Client will not be available", - acarsClientId, - maxRetries); - break; - } - } - } - - public Task GetAcarsClient(string acarsClientId, CancellationToken cancellationToken) - { - if (!_clients.TryGetValue(acarsClientId, out var acarsClientHandle)) - { - throw new ConfigurationNotFoundException(acarsClientId); - } - - return Task.FromResult(acarsClientHandle.Client); - } - - public Task GetAcarsClientForStation(string stationId, CancellationToken cancellationToken) - { - var acarsClientHandle = _clients.Values.FirstOrDefault(h => h.Client.StationId == stationId); - if (acarsClientHandle is null) - { - throw new Exception($"No ACARS client found for station '{stationId}'"); - } - - return Task.FromResult(acarsClientHandle.Client); - } - - public Task GetConfigurationForStation(string stationId, CancellationToken cancellationToken) - { - var configuration = _acarsConfigurations.FirstOrDefault(c => c switch - { - HoppiesConfiguration hoppieConfig => hoppieConfig.StationIdentifier == stationId, - _ => throw new NotSupportedException($"ACARS configuration type {c.GetType().Name} is not supported") - }); - - if (configuration is null) - { - throw new Exception($"No ACARS configuration found for station '{stationId}'"); - } - - return Task.FromResult(configuration); - } - - public Task FindAcarsClientId(string stationId, CancellationToken cancellationToken) - { - var acarsClientId = _clients - .Where(c => string.Equals(c.Value.Client.StationId, stationId, StringComparison.OrdinalIgnoreCase)) - .Select(c => c.Key) - .FirstOrDefault(); - - return Task.FromResult(acarsClientId); - } - - async Task CreateAcarsClient(string acarsClientId, CancellationToken cancellationToken) - { - var configuration = _acarsConfigurations.FirstOrDefault(c => c.ClientId == acarsClientId); - if (configuration is null) - throw new ConfigurationNotFoundException(acarsClientId); - - IAcarsClient acarsClient = configuration switch - { - HoppiesConfiguration hoppieConfig => CreateHoppieClient(hoppieConfig), - _ => throw new NotSupportedException($"ACARS configuration type {configuration.GetType().Name} is not supported") - }; - - var stationId = configuration switch - { - HoppiesConfiguration hoppieConfig => hoppieConfig.StationIdentifier, - _ => throw new NotSupportedException($"ACARS configuration type {configuration.GetType().Name} is not supported") - }; - - var subscribeTaskCancellationSource = new CancellationTokenSource(); - var subscribeTask = Task.WhenAll( - Subscribe( - acarsClientId, - stationId, - acarsClient, - _mediator, - subscribeTaskCancellationSource.Token), - SubscribeAdsc( - acarsClientId, - stationId, - acarsClient, - _mediator, - subscribeTaskCancellationSource.Token)); - - var acarsClientHandle = new AcarsClientHandle(acarsClient, subscribeTask, subscribeTaskCancellationSource); - - await acarsClient.Connect(cancellationToken); - - _logger.Information("Connected to ACARS client {ClientId}", acarsClientId); - - return acarsClientHandle; - } - - HoppieAcarsClient CreateHoppieClient(HoppiesConfiguration configuration) - { - var httpClient = new HttpClient(); - httpClient.BaseAddress = configuration.Url; - - return new HoppieAcarsClient( - configuration, - httpClient, - _clock, - _adscMessageLogRepository, - _logger.ForContext()); - } - - async Task Subscribe(string acarsClientId, string stationId, IAcarsClient acarsClient, IMediator mediator, CancellationToken cancellationToken) - { - var subscriptionLogger = _logger.ForContext("AcarsClientId", acarsClientId); - - try - { - await foreach (var downlinkMessage in acarsClient.MessageReader.ReadAllAsync(cancellationToken)) - { - // TODO: Make this configurable - var publishTimeoutCancellationTokenSource = new CancellationTokenSource(); - publishTimeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10)); - - try - { - await mediator.Publish( - new DownlinkReceivedNotification( - acarsClientId, - stationId, - downlinkMessage), - publishTimeoutCancellationTokenSource.Token); - } - catch (OperationCanceledException) when (publishTimeoutCancellationTokenSource.Token.IsCancellationRequested) - { - subscriptionLogger.Warning("Timeout handling downlink {Downlink}", downlinkMessage); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - subscriptionLogger.Information("Subscription canceled"); - return; - } - catch (Exception ex) - { - subscriptionLogger.Error(ex, "Failed to relay {MessageType}", downlinkMessage.GetType()); - } - } - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - subscriptionLogger.Information("Subscription canceled"); - } - } - - async Task SubscribeAdsc(string acarsClientId, string stationId, IAcarsClient acarsClient, IMediator mediator, CancellationToken cancellationToken) - { - var subscriptionLogger = _logger.ForContext("AcarsClientId", acarsClientId); - - try - { - await foreach (var adscMessage in acarsClient.AdscMessageReader.ReadAllAsync(cancellationToken)) - { - // TODO: Make this configurable - using var publishTimeoutCancellationTokenSource = new CancellationTokenSource(); - publishTimeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10)); - - try - { - await mediator.Publish( - new AdscMessageReceivedNotification( - acarsClientId, - stationId, - adscMessage), - publishTimeoutCancellationTokenSource.Token); - } - catch (OperationCanceledException) when (publishTimeoutCancellationTokenSource.Token.IsCancellationRequested) - { - subscriptionLogger.Warning("Timeout handling ADS-C message {AdscMessage}", adscMessage); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - subscriptionLogger.Information("ADS-C subscription canceled"); - return; - } - catch (Exception ex) - { - subscriptionLogger.Error(ex, "Failed to relay {MessageType}", adscMessage.GetType()); - } - } - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - subscriptionLogger.Information("ADS-C subscription canceled"); - } - } - - record AcarsClientHandle( - IAcarsClient Client, - Task SubscribeTask, - CancellationTokenSource SubscribeCancellationTokenSource) : IAsyncDisposable - { - public async ValueTask DisposeAsync() - { - await Client.DisposeAsync(); - - await SubscribeCancellationTokenSource.CancelAsync(); - - try - { - await SubscribeTask; - } - catch (OperationCanceledException) - { - // Expected during shutdown - } - - SubscribeCancellationTokenSource.Dispose(); - SubscribeTask.Dispose(); - } - } - - - public override async Task StopAsync(CancellationToken cancellationToken) - { - _logger.Information("Stopping ACARS client manager and disposing all clients"); - - await base.StopAsync(cancellationToken); - - foreach (var (_, clientHandle) in _clients) - { - await clientHandle.DisposeAsync(); - } - - _clients.Clear(); - _semaphoreSlim.Dispose(); - } -} diff --git a/source/CPDLCServer/Messages/ControllerConnectedNotification.cs b/source/CPDLCServer/Controllers/ControllerConnectedNotification.cs similarity index 78% rename from source/CPDLCServer/Messages/ControllerConnectedNotification.cs rename to source/CPDLCServer/Controllers/ControllerConnectedNotification.cs index a6275d4..a81405c 100644 --- a/source/CPDLCServer/Messages/ControllerConnectedNotification.cs +++ b/source/CPDLCServer/Controllers/ControllerConnectedNotification.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Controllers; public record ControllerConnectedNotification(Guid UserId, string StationId, string Callsign) : INotification; diff --git a/source/CPDLCServer/Handlers/ControllerConnectedNotificationHandler.cs b/source/CPDLCServer/Controllers/ControllerConnectedNotificationHandler.cs similarity index 76% rename from source/CPDLCServer/Handlers/ControllerConnectedNotificationHandler.cs rename to source/CPDLCServer/Controllers/ControllerConnectedNotificationHandler.cs index 9425f1d..0f342d9 100644 --- a/source/CPDLCServer/Handlers/ControllerConnectedNotificationHandler.cs +++ b/source/CPDLCServer/Controllers/ControllerConnectedNotificationHandler.cs @@ -1,15 +1,15 @@ using CPDLCServer.Contracts; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Controllers; public class ControllerConnectedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -32,15 +32,14 @@ public async Task Handle(ControllerConnectedNotification notification, Cancellat } // Notify all other controllers that a peer controller has connected - await hubContext.Clients + var controllerDto = new ControllerConnectionDto( + notification.StationId, + notification.Callsign, + controllers.First(c => c.UserId == notification.UserId).VatsimCid); + + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(otherControllers.Select(c => c.ConnectionId)) - .SendAsync( - "ControllerConnectionUpdated", - new ControllerConnectionDto( - notification.StationId, - notification.Callsign, - controllers.First(c => c.UserId == notification.UserId).VatsimCid), - cancellationToken); + .SendAsync("ControllerConnectionUpdated", controllerDto, ct)); logger.Information( "Notified {ControllerCount} controller(s) about connected controller {Callsign}", diff --git a/source/CPDLCServer/Messages/ControllerDisconnectedNotification.cs b/source/CPDLCServer/Controllers/ControllerDisconnectedNotification.cs similarity index 76% rename from source/CPDLCServer/Messages/ControllerDisconnectedNotification.cs rename to source/CPDLCServer/Controllers/ControllerDisconnectedNotification.cs index d43a2e5..ac17f84 100644 --- a/source/CPDLCServer/Messages/ControllerDisconnectedNotification.cs +++ b/source/CPDLCServer/Controllers/ControllerDisconnectedNotification.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Controllers; public record ControllerDisconnectedNotification(Guid UserId, string Callsign) : INotification; diff --git a/source/CPDLCServer/Handlers/ControllerDisconnectedNotificationHandler.cs b/source/CPDLCServer/Controllers/ControllerDisconnectedNotificationHandler.cs similarity index 89% rename from source/CPDLCServer/Handlers/ControllerDisconnectedNotificationHandler.cs rename to source/CPDLCServer/Controllers/ControllerDisconnectedNotificationHandler.cs index 3717865..c08d3eb 100644 --- a/source/CPDLCServer/Handlers/ControllerDisconnectedNotificationHandler.cs +++ b/source/CPDLCServer/Controllers/ControllerDisconnectedNotificationHandler.cs @@ -1,14 +1,14 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Controllers; public class ControllerDisconnectedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -29,9 +29,9 @@ public async Task Handle(ControllerDisconnectedNotification notification, Cancel } // Notify all remaining controllers that a peer controller has disconnected - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("ControllerConnectionRemoved", notification.Callsign, cancellationToken); + .SendAsync("ControllerConnectionRemoved", notification.Callsign, ct)); logger.Information( "Notified {ControllerCount} controller(s) about disconnected controller {Callsign}", diff --git a/source/CPDLCServer/Model/ControllerInfo.cs b/source/CPDLCServer/Controllers/ControllerInfo.cs similarity index 91% rename from source/CPDLCServer/Model/ControllerInfo.cs rename to source/CPDLCServer/Controllers/ControllerInfo.cs index bafa2e7..63028f0 100644 --- a/source/CPDLCServer/Model/ControllerInfo.cs +++ b/source/CPDLCServer/Controllers/ControllerInfo.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Controllers; public class ControllerInfo( Guid userId, diff --git a/source/CPDLCServer/Controllers/ControllersServiceCollectionExtensions.cs b/source/CPDLCServer/Controllers/ControllersServiceCollectionExtensions.cs new file mode 100644 index 0000000..4844390 --- /dev/null +++ b/source/CPDLCServer/Controllers/ControllersServiceCollectionExtensions.cs @@ -0,0 +1,12 @@ +namespace CPDLCServer.Controllers; + +public static class ControllersServiceCollectionExtensions +{ + // Not AddControllers, because ASP.NET Core MVC already has a method with that name + public static IServiceCollection AddAirTrafficControllers(this IServiceCollection services) + { + services.AddSingleton(); + + return services; + } +} diff --git a/source/CPDLCServer/Messages/GetConnectedControllersRequest.cs b/source/CPDLCServer/Controllers/GetConnectedControllersRequest.cs similarity index 86% rename from source/CPDLCServer/Messages/GetConnectedControllersRequest.cs rename to source/CPDLCServer/Controllers/GetConnectedControllersRequest.cs index 3be2841..e1466b9 100644 --- a/source/CPDLCServer/Messages/GetConnectedControllersRequest.cs +++ b/source/CPDLCServer/Controllers/GetConnectedControllersRequest.cs @@ -1,7 +1,7 @@ using CPDLCServer.Contracts; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Controllers; public record GetConnectedControllersRequest : IRequest; diff --git a/source/CPDLCServer/Handlers/GetConnectedControllersRequestHandler.cs b/source/CPDLCServer/Controllers/GetConnectedControllersRequestHandler.cs similarity index 88% rename from source/CPDLCServer/Handlers/GetConnectedControllersRequestHandler.cs rename to source/CPDLCServer/Controllers/GetConnectedControllersRequestHandler.cs index a186a5b..49785ad 100644 --- a/source/CPDLCServer/Handlers/GetConnectedControllersRequestHandler.cs +++ b/source/CPDLCServer/Controllers/GetConnectedControllersRequestHandler.cs @@ -1,9 +1,7 @@ using CPDLCServer.Contracts; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Controllers; public class GetConnectedControllersRequestHandler(IControllerRepository controllerRepository) : IRequestHandler diff --git a/source/CPDLCServer/Persistence/IControllerRepository.cs b/source/CPDLCServer/Controllers/IControllerRepository.cs similarity index 86% rename from source/CPDLCServer/Persistence/IControllerRepository.cs rename to source/CPDLCServer/Controllers/IControllerRepository.cs index fa31d1b..d4a09c1 100644 --- a/source/CPDLCServer/Persistence/IControllerRepository.cs +++ b/source/CPDLCServer/Controllers/IControllerRepository.cs @@ -1,6 +1,4 @@ -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; +namespace CPDLCServer.Controllers; public interface IControllerRepository { diff --git a/source/CPDLCServer/Persistence/InMemoryControllerRepository.cs b/source/CPDLCServer/Controllers/InMemoryControllerRepository.cs similarity index 93% rename from source/CPDLCServer/Persistence/InMemoryControllerRepository.cs rename to source/CPDLCServer/Controllers/InMemoryControllerRepository.cs index 711242d..4f5d4fc 100644 --- a/source/CPDLCServer/Persistence/InMemoryControllerRepository.cs +++ b/source/CPDLCServer/Controllers/InMemoryControllerRepository.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Persistence; +namespace CPDLCServer.Controllers; public class InMemoryControllerRepository : IControllerRepository { diff --git a/source/CPDLCServer/Model/AircraftConnection.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnection.cs similarity index 94% rename from source/CPDLCServer/Model/AircraftConnection.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnection.cs index 233e142..613e573 100644 --- a/source/CPDLCServer/Model/AircraftConnection.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnection.cs @@ -1,15 +1,15 @@ using System.Diagnostics.CodeAnalysis; -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Connections; public class AircraftConnection( string callsign, - string acarsClientId, + string acarsConnectionId, string stationId, DataAuthorityState dataAuthorityState) { public string Callsign { get; } = callsign; - public string AcarsClientId { get; } = acarsClientId; + public string AcarsConnectionId { get; } = acarsConnectionId; public string StationId { get; } = stationId; public DataAuthorityState DataAuthorityState { get; private set; } = dataAuthorityState; diff --git a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionConfiguration.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionConfiguration.cs new file mode 100644 index 0000000..b7061fe --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionConfiguration.cs @@ -0,0 +1,32 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Cpdlc.Connections; + +public class AircraftConnectionConfiguration : IEntityTypeConfiguration +{ + public const string IdProperty = "Id"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("AircraftConnections"); + + // The domain model has no ID, so the key is a shadow property + builder.Property(IdProperty); + builder.HasKey(IdProperty); + + builder.Property(c => c.Callsign); + builder.Property(c => c.AcarsConnectionId); + builder.Property(c => c.StationId); + builder.Property(c => c.DataAuthorityState); + builder.Property(c => c.ConnectionState); + builder.Property(c => c.LogonRequested); + builder.Property(c => c.LogonAccepted); + builder.Property(c => c.LastSeen); + builder.Property(c => c.NextDataAuthority); + builder.Property(c => c.ExpectedTransferTime); + builder.Property(c => c.DidSentNextDataAuthorityMessage); + + builder.HasIndex(c => new { c.Callsign, c.AcarsConnectionId }); + } +} diff --git a/source/CPDLCServer/Messages/AircraftConnectionEstablished.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablished.cs similarity index 67% rename from source/CPDLCServer/Messages/AircraftConnectionEstablished.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablished.cs index bf63fcc..33ed476 100644 --- a/source/CPDLCServer/Messages/AircraftConnectionEstablished.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablished.cs @@ -1,10 +1,9 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record AircraftConnectionEstablished( - string AcarsClientId, + string AcarsConnectionId, string StationId, string Callsign, DataAuthorityState DataAuthorityState) diff --git a/source/CPDLCServer/Handlers/AircraftConnectionEstablishedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandler.cs similarity index 78% rename from source/CPDLCServer/Handlers/AircraftConnectionEstablishedNotificationHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandler.cs index 736849c..9e8ba6b 100644 --- a/source/CPDLCServer/Handlers/AircraftConnectionEstablishedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandler.cs @@ -1,26 +1,26 @@ -using CPDLCServer.Clients; -using CPDLCServer.Contracts; -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Persistence; +using CPDLCServer.Web; +using CPDLCServer.Contracts; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class AircraftConnectionEstablishedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { public async Task Handle(AircraftConnectionEstablished notification, CancellationToken cancellationToken) { logger.Information( - "Aircraft {Callsign} connected on {AcarsClientId} with data authority state {DataAuthorityState}", + "Aircraft {Callsign} connected on {AcarsConnectionId} with data authority state {DataAuthorityState}", notification.Callsign, - notification.AcarsClientId, + notification.AcarsConnectionId, notification.DataAuthorityState); // Find all controllers on the same network and station @@ -35,12 +35,12 @@ public async Task Handle(AircraftConnectionEstablished notification, Cancellatio } // Notify all controllers that an aircraft has connected - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) .SendAsync( "AircraftConnectionUpdated", new AircraftConnectionDto(notification.Callsign, notification.StationId, DialogueConverter.ToDto(notification.DataAuthorityState)), - cancellationToken); + ct)); logger.Information( "Notified {ControllerCount} controller(s) about connected aircraft {Callsign}", diff --git a/source/CPDLCServer/Messages/AircraftConnectionLost.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLost.cs similarity index 57% rename from source/CPDLCServer/Messages/AircraftConnectionLost.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLost.cs index e9cecac..069c73b 100644 --- a/source/CPDLCServer/Messages/AircraftConnectionLost.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLost.cs @@ -1,8 +1,8 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record AircraftConnectionLost( - string AcarsClientId, + string AcarsConnectionId, string Callsign) : INotification; diff --git a/source/CPDLCServer/Handlers/AircraftConnectionLostNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs similarity index 86% rename from source/CPDLCServer/Handlers/AircraftConnectionLostNotificationHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs index c7f372c..0a34aba 100644 --- a/source/CPDLCServer/Handlers/AircraftConnectionLostNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs @@ -1,13 +1,14 @@ -using CPDLCServer.Hubs; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; -using CPDLCServer.Services; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class AircraftConnectionLostNotificationHandler( IAircraftRepository aircraftRepository, @@ -17,32 +18,33 @@ public class AircraftConnectionLostNotificationHandler( IMessageIdProvider messageIdProvider, IPublisher publisher, IClock clock, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { public async Task Handle(AircraftConnectionLost notification, CancellationToken cancellationToken) { var aircraft = await aircraftRepository.Find( - new(notification.Callsign, notification.AcarsClientId), + new(notification.Callsign, notification.AcarsConnectionId), cancellationToken); if (aircraft is null) { logger.Information( - "Aircraft {Callsign} already removed from tracking on {AcarsClientId}", + "Aircraft {Callsign} already removed from tracking on {AcarsConnectionId}", notification.Callsign, - notification.AcarsClientId); + notification.AcarsConnectionId); return; } // Remove aircraft from tracking await aircraftRepository.Remove( - new(notification.Callsign, notification.AcarsClientId), + new(notification.Callsign, notification.AcarsConnectionId), cancellationToken); logger.Information( - "Aircraft {Callsign} lost on {AcarsClientId}", + "Aircraft {Callsign} lost on {AcarsConnectionId}", notification.Callsign, - notification.AcarsClientId); + notification.AcarsConnectionId); // Find all controllers on the same network and station var controllers = await controllerRepository.All(cancellationToken); @@ -79,7 +81,7 @@ await aircraftRepository.Remove( } var messageId = await messageIdProvider.GetNextMessageId( - notification.AcarsClientId, + notification.AcarsConnectionId, notification.Callsign, cancellationToken); @@ -109,7 +111,7 @@ await aircraftRepository.Remove( { // No open dialogues, create a new one with the error message var messageId = await messageIdProvider.GetNextMessageId( - notification.AcarsClientId, + notification.AcarsConnectionId, notification.Callsign, cancellationToken); @@ -136,9 +138,9 @@ await aircraftRepository.Remove( // Notify controllers that the aircraft has disconnected var controllerConnectionIds = controllers.Select(c => c.ConnectionId).ToArray(); - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllerConnectionIds) - .SendAsync("AircraftConnectionRemoved", notification.Callsign, aircraft.StationId, cancellationToken); + .SendAsync("AircraftConnectionRemoved", notification.Callsign, aircraft.StationId, ct)); logger.Information( "Notified {ControllerCount} controller(s) about lost aircraft {Callsign}", diff --git a/source/CPDLCServer/Messages/AircraftConnectionTerminated.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminated.cs similarity index 63% rename from source/CPDLCServer/Messages/AircraftConnectionTerminated.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminated.cs index ee76389..8f726f4 100644 --- a/source/CPDLCServer/Messages/AircraftConnectionTerminated.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminated.cs @@ -1,9 +1,9 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record AircraftConnectionTerminated( - string AcarsClientId, + string AcarsConnectionId, string StationId, string Callsign) : INotification; diff --git a/source/CPDLCServer/Handlers/AircraftConnectionTerminatedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandler.cs similarity index 77% rename from source/CPDLCServer/Handlers/AircraftConnectionTerminatedNotificationHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandler.cs index ea08d38..5f7008c 100644 --- a/source/CPDLCServer/Handlers/AircraftConnectionTerminatedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandler.cs @@ -1,23 +1,24 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; +using CPDLCServer.Controllers; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class AircraftConnectionTerminatedNotificationHandler( IControllerRepository controllerRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { public async Task Handle(AircraftConnectionTerminated notification, CancellationToken cancellationToken) { logger.Information( - "Aircraft {Callsign} disconnected from {AcarsClientId}", + "Aircraft {Callsign} disconnected from {AcarsConnectionId}", notification.Callsign, - notification.AcarsClientId); + notification.AcarsConnectionId); var controllers = await controllerRepository.All(cancellationToken); if (!controllers.Any()) @@ -29,9 +30,9 @@ public async Task Handle(AircraftConnectionTerminated notification, Cancellation } // Notify all controllers that an aircraft has disconnected - await hubContext.Clients + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("AircraftConnectionRemoved", notification.Callsign, notification.StationId, cancellationToken); + .SendAsync("AircraftConnectionRemoved", notification.Callsign, notification.StationId, ct)); logger.Information( "Notified {ControllerCount} controller(s) about disconnected aircraft {Callsign}", diff --git a/source/CPDLCServer/Cpdlc/Connections/AircraftRepository.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftRepository.cs new file mode 100644 index 0000000..1c31ba6 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftRepository.cs @@ -0,0 +1,46 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Cpdlc.Connections; + +// The changes are saved when the unit of work is committed. +// Queries load the rows into the context, then read the local entities, so that the results include entities that are +// added in the unit of work and exclude entities that are removed in it. +public class AircraftRepository(CpdlcDbContext dbContext) : IAircraftRepository +{ + public async Task Add(AircraftKey aircraftKey, AircraftConnection connection, CancellationToken cancellationToken) + { + // A new connection replaces the connection with the same key + var existing = await Find(aircraftKey, cancellationToken); + if (existing is not null) + dbContext.AircraftConnections.Remove(existing); + + dbContext.AircraftConnections.Add(connection); + } + + public async Task Find(AircraftKey aircraftKey, CancellationToken cancellationToken) + { + await dbContext.AircraftConnections + .Where(c => c.Callsign == aircraftKey.Callsign && c.AcarsConnectionId == aircraftKey.AcarsConnectionId) + .LoadAsync(cancellationToken); + + return dbContext.AircraftConnections.Local + .FirstOrDefault(c => c.Callsign == aircraftKey.Callsign && c.AcarsConnectionId == aircraftKey.AcarsConnectionId); + } + + public async Task All(CancellationToken cancellationToken) + { + await dbContext.AircraftConnections.LoadAsync(cancellationToken); + return dbContext.AircraftConnections.Local.ToArray(); + } + + public async Task Remove(AircraftKey aircraftKey, CancellationToken cancellationToken) + { + var connection = await Find(aircraftKey, cancellationToken); + if (connection is null) + return false; + + dbContext.AircraftConnections.Remove(connection); + return true; + } +} diff --git a/source/CPDLCServer/Messages/CheckLostAircraftConnectionsRequest.cs b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequest.cs similarity index 72% rename from source/CPDLCServer/Messages/CheckLostAircraftConnectionsRequest.cs rename to source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequest.cs index d6ec935..232b345 100644 --- a/source/CPDLCServer/Messages/CheckLostAircraftConnectionsRequest.cs +++ b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequest.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record CheckLostAircraftConnectionsRequest(TimeSpan ConnectionTimeout) : IRequest; diff --git a/source/CPDLCServer/Handlers/CheckLostAircraftConnectionsRequestHandler.cs b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandler.cs similarity index 67% rename from source/CPDLCServer/Handlers/CheckLostAircraftConnectionsRequestHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandler.cs index d67588b..cdc5110 100644 --- a/source/CPDLCServer/Handlers/CheckLostAircraftConnectionsRequestHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandler.cs @@ -1,21 +1,28 @@ using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class CheckLostAircraftConnectionsRequestHandler( IAircraftRepository aircraftRepository, IClock clock, + ServerStartTime serverStartTime, IMediator mediator, ILogger logger) : IRequestHandler { public async Task Handle(CheckLostAircraftConnectionsRequest request, CancellationToken cancellationToken) { - var connections = await aircraftRepository.All(cancellationToken); var now = clock.UtcNow(); + // The last seen times do not change while the server is stopped + if (now - serverStartTime.Started <= request.ConnectionTimeout) + { + logger.Debug("Server has not been online for longer than the connection timeout, not checking for lost connections"); + return; + } + + var connections = await aircraftRepository.All(cancellationToken); + foreach (var connection in connections) { var timeSinceLastSeen = now - connection.LastSeen; @@ -30,7 +37,7 @@ public async Task Handle(CheckLostAircraftConnectionsRequest request, Cancellati timeSinceLastSeen); await mediator.Publish( - new AircraftConnectionLost(connection.AcarsClientId, connection.Callsign), + new AircraftConnectionLost(connection.AcarsConnectionId, connection.Callsign), cancellationToken); } } diff --git a/source/CPDLCServer/Model/ConnectionState.cs b/source/CPDLCServer/Cpdlc/Connections/ConnectionState.cs similarity index 59% rename from source/CPDLCServer/Model/ConnectionState.cs rename to source/CPDLCServer/Cpdlc/Connections/ConnectionState.cs index 5be73f8..76e010e 100644 --- a/source/CPDLCServer/Model/ConnectionState.cs +++ b/source/CPDLCServer/Cpdlc/Connections/ConnectionState.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Connections; public enum ConnectionState { diff --git a/source/CPDLCServer/Model/DataAuthorityState.cs b/source/CPDLCServer/Cpdlc/Connections/DataAuthorityState.cs similarity index 66% rename from source/CPDLCServer/Model/DataAuthorityState.cs rename to source/CPDLCServer/Cpdlc/Connections/DataAuthorityState.cs index 5676dab..5e9fef8 100644 --- a/source/CPDLCServer/Model/DataAuthorityState.cs +++ b/source/CPDLCServer/Cpdlc/Connections/DataAuthorityState.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Connections; public enum DataAuthorityState { diff --git a/source/CPDLCServer/Messages/GetConnectedAircraftRequest.cs b/source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequest.cs similarity index 83% rename from source/CPDLCServer/Messages/GetConnectedAircraftRequest.cs rename to source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequest.cs index 78cb56c..36529bf 100644 --- a/source/CPDLCServer/Messages/GetConnectedAircraftRequest.cs +++ b/source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequest.cs @@ -1,7 +1,7 @@ using CPDLCServer.Contracts; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record GetConnectedAircraftRequest : IRequest; diff --git a/source/CPDLCServer/Handlers/GetConnectedAircraftRequestHandler.cs b/source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequestHandler.cs similarity index 86% rename from source/CPDLCServer/Handlers/GetConnectedAircraftRequestHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequestHandler.cs index 481a5f9..2cbc945 100644 --- a/source/CPDLCServer/Handlers/GetConnectedAircraftRequestHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/GetConnectedAircraftRequestHandler.cs @@ -1,10 +1,8 @@ +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Contracts; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class GetConnectedAircraftRequestHandler(IAircraftRepository aircraftRepository) : IRequestHandler diff --git a/source/CPDLCServer/Persistence/IAircraftRepository.cs b/source/CPDLCServer/Cpdlc/Connections/IAircraftRepository.cs similarity index 76% rename from source/CPDLCServer/Persistence/IAircraftRepository.cs rename to source/CPDLCServer/Cpdlc/Connections/IAircraftRepository.cs index b26c53f..0d2d28f 100644 --- a/source/CPDLCServer/Persistence/IAircraftRepository.cs +++ b/source/CPDLCServer/Cpdlc/Connections/IAircraftRepository.cs @@ -1,6 +1,4 @@ -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; +namespace CPDLCServer.Cpdlc.Connections; public interface IAircraftRepository { @@ -10,4 +8,4 @@ public interface IAircraftRepository Task Remove(AircraftKey aircraftKey, CancellationToken cancellationToken); } -public record AircraftKey(string Callsign, string AcarsClientId); +public record AircraftKey(string Callsign, string AcarsConnectionId); diff --git a/source/CPDLCServer/Messages/LogonCommand.cs b/source/CPDLCServer/Cpdlc/Connections/LogonCommand.cs similarity index 63% rename from source/CPDLCServer/Messages/LogonCommand.cs rename to source/CPDLCServer/Cpdlc/Connections/LogonCommand.cs index d3ea11a..9f68f36 100644 --- a/source/CPDLCServer/Messages/LogonCommand.cs +++ b/source/CPDLCServer/Cpdlc/Connections/LogonCommand.cs @@ -1,7 +1,8 @@ -using CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record LogonCommand( int DownlinkId, @@ -11,4 +12,4 @@ public record LogonCommand( AlertType DownlinkAlertType, string DownlinkContent, DateTimeOffset DownlinkReceived, - string AcarsClientId) : IRequest; + string AcarsConnectionId) : IRequest; diff --git a/source/CPDLCServer/Handlers/LogonCommandHandler.cs b/source/CPDLCServer/Cpdlc/Connections/LogonCommandHandler.cs similarity index 66% rename from source/CPDLCServer/Handlers/LogonCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/LogonCommandHandler.cs index 7e83caa..7dfd7f7 100644 --- a/source/CPDLCServer/Handlers/LogonCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/LogonCommandHandler.cs @@ -1,53 +1,54 @@ -using CPDLCServer.Clients; +using CPDLCServer.AcarsConnections; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; -using CPDLCServer.Services; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class LogonCommandHandler( - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IAircraftRepository aircraftRepository, IControllerRepository controllerRepository, IDialogueRepository dialogueRepository, IMessageIdProvider messageIdProvider, IClock clock, IMediator mediator, + IUnitOfWork unitOfWork, ILogger logger) : IRequestHandler { public async Task Handle(LogonCommand request, CancellationToken cancellationToken) { - var client = await clientManager.GetAcarsClient(request.AcarsClientId, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(request.AcarsConnectionId, cancellationToken); // If the aircraft already exists, simply accept the connection again // Likely an issue with the aircraft requiring a reconnect var aircraft = await aircraftRepository.Find( - new(request.AcarsClientId, request.Callsign), + new(request.Callsign, request.AcarsConnectionId), cancellationToken); if (aircraft is not null) { - logger.Verbose("Duplicate connection request received from {Callsign} on {ClientId}. Accepting the request.", request.Callsign, request.AcarsClientId); + logger.Verbose("Duplicate connection request received from {Callsign} on {AcarsConnectionId}. Accepting the request.", request.Callsign, request.AcarsConnectionId); - await Reply(client, request, "LOGON ACCEPTED", cancellationToken); + await Reply(acarsConnection, request, "LOGON ACCEPTED", cancellationToken); return; } aircraft = new AircraftConnection( request.Callsign, - request.AcarsClientId, - client.StationId, + request.AcarsConnectionId, + acarsConnection.StationId, DataAuthorityState.NextDataAuthority); aircraft.RequestLogon(clock.UtcNow()); await aircraftRepository.Add( - new(request.Callsign, request.AcarsClientId), + new(request.Callsign, request.AcarsConnectionId), aircraft, cancellationToken); @@ -55,27 +56,27 @@ await aircraftRepository.Add( var activeControllers = await controllerRepository.All(cancellationToken); if (activeControllers.Length == 0) { - logger.Information("New connection request received from {Callsign} on {ClientId}, but no ATS is online. Rejecting the request.", request.Callsign, request.AcarsClientId); + logger.Information("New connection request received from {Callsign} on {AcarsConnectionId}, but no ATS is online. Rejecting the request.", request.Callsign, request.AcarsConnectionId); - await Reply(client, request, "LOGON REJECTED. NO ATS AVBL.", cancellationToken); + await Reply(acarsConnection, request, "LOGON REJECTED. NO ATS AVBL.", cancellationToken); await aircraftRepository.Remove( - new AircraftKey(request.Callsign, request.AcarsClientId), + new AircraftKey(request.Callsign, request.AcarsConnectionId), cancellationToken); return; } - logger.Information("New connection request received from {Callsign} on {ClientId}. Accepting the request.", request.Callsign, request.AcarsClientId); + logger.Information("New connection request received from {Callsign} on {AcarsConnectionId}. Accepting the request.", request.Callsign, request.AcarsConnectionId); // Immediately accept it for now aircraft.AcceptLogon(clock.UtcNow()); - await Reply(client, request, "LOGON ACCEPTED", cancellationToken); + await Reply(acarsConnection, request, "LOGON ACCEPTED", cancellationToken); await mediator.Publish( new AircraftConnectionEstablished( - request.AcarsClientId, + request.AcarsConnectionId, aircraft.StationId, request.Callsign, aircraft.DataAuthorityState), @@ -83,7 +84,7 @@ await mediator.Publish( } async Task Reply( - IAcarsClient client, + IAcarsConnection acarsConnection, LogonCommand request, string content, CancellationToken cancellationToken) @@ -99,7 +100,7 @@ async Task Reply( request.DownlinkReceived); var messageId = await messageIdProvider.GetNextMessageId( - request.AcarsClientId, + request.AcarsConnectionId, request.Callsign, cancellationToken); @@ -118,7 +119,10 @@ async Task Reply( await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - await client.Send(uplinkMessage, cancellationToken); - logger.Information("Sent CPDLC message from SYSTEM to {Callsign}", request.Callsign); + unitOfWork.AfterCommit(async ct => + { + await acarsConnection.Send(uplinkMessage, ct); + logger.Information("Sent CPDLC message from SYSTEM to {Callsign}", request.Callsign); + }); } } diff --git a/source/CPDLCServer/Services/LostConnectionService.cs b/source/CPDLCServer/Cpdlc/Connections/LostConnectionService.cs similarity index 64% rename from source/CPDLCServer/Services/LostConnectionService.cs rename to source/CPDLCServer/Cpdlc/Connections/LostConnectionService.cs index a03f95d..1179e14 100644 --- a/source/CPDLCServer/Services/LostConnectionService.cs +++ b/source/CPDLCServer/Cpdlc/Connections/LostConnectionService.cs @@ -1,39 +1,22 @@ -using CPDLCServer.Messages; -using MediatR; +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; -namespace CPDLCServer.Services; +namespace CPDLCServer.Cpdlc.Connections; public class LostConnectionService : IHostedService, IDisposable { readonly TimeSpan _checkInterval = TimeSpan.FromMinutes(1); - readonly TimeSpan _connectionTimeout; - readonly IMediator _mediator; + readonly IUnitOfWorkMediator _mediator; readonly ILogger _logger; CancellationTokenSource? _cancellationTokenSource; Task? _task; - public LostConnectionService(IConfiguration configuration, IMediator mediator, ILogger logger) + public LostConnectionService(IUnitOfWorkMediator mediator, ILogger logger) { _mediator = mediator; _logger = logger.ForContext(); - - // The connectivity check updates the last seen time of each aircraft at this interval. - var refreshIntervalMinutes = configuration.GetValue("ConnectivityCheckIntervalMinutes", 15); - var refreshInterval = TimeSpan.FromMinutes(refreshIntervalMinutes); - - // The default timeout lets the connection continue if one refresh fails. - _connectionTimeout = configuration.GetValue("AircraftConnectionTimeout", refreshInterval * 3); - - // If one refresh fails, the time between two updates is two refresh intervals. - if (_connectionTimeout <= refreshInterval * 2) - { - _logger.Warning( - "AircraftConnectionTimeout ({ConnectionTimeout}) is not more than two times the connectivity check interval ({RefreshInterval}). One failed refresh will cause connections to time out.", - _connectionTimeout, - refreshInterval); - } } public Task StartAsync(CancellationToken cancellationToken) @@ -74,9 +57,9 @@ async Task DoWork(CancellationToken stoppingToken) using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); - await _mediator.Send( - new CheckLostAircraftConnectionsRequest(_connectionTimeout), - timeoutCts.Token); + var settings = await _mediator.Send(new GetServerSettingsRequest(), timeoutCts.Token); + var connectionTimeout = TimeSpan.FromMinutes(settings.AircraftConnectionTimeoutMinutes); + await _mediator.Send(new CheckLostAircraftConnectionsRequest(connectionTimeout), timeoutCts.Token); await Task.Delay(_checkInterval, stoppingToken); } diff --git a/source/CPDLCServer/Services/NdaUplinkService.cs b/source/CPDLCServer/Cpdlc/Connections/NdaUplinkService.cs similarity index 90% rename from source/CPDLCServer/Services/NdaUplinkService.cs rename to source/CPDLCServer/Cpdlc/Connections/NdaUplinkService.cs index 1da6785..e672222 100644 --- a/source/CPDLCServer/Services/NdaUplinkService.cs +++ b/source/CPDLCServer/Cpdlc/Connections/NdaUplinkService.cs @@ -1,14 +1,13 @@ -using CPDLCServer.Exceptions; -using CPDLCServer.Messages; -using MediatR; +using CPDLCServer.AcarsConnections; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Services; +namespace CPDLCServer.Cpdlc.Connections; /// /// Periodically dispatches to ensure handoff messages are sent to aircraft /// within the configured lead time before their expected transfer. /// -public class NdaUplinkService(IMediator mediator, ILogger logger) : IHostedService, IDisposable +public class NdaUplinkService(IUnitOfWorkMediator mediator, ILogger logger) : IHostedService, IDisposable { readonly TimeSpan _interval = TimeSpan.FromMinutes(1); readonly TimeSpan _errorInterval = TimeSpan.FromSeconds(5); @@ -64,7 +63,7 @@ async Task DoWork(CancellationToken cancellationToken) } catch (ConfigurationNotFoundException) { - // Race condition: Client manager probably hasn't created the client yet + // Race condition: the connection manager probably has not created the connection yet await Task.Delay(_errorInterval, cancellationToken); } catch (Exception exception) diff --git a/source/CPDLCServer/Messages/SendConnectionRequestCommand.cs b/source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommand.cs similarity index 74% rename from source/CPDLCServer/Messages/SendConnectionRequestCommand.cs rename to source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommand.cs index 17e9a06..456dde3 100644 --- a/source/CPDLCServer/Messages/SendConnectionRequestCommand.cs +++ b/source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommand.cs @@ -1,6 +1,6 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record SendConnectionRequestCommand( string Callsign, diff --git a/source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommandHandler.cs b/source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommandHandler.cs new file mode 100644 index 0000000..b833593 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/SendConnectionRequestCommandHandler.cs @@ -0,0 +1,49 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Cpdlc.Connections; + +public class SendConnectionRequestCommandHandler( + IAcarsConnectionManager acarsConnectionManager, + IMessageIdProvider messageIdProvider, + IClock clock, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(SendConnectionRequestCommand request, CancellationToken cancellationToken) + { + var acarsConnectionId = await acarsConnectionManager.FindAcarsConnectionId(request.StationId, cancellationToken); + if (acarsConnectionId is null) + throw new Exception($"No ACARS connection is configured for {request.StationId}"); + + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(acarsConnectionId, cancellationToken); + + var messageId = await messageIdProvider.GetNextMessageId( + acarsConnectionId, + request.Callsign, + cancellationToken); + + // This is a system message. It does not start a dialogue. + var uplinkMessage = new UplinkMessage( + Guid.Empty, + messageId, + null, + request.Callsign, + "SYSTEM", + CpdlcUplinkResponseType.NoResponse, + AlertType.None, + $"CONNECTION REQUESTED @{request.StationId}@", + clock.UtcNow()); + + unitOfWork.AfterCommit(async ct => + { + await acarsConnection.Send(uplinkMessage, ct); + logger.Information("Sent connection request for {StationId} to {Callsign}", request.StationId, request.Callsign); + }); + } +} diff --git a/source/CPDLCServer/Handlers/TerminateConnectionHandler.cs b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionHandler.cs similarity index 89% rename from source/CPDLCServer/Handlers/TerminateConnectionHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/TerminateConnectionHandler.cs index 11dfb03..25ec7ed 100644 --- a/source/CPDLCServer/Handlers/TerminateConnectionHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionHandler.cs @@ -1,9 +1,8 @@ +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class TerminateConnectionHandler( IAircraftRepository aircraftRepository, @@ -15,9 +14,9 @@ public class TerminateConnectionHandler( { public async Task Handle(TerminateConnectionRequest request, CancellationToken cancellationToken) { - logger.Information("Connection between {StationId} and {Callsign} terminating", request.AcarsClientId, request.Callsign); + logger.Information("Connection between {StationId} and {Callsign} terminating", request.AcarsConnectionId, request.Callsign); - var aircraftKey = new AircraftKey(request.Callsign, request.AcarsClientId); + var aircraftKey = new AircraftKey(request.Callsign, request.AcarsConnectionId); // Get the aircraft connection before removing it so we can get the StationId var aircraftConnection = await aircraftRepository.Find(aircraftKey, cancellationToken); @@ -47,7 +46,7 @@ public async Task Handle(TerminateConnectionRequest request, CancellationToken c await mediator.Publish( new AircraftConnectionTerminated( - request.AcarsClientId, + request.AcarsConnectionId, aircraftConnection.StationId, request.Callsign), cancellationToken); diff --git a/source/CPDLCServer/Handlers/TerminateConnectionOnDialogueClosedHandler.cs b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs similarity index 90% rename from source/CPDLCServer/Handlers/TerminateConnectionOnDialogueClosedHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs index 6ed7ebe..94b9b93 100644 --- a/source/CPDLCServer/Handlers/TerminateConnectionOnDialogueClosedHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs @@ -1,9 +1,8 @@ -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class TerminateConnectionOnDialogueClosedHandler( IAircraftRepository aircraftRepository, @@ -46,7 +45,7 @@ public async Task Handle(DialogueChangedNotification notification, CancellationT await mediator.Send( new TerminateConnectionRequest( aircraftConnection.Callsign, - aircraftConnection.AcarsClientId), + aircraftConnection.AcarsConnectionId), cancellationToken); } } diff --git a/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionRequest.cs b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionRequest.cs new file mode 100644 index 0000000..f5fd2b6 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionRequest.cs @@ -0,0 +1,7 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Connections; + +public record TerminateConnectionRequest( + string Callsign, + string AcarsConnectionId) : IRequest; diff --git a/source/CPDLCServer/Messages/TransmitPendingNdaUplinksCommand.cs b/source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommand.cs similarity index 64% rename from source/CPDLCServer/Messages/TransmitPendingNdaUplinksCommand.cs rename to source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommand.cs index a5ee6c5..d456bfd 100644 --- a/source/CPDLCServer/Messages/TransmitPendingNdaUplinksCommand.cs +++ b/source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommand.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record TransmitPendingNdaUplinksCommand : IRequest; diff --git a/source/CPDLCServer/Handlers/TransmitPendingNdaUplinksCommandHandler.cs b/source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandler.cs similarity index 86% rename from source/CPDLCServer/Handlers/TransmitPendingNdaUplinksCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandler.cs index 7dc8e2c..4faa248 100644 --- a/source/CPDLCServer/Handlers/TransmitPendingNdaUplinksCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/TransmitPendingNdaUplinksCommandHandler.cs @@ -1,10 +1,10 @@ +using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.Settings; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class TransmitPendingNdaUplinksCommandHandler( IAircraftRepository aircraftRepository, @@ -12,14 +12,14 @@ public class TransmitPendingNdaUplinksCommandHandler( IMediator mediator, IClock clock, ILogger logger, - IConfiguration configuration) + IServerSettingsProvider settingsProvider) : IRequestHandler { - readonly TimeSpan _notificationLeadTime = TimeSpan.FromMinutes( - configuration["Handoff:NotificationLeadTime"] is { } value && int.TryParse(value, out var minutes) ? minutes : 20); - public async Task Handle(TransmitPendingNdaUplinksCommand request, CancellationToken cancellationToken) { + var settings = await settingsProvider.Load(cancellationToken); + var notificationLeadTime = TimeSpan.FromMinutes(settings.HandoffNotificationLeadTimeMinutes); + var trackedConnections = await aircraftRepository.All(cancellationToken); var onlineCallsigns = await acarsConnectedCallsignsRepository.All(cancellationToken); @@ -37,7 +37,7 @@ public async Task Handle(TransmitPendingNdaUplinksCommand request, CancellationT continue; } - var transmitTime = aircraftConnection.ExpectedTransferTime.Value.Subtract(_notificationLeadTime); + var transmitTime = aircraftConnection.ExpectedTransferTime.Value.Subtract(notificationLeadTime); if (clock.UtcNow() <= transmitTime) { logger.Debug("{Callsign}: transmit time {TransmitTime} not reached, skipping", aircraftConnection.Callsign, transmitTime); diff --git a/source/CPDLCServer/Messages/UpdateNextDataAuthorityCommand.cs b/source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommand.cs similarity index 82% rename from source/CPDLCServer/Messages/UpdateNextDataAuthorityCommand.cs rename to source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommand.cs index 7b3f86e..2ac680a 100644 --- a/source/CPDLCServer/Messages/UpdateNextDataAuthorityCommand.cs +++ b/source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommand.cs @@ -1,6 +1,6 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Connections; public record UpdateNextDataAuthorityCommand( string StationId, diff --git a/source/CPDLCServer/Handlers/UpdateNextDataAuthorityCommandHandler.cs b/source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandler.cs similarity index 94% rename from source/CPDLCServer/Handlers/UpdateNextDataAuthorityCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandler.cs index 4add916..0afd28a 100644 --- a/source/CPDLCServer/Handlers/UpdateNextDataAuthorityCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/UpdateNextDataAuthorityCommandHandler.cs @@ -1,8 +1,6 @@ -using CPDLCServer.Messages; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Connections; public class UpdateNextDataAuthorityCommandHandler( IAircraftRepository aircraftRepository, diff --git a/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs b/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs new file mode 100644 index 0000000..39d9cdb --- /dev/null +++ b/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs @@ -0,0 +1,22 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; + +namespace CPDLCServer.Cpdlc; + +public static class CpdlcServiceCollectionExtensions +{ + public static IServiceCollection AddCpdlc(this IServiceCollection services) + { + services.AddScoped(); + services.AddHostedService(); + services.AddHostedService(); + + services.AddScoped(); + services.AddHostedService(); + + services.AddScoped(); + + return services; + } +} diff --git a/source/CPDLCServer/Model/AlertType.cs b/source/CPDLCServer/Cpdlc/Dialogues/AlertType.cs similarity index 62% rename from source/CPDLCServer/Model/AlertType.cs rename to source/CPDLCServer/Cpdlc/Dialogues/AlertType.cs index a944b0f..5b3fd71 100644 --- a/source/CPDLCServer/Model/AlertType.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/AlertType.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Dialogues; public enum AlertType { diff --git a/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequest.cs b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequest.cs new file mode 100644 index 0000000..1d875b2 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public record ArchiveCompletedDialoguesRequest : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandler.cs new file mode 100644 index 0000000..09ab081 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandler.cs @@ -0,0 +1,46 @@ +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class ArchiveCompletedDialoguesRequestHandler( + IDialogueRepository dialogueRepository, + IClock clock, + IPublisher publisher, + ILogger logger) + : IRequestHandler +{ + readonly TimeSpan _archiveDelay = TimeSpan.FromSeconds(10); + + public async Task Handle(ArchiveCompletedDialoguesRequest request, CancellationToken cancellationToken) + { + var now = clock.UtcNow(); + var dialogues = await dialogueRepository.FindClosedAndNotArchived(cancellationToken); + + logger.Verbose("Checking for completed dialogues to archive"); + + foreach (var dialogue in dialogues) + { + // Ensure all messages are acknowledged before archiving + if (!dialogue.Messages.All(m => m.IsAcknowledged)) + continue; + + // Find the last acknowledged time across all messages + var lastAckTime = dialogue.Messages.Max(m => m.Acknowledged); + + // Take the later of the last acknowledgement time or dialogue closed time + var latest = lastAckTime.Value > dialogue.Closed + ? lastAckTime.Value + : dialogue.Closed; + + var archiveTime = latest.Value.Add(_archiveDelay); + if (now < archiveTime) + continue; + + logger.Verbose("Archiving dialogue for {Callsign}", dialogue.AircraftCallsign); + dialogue.Archive(now); + + await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); + } + } +} diff --git a/source/CPDLCServer/Messages/ArchiveDialogueCommand.cs b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommand.cs similarity index 68% rename from source/CPDLCServer/Messages/ArchiveDialogueCommand.cs rename to source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommand.cs index cdd46b4..687f5aa 100644 --- a/source/CPDLCServer/Messages/ArchiveDialogueCommand.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommand.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Dialogues; public record ArchiveDialogueCommand(Guid DialogueId) : IRequest; diff --git a/source/CPDLCServer/Handlers/ArchiveDialogueCommandHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommandHandler.cs similarity index 91% rename from source/CPDLCServer/Handlers/ArchiveDialogueCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommandHandler.cs index f644a87..9da98ec 100644 --- a/source/CPDLCServer/Handlers/ArchiveDialogueCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommandHandler.cs @@ -1,51 +1,49 @@ -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class ArchiveDialogueCommandHandler( - IDialogueRepository dialogueRepository, - IClock clock, - IPublisher publisher, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(ArchiveDialogueCommand request, CancellationToken cancellationToken) - { - var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); - - if (dialogue is null) - { - logger.Warning("Dialogue not found for archival: {DialogueId}", request.DialogueId); - return; // Silently succeed - already archived or doesn't exist - } - - if (dialogue.IsArchived) - { - logger.Verbose("Dialogue {DialogueId} is already archived", request.DialogueId); - return; // Idempotent - already archived - } - - if (!dialogue.IsClosed) - { - logger.Warning( - "Attempted to archive an open dialogue {DialogueId} for {AircraftCallsign}", - request.DialogueId, - dialogue.AircraftCallsign); - return; - } - - dialogue.Archive(clock.UtcNow()); - - logger.Information( - "Manually archived dialogue {DialogueId} for {AircraftCallsign}", - request.DialogueId, - dialogue.AircraftCallsign); - - await publisher.Publish( - new DialogueChangedNotification(dialogue), - cancellationToken); - } -} +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class ArchiveDialogueCommandHandler( + IDialogueRepository dialogueRepository, + IClock clock, + IPublisher publisher, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(ArchiveDialogueCommand request, CancellationToken cancellationToken) + { + var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); + + if (dialogue is null) + { + logger.Warning("Dialogue not found for archival: {DialogueId}", request.DialogueId); + return; // Silently succeed - already archived or doesn't exist + } + + if (dialogue.IsArchived) + { + logger.Verbose("Dialogue {DialogueId} is already archived", request.DialogueId); + return; // Idempotent - already archived + } + + if (!dialogue.IsClosed) + { + logger.Warning( + "Attempted to archive an open dialogue {DialogueId} for {AircraftCallsign}", + request.DialogueId, + dialogue.AircraftCallsign); + return; + } + + dialogue.Archive(clock.UtcNow()); + + logger.Information( + "Manually archived dialogue {DialogueId} for {AircraftCallsign}", + request.DialogueId, + dialogue.AircraftCallsign); + + await publisher.Publish( + new DialogueChangedNotification(dialogue), + cancellationToken); + } +} diff --git a/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequest.cs b/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequest.cs new file mode 100644 index 0000000..46961e5 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public record CheckMessageTimeoutsRequest : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandler.cs new file mode 100644 index 0000000..d35d9a2 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandler.cs @@ -0,0 +1,96 @@ +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class CheckMessageTimeoutsRequestHandler( + IDialogueRepository dialogueRepository, + IClock clock, + IPublisher publisher, + ILogger logger) + : IRequestHandler +{ + readonly TimeSpan _pilotLateTimeout = TimeSpan.FromMinutes(2); + readonly TimeSpan _controllerLateTimeout = TimeSpan.FromMinutes(2); + + public async Task Handle(CheckMessageTimeoutsRequest request, CancellationToken cancellationToken) + { + // TODO: Time out entire dialogues when they take too long + // TODO: Verify if this is supposed to apply to message closures or acknowledgements. + + var now = clock.UtcNow(); + var dialogues = await dialogueRepository.FindOpen(cancellationToken); + + logger.Verbose("Checking for timeouts in {DialogueCount} dialogues", dialogues.Length); + + foreach (var dialogue in dialogues) + { + var anyChanges = false; + foreach (var message in dialogue.Messages) + { + switch (message) + { + case UplinkMessage uplink: + if (CheckUplinkTimeout(uplink, now)) + { + anyChanges = true; + } + break; + + case DownlinkMessage downlink: + if (CheckDownlinkTimeout(downlink, now)) + { + anyChanges = true; + } + break; + } + } + + if (anyChanges) + { + await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); + } + } + } + + bool CheckUplinkTimeout(UplinkMessage uplink, DateTimeOffset now) + { + // Skip if already closed, in timeout/failed state, or doesn't require response + if (uplink.IsClosed || + uplink.IsPilotLate || + uplink.IsTransmissionFailed || + uplink.ResponseType == CpdlcUplinkResponseType.NoResponse) + return false; + + // Check if timeout has been exceeded + var timeSinceSent = now - uplink.Sent; + if (timeSinceSent < _pilotLateTimeout) + return false; + + logger.Verbose("Uplink message {UplinkId} marked as pilot late (time since sent: {TimeSinceSent}s)", + uplink.MessageId, timeSinceSent.TotalSeconds); + uplink.IsPilotLate = true; + return true; + } + + bool CheckDownlinkTimeout(DownlinkMessage downlink, DateTimeOffset now) + { + // Skip if already closed, in timeout state, or doesn't require response + if (downlink.IsClosed || + downlink.IsControllerLate || + downlink.ResponseType == CpdlcDownlinkResponseType.NoResponse) + return false; + + // Check if timeout has been exceeded + var timeSinceReceived = now - downlink.Received; + if (timeSinceReceived < _controllerLateTimeout) + return false; + + logger.Verbose("Downlink message {DownlinkId} marked as controller late (time since received: {TimeSinceReceived}s)", + downlink.MessageId, timeSinceReceived.TotalSeconds); + downlink.IsControllerLate = true; + return true; + } +} diff --git a/source/CPDLCServer/Model/ControlMessages.cs b/source/CPDLCServer/Cpdlc/Dialogues/ControlMessages.cs similarity index 84% rename from source/CPDLCServer/Model/ControlMessages.cs rename to source/CPDLCServer/Cpdlc/Dialogues/ControlMessages.cs index 9b97271..cacf49b 100644 --- a/source/CPDLCServer/Model/ControlMessages.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/ControlMessages.cs @@ -1,4 +1,6 @@ -namespace CPDLCServer.Model; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +namespace CPDLCServer.Cpdlc.Dialogues; public static class ControlMessages { diff --git a/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessage.cs b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessage.cs new file mode 100644 index 0000000..3ac5d3c --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessage.cs @@ -0,0 +1,26 @@ +namespace CPDLCServer.Cpdlc.Dialogues; + +public abstract class CpdlcMessage( + Guid dialogueId, + int messageId, + int? messageReference, + AlertType alertType) +{ + public Guid DialogueId { get; } = dialogueId; + public int MessageId { get; } = messageId; + public int? MessageReference { get; } = messageReference; + public AlertType AlertType { get; } = alertType; + + public abstract DateTimeOffset Time { get; } + + // The place of the message in its dialogue. The dialogue sets it. + public int Position { get; internal set; } + + public DateTimeOffset? Closed { get; protected set; } + public bool IsClosed => Closed is not null; + + public DateTimeOffset? Acknowledged { get; protected set; } + public bool IsAcknowledged => Acknowledged is not null; + + public abstract void Close(DateTimeOffset time); +} diff --git a/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessageConfiguration.cs b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessageConfiguration.cs new file mode 100644 index 0000000..26c868d --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessageConfiguration.cs @@ -0,0 +1,61 @@ +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Cpdlc.Dialogues; + +// Uplink and downlink messages are kept in one table +public class CpdlcMessageConfiguration : IEntityTypeConfiguration +{ + // The message ID comes from the aircraft or the server, so it is not unique. The key is a shadow property. + public const string IdProperty = "Id"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("CpdlcMessages"); + + builder.Property(IdProperty); + builder.HasKey(IdProperty); + + builder.HasDiscriminator("Direction") + .HasValue("Uplink") + .HasValue("Downlink"); + + builder.Property(m => m.DialogueId); + builder.Property(m => m.MessageId); + builder.Property(m => m.MessageReference); + builder.Property(m => m.Position); + builder.Property(m => m.AlertType); + builder.Property(m => m.Closed); + builder.Property(m => m.Acknowledged); + builder.Ignore(m => m.Time); + } +} + +public class UplinkMessageConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.Property(m => m.Recipient); + builder.Property(m => m.SenderCallsign); + builder.Property(m => m.ResponseType).HasColumnName("UplinkResponseType"); + builder.Property(m => m.Content).HasColumnName("Content"); + builder.Property(m => m.Sent); + builder.Property(m => m.ClosedManually); + builder.Property(m => m.IsPilotLate); + builder.Property(m => m.IsTransmissionFailed); + } +} + +public class DownlinkMessageConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.Property(m => m.Sender); + builder.Property(m => m.ResponseType).HasColumnName("DownlinkResponseType"); + builder.Property(m => m.Content).HasColumnName("Content"); + builder.Property(m => m.Received); + builder.Property(m => m.IsControllerLate); + } +} diff --git a/source/CPDLCServer/Model/Dialogue.cs b/source/CPDLCServer/Cpdlc/Dialogues/Dialogue.cs similarity index 82% rename from source/CPDLCServer/Model/Dialogue.cs rename to source/CPDLCServer/Cpdlc/Dialogues/Dialogue.cs index 5633c96..bdd6ce4 100644 --- a/source/CPDLCServer/Model/Dialogue.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/Dialogue.cs @@ -1,7 +1,9 @@ using System.Diagnostics.CodeAnalysis; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using Serilog; -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Dialogues; // Messages that are related (e.g. a CPDLC downlink request, the corresponding CPDLC uplink clearance and the subsequent // pilot response) constitute a CPDLC dialogue. @@ -16,7 +18,7 @@ namespace CPDLCServer.Model; public class Dialogue { - readonly List _messages = []; + readonly List _messages = []; public Dialogue(string aircraftCallsign) { @@ -26,7 +28,7 @@ public Dialogue(string aircraftCallsign) public Guid Id { get; } = Guid.NewGuid(); public string AircraftCallsign { get; } - public IReadOnlyList Messages => _messages.AsReadOnly(); + public IReadOnlyList Messages => _messages.AsReadOnly(); public DateTimeOffset Opened { get; private set; } public DateTimeOffset? Closed { get; private set; } @@ -67,17 +69,45 @@ public DownlinkMessage AddDownlink( return message; } - void AddMessage(ICpdlcMessage message) + void AddMessage(CpdlcMessage message) { if (_messages.Count == 0) Opened = message.Time; - _messages.Add(message); + Insert(message); // Apply closure rules then check if dialogue closes ProcessMessage(message); } + // The messages are in the order of their times. A message always comes after the message that its message + // reference number (MRN) refers to, also when its time is earlier. + void Insert(CpdlcMessage message) + { + var index = _messages.FindLastIndex(m => m.Time <= message.Time) + 1; + + var referencedMessage = FindReferencedMessage(message); + if (referencedMessage is not null) + index = Math.Max(index, _messages.IndexOf(referencedMessage) + 1); + + _messages.Insert(index, message); + + for (var position = 0; position < _messages.Count; position++) + _messages[position].Position = position; + } + + CpdlcMessage? FindReferencedMessage(CpdlcMessage message) + { + return message switch + { + UplinkMessage { MessageReference: { } reference } => + _messages.OfType().FirstOrDefault(d => d.MessageId == reference), + DownlinkMessage { MessageReference: { } reference } => + _messages.OfType().FirstOrDefault(u => u.MessageId == reference), + _ => null + }; + } + public void Archive(DateTimeOffset now) { foreach (var downlink in _messages.OfType().Where(d => !d.IsAcknowledged)) @@ -112,7 +142,7 @@ public void AcknowledgeDownlink(int downlinkMessageId, DateTimeOffset now) downlink.Acknowledge(now); } - void ProcessMessage(ICpdlcMessage message) + void ProcessMessage(CpdlcMessage message) { switch (message) { @@ -173,7 +203,7 @@ public void TryClose(DateTimeOffset now) } } - void TryArchive(ICpdlcMessage message) + void TryArchive(CpdlcMessage message) { // Immediately archive when certain uplinks are added if (message is UplinkMessage uplink && ShouldAutoArchive(uplink)) diff --git a/source/CPDLCServer/Messages/DialogueChangedNotification.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotification.cs similarity index 62% rename from source/CPDLCServer/Messages/DialogueChangedNotification.cs rename to source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotification.cs index 992833d..1ae1ad1 100644 --- a/source/CPDLCServer/Messages/DialogueChangedNotification.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotification.cs @@ -1,6 +1,5 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Dialogues; public record DialogueChangedNotification(Dialogue Dialogue) : INotification; \ No newline at end of file diff --git a/source/CPDLCServer/Handlers/DialogueChangedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotificationHandler.cs similarity index 84% rename from source/CPDLCServer/Handlers/DialogueChangedNotificationHandler.cs rename to source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotificationHandler.cs index ced4c9d..1acc221 100644 --- a/source/CPDLCServer/Handlers/DialogueChangedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotificationHandler.cs @@ -1,50 +1,50 @@ -using CPDLCServer.Hubs; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; -using Microsoft.AspNetCore.SignalR; - -namespace CPDLCServer.Handlers; - -public class DialogueChangedNotificationHandler( - IControllerRepository controllerRepository, - IHubContext hubContext, - ILogger logger) - : INotificationHandler -{ - public async Task Handle(DialogueChangedNotification notification, CancellationToken cancellationToken) - { - var dialogue = notification.Dialogue; - - logger.Verbose( - "Dialogue {DialogueId} changed for {Callsign} - Closed: {Closed}, Archived: {Archived}", - dialogue.Id, - dialogue.AircraftCallsign, - dialogue.IsClosed, - dialogue.IsArchived); - - // Find all controllers on the same network and station - var controllers = await controllerRepository.All(cancellationToken); - if (controllers.Length == 0) - { - logger.Verbose( - "No controllers to notify about dialogue change for {Callsign}", - dialogue.AircraftCallsign); - return; - } - - // Convert to DTO and broadcast - var dialogueDto = DialogueConverter.ToDto(dialogue); - - await hubContext.Clients - .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("DialogueChanged", dialogueDto, cancellationToken); - - logger.Information( - "Notified {ControllerCount} controller(s) about dialogue {DialogueId} change for {Callsign}", - controllers.Length, - dialogue.Id, - dialogue.AircraftCallsign); - } -} +using CPDLCServer.Controllers; +using CPDLCServer.Persistence; +using CPDLCServer.Web; +using MediatR; +using Microsoft.AspNetCore.SignalR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class DialogueChangedNotificationHandler( + IControllerRepository controllerRepository, + IHubContext hubContext, + IUnitOfWork unitOfWork, + ILogger logger) + : INotificationHandler +{ + public async Task Handle(DialogueChangedNotification notification, CancellationToken cancellationToken) + { + var dialogue = notification.Dialogue; + + logger.Verbose( + "Dialogue {DialogueId} changed for {Callsign} - Closed: {Closed}, Archived: {Archived}", + dialogue.Id, + dialogue.AircraftCallsign, + dialogue.IsClosed, + dialogue.IsArchived); + + // Find all controllers on the same network and station + var controllers = await controllerRepository.All(cancellationToken); + if (controllers.Length == 0) + { + logger.Verbose( + "No controllers to notify about dialogue change for {Callsign}", + dialogue.AircraftCallsign); + return; + } + + // Convert to DTO and broadcast + var dialogueDto = DialogueConverter.ToDto(dialogue); + + unitOfWork.AfterCommit(ct => hubContext.Clients + .Clients(controllers.Select(c => c.ConnectionId)) + .SendAsync("DialogueChanged", dialogueDto, ct)); + + logger.Information( + "Notified {ControllerCount} controller(s) about dialogue {DialogueId} change for {Callsign}", + controllers.Length, + dialogue.Id, + dialogue.AircraftCallsign); + } +} diff --git a/source/CPDLCServer/Cpdlc/Dialogues/DialogueConfiguration.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConfiguration.cs new file mode 100644 index 0000000..02de8cc --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConfiguration.cs @@ -0,0 +1,31 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class DialogueConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Dialogues"); + + builder.HasKey(d => d.Id); + builder.Property(d => d.Id).ValueGeneratedNever(); + + builder.Property(d => d.AircraftCallsign); + builder.Property(d => d.Opened); + builder.Property(d => d.Closed); + builder.Property(d => d.Archived); + + builder.HasMany(d => d.Messages) + .WithOne() + .HasForeignKey(m => m.DialogueId) + .OnDelete(DeleteBehavior.Cascade); + + builder.Navigation(d => d.Messages) + .HasField("_messages") + .UsePropertyAccessMode(PropertyAccessMode.Field); + + builder.HasIndex(d => d.AircraftCallsign); + } +} diff --git a/source/CPDLCServer/Model/DialogueConverter.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConverter.cs similarity index 68% rename from source/CPDLCServer/Model/DialogueConverter.cs rename to source/CPDLCServer/Cpdlc/Dialogues/DialogueConverter.cs index e1bac55..a57c970 100644 --- a/source/CPDLCServer/Model/DialogueConverter.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConverter.cs @@ -1,6 +1,8 @@ using CPDLCServer.Contracts; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Dialogues; public static class DialogueConverter { @@ -15,7 +17,7 @@ public static DialogueDto ToDto(Dialogue dialogue) dialogue.Archived); } - public static CpdlcMessageDto ToMessageDto(ICpdlcMessage message) + public static CpdlcMessageDto ToMessageDto(CpdlcMessage message) { return message switch { @@ -25,24 +27,24 @@ public static CpdlcMessageDto ToMessageDto(ICpdlcMessage message) }; } - public static Contracts.CpdlcUplinkResponseType ToDto(CpdlcUplinkResponseType uplinkResponseType) + public static Contracts.CpdlcUplinkResponseType ToDto(Uplinks.CpdlcUplinkResponseType uplinkResponseType) { return uplinkResponseType switch { - CpdlcUplinkResponseType.NoResponse => Contracts.CpdlcUplinkResponseType.NoResponse, - CpdlcUplinkResponseType.WilcoUnable => Contracts.CpdlcUplinkResponseType.WilcoUnable, - CpdlcUplinkResponseType.AffirmativeNegative => Contracts.CpdlcUplinkResponseType.AffirmativeNegative, - CpdlcUplinkResponseType.Roger => Contracts.CpdlcUplinkResponseType.Roger, + Uplinks.CpdlcUplinkResponseType.NoResponse => Contracts.CpdlcUplinkResponseType.NoResponse, + Uplinks.CpdlcUplinkResponseType.WilcoUnable => Contracts.CpdlcUplinkResponseType.WilcoUnable, + Uplinks.CpdlcUplinkResponseType.AffirmativeNegative => Contracts.CpdlcUplinkResponseType.AffirmativeNegative, + Uplinks.CpdlcUplinkResponseType.Roger => Contracts.CpdlcUplinkResponseType.Roger, _ => throw new ArgumentException($"Unknown uplink response type: {uplinkResponseType}") }; } - public static Contracts.CpdlcDownlinkResponseType ToDto(CpdlcDownlinkResponseType downlinkResponseType) + public static Contracts.CpdlcDownlinkResponseType ToDto(Downlinks.CpdlcDownlinkResponseType downlinkResponseType) { return downlinkResponseType switch { - CpdlcDownlinkResponseType.NoResponse => Contracts.CpdlcDownlinkResponseType.NoResponse, - CpdlcDownlinkResponseType.ResponseRequired => Contracts.CpdlcDownlinkResponseType.ResponseRequired, + Downlinks.CpdlcDownlinkResponseType.NoResponse => Contracts.CpdlcDownlinkResponseType.NoResponse, + Downlinks.CpdlcDownlinkResponseType.ResponseRequired => Contracts.CpdlcDownlinkResponseType.ResponseRequired, _ => throw new ArgumentException($"Unknown downlink response type: {downlinkResponseType}") }; } @@ -98,12 +100,12 @@ public static DownlinkMessageDto ToDto(DownlinkMessage downlink) }; } - public static Contracts.DataAuthorityState ToDto(DataAuthorityState dataAuthorityState) + public static Contracts.DataAuthorityState ToDto(Connections.DataAuthorityState dataAuthorityState) { return dataAuthorityState switch { - DataAuthorityState.NextDataAuthority => Contracts.DataAuthorityState.NextDataAuthority, - DataAuthorityState.CurrentDataAuthority => Contracts.DataAuthorityState.CurrentDataAuthority, + Connections.DataAuthorityState.NextDataAuthority => Contracts.DataAuthorityState.NextDataAuthority, + Connections.DataAuthorityState.CurrentDataAuthority => Contracts.DataAuthorityState.CurrentDataAuthority, _ => throw new ArgumentException($"Unknown data authority state: {dataAuthorityState}") }; } diff --git a/source/CPDLCServer/Cpdlc/Dialogues/DialogueRepository.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueRepository.cs new file mode 100644 index 0000000..e6733d4 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueRepository.cs @@ -0,0 +1,97 @@ +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Cpdlc.Dialogues; + +// The changes are saved when the unit of work is committed. +// Queries load the rows into the context, then read the local entities, so that the results include entities that are +// added in the unit of work and exclude entities that are removed in it. +public class DialogueRepository(CpdlcDbContext dbContext) : IDialogueRepository +{ + public Task Add(Dialogue dialogue, CancellationToken cancellationToken) + { + dbContext.Dialogues.Add(dialogue); + return Task.CompletedTask; + } + + public async Task FindOpenDialogueByUplink( + string aircraftCallsign, + int uplinkMessageId, + CancellationToken cancellationToken) + { + await DialoguesWithMessages() + .Where(d => d.AircraftCallsign == aircraftCallsign && d.Closed == null) + .LoadAsync(cancellationToken); + + // BUG: It's possible to have messageId collisions, since the server generates incrementing ids, and some + // aircraft have their own incrementing ids ticking along too. + // We need to remove this method, and re-factor how messages are correlated to Dialogues. + // Idea: + // Split into multiple streams: + // 1. ReplyToDownlink (DialogueId, MessageId) + // 2. CreateDialogueFromUplink (No params) + // 3. AddReplyToUplink (UplinkId), Hoppie doesn't track Dialogue IDs, so we need to look through open dialogues for an uplink with that ID. + // 4. CreateDialogueFromDownlink (DownlinkId) + return dbContext.Dialogues.Local + .FirstOrDefault(d => + d.AircraftCallsign == aircraftCallsign && + !d.IsClosed && + d.Messages.OfType().Any(m => m.MessageId == uplinkMessageId)); + } + + public async Task FindById(Guid id, CancellationToken cancellationToken) + { + await DialoguesWithMessages() + .Where(d => d.Id == id) + .LoadAsync(cancellationToken); + + return dbContext.Dialogues.Local.FirstOrDefault(d => d.Id == id); + } + + public async Task FindOpen(CancellationToken cancellationToken) + { + await DialoguesWithMessages() + .Where(d => d.Closed == null) + .LoadAsync(cancellationToken); + + return dbContext.Dialogues.Local.Where(d => !d.IsClosed).ToArray(); + } + + public async Task FindClosedAndNotArchived(CancellationToken cancellationToken) + { + await DialoguesWithMessages() + .Where(d => d.Closed != null && d.Archived == null) + .LoadAsync(cancellationToken); + + return dbContext.Dialogues.Local.Where(d => d.IsClosed && !d.IsArchived).ToArray(); + } + + public async Task FindOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken) + { + await DialoguesWithMessages() + .Where(d => d.Opened < cutoff) + .LoadAsync(cancellationToken); + + return dbContext.Dialogues.Local.Where(d => d.Opened < cutoff).ToArray(); + } + + public async Task All(CancellationToken cancellationToken) + { + await DialoguesWithMessages().LoadAsync(cancellationToken); + return dbContext.Dialogues.Local.ToArray(); + } + + public Task Remove(Dialogue dialogue, CancellationToken cancellationToken) + { + dbContext.Dialogues.Remove(dialogue); + return Task.CompletedTask; + } + + IQueryable DialoguesWithMessages() + { + // Load the messages in their order in the dialogue + return dbContext.Dialogues + .Include(d => d.Messages.OrderBy(m => m.Position)); + } +} diff --git a/source/CPDLCServer/Persistence/IDialogueRepository.cs b/source/CPDLCServer/Cpdlc/Dialogues/IDialogueRepository.cs similarity index 63% rename from source/CPDLCServer/Persistence/IDialogueRepository.cs rename to source/CPDLCServer/Cpdlc/Dialogues/IDialogueRepository.cs index e201349..9759966 100644 --- a/source/CPDLCServer/Persistence/IDialogueRepository.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/IDialogueRepository.cs @@ -1,7 +1,6 @@ using System.Collections; -using CPDLCServer.Model; -namespace CPDLCServer.Persistence; +namespace CPDLCServer.Cpdlc.Dialogues; public interface IDialogueRepository { @@ -14,6 +13,12 @@ public interface IDialogueRepository Task FindById(Guid id, CancellationToken cancellationToken); + Task FindOpen(CancellationToken cancellationToken); + + Task FindClosedAndNotArchived(CancellationToken cancellationToken); + + Task FindOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken); + Task All(CancellationToken cancellationToken); Task Remove(Dialogue dialogue, CancellationToken cancellationToken); diff --git a/source/CPDLCServer/Cpdlc/Dialogues/MessageMonitorService.cs b/source/CPDLCServer/Cpdlc/Dialogues/MessageMonitorService.cs new file mode 100644 index 0000000..3bb34fa --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/MessageMonitorService.cs @@ -0,0 +1,51 @@ +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class MessageMonitorService( + IUnitOfWorkMediator mediator, + ILogger logger) + : BackgroundService +{ + readonly TimeSpan _timeoutCheckInterval = TimeSpan.FromSeconds(5); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + logger.Information("Starting message monitor service"); + try + { + while (!stoppingToken.IsCancellationRequested) + { + logger.Verbose("Running message monitor iteration"); + + // Each request is a separate unit of work, so that a failure in one does not stop the others + await Send(new PurgeExpiredCpdlcDataRequest(), stoppingToken); + await Send(new CheckMessageTimeoutsRequest(), stoppingToken); + await Send(new ArchiveCompletedDialoguesRequest(), stoppingToken); + + await Task.Delay(_timeoutCheckInterval, stoppingToken); + } + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + logger.Information("Message monitor task stopped"); + } + catch (Exception ex) + { + logger.Error(ex, "Fatal error in message monitor task"); + } + } + + async Task Send(IRequest request, CancellationToken stoppingToken) + { + try + { + await mediator.Send(request, stoppingToken); + } + catch (Exception ex) when (!stoppingToken.IsCancellationRequested) + { + logger.Error(ex, "Error during message monitoring ({RequestType})", request.GetType().Name); + } + } +} diff --git a/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequest.cs b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequest.cs new file mode 100644 index 0000000..9af5327 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public record PurgeExpiredCpdlcDataRequest : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs new file mode 100644 index 0000000..d24613f --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs @@ -0,0 +1,26 @@ +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Dialogues; + +public class PurgeExpiredCpdlcDataRequestHandler( + IDialogueRepository dialogueRepository, + IClock clock, + ILogger logger) + : IRequestHandler +{ + readonly TimeSpan _purgeTimeout = TimeSpan.FromHours(24); + + public async Task Handle(PurgeExpiredCpdlcDataRequest request, CancellationToken cancellationToken) + { + var now = clock.UtcNow(); + + // I don't care if it's closed or not. It's been long enough. + var oldDialogues = await dialogueRepository.FindOpenedBefore(now - _purgeTimeout, cancellationToken); + foreach (var dialogue in oldDialogues) + { + await dialogueRepository.Remove(dialogue, cancellationToken); + logger.Information("Purging dialogue"); // TODO: Dialogue identifier + } + } +} diff --git a/source/CPDLCServer/Messages/AcknowledgeDownlinkCommand.cs b/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommand.cs similarity index 73% rename from source/CPDLCServer/Messages/AcknowledgeDownlinkCommand.cs rename to source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommand.cs index 4c9eff0..fa80030 100644 --- a/source/CPDLCServer/Messages/AcknowledgeDownlinkCommand.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommand.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Downlinks; public record AcknowledgeDownlinkCommand(Guid DialogueId, int DownlinkMessageId) : IRequest; \ No newline at end of file diff --git a/source/CPDLCServer/Handlers/AcknowledgeDownlinkCommandHandler.cs b/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandler.cs similarity index 90% rename from source/CPDLCServer/Handlers/AcknowledgeDownlinkCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandler.cs index d235d2d..fbe2018 100644 --- a/source/CPDLCServer/Handlers/AcknowledgeDownlinkCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandler.cs @@ -1,37 +1,36 @@ -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Persistence; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class AcknowledgeDownlinkCommandHandler( - IDialogueRepository dialogueRepository, - IClock clock, - IPublisher publisher, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(AcknowledgeDownlinkCommand request, CancellationToken cancellationToken) - { - var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); - - if (dialogue is null) - { - logger.Warning("Dialogue not found for downlink acknowledgment: {DialogueId}", request.DialogueId); - throw new InvalidOperationException($"Dialogue not found: {request.DialogueId}"); - } - - dialogue.AcknowledgeDownlink(request.DownlinkMessageId, clock.UtcNow()); - - logger.Information( - "Acknowledged downlink {MessageId} in dialogue {DialogueId} for {AircraftCallsign}", - request.DownlinkMessageId, - request.DialogueId, - dialogue.AircraftCallsign); - - await publisher.Publish( - new DialogueChangedNotification(dialogue), - cancellationToken); - } -} +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.Cpdlc.Downlinks; + +public class AcknowledgeDownlinkCommandHandler( + IDialogueRepository dialogueRepository, + IClock clock, + IPublisher publisher, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(AcknowledgeDownlinkCommand request, CancellationToken cancellationToken) + { + var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); + + if (dialogue is null) + { + logger.Warning("Dialogue not found for downlink acknowledgment: {DialogueId}", request.DialogueId); + throw new InvalidOperationException($"Dialogue not found: {request.DialogueId}"); + } + + dialogue.AcknowledgeDownlink(request.DownlinkMessageId, clock.UtcNow()); + + logger.Information( + "Acknowledged downlink {MessageId} in dialogue {DialogueId} for {AircraftCallsign}", + request.DownlinkMessageId, + request.DialogueId, + dialogue.AircraftCallsign); + + await publisher.Publish( + new DialogueChangedNotification(dialogue), + cancellationToken); + } +} diff --git a/source/CPDLCServer/Model/CpdlcDownlinkResponseType.cs b/source/CPDLCServer/Cpdlc/Downlinks/CpdlcDownlinkResponseType.cs similarity index 66% rename from source/CPDLCServer/Model/CpdlcDownlinkResponseType.cs rename to source/CPDLCServer/Cpdlc/Downlinks/CpdlcDownlinkResponseType.cs index 92074e6..58acfd2 100644 --- a/source/CPDLCServer/Model/CpdlcDownlinkResponseType.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/CpdlcDownlinkResponseType.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Downlinks; public enum CpdlcDownlinkResponseType { diff --git a/source/CPDLCServer/Cpdlc/Downlinks/DownlinkMessage.cs b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkMessage.cs new file mode 100644 index 0000000..7aebc3c --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkMessage.cs @@ -0,0 +1,45 @@ +using CPDLCServer.Cpdlc.Dialogues; +namespace CPDLCServer.Cpdlc.Downlinks; + +public class DownlinkMessage : CpdlcMessage +{ + public DownlinkMessage( + Guid dialogueId, + int messageId, + int? messageReference, + string sender, + CpdlcDownlinkResponseType responseType, + AlertType alertType, + string content, + DateTimeOffset received) + : base(dialogueId, messageId, messageReference, alertType) + { + Sender = sender; + ResponseType = responseType; + Content = content; + Received = received; + + // Downlink messages requiring no response are self-closing + Closed = responseType == CpdlcDownlinkResponseType.NoResponse ? received : null; + } + + public string Sender { get; } + public CpdlcDownlinkResponseType ResponseType { get; } + public string Content { get; } + public DateTimeOffset Received { get; } + + public bool IsControllerLate { get; set; } + + public override DateTimeOffset Time => Received; + + public override void Close(DateTimeOffset time) + { + Closed = time; + IsControllerLate = false; + } + + public void Acknowledge(DateTimeOffset now) + { + Acknowledged = now; + } +} diff --git a/source/CPDLCServer/Messages/DownlinkReceivedNotification.cs b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotification.cs similarity index 61% rename from source/CPDLCServer/Messages/DownlinkReceivedNotification.cs rename to source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotification.cs index 6d9167c..ea9b4b2 100644 --- a/source/CPDLCServer/Messages/DownlinkReceivedNotification.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotification.cs @@ -1,10 +1,9 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Downlinks; public record DownlinkReceivedNotification( - string AcarsClientId, + string AcarsConnectionId, string StationId, ReceivedDownlink Downlink) : INotification; diff --git a/source/CPDLCServer/Handlers/DownlinkReceivedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs similarity index 88% rename from source/CPDLCServer/Handlers/DownlinkReceivedNotificationHandler.cs rename to source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs index 6774d93..3035a3f 100644 --- a/source/CPDLCServer/Handlers/DownlinkReceivedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs @@ -1,12 +1,13 @@ -using CPDLCServer.Hubs; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; +using CPDLCServer.Web; using MediatR; using Microsoft.AspNetCore.SignalR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Downlinks; public class DownlinkReceivedNotificationHandler( IAircraftRepository aircraftRepository, @@ -15,6 +16,7 @@ public class DownlinkReceivedNotificationHandler( IControllerRepository controllerRepository, IDialogueRepository dialogueRepository, IHubContext hubContext, + IUnitOfWork unitOfWork, ILogger logger) : INotificationHandler { @@ -35,13 +37,13 @@ await mediator.Send( downlink.AlertType, downlink.Content, downlink.Received, - notification.AcarsClientId), + notification.AcarsConnectionId), cancellationToken); return; } var aircraftConnection = await aircraftRepository.Find( - new(downlink.Sender, notification.AcarsClientId), + new(downlink.Sender, notification.AcarsConnectionId), cancellationToken); // Scenario 2: Unknown aircraft @@ -71,7 +73,7 @@ await mediator.Send( await mediator.Publish(new DialogueChangedNotification(logoffDialogue), cancellationToken); - await mediator.Send(new TerminateConnectionRequest(downlink.Sender, notification.AcarsClientId), cancellationToken); + await mediator.Send(new TerminateConnectionRequest(downlink.Sender, notification.AcarsConnectionId), cancellationToken); return; } @@ -86,15 +88,14 @@ await mediator.Send( var controllers = await controllerRepository.All(cancellationToken); if (controllers.Any()) { - await hubContext.Clients + var aircraftConnectionDto = new Contracts.AircraftConnectionDto( + aircraftConnection.Callsign, + notification.StationId, + DialogueConverter.ToDto(aircraftConnection.DataAuthorityState)); + + unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync( - "AircraftConnectionUpdated", - new Contracts.AircraftConnectionDto( - aircraftConnection.Callsign, - notification.StationId, - DialogueConverter.ToDto(aircraftConnection.DataAuthorityState)), - cancellationToken); + .SendAsync("AircraftConnectionUpdated", aircraftConnectionDto, ct)); logger.Information( "Notified {ControllerCount} controller(s) that aircraft {Callsign} was promoted to CurrentDataAuthority", diff --git a/source/CPDLCServer/Model/ReceivedDownlink.cs b/source/CPDLCServer/Cpdlc/Downlinks/ReceivedDownlink.cs similarity index 80% rename from source/CPDLCServer/Model/ReceivedDownlink.cs rename to source/CPDLCServer/Cpdlc/Downlinks/ReceivedDownlink.cs index 405691a..c414171 100644 --- a/source/CPDLCServer/Model/ReceivedDownlink.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/ReceivedDownlink.cs @@ -1,4 +1,5 @@ -namespace CPDLCServer.Model; +using CPDLCServer.Cpdlc.Dialogues; +namespace CPDLCServer.Cpdlc.Downlinks; // Raw downlink data as parsed from an ACARS packet, before being assigned to a dialogue. public record ReceivedDownlink( diff --git a/source/CPDLCServer/Messages/AcknowledgeUplinkCommand.cs b/source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommand.cs similarity index 73% rename from source/CPDLCServer/Messages/AcknowledgeUplinkCommand.cs rename to source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommand.cs index 00039ac..418e7a7 100644 --- a/source/CPDLCServer/Messages/AcknowledgeUplinkCommand.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommand.cs @@ -1,5 +1,5 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Uplinks; public record AcknowledgeUplinkCommand(Guid DialogueId, int UplinkMessageId) : IRequest; \ No newline at end of file diff --git a/source/CPDLCServer/Handlers/AcknowledgeUplinkCommandHandler.cs b/source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandler.cs similarity index 93% rename from source/CPDLCServer/Handlers/AcknowledgeUplinkCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandler.cs index 81686bd..b6b213e 100644 --- a/source/CPDLCServer/Handlers/AcknowledgeUplinkCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandler.cs @@ -1,10 +1,8 @@ +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Uplinks; // TODO: Tests diff --git a/source/CPDLCServer/Messages/BeginDialogueCommand.cs b/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommand.cs similarity index 75% rename from source/CPDLCServer/Messages/BeginDialogueCommand.cs rename to source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommand.cs index dcf6264..ddcf46b 100644 --- a/source/CPDLCServer/Messages/BeginDialogueCommand.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommand.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Uplinks; public record BeginDialogueCommand( string Sender, diff --git a/source/CPDLCServer/Handlers/BeginDialogueCommandHandler.cs b/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommandHandler.cs similarity index 74% rename from source/CPDLCServer/Handlers/BeginDialogueCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommandHandler.cs index e172077..56bd6e1 100644 --- a/source/CPDLCServer/Handlers/BeginDialogueCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommandHandler.cs @@ -1,20 +1,20 @@ -using CPDLCServer.Clients; +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; -using CPDLCServer.Services; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Uplinks; public class BeginDialogueCommandHandler( IAircraftRepository aircraftRepository, - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IMessageIdProvider messageIdProvider, IDialogueRepository dialogueRepository, IMediator mediator, IClock clock, + IUnitOfWork unitOfWork, ILogger logger) : IRequestHandler { @@ -30,10 +30,10 @@ public async Task Handle(BeginDialogueCommand request, CancellationToken cancell if (aircraftConnection is null) throw new Exception($"{request.Recipient} is not connected"); - var client = await clientManager.GetAcarsClient(aircraftConnection.AcarsClientId, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(aircraftConnection.AcarsConnectionId, cancellationToken); var messageId = await messageIdProvider.GetNextMessageId( - aircraftConnection.AcarsClientId, + aircraftConnection.AcarsConnectionId, request.Recipient, cancellationToken); @@ -54,7 +54,10 @@ public async Task Handle(BeginDialogueCommand request, CancellationToken cancell await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - await client.Send(uplinkMessage, cancellationToken); - logger.Information("Sent CPDLC message from {Sender} to {Recipient}", request.Sender, request.Recipient); + unitOfWork.AfterCommit(async ct => + { + await acarsConnection.Send(uplinkMessage, ct); + logger.Information("Sent CPDLC message from {Sender} to {Recipient}", request.Sender, request.Recipient); + }); } } diff --git a/source/CPDLCServer/Model/CpdlcUplinkResponseType.cs b/source/CPDLCServer/Cpdlc/Uplinks/CpdlcUplinkResponseType.cs similarity index 74% rename from source/CPDLCServer/Model/CpdlcUplinkResponseType.cs rename to source/CPDLCServer/Cpdlc/Uplinks/CpdlcUplinkResponseType.cs index 3f9e43b..dce267e 100644 --- a/source/CPDLCServer/Model/CpdlcUplinkResponseType.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/CpdlcUplinkResponseType.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.Cpdlc.Uplinks; public enum CpdlcUplinkResponseType { diff --git a/source/CPDLCServer/Cpdlc/Uplinks/MessageIdProvider.cs b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdProvider.cs new file mode 100644 index 0000000..46b2646 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdProvider.cs @@ -0,0 +1,30 @@ +using CPDLCServer.Persistence; + +namespace CPDLCServer.Cpdlc.Uplinks; + +public interface IMessageIdProvider +{ + Task GetNextMessageId( + string acarsConnectionId, + string callsign, + CancellationToken cancellationToken); +} + +// The last message ID is saved with the unit of work, so that the IDs continue after a restart +public class MessageIdProvider(CpdlcDbContext dbContext) : IMessageIdProvider +{ + public async Task GetNextMessageId( + string acarsConnectionId, + string callsign, + CancellationToken cancellationToken) + { + var sequence = await dbContext.MessageIdSequences.FindAsync([acarsConnectionId, callsign], cancellationToken); + if (sequence is null) + { + sequence = new MessageIdSequence(acarsConnectionId, callsign); + dbContext.MessageIdSequences.Add(sequence); + } + + return sequence.Next(); + } +} diff --git a/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequence.cs b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequence.cs new file mode 100644 index 0000000..332d66b --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequence.cs @@ -0,0 +1,15 @@ +namespace CPDLCServer.Cpdlc.Uplinks; + +// The last CPDLC message ID that the server sent to an aircraft on an ACARS connection +public class MessageIdSequence(string acarsConnectionId, string callsign) +{ + public string AcarsConnectionId { get; } = acarsConnectionId; + public string Callsign { get; } = callsign; + public int LastMessageId { get; private set; } + + public int Next() + { + LastMessageId++; + return LastMessageId; + } +} diff --git a/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequenceConfiguration.cs b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequenceConfiguration.cs new file mode 100644 index 0000000..127575b --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdSequenceConfiguration.cs @@ -0,0 +1,18 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Cpdlc.Uplinks; + +public class MessageIdSequenceConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("MessageIdSequences"); + + builder.HasKey(s => new { s.AcarsConnectionId, s.Callsign }); + + builder.Property(s => s.AcarsConnectionId); + builder.Property(s => s.Callsign); + builder.Property(s => s.LastMessageId); + } +} diff --git a/source/CPDLCServer/Messages/ReplyToDownlinkCommand.cs b/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommand.cs similarity index 77% rename from source/CPDLCServer/Messages/ReplyToDownlinkCommand.cs rename to source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommand.cs index b7dd5bb..00c577f 100644 --- a/source/CPDLCServer/Messages/ReplyToDownlinkCommand.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommand.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Model; using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.Cpdlc.Uplinks; public record ReplyToDownlinkCommand( string Sender, diff --git a/source/CPDLCServer/Handlers/ReplyToDownlinkCommandHandler.cs b/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommandHandler.cs similarity index 76% rename from source/CPDLCServer/Handlers/ReplyToDownlinkCommandHandler.cs rename to source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommandHandler.cs index 8dfc823..a0f0696 100644 --- a/source/CPDLCServer/Handlers/ReplyToDownlinkCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommandHandler.cs @@ -1,20 +1,20 @@ -using CPDLCServer.Clients; +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; using CPDLCServer.Persistence; -using CPDLCServer.Services; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.Cpdlc.Uplinks; public class ReplyToDownlinkCommandHandler( IAircraftRepository aircraftRepository, - IClientManager clientManager, + IAcarsConnectionManager acarsConnectionManager, IMessageIdProvider messageIdProvider, IDialogueRepository dialogueRepository, IMediator mediator, IClock clock, + IUnitOfWork unitOfWork, ILogger logger) : IRequestHandler { @@ -35,10 +35,10 @@ public async Task Handle(ReplyToDownlinkCommand request, CancellationToken cance if (aircraftConnection is null) throw new Exception($"{callsign} is not connected"); - var client = await clientManager.GetAcarsClient(aircraftConnection.AcarsClientId, cancellationToken); + var acarsConnection = await acarsConnectionManager.GetAcarsConnection(aircraftConnection.AcarsConnectionId, cancellationToken); var messageId = await messageIdProvider.GetNextMessageId( - aircraftConnection.AcarsClientId, + aircraftConnection.AcarsConnectionId, callsign, cancellationToken); @@ -57,7 +57,10 @@ public async Task Handle(ReplyToDownlinkCommand request, CancellationToken cance await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - await client.Send(uplinkMessage, cancellationToken); - logger.Information("Sent CPDLC message from {Sender} to {Callsign}", request.Sender, callsign); + unitOfWork.AfterCommit(async ct => + { + await acarsConnection.Send(uplinkMessage, ct); + logger.Information("Sent CPDLC message from {Sender} to {Callsign}", request.Sender, callsign); + }); } } diff --git a/source/CPDLCServer/Cpdlc/Uplinks/UplinkMessage.cs b/source/CPDLCServer/Cpdlc/Uplinks/UplinkMessage.cs new file mode 100644 index 0000000..b11f2e7 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/UplinkMessage.cs @@ -0,0 +1,55 @@ +using CPDLCServer.Cpdlc.Dialogues; +namespace CPDLCServer.Cpdlc.Uplinks; + +// TODO: Separate formatted and plaintext contents. + +public class UplinkMessage : CpdlcMessage +{ + public UplinkMessage( + Guid dialogueId, + int messageId, + int? messageReference, + string recipient, + string senderCallsign, + CpdlcUplinkResponseType responseType, + AlertType alertType, + string content, + DateTimeOffset sent) + : base(dialogueId, messageId, messageReference, alertType) + { + Recipient = recipient; + SenderCallsign = senderCallsign; + ResponseType = responseType; + Content = content; + Sent = sent; + + // Uplink messages requiring no response are self-closing + Closed = responseType == CpdlcUplinkResponseType.NoResponse ? sent : null; + + // Uplinks are automatically acknowledged + Acknowledged = sent; + } + + public string Recipient { get; } + public string SenderCallsign { get; } + public CpdlcUplinkResponseType ResponseType { get; } + public string Content { get; } + public DateTimeOffset Sent { get; } + public bool ClosedManually { get; private set; } + + // public bool CanAction { get; set; } + // public bool Actioned { get; set; } + public bool IsPilotLate { get; set; } + public bool IsTransmissionFailed { get; set; } + + public override DateTimeOffset Time => Sent; + + public override void Close(DateTimeOffset time) => Close(time, false); + + public void Close(DateTimeOffset time, bool manual) + { + Closed = time; + ClosedManually = manual; + IsPilotLate = false; + } +} diff --git a/source/CPDLCServer/Dockerfile b/source/CPDLCServer/Dockerfile index 05ab5a0..f2baa4c 100644 --- a/source/CPDLCServer/Dockerfile +++ b/source/CPDLCServer/Dockerfile @@ -1,4 +1,7 @@ FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base +# The data directory: the SQLite database +RUN mkdir -p /data && chown $APP_UID /data +VOLUME /data USER $APP_UID WORKDIR /app EXPOSE 8080 diff --git a/source/CPDLCServer/Exceptions/ConfigurationNotFoundException.cs b/source/CPDLCServer/Exceptions/ConfigurationNotFoundException.cs deleted file mode 100644 index 9d80547..0000000 --- a/source/CPDLCServer/Exceptions/ConfigurationNotFoundException.cs +++ /dev/null @@ -1,4 +0,0 @@ -namespace CPDLCServer.Exceptions; - -public sealed class ConfigurationNotFoundException(string acarsClientId) - : Exception($"No ACARS configuration found for client ID '{acarsClientId}'"); \ No newline at end of file diff --git a/source/CPDLCServer/Handlers/SendConnectionRequestCommandHandler.cs b/source/CPDLCServer/Handlers/SendConnectionRequestCommandHandler.cs deleted file mode 100644 index 340681d..0000000 --- a/source/CPDLCServer/Handlers/SendConnectionRequestCommandHandler.cs +++ /dev/null @@ -1,45 +0,0 @@ -using CPDLCServer.Clients; -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Services; -using MediatR; - -namespace CPDLCServer.Handlers; - -public class SendConnectionRequestCommandHandler( - IClientManager clientManager, - IMessageIdProvider messageIdProvider, - IClock clock, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(SendConnectionRequestCommand request, CancellationToken cancellationToken) - { - var acarsClientId = await clientManager.FindAcarsClientId(request.StationId, cancellationToken); - if (acarsClientId is null) - throw new Exception($"No ACARS client is configured for {request.StationId}"); - - var client = await clientManager.GetAcarsClient(acarsClientId, cancellationToken); - - var messageId = await messageIdProvider.GetNextMessageId( - acarsClientId, - request.Callsign, - cancellationToken); - - // This is a system message. It does not start a dialogue. - var uplinkMessage = new UplinkMessage( - Guid.Empty, - messageId, - null, - request.Callsign, - "SYSTEM", - CpdlcUplinkResponseType.NoResponse, - AlertType.None, - $"CONNECTION REQUESTED @{request.StationId}@", - clock.UtcNow()); - - await client.Send(uplinkMessage, cancellationToken); - logger.Information("Sent connection request for {StationId} to {Callsign}", request.StationId, request.Callsign); - } -} diff --git a/source/CPDLCServer/Infrastructure/ApiKeyHasher.cs b/source/CPDLCServer/Infrastructure/ApiKeyHasher.cs deleted file mode 100644 index 505f219..0000000 --- a/source/CPDLCServer/Infrastructure/ApiKeyHasher.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Security.Cryptography; -using System.Text; - -namespace CPDLCServer.Infrastructure; - -public static class ApiKeyHasher -{ - public static string HashApiKey(string apiKey) - { - var hashBytes = SHA256.HashData(Encoding.UTF8.GetBytes(apiKey)); - return Convert.ToBase64String(hashBytes); - } -} diff --git a/source/CPDLCServer/Infrastructure/ConfigurationExtensionMethods.cs b/source/CPDLCServer/Infrastructure/ConfigurationExtensionMethods.cs new file mode 100644 index 0000000..2766b5b --- /dev/null +++ b/source/CPDLCServer/Infrastructure/ConfigurationExtensionMethods.cs @@ -0,0 +1,9 @@ +namespace CPDLCServer.Infrastructure; + +public static class ConfigurationExtensionMethods +{ + public static string GetRequiredValue(this IConfiguration configuration, string key) + { + return configuration[key] ?? throw new Exception($"{key} is required but was not configured."); + } +} diff --git a/source/CPDLCServer/Infrastructure/InfrastructureServiceCollectionExtensions.cs b/source/CPDLCServer/Infrastructure/InfrastructureServiceCollectionExtensions.cs new file mode 100644 index 0000000..00fdafa --- /dev/null +++ b/source/CPDLCServer/Infrastructure/InfrastructureServiceCollectionExtensions.cs @@ -0,0 +1,17 @@ +namespace CPDLCServer.Infrastructure; + +public static class InfrastructureServiceCollectionExtensions +{ + public static IServiceCollection AddInfrastructure(this IServiceCollection services) + { + // The start time is recorded now, when the server starts, and not when the service is first used + var clock = new SystemClock(); + services.AddSingleton(clock); + services.AddSingleton(new ServerStartTime(clock.UtcNow())); + + services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(InfrastructureServiceCollectionExtensions).Assembly)); + services.AddSingleton(); + + return services; + } +} diff --git a/source/CPDLCServer/Extensions/SemaphoreSlimExtensionMethods.cs b/source/CPDLCServer/Infrastructure/SemaphoreSlimExtensionMethods.cs similarity index 92% rename from source/CPDLCServer/Extensions/SemaphoreSlimExtensionMethods.cs rename to source/CPDLCServer/Infrastructure/SemaphoreSlimExtensionMethods.cs index e880504..069b964 100644 --- a/source/CPDLCServer/Extensions/SemaphoreSlimExtensionMethods.cs +++ b/source/CPDLCServer/Infrastructure/SemaphoreSlimExtensionMethods.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Extensions; +namespace CPDLCServer.Infrastructure; public static class SemaphoreSlimExtensionMethods { diff --git a/source/CPDLCServer/Infrastructure/ServerStartTime.cs b/source/CPDLCServer/Infrastructure/ServerStartTime.cs new file mode 100644 index 0000000..a483356 --- /dev/null +++ b/source/CPDLCServer/Infrastructure/ServerStartTime.cs @@ -0,0 +1,9 @@ +namespace CPDLCServer.Infrastructure; + +// The time that the server started. +// The server does not update the saved data while it is stopped, so a timeout applies only when the server has been +// online for longer than the timeout. +public class ServerStartTime(DateTimeOffset started) +{ + public DateTimeOffset Started { get; } = started; +} diff --git a/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs b/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs new file mode 100644 index 0000000..22e3ac3 --- /dev/null +++ b/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs @@ -0,0 +1,68 @@ +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Infrastructure; + +// The entry point for work that does not come from a handler: the hub, the ACARS connections and the background services. +// Each call runs in a new service scope, and commits the unit of work of that scope. +// Handlers use the IMediator of their own scope, so that nested requests and notifications are in the same unit of work. +public interface IUnitOfWorkMediator +{ + Task Send(IRequest request, CancellationToken cancellationToken = default); + Task Send(IRequest request, CancellationToken cancellationToken = default); + Task Publish(INotification notification, CancellationToken cancellationToken = default); +} + +public class UnitOfWorkMediator(IServiceScopeFactory serviceScopeFactory) : IUnitOfWorkMediator, IDisposable +{ + // Only one unit of work runs at a time. + // Two units of work cannot then change the same entity, and the messages are sent in the order of the changes. + readonly SemaphoreSlim _semaphore = new(1, 1); + + public async Task Send(IRequest request, CancellationToken cancellationToken = default) + { + await Run( + async mediator => + { + await mediator.Send(request, cancellationToken); + return true; + }, + cancellationToken); + } + + public async Task Send(IRequest request, CancellationToken cancellationToken = default) + { + return await Run(mediator => mediator.Send(request, cancellationToken), cancellationToken); + } + + public async Task Publish(INotification notification, CancellationToken cancellationToken = default) + { + await Run( + async mediator => + { + await mediator.Publish(notification, cancellationToken); + return true; + }, + cancellationToken); + } + + async Task Run(Func> action, CancellationToken cancellationToken) + { + using (await _semaphore.LockAsync(cancellationToken)) + { + await using var scope = serviceScopeFactory.CreateAsyncScope(); + var mediator = scope.ServiceProvider.GetRequiredService(); + var unitOfWork = scope.ServiceProvider.GetRequiredService(); + + var result = await action(mediator); + await unitOfWork.Commit(cancellationToken); + + return result; + } + } + + public void Dispose() + { + _semaphore.Dispose(); + } +} diff --git a/source/CPDLCServer/Logging/LogBuffer.cs b/source/CPDLCServer/Logging/LogBuffer.cs new file mode 100644 index 0000000..d59022b --- /dev/null +++ b/source/CPDLCServer/Logging/LogBuffer.cs @@ -0,0 +1,64 @@ +using System.Threading.Channels; + +namespace CPDLCServer.Logging; + +// Keeps the most recent log entries in memory, and sends each new entry to the subscribers +public class LogBuffer(int capacity = 1000) +{ + readonly object _lock = new(); + readonly Queue _entries = new(); + readonly List> _subscribers = []; + long _nextSequence = 1; + + public void Add(LogEntry entry) + { + lock (_lock) + { + var sequencedEntry = entry with { Sequence = _nextSequence++ }; + + _entries.Enqueue(sequencedEntry); + if (_entries.Count > capacity) + _entries.Dequeue(); + + foreach (var subscriber in _subscribers) + subscriber.Writer.TryWrite(sequencedEntry); + } + } + + // The subscription gets the recent entries, then each new entry. + // A slow subscriber loses its oldest entries, so that it cannot use too much memory. + public LogSubscription Subscribe() + { + lock (_lock) + { + var channel = Channel.CreateBounded(new BoundedChannelOptions(capacity) + { + FullMode = BoundedChannelFullMode.DropOldest, + SingleReader = true + }); + + _subscribers.Add(channel); + + return new LogSubscription(_entries.ToArray(), channel.Reader, () => Unsubscribe(channel)); + } + } + + void Unsubscribe(Channel channel) + { + lock (_lock) + { + _subscribers.Remove(channel); + } + + channel.Writer.TryComplete(); + } +} + +public sealed class LogSubscription(LogEntry[] recentEntries, ChannelReader newEntries, Action unsubscribe) + : IDisposable +{ + public LogEntry[] RecentEntries { get; } = recentEntries; + public ChannelReader NewEntries { get; } = newEntries; + + public void Dispose() => unsubscribe(); +} diff --git a/source/CPDLCServer/Logging/LogBufferSink.cs b/source/CPDLCServer/Logging/LogBufferSink.cs new file mode 100644 index 0000000..8ca4b5f --- /dev/null +++ b/source/CPDLCServer/Logging/LogBufferSink.cs @@ -0,0 +1,41 @@ +using Serilog.Core; +using Serilog.Events; +using Serilog.Formatting.Display; + +namespace CPDLCServer.Logging; + +// Writes the log events to the LogBuffer, for the Logs page +public class LogBufferSink(LogBuffer logBuffer) : ILogEventSink +{ + // The same text as the console output, without the timestamp, the level and the exception + readonly MessageTemplateTextFormatter _messageFormatter = new("{Message:lj}"); + + public void Emit(LogEvent logEvent) + { + using var writer = new StringWriter(); + _messageFormatter.Format(logEvent, writer); + + logBuffer.Add(new LogEntry( + Sequence: 0, // The LogBuffer sets the sequence number + Time: logEvent.Timestamp.ToString("HH:mm:ss"), + Level: logEvent.Level.ToString(), + LevelCode: LevelCode(logEvent.Level), + Message: writer.ToString(), + Exception: logEvent.Exception?.ToString())); + } + + // The same codes as {Level:u3} in the console output + static string LevelCode(LogEventLevel level) + { + return level switch + { + LogEventLevel.Verbose => "VRB", + LogEventLevel.Debug => "DBG", + LogEventLevel.Information => "INF", + LogEventLevel.Warning => "WRN", + LogEventLevel.Error => "ERR", + LogEventLevel.Fatal => "FTL", + _ => level.ToString().ToUpperInvariant() + }; + } +} diff --git a/source/CPDLCServer/Logging/LogEntry.cs b/source/CPDLCServer/Logging/LogEntry.cs new file mode 100644 index 0000000..1a97e6c --- /dev/null +++ b/source/CPDLCServer/Logging/LogEntry.cs @@ -0,0 +1,11 @@ +namespace CPDLCServer.Logging; + +// A log event, as the Logs page shows it. +// The sequence number increases by one for each entry, so that a client can ignore the entries that it already has. +public record LogEntry( + long Sequence, + string Time, + string Level, + string LevelCode, + string Message, + string? Exception); diff --git a/source/CPDLCServer/Logging/LogStreamEndpoint.cs b/source/CPDLCServer/Logging/LogStreamEndpoint.cs new file mode 100644 index 0000000..6f05d5e --- /dev/null +++ b/source/CPDLCServer/Logging/LogStreamEndpoint.cs @@ -0,0 +1,51 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Http.Features; + +namespace CPDLCServer.Logging; + +// Sends the log entries to the Logs page as Server-Sent Events. +// First it sends the recent entries, then each new entry until the browser disconnects. +public static class LogStreamEndpoint +{ + static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + + public static async Task Handle(HttpContext context, LogBuffer logBuffer, IHostApplicationLifetime lifetime) + { + // Stop the stream when the server stops, so that the shutdown does not wait for the browser + using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource( + context.RequestAborted, + lifetime.ApplicationStopping); + var cancellationToken = cancellationTokenSource.Token; + + context.Response.ContentType = "text/event-stream"; + context.Response.Headers.CacheControl = "no-cache"; + context.Features.Get()?.DisableBuffering(); + + using var subscription = logBuffer.Subscribe(); + + try + { + foreach (var entry in subscription.RecentEntries) + await WriteEvent(context.Response, entry, cancellationToken); + + await context.Response.Body.FlushAsync(cancellationToken); + + await foreach (var entry in subscription.NewEntries.ReadAllAsync(cancellationToken)) + { + await WriteEvent(context.Response, entry, cancellationToken); + await context.Response.Body.FlushAsync(cancellationToken); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // The browser disconnected, or the server is stopping + } + } + + static async Task WriteEvent(HttpResponse response, LogEntry entry, CancellationToken cancellationToken) + { + // The JSON has no line breaks, so one data line holds the entry + var json = JsonSerializer.Serialize(entry, JsonOptions); + await response.WriteAsync($"id: {entry.Sequence}\ndata: {json}\n\n", cancellationToken); + } +} diff --git a/source/CPDLCServer/Messages/RefreshAcarsCallsignsRequest.cs b/source/CPDLCServer/Messages/RefreshAcarsCallsignsRequest.cs deleted file mode 100644 index ec7a3dd..0000000 --- a/source/CPDLCServer/Messages/RefreshAcarsCallsignsRequest.cs +++ /dev/null @@ -1,5 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Messages; - -public record RefreshAcarsCallsignsRequest(string AcarsClientId) : IRequest; diff --git a/source/CPDLCServer/Messages/TerminateConnectionRequest.cs b/source/CPDLCServer/Messages/TerminateConnectionRequest.cs deleted file mode 100644 index a41aacb..0000000 --- a/source/CPDLCServer/Messages/TerminateConnectionRequest.cs +++ /dev/null @@ -1,7 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Messages; - -public record TerminateConnectionRequest( - string Callsign, - string AcarsClientId) : IRequest; diff --git a/source/CPDLCServer/Model/AircraftAdscReport.cs b/source/CPDLCServer/Model/AircraftAdscReport.cs deleted file mode 100644 index 25a8688..0000000 --- a/source/CPDLCServer/Model/AircraftAdscReport.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace CPDLCServer.Model; - -// An ADS-C report from an aircraft, and the ATSU that received it -public record AircraftAdscReport( - string Callsign, - string StationId, - AdscReport Report, - DateTimeOffset Received); diff --git a/source/CPDLCServer/Model/DownlinkMessage.cs b/source/CPDLCServer/Model/DownlinkMessage.cs deleted file mode 100644 index b7c80f9..0000000 --- a/source/CPDLCServer/Model/DownlinkMessage.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace CPDLCServer.Model; - -public class DownlinkMessage( - Guid dialogueId, - int messageId, - int? messageReference, - string sender, - CpdlcDownlinkResponseType responseType, - AlertType alertType, - string content, - DateTimeOffset received) - : ICpdlcMessage -{ - public Guid DialogueId { get; } = dialogueId; - public int MessageId { get; } = messageId; - public int? MessageReference { get; } = messageReference; - public string Sender { get; } = sender; - public CpdlcDownlinkResponseType ResponseType { get; } = responseType; - public AlertType AlertType { get; } = alertType; - public string Content { get; } = content; - public DateTimeOffset Received { get; } = received; - - public DateTimeOffset? Closed { get; private set; } = responseType == CpdlcDownlinkResponseType.NoResponse ? received : null; // Downlink messages requiring no response are self-closing - public bool IsClosed => Closed is not null; - - public DateTimeOffset? Acknowledged { get; private set; } - public bool IsAcknowledged => Acknowledged is not null; - - public bool IsControllerLate { get; set; } - - DateTimeOffset ICpdlcMessage.Time => Received; - - public void Close(DateTimeOffset time) - { - Closed = time; - IsControllerLate = false; - } - - public void Acknowledge(DateTimeOffset now) - { - Acknowledged = now; - } -} diff --git a/source/CPDLCServer/Model/ICpdlcMessage.cs b/source/CPDLCServer/Model/ICpdlcMessage.cs deleted file mode 100644 index 03603a7..0000000 --- a/source/CPDLCServer/Model/ICpdlcMessage.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace CPDLCServer.Model; - -public interface ICpdlcMessage -{ - public Guid DialogueId { get; } - public int MessageId { get; } - public int? MessageReference { get; } - AlertType AlertType { get; } - DateTimeOffset Time { get; } - - DateTimeOffset? Closed { get; } - bool IsClosed { get; } - - DateTimeOffset? Acknowledged { get; } - bool IsAcknowledged { get; } - - void Close(DateTimeOffset time); -} \ No newline at end of file diff --git a/source/CPDLCServer/Model/UplinkMessage.cs b/source/CPDLCServer/Model/UplinkMessage.cs deleted file mode 100644 index c58f0a9..0000000 --- a/source/CPDLCServer/Model/UplinkMessage.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace CPDLCServer.Model; - -// TODO: Separate formatted and plaintext contents. - -public class UplinkMessage( - Guid dialogueId, - int messageId, - int? messageReference, - string recipient, - string senderCallsign, - CpdlcUplinkResponseType responseType, - AlertType alertType, - string content, - DateTimeOffset sent) - : ICpdlcMessage -{ - public Guid DialogueId { get; } = dialogueId; - public int MessageId { get; } = messageId; - public int? MessageReference { get; } = messageReference; - public string Recipient { get; } = recipient; - public string SenderCallsign { get; } = senderCallsign; - public CpdlcUplinkResponseType ResponseType { get; } = responseType; - public AlertType AlertType { get; } = alertType; - public string Content { get; } = content; - public DateTimeOffset Sent { get; } = sent; - public DateTimeOffset? Closed { get; private set; } = responseType == CpdlcUplinkResponseType.NoResponse ? sent : null; // Uplink messages requiring no response are self-closing - public bool IsClosed => Closed is not null; - public bool ClosedManually { get; private set; } - - // Uplinks are automatically acknowledged - DateTimeOffset? ICpdlcMessage.Acknowledged => Sent; - public bool IsAcknowledged => true; - - // public bool CanAction { get; set; } - // public bool Actioned { get; set; } - public bool IsPilotLate { get; set; } - public bool IsTransmissionFailed { get; set; } - - DateTimeOffset ICpdlcMessage.Time => Sent; - - public void Close(DateTimeOffset time, bool manual = false) - { - Closed = time; - ClosedManually = manual; - IsPilotLate = false; - } - - void ICpdlcMessage.Close(DateTimeOffset time) => Close(time, false); -} \ No newline at end of file diff --git a/source/CPDLCServer/Pages/Connections/Index.cshtml b/source/CPDLCServer/Pages/Connections/Index.cshtml deleted file mode 100644 index 782efa2..0000000 --- a/source/CPDLCServer/Pages/Connections/Index.cshtml +++ /dev/null @@ -1,96 +0,0 @@ -@page "/connections" -@model CPDLCServer.Pages.Dashboard.Connections.IndexModel -@{ - ViewData["Title"] = "Connections"; -} - - - -

Connections

- -
-
-
-
-
ATC Connections
-
-
- @if (Model.Controllers.Length == 0) - { -

No ATC connections.

- } - else - { -
- - - - - - - - - - @foreach (var controller in Model.Controllers) - { - - - - - - } - -
CallsignATSU CodeConnection ID
@controller.Callsign@controller.StationId@controller.ConnectionId
-
- } -
-
-
- -
-
-
-
Pilot Connections
-
-
- @if (Model.Aircraft.Length == 0) - { -

No pilot connections.

- } - else - { -
- - - - - - - - - - - - @foreach (var aircraft in Model.Aircraft) - { - - - - - - - - } - -
CallsignATSU CodeData AuthorityACARS NetworkLast Seen
@aircraft.Callsign@aircraft.StationId@aircraft.DataAuthorityState@aircraft.AcarsClientId@aircraft.LastSeen.ToString("yyyy-MM-dd HH:mm:ss")
-
- } -
-
-
-
diff --git a/source/CPDLCServer/Pages/Connections/Index.cshtml.cs b/source/CPDLCServer/Pages/Connections/Index.cshtml.cs deleted file mode 100644 index 5fc4575..0000000 --- a/source/CPDLCServer/Pages/Connections/Index.cshtml.cs +++ /dev/null @@ -1,28 +0,0 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace CPDLCServer.Pages.Dashboard.Connections; - -public class IndexModel : PageModel -{ - private readonly IControllerRepository _controllerRepository; - private readonly IAircraftRepository _aircraftRepository; - - public IndexModel( - IControllerRepository controllerRepository, - IAircraftRepository aircraftRepository) - { - _controllerRepository = controllerRepository; - _aircraftRepository = aircraftRepository; - } - - public ControllerInfo[] Controllers { get; private set; } = []; - public AircraftConnection[] Aircraft { get; private set; } = []; - - public async Task OnGetAsync(CancellationToken cancellationToken) - { - Controllers = await _controllerRepository.All(cancellationToken); - Aircraft = await _aircraftRepository.All(cancellationToken); - } -} diff --git a/source/CPDLCServer/Pages/Index.cshtml b/source/CPDLCServer/Pages/Index.cshtml deleted file mode 100644 index 3e76e7d..0000000 --- a/source/CPDLCServer/Pages/Index.cshtml +++ /dev/null @@ -1,53 +0,0 @@ -@page "/" -@model CPDLCServer.Pages.Dashboard.IndexModel -@{ - ViewData["Title"] = "CPDLC Server"; -} - -

Dashboard

- - diff --git a/source/CPDLCServer/Pages/Index.cshtml.cs b/source/CPDLCServer/Pages/Index.cshtml.cs deleted file mode 100644 index c4458eb..0000000 --- a/source/CPDLCServer/Pages/Index.cshtml.cs +++ /dev/null @@ -1,38 +0,0 @@ -using CPDLCServer.Persistence; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace CPDLCServer.Pages.Dashboard; - -public class IndexModel : PageModel -{ - private readonly IControllerRepository _controllerRepository; - private readonly IAircraftRepository _aircraftRepository; - private readonly IDialogueRepository _dialogueRepository; - - public IndexModel( - IControllerRepository controllerRepository, - IAircraftRepository aircraftRepository, - IDialogueRepository dialogueRepository) - { - _controllerRepository = controllerRepository; - _aircraftRepository = aircraftRepository; - _dialogueRepository = dialogueRepository; - } - - public int AtcConnectionCount { get; private set; } - public int PilotConnectionCount { get; private set; } - public int TotalMessageCount { get; private set; } - public int OpenDialogueCount { get; private set; } - - public async Task OnGetAsync(CancellationToken cancellationToken) - { - var controllers = await _controllerRepository.All(cancellationToken); - var aircraft = await _aircraftRepository.All(cancellationToken); - var dialogues = await _dialogueRepository.All(cancellationToken); - - AtcConnectionCount = controllers.Length; - PilotConnectionCount = aircraft.Length; - TotalMessageCount = dialogues.Sum(d => d.Messages.Count); - OpenDialogueCount = dialogues.Count(d => !d.IsClosed); - } -} diff --git a/source/CPDLCServer/Pages/Messages/Index.cshtml b/source/CPDLCServer/Pages/Messages/Index.cshtml deleted file mode 100644 index dc6584b..0000000 --- a/source/CPDLCServer/Pages/Messages/Index.cshtml +++ /dev/null @@ -1,71 +0,0 @@ -@page "/messages" -@model CPDLCServer.Pages.Dashboard.Messages.IndexModel -@{ - ViewData["Title"] = "Messages"; -} - - - -

Messages

- -
- -
- -@if (Model.TotalPages > 1) -{ - -} diff --git a/source/CPDLCServer/Pages/Messages/Index.cshtml.cs b/source/CPDLCServer/Pages/Messages/Index.cshtml.cs deleted file mode 100644 index a77271d..0000000 --- a/source/CPDLCServer/Pages/Messages/Index.cshtml.cs +++ /dev/null @@ -1,88 +0,0 @@ -using CPDLCServer.Model; -using CPDLCServer.Pages.ViewModels; -using CPDLCServer.Persistence; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace CPDLCServer.Pages.Dashboard.Messages; - -public class IndexModel : PageModel -{ - private readonly IDialogueRepository _dialogueRepository; - private readonly IAircraftRepository _aircraftRepository; - private const int PageSize = 50; - - public IndexModel( - IDialogueRepository dialogueRepository, - IAircraftRepository aircraftRepository) - { - _dialogueRepository = dialogueRepository; - _aircraftRepository = aircraftRepository; - } - - [BindProperty(SupportsGet = true)] - public int PageNumber { get; set; } = 1; - - public List Messages { get; private set; } = []; - public int TotalPages { get; private set; } - public int CurrentPage => PageNumber; - - public async Task OnGetAsync(CancellationToken cancellationToken) - { - var dialogues = await _dialogueRepository.All(cancellationToken); - var aircraft = await _aircraftRepository.All(cancellationToken); - var aircraftLookup = aircraft.ToDictionary(a => a.Callsign, a => a); - - var allMessages = dialogues - .SelectMany(d => d.Messages.Select(m => ToViewModel(d, m, aircraftLookup))) - .OrderByDescending(m => m.Timestamp) - .ToList(); - - TotalPages = (int)Math.Ceiling(allMessages.Count / (double)PageSize); - PageNumber = Math.Clamp(PageNumber, 1, Math.Max(1, TotalPages)); - - Messages = allMessages - .Skip((PageNumber - 1) * PageSize) - .Take(PageSize) - .ToList(); - } - - public static MessageRowViewModel ToViewModel( - Model.Dialogue dialogue, - ICpdlcMessage message, - Dictionary aircraftLookup) - { - var aircraft = aircraftLookup.GetValueOrDefault(dialogue.AircraftCallsign); - var acarsNetwork = aircraft?.AcarsClientId ?? "Unknown"; - var stationId = aircraft?.StationId ?? "Unknown"; - - return message switch - { - UplinkMessage uplink => new MessageRowViewModel( - DialogueId: dialogue.Id, - Timestamp: uplink.Sent, - AcarsNetwork: acarsNetwork, - IsUplink: true, - Sender: $"{stationId} ({uplink.SenderCallsign})", - Receiver: uplink.Recipient, - AlertType: uplink.AlertType.ToString(), - ResponseType: uplink.ResponseType.ToString(), - Content: uplink.Content, - IsClosed: uplink.IsClosed), - - DownlinkMessage downlink => new MessageRowViewModel( - DialogueId: dialogue.Id, - Timestamp: downlink.Received, - AcarsNetwork: acarsNetwork, - IsUplink: false, - Sender: downlink.Sender, - Receiver: stationId, - AlertType: downlink.AlertType.ToString(), - ResponseType: downlink.ResponseType.ToString(), - Content: downlink.Content, - IsClosed: downlink.IsClosed), - - _ => throw new InvalidOperationException("Unknown message type") - }; - } -} diff --git a/source/CPDLCServer/Pages/ViewModels/MessageRowViewModel.cs b/source/CPDLCServer/Pages/ViewModels/MessageRowViewModel.cs deleted file mode 100644 index f130cf9..0000000 --- a/source/CPDLCServer/Pages/ViewModels/MessageRowViewModel.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace CPDLCServer.Pages.ViewModels; - -public record MessageRowViewModel( - Guid DialogueId, - DateTimeOffset Timestamp, - string AcarsNetwork, - bool IsUplink, - string Sender, - string Receiver, - string AlertType, - string ResponseType, - string Content, - bool IsClosed); diff --git a/source/CPDLCServer/Persistence/CpdlcDbContext.cs b/source/CPDLCServer/Persistence/CpdlcDbContext.cs new file mode 100644 index 0000000..65a8f0e --- /dev/null +++ b/source/CPDLCServer/Persistence/CpdlcDbContext.cs @@ -0,0 +1,57 @@ +using CPDLCServer.AcarsConnections.ConnectionSettings; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Auth.Users; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Settings; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Persistence; + +// The provider-specific contexts (SqliteCpdlcDbContext, PostgreSqlCpdlcDbContext) derive from this context, +// because EF Core keeps one set of migrations for each context type +public class CpdlcDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet AircraftConnections => Set(); + public DbSet Dialogues => Set(); + public DbSet AdscContracts => Set(); + public DbSet AdscReports => Set(); + public DbSet MessageIdSequences => Set(); + public DbSet ServerSettings => Set(); + public DbSet AcarsConnections => Set(); + public DbSet Users => Set(); + + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) + { + // SQLite cannot compare or sort DateTimeOffset values in a query, so store them as UTC ticks + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + + // Store the enums as text, so that a change to the order of the members does not change the data + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + configurationBuilder.Properties().HaveConversion(); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.ApplyConfiguration(new AircraftConnectionConfiguration()); + modelBuilder.ApplyConfiguration(new DialogueConfiguration()); + modelBuilder.ApplyConfiguration(new CpdlcMessageConfiguration()); + modelBuilder.ApplyConfiguration(new UplinkMessageConfiguration()); + modelBuilder.ApplyConfiguration(new DownlinkMessageConfiguration()); + modelBuilder.ApplyConfiguration(new AdscContractConfiguration()); + modelBuilder.ApplyConfiguration(new AircraftAdscReportConfiguration()); + modelBuilder.ApplyConfiguration(new MessageIdSequenceConfiguration()); + modelBuilder.ApplyConfiguration(new ServerSettingsConfiguration()); + modelBuilder.ApplyConfiguration(new AcarsConnectionSettingsConfiguration()); + modelBuilder.ApplyConfiguration(new UserConfiguration()); + } +} diff --git a/source/CPDLCServer/Persistence/DatabaseProvider.cs b/source/CPDLCServer/Persistence/DatabaseProvider.cs new file mode 100644 index 0000000..891a87d --- /dev/null +++ b/source/CPDLCServer/Persistence/DatabaseProvider.cs @@ -0,0 +1,7 @@ +namespace CPDLCServer.Persistence; + +public enum DatabaseProvider +{ + Sqlite, + PostgreSql +} diff --git a/source/CPDLCServer/Persistence/IAdscReportRepository.cs b/source/CPDLCServer/Persistence/IAdscReportRepository.cs deleted file mode 100644 index d747265..0000000 --- a/source/CPDLCServer/Persistence/IAdscReportRepository.cs +++ /dev/null @@ -1,15 +0,0 @@ -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; - -// Holds the latest ADS-C report for each aircraft -public interface IAdscReportRepository -{ - // Stores the report, unless the repository has a newer report for the same aircraft. - // A report from Hoppie always replaces a report from VATSIM. - Task Add(AircraftAdscReport report, CancellationToken cancellationToken); - Task Find(string callsign, CancellationToken cancellationToken); - Task All(CancellationToken cancellationToken); - - Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken); -} diff --git a/source/CPDLCServer/Persistence/InMemoryAdscContractRepository.cs b/source/CPDLCServer/Persistence/InMemoryAdscContractRepository.cs deleted file mode 100644 index dbad12e..0000000 --- a/source/CPDLCServer/Persistence/InMemoryAdscContractRepository.cs +++ /dev/null @@ -1,46 +0,0 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; - -public class InMemoryAdscContractRepository : IAdscContractRepository -{ - readonly SemaphoreSlim _semaphore = new(1, 1); - - private readonly Dictionary _contracts = new(); - - public async Task Add(AdscContractKey contractKey, AdscContract contract, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _contracts[contractKey] = contract; - } - } - - public async Task Find(AdscContractKey contractKey, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _contracts.TryGetValue(contractKey, out var contract); - return contract; - } - } - - public async Task All(CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _contracts - .Select(kvp => kvp.Value) - .ToArray(); - } - } - - public async Task Remove(AdscContractKey contractKey, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _contracts.Remove(contractKey); - } - } -} diff --git a/source/CPDLCServer/Persistence/InMemoryAdscReportRepository.cs b/source/CPDLCServer/Persistence/InMemoryAdscReportRepository.cs deleted file mode 100644 index 996ff90..0000000 --- a/source/CPDLCServer/Persistence/InMemoryAdscReportRepository.cs +++ /dev/null @@ -1,55 +0,0 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; - -public class InMemoryAdscReportRepository : IAdscReportRepository -{ - readonly SemaphoreSlim _semaphore = new(1, 1); - - private readonly Dictionary _reports = new(); - - public async Task Add(AircraftAdscReport report, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - if (_reports.TryGetValue(report.Callsign, out var existing)) - { - // A report from Hoppie always replaces a report from VATSIM - var replacesVatsimReport = report.Report.Source == AdscReportSource.Hoppie && - existing.Report.Source == AdscReportSource.VATSIM; - - // An aircraft can report to more than one ATSU, so reports can arrive out of order - if (!replacesVatsimReport && existing.Report.Timestamp > report.Report.Timestamp) - return; - } - - _reports[report.Callsign] = report; - } - } - - public async Task Find(string callsign, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _reports.GetValueOrDefault(callsign); - } - } - - public async Task All(CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _reports.Values.ToArray(); - } - } - - public async Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - foreach (var report in _reports.Values.Where(r => r.Received < cutoff).ToArray()) - _reports.Remove(report.Callsign); - } - } -} diff --git a/source/CPDLCServer/Persistence/InMemoryAircraftRepository.cs b/source/CPDLCServer/Persistence/InMemoryAircraftRepository.cs deleted file mode 100644 index ecf08bf..0000000 --- a/source/CPDLCServer/Persistence/InMemoryAircraftRepository.cs +++ /dev/null @@ -1,46 +0,0 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; - -public class InMemoryAircraftRepository : IAircraftRepository -{ - readonly SemaphoreSlim _semaphore = new(1, 1); - - private readonly Dictionary _connections = new(); - - public async Task Add(AircraftKey aircraftKey, AircraftConnection connection, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _connections[aircraftKey] = connection; - } - } - - public async Task Find(AircraftKey aircraftKey, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _connections.TryGetValue(aircraftKey, out var connection); - return connection; - } - } - - public async Task All(CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _connections - .Select(kvp => kvp.Value) - .ToArray(); - } - } - - public async Task Remove(AircraftKey aircraftKey, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _connections.Remove(aircraftKey); - } - } -} diff --git a/source/CPDLCServer/Persistence/InMemoryDialogueRepository.cs b/source/CPDLCServer/Persistence/InMemoryDialogueRepository.cs deleted file mode 100644 index 0b9d695..0000000 --- a/source/CPDLCServer/Persistence/InMemoryDialogueRepository.cs +++ /dev/null @@ -1,67 +0,0 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; - -public class InMemoryDialogueRepository : IDialogueRepository -{ - readonly SemaphoreSlim _semaphore = new(1, 1); - - private readonly List _dialogues = new(); - - public async Task Add(Dialogue dialogue, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _dialogues.Add(dialogue); - } - } - - public async Task FindOpenDialogueByUplink( - string aircraftCallsign, - int uplinkMessageId, - CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - // BUG: It's possible to have messageId collisions, since the server generates incrementing ids, and some - // aircraft have their own incrementing ids ticking along too. - // We need to remove this method, and re-factor how messages are correlated to Dialogues. - // Idea: - // Split into multiple streams: - // 1. ReplyToDownlink (DialogueId, MessageId) - // 2. CreateDialogueFromUplink (No params) - // 3. AddReplyToUplink (UplinkId), Hoppie doesn't track Dialogue IDs, so we need to look through open dialogues for an uplink with that ID. - // 4. CreateDialogueFromDownlink (DownlinkId) - return _dialogues - .FirstOrDefault(d => - d.AircraftCallsign == aircraftCallsign && - !d.IsClosed && - d.Messages.OfType().Any(m => m.MessageId == uplinkMessageId)); - } - } - - public async Task FindById(Guid id, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _dialogues.FirstOrDefault(d => d.Id == id); - } - } - - public async Task All(CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - return _dialogues.ToArray(); - } - } - - public async Task Remove(Dialogue dialogue, CancellationToken cancellationToken) - { - using (await _semaphore.LockAsync(cancellationToken)) - { - _dialogues.Remove(dialogue); - } - } -} diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.Designer.cs new file mode 100644 index 0000000..2e43b38 --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.Designer.cs @@ -0,0 +1,462 @@ +// +using System; +using System.Collections.Generic; +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.PostgreSql +{ + [DbContext(typeof(PostgreSqlCpdlcDbContext))] + [Migration("20261107042236_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("CPDLCServer.AcarsConnections.ConnectionSettings.AcarsConnectionSettings", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("DefaultAdscReportingInterval") + .HasColumnType("integer"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("EncryptedAuthenticationCode") + .IsRequired() + .HasColumnType("text"); + + b.Property("FlightSimulationNetwork") + .IsRequired() + .HasColumnType("text"); + + b.Property("Notes") + .HasColumnType("text"); + + b.Property("SelectedAdscContractDuration") + .HasColumnType("integer"); + + b.Property("StationIdentifier") + .IsRequired() + .HasColumnType("text"); + + b.Property("Type") + .IsRequired() + .HasColumnType("text"); + + b.Property("Url") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("StationIdentifier") + .IsUnique(); + + b.ToTable("AcarsConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.AdscContract", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("DefaultContractState") + .HasColumnType("text"); + + b.Property("DemandContractState") + .HasColumnType("text"); + + b.Property("LastActivity") + .HasColumnType("bigint"); + + b.Property("ReportingInterval") + .HasColumnType("bigint"); + + b.Property("SelectedContractEnds") + .HasColumnType("bigint"); + + b.Property("SelectedContractState") + .HasColumnType("text"); + + b.Property("SelectedReportingInterval") + .HasColumnType("bigint"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId"); + + b.ToTable("AdscContracts", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.Reports.AircraftAdscReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsLatest") + .HasColumnType("boolean"); + + b.Property("Received") + .HasColumnType("bigint"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => + { + b1.IsRequired(); + + b1.Property("Altitude") + .HasColumnType("integer") + .HasColumnName("Altitude"); + + b1.Property("Latitude") + .HasColumnType("double precision") + .HasColumnName("Latitude"); + + b1.Property("Longitude") + .HasColumnType("double precision") + .HasColumnName("Longitude"); + + b1.Property("Source") + .IsRequired() + .HasColumnType("text") + .HasColumnName("Source"); + + b1.Property("Timestamp") + .HasColumnType("bigint") + .HasColumnName("Timestamp"); + }); + + b.HasKey("Id"); + + b.HasIndex("Callsign"); + + b.HasIndex("Received"); + + b.ToTable("AdscReports", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.Users.User", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("Created") + .HasColumnType("bigint"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AcarsConnectionId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("ConnectionState") + .IsRequired() + .HasColumnType("text"); + + b.Property("DataAuthorityState") + .IsRequired() + .HasColumnType("text"); + + b.Property("DidSentNextDataAuthorityMessage") + .HasColumnType("boolean"); + + b.Property("ExpectedTransferTime") + .HasColumnType("bigint"); + + b.Property("LastSeen") + .HasColumnType("bigint"); + + b.Property("LogonAccepted") + .HasColumnType("bigint"); + + b.Property("LogonRequested") + .HasColumnType("bigint"); + + b.Property("NextDataAuthority") + .HasColumnType("text"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "AcarsConnectionId"); + + b.ToTable("AircraftConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Acknowledged") + .HasColumnType("bigint"); + + b.Property("AlertType") + .IsRequired() + .HasColumnType("text"); + + b.Property("Closed") + .HasColumnType("bigint"); + + b.Property("DialogueId") + .HasColumnType("uuid"); + + b.Property("Direction") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("character varying(13)"); + + b.Property("MessageId") + .HasColumnType("integer"); + + b.Property("MessageReference") + .HasColumnType("integer"); + + b.Property("Position") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DialogueId"); + + b.ToTable("CpdlcMessages", (string)null); + + b.HasDiscriminator("Direction").HasValue("CpdlcMessage"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("AircraftCallsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Archived") + .HasColumnType("bigint"); + + b.Property("Closed") + .HasColumnType("bigint"); + + b.Property("Opened") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("AircraftCallsign"); + + b.ToTable("Dialogues", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.MessageIdSequence", b => + { + b.Property("AcarsConnectionId") + .HasColumnType("text"); + + b.Property("Callsign") + .HasColumnType("text"); + + b.Property("LastMessageId") + .HasColumnType("integer"); + + b.HasKey("AcarsConnectionId", "Callsign"); + + b.ToTable("MessageIdSequences", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Settings.ServerSettings", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdscContractTimeoutMinutes") + .HasColumnType("integer"); + + b.Property("AdscReportRetentionHours") + .HasColumnType("integer"); + + b.Property("AircraftConnectionTimeoutMinutes") + .HasColumnType("integer"); + + b.Property("ConnectivityCheckIntervalMinutes") + .HasColumnType("integer"); + + b.Property("HandoffNotificationLeadTimeMinutes") + .HasColumnType("integer"); + + b.Property("VatsimStatusAllowNonEquippedAircraft") + .HasColumnType("boolean"); + + b.Property("VatsimStatusEnabled") + .HasColumnType("boolean"); + + b.Property("VatsimStatusPollingIntervalSeconds") + .HasColumnType("integer"); + + b.Property("VatsimStatusUrl") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("ServerSettings", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Downlinks.DownlinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("text") + .HasColumnName("Content"); + + b.Property("IsControllerLate") + .HasColumnType("boolean"); + + b.Property("Received") + .HasColumnType("bigint"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("DownlinkResponseType"); + + b.Property("Sender") + .IsRequired() + .HasColumnType("text"); + + b.HasDiscriminator().HasValue("Downlink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.UplinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("ClosedManually") + .HasColumnType("boolean"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("text") + .HasColumnName("Content"); + + b.Property("IsPilotLate") + .HasColumnType("boolean"); + + b.Property("IsTransmissionFailed") + .HasColumnType("boolean"); + + b.Property("Recipient") + .IsRequired() + .HasColumnType("text"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("UplinkResponseType"); + + b.Property("SenderCallsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Sent") + .HasColumnType("bigint"); + + b.HasDiscriminator().HasValue("Uplink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.HasOne("CPDLCServer.Cpdlc.Dialogues.Dialogue", null) + .WithMany("Messages") + .HasForeignKey("DialogueId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Navigation("Messages"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.cs new file mode 100644 index 0000000..31c11a2 --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.cs @@ -0,0 +1,275 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.PostgreSql +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AcarsConnections", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Type = table.Column(type: "text", nullable: false), + Enabled = table.Column(type: "boolean", nullable: false), + StationIdentifier = table.Column(type: "text", nullable: false), + FlightSimulationNetwork = table.Column(type: "text", nullable: false), + Url = table.Column(type: "text", nullable: false), + EncryptedAuthenticationCode = table.Column(type: "text", nullable: false), + DefaultAdscReportingInterval = table.Column(type: "integer", nullable: false), + SelectedAdscContractDuration = table.Column(type: "integer", nullable: false), + Notes = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AcarsConnections", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AdscContracts", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Callsign = table.Column(type: "text", nullable: false), + StationId = table.Column(type: "text", nullable: false), + ReportingInterval = table.Column(type: "bigint", nullable: true), + DefaultContractState = table.Column(type: "text", nullable: true), + SelectedReportingInterval = table.Column(type: "bigint", nullable: true), + SelectedContractState = table.Column(type: "text", nullable: true), + SelectedContractEnds = table.Column(type: "bigint", nullable: true), + DemandContractState = table.Column(type: "text", nullable: true), + LastActivity = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AdscContracts", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AdscReports", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Callsign = table.Column(type: "text", nullable: false), + StationId = table.Column(type: "text", nullable: false), + Received = table.Column(type: "bigint", nullable: false), + IsLatest = table.Column(type: "boolean", nullable: false), + Altitude = table.Column(type: "integer", nullable: false), + Latitude = table.Column(type: "double precision", nullable: false), + Longitude = table.Column(type: "double precision", nullable: false), + Source = table.Column(type: "text", nullable: false), + Timestamp = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AdscReports", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AircraftConnections", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Callsign = table.Column(type: "text", nullable: false), + AcarsConnectionId = table.Column(type: "text", nullable: false), + StationId = table.Column(type: "text", nullable: false), + DataAuthorityState = table.Column(type: "text", nullable: false), + ConnectionState = table.Column(type: "text", nullable: false), + LogonRequested = table.Column(type: "bigint", nullable: false), + LogonAccepted = table.Column(type: "bigint", nullable: true), + LastSeen = table.Column(type: "bigint", nullable: false), + NextDataAuthority = table.Column(type: "text", nullable: true), + ExpectedTransferTime = table.Column(type: "bigint", nullable: true), + DidSentNextDataAuthorityMessage = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AircraftConnections", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Dialogues", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + AircraftCallsign = table.Column(type: "text", nullable: false), + Opened = table.Column(type: "bigint", nullable: false), + Closed = table.Column(type: "bigint", nullable: true), + Archived = table.Column(type: "bigint", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Dialogues", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "MessageIdSequences", + columns: table => new + { + AcarsConnectionId = table.Column(type: "text", nullable: false), + Callsign = table.Column(type: "text", nullable: false), + LastMessageId = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MessageIdSequences", x => new { x.AcarsConnectionId, x.Callsign }); + }); + + migrationBuilder.CreateTable( + name: "ServerSettings", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ConnectivityCheckIntervalMinutes = table.Column(type: "integer", nullable: false), + AircraftConnectionTimeoutMinutes = table.Column(type: "integer", nullable: false), + AdscContractTimeoutMinutes = table.Column(type: "integer", nullable: false), + AdscReportRetentionHours = table.Column(type: "integer", nullable: false), + HandoffNotificationLeadTimeMinutes = table.Column(type: "integer", nullable: false), + VatsimStatusEnabled = table.Column(type: "boolean", nullable: false), + VatsimStatusUrl = table.Column(type: "text", nullable: false), + VatsimStatusPollingIntervalSeconds = table.Column(type: "integer", nullable: false), + VatsimStatusAllowNonEquippedAircraft = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ServerSettings", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Username = table.Column(type: "text", nullable: false), + PasswordHash = table.Column(type: "text", nullable: false), + Created = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "CpdlcMessages", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + DialogueId = table.Column(type: "uuid", nullable: false), + MessageId = table.Column(type: "integer", nullable: false), + MessageReference = table.Column(type: "integer", nullable: true), + AlertType = table.Column(type: "text", nullable: false), + Position = table.Column(type: "integer", nullable: false), + Closed = table.Column(type: "bigint", nullable: true), + Acknowledged = table.Column(type: "bigint", nullable: true), + Direction = table.Column(type: "character varying(13)", maxLength: 13, nullable: false), + Sender = table.Column(type: "text", nullable: true), + DownlinkResponseType = table.Column(type: "text", nullable: true), + Content = table.Column(type: "text", nullable: true), + Received = table.Column(type: "bigint", nullable: true), + IsControllerLate = table.Column(type: "boolean", nullable: true), + Recipient = table.Column(type: "text", nullable: true), + SenderCallsign = table.Column(type: "text", nullable: true), + UplinkResponseType = table.Column(type: "text", nullable: true), + Sent = table.Column(type: "bigint", nullable: true), + ClosedManually = table.Column(type: "boolean", nullable: true), + IsPilotLate = table.Column(type: "boolean", nullable: true), + IsTransmissionFailed = table.Column(type: "boolean", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_CpdlcMessages", x => x.Id); + table.ForeignKey( + name: "FK_CpdlcMessages_Dialogues_DialogueId", + column: x => x.DialogueId, + principalTable: "Dialogues", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AcarsConnections_StationIdentifier", + table: "AcarsConnections", + column: "StationIdentifier", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AdscContracts_Callsign_StationId", + table: "AdscContracts", + columns: new[] { "Callsign", "StationId" }); + + migrationBuilder.CreateIndex( + name: "IX_AdscReports_Callsign", + table: "AdscReports", + column: "Callsign"); + + migrationBuilder.CreateIndex( + name: "IX_AdscReports_Received", + table: "AdscReports", + column: "Received"); + + migrationBuilder.CreateIndex( + name: "IX_AircraftConnections_Callsign_AcarsConnectionId", + table: "AircraftConnections", + columns: new[] { "Callsign", "AcarsConnectionId" }); + + migrationBuilder.CreateIndex( + name: "IX_CpdlcMessages_DialogueId", + table: "CpdlcMessages", + column: "DialogueId"); + + migrationBuilder.CreateIndex( + name: "IX_Dialogues_AircraftCallsign", + table: "Dialogues", + column: "AircraftCallsign"); + + migrationBuilder.CreateIndex( + name: "IX_Users_Username", + table: "Users", + column: "Username", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AcarsConnections"); + + migrationBuilder.DropTable( + name: "AdscContracts"); + + migrationBuilder.DropTable( + name: "AdscReports"); + + migrationBuilder.DropTable( + name: "AircraftConnections"); + + migrationBuilder.DropTable( + name: "CpdlcMessages"); + + migrationBuilder.DropTable( + name: "MessageIdSequences"); + + migrationBuilder.DropTable( + name: "ServerSettings"); + + migrationBuilder.DropTable( + name: "Users"); + + migrationBuilder.DropTable( + name: "Dialogues"); + } + } +} diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs new file mode 100644 index 0000000..e2e3d59 --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs @@ -0,0 +1,459 @@ +// +using System; +using System.Collections.Generic; +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.PostgreSql +{ + [DbContext(typeof(PostgreSqlCpdlcDbContext))] + partial class PostgreSqlCpdlcDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("CPDLCServer.AcarsConnections.ConnectionSettings.AcarsConnectionSettings", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("DefaultAdscReportingInterval") + .HasColumnType("integer"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("EncryptedAuthenticationCode") + .IsRequired() + .HasColumnType("text"); + + b.Property("FlightSimulationNetwork") + .IsRequired() + .HasColumnType("text"); + + b.Property("Notes") + .HasColumnType("text"); + + b.Property("SelectedAdscContractDuration") + .HasColumnType("integer"); + + b.Property("StationIdentifier") + .IsRequired() + .HasColumnType("text"); + + b.Property("Type") + .IsRequired() + .HasColumnType("text"); + + b.Property("Url") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("StationIdentifier") + .IsUnique(); + + b.ToTable("AcarsConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.AdscContract", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("DefaultContractState") + .HasColumnType("text"); + + b.Property("DemandContractState") + .HasColumnType("text"); + + b.Property("LastActivity") + .HasColumnType("bigint"); + + b.Property("ReportingInterval") + .HasColumnType("bigint"); + + b.Property("SelectedContractEnds") + .HasColumnType("bigint"); + + b.Property("SelectedContractState") + .HasColumnType("text"); + + b.Property("SelectedReportingInterval") + .HasColumnType("bigint"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId"); + + b.ToTable("AdscContracts", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.Reports.AircraftAdscReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsLatest") + .HasColumnType("boolean"); + + b.Property("Received") + .HasColumnType("bigint"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => + { + b1.IsRequired(); + + b1.Property("Altitude") + .HasColumnType("integer") + .HasColumnName("Altitude"); + + b1.Property("Latitude") + .HasColumnType("double precision") + .HasColumnName("Latitude"); + + b1.Property("Longitude") + .HasColumnType("double precision") + .HasColumnName("Longitude"); + + b1.Property("Source") + .IsRequired() + .HasColumnType("text") + .HasColumnName("Source"); + + b1.Property("Timestamp") + .HasColumnType("bigint") + .HasColumnName("Timestamp"); + }); + + b.HasKey("Id"); + + b.HasIndex("Callsign"); + + b.HasIndex("Received"); + + b.ToTable("AdscReports", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.Users.User", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("Created") + .HasColumnType("bigint"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AcarsConnectionId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("ConnectionState") + .IsRequired() + .HasColumnType("text"); + + b.Property("DataAuthorityState") + .IsRequired() + .HasColumnType("text"); + + b.Property("DidSentNextDataAuthorityMessage") + .HasColumnType("boolean"); + + b.Property("ExpectedTransferTime") + .HasColumnType("bigint"); + + b.Property("LastSeen") + .HasColumnType("bigint"); + + b.Property("LogonAccepted") + .HasColumnType("bigint"); + + b.Property("LogonRequested") + .HasColumnType("bigint"); + + b.Property("NextDataAuthority") + .HasColumnType("text"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "AcarsConnectionId"); + + b.ToTable("AircraftConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Acknowledged") + .HasColumnType("bigint"); + + b.Property("AlertType") + .IsRequired() + .HasColumnType("text"); + + b.Property("Closed") + .HasColumnType("bigint"); + + b.Property("DialogueId") + .HasColumnType("uuid"); + + b.Property("Direction") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("character varying(13)"); + + b.Property("MessageId") + .HasColumnType("integer"); + + b.Property("MessageReference") + .HasColumnType("integer"); + + b.Property("Position") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DialogueId"); + + b.ToTable("CpdlcMessages", (string)null); + + b.HasDiscriminator("Direction").HasValue("CpdlcMessage"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("AircraftCallsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Archived") + .HasColumnType("bigint"); + + b.Property("Closed") + .HasColumnType("bigint"); + + b.Property("Opened") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("AircraftCallsign"); + + b.ToTable("Dialogues", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.MessageIdSequence", b => + { + b.Property("AcarsConnectionId") + .HasColumnType("text"); + + b.Property("Callsign") + .HasColumnType("text"); + + b.Property("LastMessageId") + .HasColumnType("integer"); + + b.HasKey("AcarsConnectionId", "Callsign"); + + b.ToTable("MessageIdSequences", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Settings.ServerSettings", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AdscContractTimeoutMinutes") + .HasColumnType("integer"); + + b.Property("AdscReportRetentionHours") + .HasColumnType("integer"); + + b.Property("AircraftConnectionTimeoutMinutes") + .HasColumnType("integer"); + + b.Property("ConnectivityCheckIntervalMinutes") + .HasColumnType("integer"); + + b.Property("HandoffNotificationLeadTimeMinutes") + .HasColumnType("integer"); + + b.Property("VatsimStatusAllowNonEquippedAircraft") + .HasColumnType("boolean"); + + b.Property("VatsimStatusEnabled") + .HasColumnType("boolean"); + + b.Property("VatsimStatusPollingIntervalSeconds") + .HasColumnType("integer"); + + b.Property("VatsimStatusUrl") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("ServerSettings", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Downlinks.DownlinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("text") + .HasColumnName("Content"); + + b.Property("IsControllerLate") + .HasColumnType("boolean"); + + b.Property("Received") + .HasColumnType("bigint"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("DownlinkResponseType"); + + b.Property("Sender") + .IsRequired() + .HasColumnType("text"); + + b.HasDiscriminator().HasValue("Downlink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.UplinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("ClosedManually") + .HasColumnType("boolean"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("text") + .HasColumnName("Content"); + + b.Property("IsPilotLate") + .HasColumnType("boolean"); + + b.Property("IsTransmissionFailed") + .HasColumnType("boolean"); + + b.Property("Recipient") + .IsRequired() + .HasColumnType("text"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("UplinkResponseType"); + + b.Property("SenderCallsign") + .IsRequired() + .HasColumnType("text"); + + b.Property("Sent") + .HasColumnType("bigint"); + + b.HasDiscriminator().HasValue("Uplink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.HasOne("CPDLCServer.Cpdlc.Dialogues.Dialogue", null) + .WithMany("Messages") + .HasForeignKey("DialogueId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Navigation("Messages"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.Designer.cs new file mode 100644 index 0000000..8e3c78b --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.Designer.cs @@ -0,0 +1,447 @@ +// +using System; +using System.Collections.Generic; +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.Sqlite +{ + [DbContext(typeof(SqliteCpdlcDbContext))] + [Migration("20261107042233_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.14"); + + modelBuilder.Entity("CPDLCServer.AcarsConnections.ConnectionSettings.AcarsConnectionSettings", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("DefaultAdscReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("EncryptedAuthenticationCode") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FlightSimulationNetwork") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Notes") + .HasColumnType("TEXT"); + + b.Property("SelectedAdscContractDuration") + .HasColumnType("INTEGER"); + + b.Property("StationIdentifier") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Url") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("StationIdentifier") + .IsUnique(); + + b.ToTable("AcarsConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.AdscContract", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("DefaultContractState") + .HasColumnType("TEXT"); + + b.Property("DemandContractState") + .HasColumnType("TEXT"); + + b.Property("LastActivity") + .HasColumnType("INTEGER"); + + b.Property("ReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("SelectedContractEnds") + .HasColumnType("INTEGER"); + + b.Property("SelectedContractState") + .HasColumnType("TEXT"); + + b.Property("SelectedReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId"); + + b.ToTable("AdscContracts", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.Reports.AircraftAdscReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IsLatest") + .HasColumnType("INTEGER"); + + b.Property("Received") + .HasColumnType("INTEGER"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => + { + b1.IsRequired(); + + b1.Property("Altitude") + .HasColumnType("INTEGER") + .HasColumnName("Altitude"); + + b1.Property("Latitude") + .HasColumnType("REAL") + .HasColumnName("Latitude"); + + b1.Property("Longitude") + .HasColumnType("REAL") + .HasColumnName("Longitude"); + + b1.Property("Source") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("Source"); + + b1.Property("Timestamp") + .HasColumnType("INTEGER") + .HasColumnName("Timestamp"); + }); + + b.HasKey("Id"); + + b.HasIndex("Callsign"); + + b.HasIndex("Received"); + + b.ToTable("AdscReports", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.Users.User", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AcarsConnectionId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ConnectionState") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("DataAuthorityState") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("DidSentNextDataAuthorityMessage") + .HasColumnType("INTEGER"); + + b.Property("ExpectedTransferTime") + .HasColumnType("INTEGER"); + + b.Property("LastSeen") + .HasColumnType("INTEGER"); + + b.Property("LogonAccepted") + .HasColumnType("INTEGER"); + + b.Property("LogonRequested") + .HasColumnType("INTEGER"); + + b.Property("NextDataAuthority") + .HasColumnType("TEXT"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "AcarsConnectionId"); + + b.ToTable("AircraftConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Acknowledged") + .HasColumnType("INTEGER"); + + b.Property("AlertType") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Closed") + .HasColumnType("INTEGER"); + + b.Property("DialogueId") + .HasColumnType("TEXT"); + + b.Property("Direction") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT"); + + b.Property("MessageId") + .HasColumnType("INTEGER"); + + b.Property("MessageReference") + .HasColumnType("INTEGER"); + + b.Property("Position") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("DialogueId"); + + b.ToTable("CpdlcMessages", (string)null); + + b.HasDiscriminator("Direction").HasValue("CpdlcMessage"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AircraftCallsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Archived") + .HasColumnType("INTEGER"); + + b.Property("Closed") + .HasColumnType("INTEGER"); + + b.Property("Opened") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AircraftCallsign"); + + b.ToTable("Dialogues", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.MessageIdSequence", b => + { + b.Property("AcarsConnectionId") + .HasColumnType("TEXT"); + + b.Property("Callsign") + .HasColumnType("TEXT"); + + b.Property("LastMessageId") + .HasColumnType("INTEGER"); + + b.HasKey("AcarsConnectionId", "Callsign"); + + b.ToTable("MessageIdSequences", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Settings.ServerSettings", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdscContractTimeoutMinutes") + .HasColumnType("INTEGER"); + + b.Property("AdscReportRetentionHours") + .HasColumnType("INTEGER"); + + b.Property("AircraftConnectionTimeoutMinutes") + .HasColumnType("INTEGER"); + + b.Property("ConnectivityCheckIntervalMinutes") + .HasColumnType("INTEGER"); + + b.Property("HandoffNotificationLeadTimeMinutes") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusAllowNonEquippedAircraft") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusEnabled") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusPollingIntervalSeconds") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusUrl") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("ServerSettings", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Downlinks.DownlinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("TEXT") + .HasColumnName("Content"); + + b.Property("IsControllerLate") + .HasColumnType("INTEGER"); + + b.Property("Received") + .HasColumnType("INTEGER"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("DownlinkResponseType"); + + b.Property("Sender") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("Downlink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.UplinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("ClosedManually") + .HasColumnType("INTEGER"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("TEXT") + .HasColumnName("Content"); + + b.Property("IsPilotLate") + .HasColumnType("INTEGER"); + + b.Property("IsTransmissionFailed") + .HasColumnType("INTEGER"); + + b.Property("Recipient") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("UplinkResponseType"); + + b.Property("SenderCallsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Sent") + .HasColumnType("INTEGER"); + + b.HasDiscriminator().HasValue("Uplink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.HasOne("CPDLCServer.Cpdlc.Dialogues.Dialogue", null) + .WithMany("Messages") + .HasForeignKey("DialogueId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Navigation("Messages"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.cs new file mode 100644 index 0000000..887bdd3 --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.cs @@ -0,0 +1,274 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.Sqlite +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AcarsConnections", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Type = table.Column(type: "TEXT", nullable: false), + Enabled = table.Column(type: "INTEGER", nullable: false), + StationIdentifier = table.Column(type: "TEXT", nullable: false), + FlightSimulationNetwork = table.Column(type: "TEXT", nullable: false), + Url = table.Column(type: "TEXT", nullable: false), + EncryptedAuthenticationCode = table.Column(type: "TEXT", nullable: false), + DefaultAdscReportingInterval = table.Column(type: "INTEGER", nullable: false), + SelectedAdscContractDuration = table.Column(type: "INTEGER", nullable: false), + Notes = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AcarsConnections", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AdscContracts", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Callsign = table.Column(type: "TEXT", nullable: false), + StationId = table.Column(type: "TEXT", nullable: false), + ReportingInterval = table.Column(type: "INTEGER", nullable: true), + DefaultContractState = table.Column(type: "TEXT", nullable: true), + SelectedReportingInterval = table.Column(type: "INTEGER", nullable: true), + SelectedContractState = table.Column(type: "TEXT", nullable: true), + SelectedContractEnds = table.Column(type: "INTEGER", nullable: true), + DemandContractState = table.Column(type: "TEXT", nullable: true), + LastActivity = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AdscContracts", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AdscReports", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Callsign = table.Column(type: "TEXT", nullable: false), + StationId = table.Column(type: "TEXT", nullable: false), + Received = table.Column(type: "INTEGER", nullable: false), + IsLatest = table.Column(type: "INTEGER", nullable: false), + Altitude = table.Column(type: "INTEGER", nullable: false), + Latitude = table.Column(type: "REAL", nullable: false), + Longitude = table.Column(type: "REAL", nullable: false), + Source = table.Column(type: "TEXT", nullable: false), + Timestamp = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AdscReports", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AircraftConnections", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Callsign = table.Column(type: "TEXT", nullable: false), + AcarsConnectionId = table.Column(type: "TEXT", nullable: false), + StationId = table.Column(type: "TEXT", nullable: false), + DataAuthorityState = table.Column(type: "TEXT", nullable: false), + ConnectionState = table.Column(type: "TEXT", nullable: false), + LogonRequested = table.Column(type: "INTEGER", nullable: false), + LogonAccepted = table.Column(type: "INTEGER", nullable: true), + LastSeen = table.Column(type: "INTEGER", nullable: false), + NextDataAuthority = table.Column(type: "TEXT", nullable: true), + ExpectedTransferTime = table.Column(type: "INTEGER", nullable: true), + DidSentNextDataAuthorityMessage = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AircraftConnections", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Dialogues", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + AircraftCallsign = table.Column(type: "TEXT", nullable: false), + Opened = table.Column(type: "INTEGER", nullable: false), + Closed = table.Column(type: "INTEGER", nullable: true), + Archived = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Dialogues", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "MessageIdSequences", + columns: table => new + { + AcarsConnectionId = table.Column(type: "TEXT", nullable: false), + Callsign = table.Column(type: "TEXT", nullable: false), + LastMessageId = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_MessageIdSequences", x => new { x.AcarsConnectionId, x.Callsign }); + }); + + migrationBuilder.CreateTable( + name: "ServerSettings", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ConnectivityCheckIntervalMinutes = table.Column(type: "INTEGER", nullable: false), + AircraftConnectionTimeoutMinutes = table.Column(type: "INTEGER", nullable: false), + AdscContractTimeoutMinutes = table.Column(type: "INTEGER", nullable: false), + AdscReportRetentionHours = table.Column(type: "INTEGER", nullable: false), + HandoffNotificationLeadTimeMinutes = table.Column(type: "INTEGER", nullable: false), + VatsimStatusEnabled = table.Column(type: "INTEGER", nullable: false), + VatsimStatusUrl = table.Column(type: "TEXT", nullable: false), + VatsimStatusPollingIntervalSeconds = table.Column(type: "INTEGER", nullable: false), + VatsimStatusAllowNonEquippedAircraft = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ServerSettings", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Username = table.Column(type: "TEXT", nullable: false), + PasswordHash = table.Column(type: "TEXT", nullable: false), + Created = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "CpdlcMessages", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + DialogueId = table.Column(type: "TEXT", nullable: false), + MessageId = table.Column(type: "INTEGER", nullable: false), + MessageReference = table.Column(type: "INTEGER", nullable: true), + AlertType = table.Column(type: "TEXT", nullable: false), + Position = table.Column(type: "INTEGER", nullable: false), + Closed = table.Column(type: "INTEGER", nullable: true), + Acknowledged = table.Column(type: "INTEGER", nullable: true), + Direction = table.Column(type: "TEXT", maxLength: 13, nullable: false), + Sender = table.Column(type: "TEXT", nullable: true), + DownlinkResponseType = table.Column(type: "TEXT", nullable: true), + Content = table.Column(type: "TEXT", nullable: true), + Received = table.Column(type: "INTEGER", nullable: true), + IsControllerLate = table.Column(type: "INTEGER", nullable: true), + Recipient = table.Column(type: "TEXT", nullable: true), + SenderCallsign = table.Column(type: "TEXT", nullable: true), + UplinkResponseType = table.Column(type: "TEXT", nullable: true), + Sent = table.Column(type: "INTEGER", nullable: true), + ClosedManually = table.Column(type: "INTEGER", nullable: true), + IsPilotLate = table.Column(type: "INTEGER", nullable: true), + IsTransmissionFailed = table.Column(type: "INTEGER", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_CpdlcMessages", x => x.Id); + table.ForeignKey( + name: "FK_CpdlcMessages_Dialogues_DialogueId", + column: x => x.DialogueId, + principalTable: "Dialogues", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AcarsConnections_StationIdentifier", + table: "AcarsConnections", + column: "StationIdentifier", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AdscContracts_Callsign_StationId", + table: "AdscContracts", + columns: new[] { "Callsign", "StationId" }); + + migrationBuilder.CreateIndex( + name: "IX_AdscReports_Callsign", + table: "AdscReports", + column: "Callsign"); + + migrationBuilder.CreateIndex( + name: "IX_AdscReports_Received", + table: "AdscReports", + column: "Received"); + + migrationBuilder.CreateIndex( + name: "IX_AircraftConnections_Callsign_AcarsConnectionId", + table: "AircraftConnections", + columns: new[] { "Callsign", "AcarsConnectionId" }); + + migrationBuilder.CreateIndex( + name: "IX_CpdlcMessages_DialogueId", + table: "CpdlcMessages", + column: "DialogueId"); + + migrationBuilder.CreateIndex( + name: "IX_Dialogues_AircraftCallsign", + table: "Dialogues", + column: "AircraftCallsign"); + + migrationBuilder.CreateIndex( + name: "IX_Users_Username", + table: "Users", + column: "Username", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AcarsConnections"); + + migrationBuilder.DropTable( + name: "AdscContracts"); + + migrationBuilder.DropTable( + name: "AdscReports"); + + migrationBuilder.DropTable( + name: "AircraftConnections"); + + migrationBuilder.DropTable( + name: "CpdlcMessages"); + + migrationBuilder.DropTable( + name: "MessageIdSequences"); + + migrationBuilder.DropTable( + name: "ServerSettings"); + + migrationBuilder.DropTable( + name: "Users"); + + migrationBuilder.DropTable( + name: "Dialogues"); + } + } +} diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs new file mode 100644 index 0000000..ffdc58d --- /dev/null +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs @@ -0,0 +1,444 @@ +// +using System; +using System.Collections.Generic; +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace CPDLCServer.Persistence.Migrations.Sqlite +{ + [DbContext(typeof(SqliteCpdlcDbContext))] + partial class SqliteCpdlcDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.14"); + + modelBuilder.Entity("CPDLCServer.AcarsConnections.ConnectionSettings.AcarsConnectionSettings", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("DefaultAdscReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("EncryptedAuthenticationCode") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FlightSimulationNetwork") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Notes") + .HasColumnType("TEXT"); + + b.Property("SelectedAdscContractDuration") + .HasColumnType("INTEGER"); + + b.Property("StationIdentifier") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Url") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("StationIdentifier") + .IsUnique(); + + b.ToTable("AcarsConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.AdscContract", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("DefaultContractState") + .HasColumnType("TEXT"); + + b.Property("DemandContractState") + .HasColumnType("TEXT"); + + b.Property("LastActivity") + .HasColumnType("INTEGER"); + + b.Property("ReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("SelectedContractEnds") + .HasColumnType("INTEGER"); + + b.Property("SelectedContractState") + .HasColumnType("TEXT"); + + b.Property("SelectedReportingInterval") + .HasColumnType("INTEGER"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "StationId"); + + b.ToTable("AdscContracts", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.AdscContracts.Reports.AircraftAdscReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IsLatest") + .HasColumnType("INTEGER"); + + b.Property("Received") + .HasColumnType("INTEGER"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => + { + b1.IsRequired(); + + b1.Property("Altitude") + .HasColumnType("INTEGER") + .HasColumnName("Altitude"); + + b1.Property("Latitude") + .HasColumnType("REAL") + .HasColumnName("Latitude"); + + b1.Property("Longitude") + .HasColumnType("REAL") + .HasColumnName("Longitude"); + + b1.Property("Source") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("Source"); + + b1.Property("Timestamp") + .HasColumnType("INTEGER") + .HasColumnName("Timestamp"); + }); + + b.HasKey("Id"); + + b.HasIndex("Callsign"); + + b.HasIndex("Received"); + + b.ToTable("AdscReports", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.Users.User", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AcarsConnectionId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Callsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ConnectionState") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("DataAuthorityState") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("DidSentNextDataAuthorityMessage") + .HasColumnType("INTEGER"); + + b.Property("ExpectedTransferTime") + .HasColumnType("INTEGER"); + + b.Property("LastSeen") + .HasColumnType("INTEGER"); + + b.Property("LogonAccepted") + .HasColumnType("INTEGER"); + + b.Property("LogonRequested") + .HasColumnType("INTEGER"); + + b.Property("NextDataAuthority") + .HasColumnType("TEXT"); + + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Callsign", "AcarsConnectionId"); + + b.ToTable("AircraftConnections", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Acknowledged") + .HasColumnType("INTEGER"); + + b.Property("AlertType") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Closed") + .HasColumnType("INTEGER"); + + b.Property("DialogueId") + .HasColumnType("TEXT"); + + b.Property("Direction") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT"); + + b.Property("MessageId") + .HasColumnType("INTEGER"); + + b.Property("MessageReference") + .HasColumnType("INTEGER"); + + b.Property("Position") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("DialogueId"); + + b.ToTable("CpdlcMessages", (string)null); + + b.HasDiscriminator("Direction").HasValue("CpdlcMessage"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AircraftCallsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Archived") + .HasColumnType("INTEGER"); + + b.Property("Closed") + .HasColumnType("INTEGER"); + + b.Property("Opened") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("AircraftCallsign"); + + b.ToTable("Dialogues", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.MessageIdSequence", b => + { + b.Property("AcarsConnectionId") + .HasColumnType("TEXT"); + + b.Property("Callsign") + .HasColumnType("TEXT"); + + b.Property("LastMessageId") + .HasColumnType("INTEGER"); + + b.HasKey("AcarsConnectionId", "Callsign"); + + b.ToTable("MessageIdSequences", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Settings.ServerSettings", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdscContractTimeoutMinutes") + .HasColumnType("INTEGER"); + + b.Property("AdscReportRetentionHours") + .HasColumnType("INTEGER"); + + b.Property("AircraftConnectionTimeoutMinutes") + .HasColumnType("INTEGER"); + + b.Property("ConnectivityCheckIntervalMinutes") + .HasColumnType("INTEGER"); + + b.Property("HandoffNotificationLeadTimeMinutes") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusAllowNonEquippedAircraft") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusEnabled") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusPollingIntervalSeconds") + .HasColumnType("INTEGER"); + + b.Property("VatsimStatusUrl") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("ServerSettings", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Downlinks.DownlinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("TEXT") + .HasColumnName("Content"); + + b.Property("IsControllerLate") + .HasColumnType("INTEGER"); + + b.Property("Received") + .HasColumnType("INTEGER"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("DownlinkResponseType"); + + b.Property("Sender") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasDiscriminator().HasValue("Downlink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Uplinks.UplinkMessage", b => + { + b.HasBaseType("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage"); + + b.Property("ClosedManually") + .HasColumnType("INTEGER"); + + b.Property("Content") + .IsRequired() + .ValueGeneratedOnUpdateSometimes() + .HasColumnType("TEXT") + .HasColumnName("Content"); + + b.Property("IsPilotLate") + .HasColumnType("INTEGER"); + + b.Property("IsTransmissionFailed") + .HasColumnType("INTEGER"); + + b.Property("Recipient") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ResponseType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnName("UplinkResponseType"); + + b.Property("SenderCallsign") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Sent") + .HasColumnType("INTEGER"); + + b.HasDiscriminator().HasValue("Uplink"); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.CpdlcMessage", b => + { + b.HasOne("CPDLCServer.Cpdlc.Dialogues.Dialogue", null) + .WithMany("Messages") + .HasForeignKey("DialogueId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("CPDLCServer.Cpdlc.Dialogues.Dialogue", b => + { + b.Navigation("Messages"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/source/CPDLCServer/Persistence/PersistenceServiceCollectionExtensions.cs b/source/CPDLCServer/Persistence/PersistenceServiceCollectionExtensions.cs new file mode 100644 index 0000000..2b79d02 --- /dev/null +++ b/source/CPDLCServer/Persistence/PersistenceServiceCollectionExtensions.cs @@ -0,0 +1,41 @@ +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Persistence; + +public static class PersistenceServiceCollectionExtensions +{ + // Registers the context of the provider. The repositories use it as CpdlcDbContext. + public static IServiceCollection AddPersistence( + this IServiceCollection services, + IConfiguration configuration, + DatabaseProvider provider, + string databasePath) + { + switch (provider) + { + case DatabaseProvider.Sqlite: + services.AddDbContext(options => + options.UseSqlite($"Data Source={databasePath}")); + services.AddScoped(sp => sp.GetRequiredService()); + break; + + case DatabaseProvider.PostgreSql: + var connectionString = configuration["DatabaseConnectionString"]; + if (string.IsNullOrWhiteSpace(connectionString)) + throw new Exception("The PostgreSQL database provider needs DatabaseConnectionString."); + + services.AddDbContext(options => + options.UseNpgsql(PostgreSqlConnectionString.Parse(connectionString))); + services.AddScoped(sp => sp.GetRequiredService()); + break; + + default: + throw new ArgumentOutOfRangeException(nameof(provider), provider, null); + } + + services.AddScoped(); + services.AddScoped(sp => sp.GetRequiredService()); + + return services; + } +} diff --git a/source/CPDLCServer/Persistence/PostgreSqlConnectionString.cs b/source/CPDLCServer/Persistence/PostgreSqlConnectionString.cs new file mode 100644 index 0000000..ea000e3 --- /dev/null +++ b/source/CPDLCServer/Persistence/PostgreSqlConnectionString.cs @@ -0,0 +1,40 @@ +using Npgsql; + +namespace CPDLCServer.Persistence; + +public static class PostgreSqlConnectionString +{ + // Npgsql accepts only "Key=Value" connection strings. + // Some platforms, for example DigitalOcean, give a URL (postgresql://user:password@host:port/database?sslmode=require). + // This changes a URL to a "Key=Value" connection string, and does not change other values. + public static string Parse(string value) + { + if (!value.StartsWith("postgres://", StringComparison.OrdinalIgnoreCase) && + !value.StartsWith("postgresql://", StringComparison.OrdinalIgnoreCase)) + return value; + + var uri = new Uri(value); + var builder = new NpgsqlConnectionStringBuilder + { + Host = uri.Host, + Database = Uri.UnescapeDataString(uri.AbsolutePath.TrimStart('/')) + }; + + if (uri.Port > 0) + builder.Port = uri.Port; + + var userInfo = uri.UserInfo.Split(':', 2); + builder.Username = Uri.UnescapeDataString(userInfo[0]); + if (userInfo.Length > 1) + builder.Password = Uri.UnescapeDataString(userInfo[1]); + + foreach (var parameter in uri.Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var parts = parameter.Split('=', 2); + if (parts.Length == 2 && parts[0].Equals("sslmode", StringComparison.OrdinalIgnoreCase)) + builder.SslMode = Enum.Parse(parts[1].Replace("-", string.Empty), ignoreCase: true); + } + + return builder.ConnectionString; + } +} diff --git a/source/CPDLCServer/Persistence/PostgreSqlCpdlcDbContext.cs b/source/CPDLCServer/Persistence/PostgreSqlCpdlcDbContext.cs new file mode 100644 index 0000000..a296be3 --- /dev/null +++ b/source/CPDLCServer/Persistence/PostgreSqlCpdlcDbContext.cs @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace CPDLCServer.Persistence; + +// Has the PostgreSQL migrations (Migrations/PostgreSql) +public class PostgreSqlCpdlcDbContext(DbContextOptions options) : CpdlcDbContext(options); + +// Lets "dotnet ef" make the PostgreSQL migrations without the configuration of the server. +// "dotnet ef migrations add" does not connect to the database. +public class PostgreSqlCpdlcDbContextFactory : IDesignTimeDbContextFactory +{ + public PostgreSqlCpdlcDbContext CreateDbContext(string[] args) + { + var options = new DbContextOptionsBuilder() + .UseNpgsql("Host=localhost;Database=cpdlc") + .Options; + + return new PostgreSqlCpdlcDbContext(options); + } +} diff --git a/source/CPDLCServer/Persistence/SqliteCpdlcDbContext.cs b/source/CPDLCServer/Persistence/SqliteCpdlcDbContext.cs new file mode 100644 index 0000000..071a0db --- /dev/null +++ b/source/CPDLCServer/Persistence/SqliteCpdlcDbContext.cs @@ -0,0 +1,20 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace CPDLCServer.Persistence; + +// Has the SQLite migrations (Migrations/Sqlite) +public class SqliteCpdlcDbContext(DbContextOptions options) : CpdlcDbContext(options); + +// Lets "dotnet ef" make the SQLite migrations without the configuration of the server +public class SqliteCpdlcDbContextFactory : IDesignTimeDbContextFactory +{ + public SqliteCpdlcDbContext CreateDbContext(string[] args) + { + var options = new DbContextOptionsBuilder() + .UseSqlite("Data Source=design-time.db") + .Options; + + return new SqliteCpdlcDbContext(options); + } +} diff --git a/source/CPDLCServer/Persistence/UnitOfWork.cs b/source/CPDLCServer/Persistence/UnitOfWork.cs new file mode 100644 index 0000000..2ce6b8e --- /dev/null +++ b/source/CPDLCServer/Persistence/UnitOfWork.cs @@ -0,0 +1,45 @@ +namespace CPDLCServer.Persistence; + +public interface IUnitOfWork +{ + // Runs the action after the changes are saved. + // Use this for all messages to controllers and aircraft, so that they do not see changes that were not saved. + void AfterCommit(Func action); +} + +// One unit of work for each service scope. +// The changes in all of the repositories are saved together. Then the messages are sent in the order that they were added. +public class UnitOfWork(CpdlcDbContext dbContext) : IUnitOfWork +{ + readonly List> _afterCommitActions = []; + + public void AfterCommit(Func action) + { + _afterCommitActions.Add(action); + } + + public async Task Commit(CancellationToken cancellationToken) + { + await dbContext.SaveChangesAsync(cancellationToken); + + var actions = _afterCommitActions.ToArray(); + _afterCommitActions.Clear(); + + // The changes are saved, so a failure of one message must not stop the other messages + var exceptions = new List(); + foreach (var action in actions) + { + try + { + await action(cancellationToken); + } + catch (Exception ex) + { + exceptions.Add(ex); + } + } + + if (exceptions.Count > 0) + throw new AggregateException("The changes were saved, but one or more messages were not sent", exceptions); + } +} diff --git a/source/CPDLCServer/Persistence/UtcTicksConverter.cs b/source/CPDLCServer/Persistence/UtcTicksConverter.cs new file mode 100644 index 0000000..b2dbbe8 --- /dev/null +++ b/source/CPDLCServer/Persistence/UtcTicksConverter.cs @@ -0,0 +1,8 @@ +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace CPDLCServer.Persistence; + +// Stores a DateTimeOffset as the number of ticks in UTC. The offset is not kept. +public class UtcTicksConverter() : ValueConverter( + value => value.UtcTicks, + value => new DateTimeOffset(value, TimeSpan.Zero)); diff --git a/source/CPDLCServer/Program.cs b/source/CPDLCServer/Program.cs index bd7fff3..3e7c00d 100644 --- a/source/CPDLCServer/Program.cs +++ b/source/CPDLCServer/Program.cs @@ -1,9 +1,20 @@ -using CPDLCServer.Clients; -using CPDLCServer.Hubs; +using CPDLCServer.AcarsConnections; +using CPDLCServer.AdscContracts; +using CPDLCServer.Auth; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc; using CPDLCServer.Infrastructure; +using CPDLCServer.Logging; using CPDLCServer.Persistence; -using CPDLCServer.Services; +using CPDLCServer.Security; +using CPDLCServer.Settings; +using CPDLCServer.Setup; +using CPDLCServer.VatsimStatus; +using CPDLCServer.Web; using DotNetEnv; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.EntityFrameworkCore; using Serilog; using Serilog.Events; @@ -12,9 +23,7 @@ // - Aggregate controller connections for multiple FIRs // - Introduce a Contracts project // - Value types for IDs -// - Improved configuration // - Re-do dashboard -// - Authentication TryLoadEnvFile(); @@ -24,41 +33,47 @@ ConfigureSerilog(builder); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(sp => sp.GetRequiredService()); -builder.Services.AddHostedService(sp => sp.GetRequiredService()); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(builder.Configuration.GetSection("VatsimStatus").Get() ?? new VatsimStatusConfiguration()); -builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly)); -builder.Services.AddSignalR() - .AddJsonProtocol(); -builder.Services.AddRazorPages(); - -builder.Services.AddHostedService(); -builder.Services.AddHostedService(); -builder.Services.AddHostedService(); -builder.Services.AddHostedService(); -builder.Services.AddHostedService(); -builder.Services.AddHostedService(); +// The data directory holds the SQLite database +var dataPath = GetDataPath(builder); + +var databaseProvider = GetDatabaseProvider(builder); +var databasePath = Path.Combine(dataPath, "cpdlc.db"); + +builder.Services.AddInfrastructure(); +builder.Services.AddPersistence(builder.Configuration, databaseProvider, databasePath); +builder.Services.AddSecurity(builder.Configuration); +builder.Services.AddSetup(); +builder.Services.AddAuth(); +builder.Services.AddSettings(); +builder.Services.AddAcarsConnections(); +builder.Services.AddAirTrafficControllers(); +builder.Services.AddCpdlc(); +builder.Services.AddAdscContracts(); +builder.Services.AddVatsimStatus(); +builder.Services.AddWeb(); var app = builder.Build(); +await MigrateDatabase(app, databaseProvider, databasePath); +await SeedServerSettings(app); + +var setupState = app.Services.GetRequiredService(); +await setupState.Load(CancellationToken.None); +app.Lifetime.ApplicationStarted.Register(() => LogSetupUrl(app, setupState)); + app.UseHttpsRedirection(); app.UseRouting(); +app.UseMiddleware(); +app.UseAuthentication(); +app.UseAuthorization(); +app.UseRateLimiter(); + app.MapRazorPages(); app.MapHub("/hubs/controller"); app.MapGet("/health", () => Results.Ok()); +app.MapGet("/logs/stream", LogStreamEndpoint.Handle).RequireAuthorization(); app.Run(); return; @@ -90,6 +105,105 @@ void TryLoadEnvFile() } } +DatabaseProvider GetDatabaseProvider(WebApplicationBuilder builder) +{ + var configuredProvider = builder.Configuration["DatabaseProvider"]; + if (string.IsNullOrWhiteSpace(configuredProvider)) + return DatabaseProvider.Sqlite; + + if (!Enum.TryParse(configuredProvider, ignoreCase: true, out var provider)) + throw new Exception($"The database provider {configuredProvider} is not supported. Use Sqlite or PostgreSql."); + + return provider; +} + +string GetDataPath(WebApplicationBuilder builder) +{ + var configuredPath = builder.Configuration["DataPath"]; + if (!string.IsNullOrWhiteSpace(configuredPath)) + return Path.GetFullPath(configuredPath); + + // For local development, keep the data in the .data directory at the root of the repository + if (builder.Environment.IsDevelopment()) + return Path.Combine(FindRepositoryRoot() ?? Directory.GetCurrentDirectory(), ".data"); + + return "/data"; +} + +string? FindRepositoryRoot() +{ + var currentDir = new DirectoryInfo(Directory.GetCurrentDirectory()); + while (currentDir != null) + { + if (Directory.Exists(Path.Combine(currentDir.FullName, ".git"))) + return currentDir.FullName; + + currentDir = currentDir.Parent; + } + + return null; +} + +void LogSetupUrl(WebApplication app, SetupState setupState) +{ + if (setupState.IsConfigured) + return; + + var setupPath = $"/setup?token={setupState.SetupToken}"; + + var addresses = app.Services.GetRequiredService().Features.Get()?.Addresses ?? []; + if (addresses.Count == 0) + { + Log.Warning("The server is not set up. Open {SetupPath} on this server to set it up", setupPath); + return; + } + + foreach (var address in addresses) + { + // The server can listen on all addresses, for example in Docker. Show an address that a browser can open. + var browserAddress = address + .Replace("://[::]", "://localhost") + .Replace("://0.0.0.0", "://localhost") + .Replace("://+", "://localhost") + .Replace("://*", "://localhost") + .TrimEnd('/'); + + Log.Warning("The server is not set up. Open {SetupUrl} to set it up", browserAddress + setupPath); + } +} + +async Task MigrateDatabase(WebApplication app, DatabaseProvider provider, string databasePath) +{ + await using var scope = app.Services.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + if (provider == DatabaseProvider.Sqlite) + { + // SQLite makes the database file, but not the directory + var databaseDirectory = Path.GetDirectoryName(databasePath); + if (databaseDirectory is not null) + Directory.CreateDirectory(databaseDirectory); + + Log.Information("Using SQLite database {DatabasePath}", databasePath); + } + else + { + // Do not write the connection string to the log, because it contains the password + var connection = dbContext.Database.GetDbConnection(); + Log.Information("Using PostgreSQL database {Database} on {Host}", connection.Database, connection.DataSource); + } + + await dbContext.Database.MigrateAsync(); +} + +// Adds the default settings to the database if they do not exist already +async Task SeedServerSettings(WebApplication app) +{ + await using var scope = app.Services.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().SeedDefaults(CancellationToken.None); + await scope.ServiceProvider.GetRequiredService().Commit(CancellationToken.None); +} + void ConfigureSerilog(WebApplicationBuilder builder) { if (!Enum.TryParse(builder.Configuration["Logging:Level"], out var logLevel)) @@ -97,15 +211,20 @@ void ConfigureSerilog(WebApplicationBuilder builder) logLevel = LogEventLevel.Information; } + // Keeps the recent log entries for the Logs page + var logBuffer = new LogBuffer(); + Log.Logger = new LoggerConfiguration() .MinimumLevel.Is(logLevel) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) .Enrich.FromLogContext() - .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}") + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Sink(new LogBufferSink(logBuffer)) .CreateLogger(); builder.Host.UseSerilog(); builder.Services.AddSingleton(Log.Logger); + builder.Services.AddSingleton(logBuffer); } diff --git a/source/CPDLCServer/Security/MasterKeyEncryption.cs b/source/CPDLCServer/Security/MasterKeyEncryption.cs new file mode 100644 index 0000000..25fa341 --- /dev/null +++ b/source/CPDLCServer/Security/MasterKeyEncryption.cs @@ -0,0 +1,69 @@ +using System.Security.Cryptography; +using System.Text; + +namespace CPDLCServer.Security; + +// Encrypts secrets with AES-GCM and the master key, so that the database does not contain them as plain text. +// The encrypted value is the nonce, the tag and the ciphertext, as Base64 text. +// If the master key changes, the server cannot decrypt the secrets that were encrypted with the old key. +// +// The key comes from the MasterKey environment variable. A missing or invalid key stops the server at startup. +public class MasterKeyEncryption(string masterKey) +{ + const int KeySize = 32; + const int NonceSize = 12; + const int TagSize = 16; + + readonly byte[] _key = ParseKey(masterKey); + + public string Encrypt(string plaintext) + { + var plaintextBytes = Encoding.UTF8.GetBytes(plaintext); + var nonce = RandomNumberGenerator.GetBytes(NonceSize); + var tag = new byte[TagSize]; + var ciphertext = new byte[plaintextBytes.Length]; + + using var aes = new AesGcm(_key, TagSize); + aes.Encrypt(nonce, plaintextBytes, ciphertext, tag); + + return Convert.ToBase64String([..nonce, ..tag, ..ciphertext]); + } + + public string Decrypt(string encrypted) + { + var bytes = Convert.FromBase64String(encrypted); + if (bytes.Length < NonceSize + TagSize) + throw new CryptographicException("The encrypted value is too short"); + + var nonce = bytes.AsSpan(0, NonceSize); + var tag = bytes.AsSpan(NonceSize, TagSize); + var ciphertext = bytes.AsSpan(NonceSize + TagSize); + var plaintextBytes = new byte[ciphertext.Length]; + + using var aes = new AesGcm(_key, TagSize); + aes.Decrypt(nonce, ciphertext, tag, plaintextBytes); + + return Encoding.UTF8.GetString(plaintextBytes); + } + + static byte[] ParseKey(string? masterKey) + { + if (string.IsNullOrWhiteSpace(masterKey)) + throw new Exception("The MasterKey environment variable is not set. Make a key with: openssl rand -base64 32"); + + byte[] key; + try + { + key = Convert.FromBase64String(masterKey); + } + catch (FormatException ex) + { + throw new Exception("The MasterKey environment variable is not valid Base64. Make a key with: openssl rand -base64 32", ex); + } + + if (key.Length != KeySize) + throw new Exception($"The MasterKey environment variable must contain a key of {KeySize} bytes. Make a key with: openssl rand -base64 32"); + + return key; + } +} diff --git a/source/CPDLCServer/Security/SecurityServiceCollectionExtensions.cs b/source/CPDLCServer/Security/SecurityServiceCollectionExtensions.cs new file mode 100644 index 0000000..11f5ddc --- /dev/null +++ b/source/CPDLCServer/Security/SecurityServiceCollectionExtensions.cs @@ -0,0 +1,15 @@ +using CPDLCServer.Infrastructure; + +namespace CPDLCServer.Security; + +public static class SecurityServiceCollectionExtensions +{ + public static IServiceCollection AddSecurity(this IServiceCollection services, IConfiguration configuration) + { + // The master key encrypts the secrets in the database. A missing or invalid MasterKey stops the server. + var masterKey = configuration.GetRequiredValue("MasterKey"); + services.AddSingleton(new MasterKeyEncryption(masterKey)); + + return services; + } +} diff --git a/source/CPDLCServer/Services/IStatisticsService.cs b/source/CPDLCServer/Services/IStatisticsService.cs deleted file mode 100644 index 9b071ed..0000000 --- a/source/CPDLCServer/Services/IStatisticsService.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace CPDLCServer.Services; - -public interface IStatisticsService -{ - ServerStatistics GetCurrentStatistics(); -} - -public class ServerStatistics -{ - public int TotalConnections { get; set; } - public int UniqueNetworks { get; set; } - public int UniqueStations { get; set; } - public List Connections { get; set; } = new(); -} - -public class ConnectionInfo -{ - public required string Network { get; set; } - public required string StationId { get; set; } - public required string Callsign { get; set; } - public required string VatsimCid { get; set; } -} diff --git a/source/CPDLCServer/Services/MessageIdProvider.cs b/source/CPDLCServer/Services/MessageIdProvider.cs deleted file mode 100644 index b9c2548..0000000 --- a/source/CPDLCServer/Services/MessageIdProvider.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace CPDLCServer.Services; - -public interface IMessageIdProvider -{ - Task GetNextMessageId( - string acarsClientId, - string callsign, - CancellationToken cancellationToken); -} - -public class MessageIdProvider : IMessageIdProvider, IDisposable -{ - private readonly Dictionary _ids = new(); - readonly SemaphoreSlim _semaphore = new(1, 1); - - public async Task GetNextMessageId( - string acarsClientId, - string callsign, - CancellationToken cancellationToken) - { - await _semaphore.WaitAsync(cancellationToken); - try - { - var key = new Key(acarsClientId, callsign); - if (!_ids.TryGetValue(key, out var nextId)) - { - nextId = 0; - } - - return _ids[key] = nextId + 1; - } - finally - { - _semaphore.Release(); - } - } - - record Key(string AcarsClientId, string Callsign); - - public void Dispose() - { - _semaphore.Dispose(); - } -} diff --git a/source/CPDLCServer/Services/MessageMonitorService.cs b/source/CPDLCServer/Services/MessageMonitorService.cs deleted file mode 100644 index a877082..0000000 --- a/source/CPDLCServer/Services/MessageMonitorService.cs +++ /dev/null @@ -1,212 +0,0 @@ -using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; -using Microsoft.EntityFrameworkCore.Metadata.Conventions; - -namespace CPDLCServer.Services; - -public class MessageMonitorService( - IDialogueRepository repository, - IAdscMessageLogRepository adscMessageLogRepository, - IAdscReportRepository adscReportRepository, - IClock clock, - IPublisher publisher, - ILogger logger) - : BackgroundService -{ - readonly TimeSpan _timeoutCheckInterval = TimeSpan.FromSeconds(5); - - readonly TimeSpan _pilotLateTimeout = TimeSpan.FromMinutes(2); - readonly TimeSpan _controllerLateTimeout = TimeSpan.FromMinutes(2); - private readonly TimeSpan _archiveDelay = TimeSpan.FromSeconds(10); - readonly TimeSpan _purgeTimeout = TimeSpan.FromHours(24); - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - logger.Information("Starting message monitor service"); - try - { - while (!stoppingToken.IsCancellationRequested) - { - try - { - // TODO: Time out entire dialogues when they take too long - - logger.Verbose("Running message monitor iteration"); - await PurgeOldDialogues(stoppingToken); - await PurgeOldAdscMessages(stoppingToken); - await PurgeOldAdscReports(stoppingToken); - await CheckForTimeouts(stoppingToken); - await ArchiveCompletedDialogues(stoppingToken); - } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { - logger.Verbose("Message monitor task cancellation requested"); - } - catch (Exception ex) - { - logger.Error(ex, "Error during message monitoring iteration"); - } - finally - { - await Task.Delay(_timeoutCheckInterval, stoppingToken); - } - } - } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { - logger.Information("Message monitor task stopped"); - } - catch (Exception ex) - { - logger.Error(ex, "Fatal error in message monitor task"); - } - } - - internal async Task PurgeOldDialogues(CancellationToken cancellationToken) - { - var now = clock.UtcNow(); - var dialogues = await repository.All(cancellationToken); - - foreach (var dialogue in dialogues) - { - var timeSinceOpened = now - dialogue.Opened; - if (timeSinceOpened < _purgeTimeout) - continue; - - // I don't care if it's closed or not. It's been long enough. - await repository.Remove(dialogue, cancellationToken); - logger.Information("Purging dialogue"); // TODO: Dialogue identifier - } - } - - internal async Task PurgeOldAdscMessages(CancellationToken cancellationToken) - { - var cutoff = clock.UtcNow() - _purgeTimeout; - await adscMessageLogRepository.RemoveOlderThan(cutoff, cancellationToken); - } - - internal async Task PurgeOldAdscReports(CancellationToken cancellationToken) - { - var cutoff = clock.UtcNow() - _purgeTimeout; - await adscReportRepository.RemoveOlderThan(cutoff, cancellationToken); - } - - internal async Task CheckForTimeouts(CancellationToken cancellationToken) - { - // TODO: Verify if this is supposed to apply to message closures or acknowledgements. - - var now = clock.UtcNow(); - var dialogues = await repository.All(cancellationToken); - - logger.Verbose("Checking for timeouts in {DialogueCount} dialogues", dialogues.Length); - - foreach (var dialogue in dialogues) - { - if (dialogue.IsClosed) - continue; - - var anyChanges = false; - foreach (var message in dialogue.Messages) - { - switch (message) - { - case UplinkMessage uplink: - if (CheckUplinkTimeout(uplink, now)) - { - anyChanges = true; - } - break; - - case DownlinkMessage downlink: - if (CheckDownlinkTimeout(downlink, now)) - { - anyChanges = true; - } - break; - } - } - - if (anyChanges) - { - await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - } - } - } - - internal async Task ArchiveCompletedDialogues(CancellationToken cancellationToken) - { - var now = clock.UtcNow(); - var dialogues = await repository.All(cancellationToken); - - logger.Verbose("Checking for completed dialogues to archive"); - - foreach (var dialogue in dialogues) - { - if (!dialogue.IsClosed || dialogue.IsArchived) - continue; - - // Ensure all messages are acknowledged before archiving - if (!dialogue.Messages.All(m => m.IsAcknowledged)) - continue; - - // Find the last acknowledged time across all messages - var lastAckTime = dialogue.Messages.Max(m => m.Acknowledged); - - // Take the later of the last acknowledgement time or dialogue closed time - var latest = lastAckTime.Value > dialogue.Closed - ? lastAckTime.Value - : dialogue.Closed; - - var archiveTime = latest.Value.Add(_archiveDelay); - if (now < archiveTime) - continue; - - logger.Verbose("Archiving dialogue for {Callsign}", dialogue.AircraftCallsign); - dialogue.Archive(now); - - await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - } - } - - bool CheckUplinkTimeout(UplinkMessage uplink, DateTimeOffset now) - { - // Skip if already closed, in timeout/failed state, or doesn't require response - if (uplink.IsClosed || - uplink.IsPilotLate || - uplink.IsTransmissionFailed || - uplink.ResponseType == CpdlcUplinkResponseType.NoResponse) - return false; - - // Check if timeout has been exceeded - var timeSinceSent = now - uplink.Sent; - if (timeSinceSent < _pilotLateTimeout) - return false; - - logger.Verbose("Uplink message {UplinkId} marked as pilot late (time since sent: {TimeSinceSent}s)", - uplink.MessageId, timeSinceSent.TotalSeconds); - uplink.IsPilotLate = true; - return true; - } - - bool CheckDownlinkTimeout(DownlinkMessage downlink, DateTimeOffset now) - { - // Skip if already closed, in timeout state, or doesn't require response - if (downlink.IsClosed || - downlink.IsControllerLate || - downlink.ResponseType == CpdlcDownlinkResponseType.NoResponse) - return false; - - // Check if timeout has been exceeded - var timeSinceReceived = now - downlink.Received; - if (timeSinceReceived < _controllerLateTimeout) - return false; - - logger.Verbose("Downlink message {DownlinkId} marked as controller late (time since received: {TimeSinceReceived}s)", - downlink.MessageId, timeSinceReceived.TotalSeconds); - downlink.IsControllerLate = true; - return true; - } -} diff --git a/source/CPDLCServer/Services/VatsimStatusConfiguration.cs b/source/CPDLCServer/Services/VatsimStatusConfiguration.cs deleted file mode 100644 index 53afe9c..0000000 --- a/source/CPDLCServer/Services/VatsimStatusConfiguration.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace CPDLCServer.Services; - -// Settings for the ADS-C reports that the server makes from the VATSIM status data -public class VatsimStatusConfiguration -{ - // When false, the server does not download the VATSIM status data - public bool Enabled { get; init; } - - public Uri Url { get; init; } = new("https://data.vatsim.net/v3/vatsim-data.json"); - - // The time in seconds between downloads of the VATSIM status data - public int PollingIntervalSeconds { get; init; } = 120; - - // When true, the server also makes reports for aircraft that do not have D1 or G1 in Item 10b of the flight plan - public bool AllowNonEquippedAircraft { get; init; } -} diff --git a/source/CPDLCServer/Settings/GetServerSettingsRequest.cs b/source/CPDLCServer/Settings/GetServerSettingsRequest.cs new file mode 100644 index 0000000..d8bca9f --- /dev/null +++ b/source/CPDLCServer/Settings/GetServerSettingsRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Settings; + +public record GetServerSettingsRequest : IRequest; diff --git a/source/CPDLCServer/Settings/GetServerSettingsRequestHandler.cs b/source/CPDLCServer/Settings/GetServerSettingsRequestHandler.cs new file mode 100644 index 0000000..f27825b --- /dev/null +++ b/source/CPDLCServer/Settings/GetServerSettingsRequestHandler.cs @@ -0,0 +1,12 @@ +using MediatR; + +namespace CPDLCServer.Settings; + +public class GetServerSettingsRequestHandler(IServerSettingsProvider settingsProvider) + : IRequestHandler +{ + public Task Handle(GetServerSettingsRequest request, CancellationToken cancellationToken) + { + return settingsProvider.Load(cancellationToken); + } +} diff --git a/source/CPDLCServer/Settings/SaveServerSettingsCommand.cs b/source/CPDLCServer/Settings/SaveServerSettingsCommand.cs new file mode 100644 index 0000000..5c39f29 --- /dev/null +++ b/source/CPDLCServer/Settings/SaveServerSettingsCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Settings; + +public record SaveServerSettingsCommand(ServerSettings Settings) : IRequest; diff --git a/source/CPDLCServer/Settings/SaveServerSettingsCommandHandler.cs b/source/CPDLCServer/Settings/SaveServerSettingsCommandHandler.cs new file mode 100644 index 0000000..d90ec51 --- /dev/null +++ b/source/CPDLCServer/Settings/SaveServerSettingsCommandHandler.cs @@ -0,0 +1,22 @@ +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Settings; + +public class SaveServerSettingsCommandHandler( + IServerSettingsProvider settingsProvider, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(SaveServerSettingsCommand request, CancellationToken cancellationToken) + { + await settingsProvider.Save(request.Settings, cancellationToken); + + unitOfWork.AfterCommit(_ => + { + logger.Information("Server settings changed: {@Settings}", request.Settings); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Settings/ServerSettings.cs b/source/CPDLCServer/Settings/ServerSettings.cs new file mode 100644 index 0000000..5ec7292 --- /dev/null +++ b/source/CPDLCServer/Settings/ServerSettings.cs @@ -0,0 +1,33 @@ +using System.ComponentModel.DataAnnotations; + +namespace CPDLCServer.Settings; + +// The settings that can be changed while the server is running. They are kept in the database. +// The initial values are the default values. +public record ServerSettings +{ + [Range(1, int.MaxValue)] + public int ConnectivityCheckIntervalMinutes { get; init; } = 15; + + [Range(1, int.MaxValue)] + public int AircraftConnectionTimeoutMinutes { get; init; } = 45; + + [Range(1, int.MaxValue)] + public int AdscContractTimeoutMinutes { get; init; } = 120; + + [Range(1, int.MaxValue)] + public int AdscReportRetentionHours { get; init; } = 24; + + [Range(0, int.MaxValue)] + public int HandoffNotificationLeadTimeMinutes { get; init; } = 20; + + public bool VatsimStatusEnabled { get; init; } + + [Required] + public Uri VatsimStatusUrl { get; init; } = new("https://data.vatsim.net/v3/vatsim-data.json"); + + [Range(1, int.MaxValue)] + public int VatsimStatusPollingIntervalSeconds { get; init; } = 120; + + public bool VatsimStatusAllowNonEquippedAircraft { get; init; } +} diff --git a/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs b/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs new file mode 100644 index 0000000..8a66d2b --- /dev/null +++ b/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Settings; + +// The table has one row +public class ServerSettingsConfiguration : IEntityTypeConfiguration +{ + public const string IdProperty = "Id"; + + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("ServerSettings"); + + // The settings have no ID, so the key is a shadow property + builder.Property(IdProperty); + builder.HasKey(IdProperty); + + builder.Property(s => s.VatsimStatusUrl).HasConversion(); + } +} diff --git a/source/CPDLCServer/Settings/ServerSettingsProvider.cs b/source/CPDLCServer/Settings/ServerSettingsProvider.cs new file mode 100644 index 0000000..ff8d24f --- /dev/null +++ b/source/CPDLCServer/Settings/ServerSettingsProvider.cs @@ -0,0 +1,36 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Settings; + +public interface IServerSettingsProvider +{ + Task Load(CancellationToken cancellationToken); + Task Save(ServerSettings settings, CancellationToken cancellationToken); +} + +// Reads and changes the settings with the database context of the current lifetime scope. +// The changes are saved when the unit of work of the scope is committed. +public class ServerSettingsProvider(CpdlcDbContext dbContext) : IServerSettingsProvider +{ + // Adds the default settings when the database has no settings, for example at the first start + public async Task SeedDefaults(CancellationToken cancellationToken) + { + if (await dbContext.ServerSettings.AnyAsync(cancellationToken)) + return; + + dbContext.ServerSettings.Add(new ServerSettings()); + } + + public async Task Load(CancellationToken cancellationToken) + { + await dbContext.ServerSettings.LoadAsync(cancellationToken); + return dbContext.ServerSettings.Local.Single(); + } + + public async Task Save(ServerSettings settings, CancellationToken cancellationToken) + { + var current = await Load(cancellationToken); + dbContext.Entry(current).CurrentValues.SetValues(settings); + } +} diff --git a/source/CPDLCServer/Settings/SettingsServiceCollectionExtensions.cs b/source/CPDLCServer/Settings/SettingsServiceCollectionExtensions.cs new file mode 100644 index 0000000..3066fab --- /dev/null +++ b/source/CPDLCServer/Settings/SettingsServiceCollectionExtensions.cs @@ -0,0 +1,12 @@ +namespace CPDLCServer.Settings; + +public static class SettingsServiceCollectionExtensions +{ + public static IServiceCollection AddSettings(this IServiceCollection services) + { + services.AddScoped(); + services.AddScoped(sp => sp.GetRequiredService()); + + return services; + } +} diff --git a/source/CPDLCServer/Setup/RedirectToSetupMiddleware.cs b/source/CPDLCServer/Setup/RedirectToSetupMiddleware.cs new file mode 100644 index 0000000..c8a53d0 --- /dev/null +++ b/source/CPDLCServer/Setup/RedirectToSetupMiddleware.cs @@ -0,0 +1,25 @@ +namespace CPDLCServer.Setup; + +/// +/// Redirects requests to the setup page until the setup has been completed. +/// +public class RedirectToSetupMiddleware(RequestDelegate next, SetupState setupState) +{ + static readonly string[] AllowedPaths = ["/setup", "/login", "/logout", "/health", "/hubs"]; + + public async Task InvokeAsync(HttpContext context) + { + if (!setupState.IsConfigured && !IsAllowed(context.Request.Path)) + { + context.Response.Redirect("/setup"); + return; + } + + await next(context); + } + + static bool IsAllowed(PathString path) + { + return AllowedPaths.Any(allowedPath => path.StartsWithSegments(allowedPath, StringComparison.OrdinalIgnoreCase)); + } +} diff --git a/source/CPDLCServer/Setup/SetupServiceCollectionExtensions.cs b/source/CPDLCServer/Setup/SetupServiceCollectionExtensions.cs new file mode 100644 index 0000000..6faa6a0 --- /dev/null +++ b/source/CPDLCServer/Setup/SetupServiceCollectionExtensions.cs @@ -0,0 +1,11 @@ +namespace CPDLCServer.Setup; + +public static class SetupServiceCollectionExtensions +{ + public static IServiceCollection AddSetup(this IServiceCollection services) + { + services.AddSingleton(); + + return services; + } +} diff --git a/source/CPDLCServer/Setup/SetupState.cs b/source/CPDLCServer/Setup/SetupState.cs new file mode 100644 index 0000000..a3ce074 --- /dev/null +++ b/source/CPDLCServer/Setup/SetupState.cs @@ -0,0 +1,41 @@ +using System.Security.Cryptography; +using System.Text; +using CPDLCServer.Auth.Users; + +namespace CPDLCServer.Setup; + +// The setup creates the first user. The server is configured when a user exists. +public class SetupState(IServiceScopeFactory serviceScopeFactory) +{ + volatile bool _isConfigured; + + // Only a person who can read the server log has this token, so only that person can create the first user. + // The server makes a new token each time that it starts. + public string SetupToken { get; } = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); + + public bool IsConfigured => _isConfigured; + + public async Task Load(CancellationToken cancellationToken) + { + await using var scope = serviceScopeFactory.CreateAsyncScope(); + var userRepository = scope.ServiceProvider.GetRequiredService(); + + _isConfigured = await userRepository.Any(cancellationToken); + } + + public bool IsValidSetupToken(string? token) + { + if (string.IsNullOrEmpty(token)) + return false; + + // Compare in constant time, so that the time of the comparison does not show the token + return CryptographicOperations.FixedTimeEquals( + Encoding.UTF8.GetBytes(token), + Encoding.UTF8.GetBytes(SetupToken)); + } + + public void MarkAdminCreated() + { + _isConfigured = true; + } +} diff --git a/source/CPDLCServer/Persistence/IVatsimPilotRepository.cs b/source/CPDLCServer/VatsimStatus/IVatsimPilotRepository.cs similarity index 83% rename from source/CPDLCServer/Persistence/IVatsimPilotRepository.cs rename to source/CPDLCServer/VatsimStatus/IVatsimPilotRepository.cs index 85e975e..88469d0 100644 --- a/source/CPDLCServer/Persistence/IVatsimPilotRepository.cs +++ b/source/CPDLCServer/VatsimStatus/IVatsimPilotRepository.cs @@ -1,6 +1,4 @@ -using CPDLCServer.Model; - -namespace CPDLCServer.Persistence; +namespace CPDLCServer.VatsimStatus; // Holds the pilots from the latest download of the VATSIM status data public interface IVatsimPilotRepository diff --git a/source/CPDLCServer/Persistence/InMemoryVatsimPilotRepository.cs b/source/CPDLCServer/VatsimStatus/InMemoryVatsimPilotRepository.cs similarity index 90% rename from source/CPDLCServer/Persistence/InMemoryVatsimPilotRepository.cs rename to source/CPDLCServer/VatsimStatus/InMemoryVatsimPilotRepository.cs index 44bab16..c4185bd 100644 --- a/source/CPDLCServer/Persistence/InMemoryVatsimPilotRepository.cs +++ b/source/CPDLCServer/VatsimStatus/InMemoryVatsimPilotRepository.cs @@ -1,7 +1,6 @@ -using CPDLCServer.Extensions; -using CPDLCServer.Model; +using CPDLCServer.Infrastructure; -namespace CPDLCServer.Persistence; +namespace CPDLCServer.VatsimStatus; public class InMemoryVatsimPilotRepository : IVatsimPilotRepository { diff --git a/source/CPDLCServer/Messages/ProduceVatsimAdscReportsRequest.cs b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequest.cs similarity index 80% rename from source/CPDLCServer/Messages/ProduceVatsimAdscReportsRequest.cs rename to source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequest.cs index 7236c67..a3bffb5 100644 --- a/source/CPDLCServer/Messages/ProduceVatsimAdscReportsRequest.cs +++ b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequest.cs @@ -1,6 +1,6 @@ using MediatR; -namespace CPDLCServer.Messages; +namespace CPDLCServer.VatsimStatus; // Makes the ADS-C reports that are due from the latest VATSIM status data public record ProduceVatsimAdscReportsRequest : IRequest; diff --git a/source/CPDLCServer/Handlers/ProduceVatsimAdscReportsRequestHandler.cs b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs similarity index 86% rename from source/CPDLCServer/Handlers/ProduceVatsimAdscReportsRequestHandler.cs rename to source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs index 1c09b7a..875e121 100644 --- a/source/CPDLCServer/Handlers/ProduceVatsimAdscReportsRequestHandler.cs +++ b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs @@ -1,11 +1,10 @@ +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Infrastructure; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using CPDLCServer.Services; +using CPDLCServer.Settings; using MediatR; -namespace CPDLCServer.Handlers; +namespace CPDLCServer.VatsimStatus; /// /// Makes ADS-C reports from the VATSIM status data, for aircraft that do not support ADS-C over Hoppie's network. @@ -19,7 +18,7 @@ public class ProduceVatsimAdscReportsRequestHandler( IAdscContractRepository adscContractRepository, IAdscReportRepository adscReportRepository, IVatsimPilotRepository vatsimPilotRepository, - VatsimStatusConfiguration configuration, + IServerSettingsProvider settingsProvider, IClock clock, IMediator mediator, ILogger logger) @@ -27,6 +26,7 @@ public class ProduceVatsimAdscReportsRequestHandler( { public async Task Handle(ProduceVatsimAdscReportsRequest request, CancellationToken cancellationToken) { + var settings = await settingsProvider.Load(cancellationToken); var contracts = await adscContractRepository.All(cancellationToken); var now = clock.UtcNow(); @@ -35,7 +35,7 @@ public async Task Handle(ProduceVatsimAdscReportsRequest request, CancellationTo // A failure for one aircraft must not stop the other aircraft try { - await ProduceReport(contract, now, cancellationToken); + await ProduceReport(contract, settings, now, cancellationToken); } catch (Exception ex) when (!cancellationToken.IsCancellationRequested) { @@ -48,12 +48,12 @@ public async Task Handle(ProduceVatsimAdscReportsRequest request, CancellationTo } } - async Task ProduceReport(AdscContract contract, DateTimeOffset now, CancellationToken cancellationToken) + async Task ProduceReport(AdscContract contract, ServerSettings settings, DateTimeOffset now, CancellationToken cancellationToken) { if (!contract.IsActive) return; - var latestReport = await adscReportRepository.Find(contract.Callsign, cancellationToken); + var latestReport = await adscReportRepository.FindLatest(contract.Callsign, cancellationToken); if (!CanUseVatsimData(contract, latestReport, now) || !IsReportDue(contract, latestReport, now)) return; @@ -64,7 +64,7 @@ async Task ProduceReport(AdscContract contract, DateTimeOffset now, Cancellation return; } - if (!pilot.IsAdscEquipped && !configuration.AllowNonEquippedAircraft) + if (!pilot.IsAdscEquipped && !settings.VatsimStatusAllowNonEquippedAircraft) { logger.Debug("{Callsign} is not ADS-C equipped, cannot make ADS-C report", contract.Callsign); return; diff --git a/source/CPDLCServer/Model/VatsimPilot.cs b/source/CPDLCServer/VatsimStatus/VatsimPilot.cs similarity index 96% rename from source/CPDLCServer/Model/VatsimPilot.cs rename to source/CPDLCServer/VatsimStatus/VatsimPilot.cs index 9e46bc8..7bd5736 100644 --- a/source/CPDLCServer/Model/VatsimPilot.cs +++ b/source/CPDLCServer/VatsimStatus/VatsimPilot.cs @@ -1,4 +1,4 @@ -namespace CPDLCServer.Model; +namespace CPDLCServer.VatsimStatus; // A pilot from the VATSIM status data. Altitude is in feet. public record VatsimPilot( diff --git a/source/CPDLCServer/Services/VatsimStatusService.cs b/source/CPDLCServer/VatsimStatus/VatsimStatusService.cs similarity index 78% rename from source/CPDLCServer/Services/VatsimStatusService.cs rename to source/CPDLCServer/VatsimStatus/VatsimStatusService.cs index 8f180cf..43d7824 100644 --- a/source/CPDLCServer/Services/VatsimStatusService.cs +++ b/source/CPDLCServer/VatsimStatus/VatsimStatusService.cs @@ -1,11 +1,9 @@ using System.Net.Http.Json; using System.Text.Json.Serialization; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; -namespace CPDLCServer.Services; +namespace CPDLCServer.VatsimStatus; /// /// Downloads the VATSIM status data, then makes the ADS-C reports that are due. @@ -13,9 +11,10 @@ namespace CPDLCServer.Services; /// public class VatsimStatusService : IHostedService, IDisposable { - readonly VatsimStatusConfiguration _configuration; + readonly TimeSpan _errorInterval = TimeSpan.FromMinutes(1); + readonly IVatsimPilotRepository _vatsimPilotRepository; - readonly IMediator _mediator; + readonly IUnitOfWorkMediator _mediator; readonly ILogger _logger; readonly HttpClient _httpClient = new(); @@ -23,12 +22,10 @@ public class VatsimStatusService : IHostedService, IDisposable Task? _task; public VatsimStatusService( - VatsimStatusConfiguration configuration, IVatsimPilotRepository vatsimPilotRepository, - IMediator mediator, + IUnitOfWorkMediator mediator, ILogger logger) { - _configuration = configuration; _vatsimPilotRepository = vatsimPilotRepository; _mediator = mediator; _logger = logger.ForContext(); @@ -59,12 +56,6 @@ public async Task StopAsync(CancellationToken cancellationToken) async Task DoWork(CancellationToken stoppingToken) { - if (!_configuration.Enabled) - { - _logger.Information("ADS-C reports from VATSIM data are disabled"); - return; - } - _logger.Information("Starting VATSIM status service"); try @@ -73,13 +64,24 @@ async Task DoWork(CancellationToken stoppingToken) { try { + // The settings can change while the server is running, so read them each time + var settings = await _mediator.Send(new GetServerSettingsRequest(), stoppingToken); + var pollingInterval = TimeSpan.FromSeconds(settings.VatsimStatusPollingIntervalSeconds); + + if (!settings.VatsimStatusEnabled) + { + _logger.Verbose("ADS-C reports from VATSIM data are disabled"); + await Task.Delay(pollingInterval, stoppingToken); + continue; + } + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); - await DownloadPilots(timeoutCts.Token); + await DownloadPilots(settings.VatsimStatusUrl, timeoutCts.Token); await _mediator.Send(new ProduceVatsimAdscReportsRequest(), timeoutCts.Token); - await Task.Delay(TimeSpan.FromSeconds(_configuration.PollingIntervalSeconds), stoppingToken); + await Task.Delay(pollingInterval, stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { @@ -88,7 +90,7 @@ async Task DoWork(CancellationToken stoppingToken) catch (Exception ex) { _logger.Error(ex, "Error downloading VATSIM status data"); - await Task.Delay(TimeSpan.FromSeconds(_configuration.PollingIntervalSeconds), stoppingToken); + await Task.Delay(_errorInterval, stoppingToken); } } } @@ -104,11 +106,11 @@ async Task DoWork(CancellationToken stoppingToken) _logger.Information("Stopped VATSIM status service"); } - async Task DownloadPilots(CancellationToken cancellationToken) + async Task DownloadPilots(Uri url, CancellationToken cancellationToken) { _logger.Debug("Downloading VATSIM status data"); - var data = await _httpClient.GetFromJsonAsync(_configuration.Url, cancellationToken); + var data = await _httpClient.GetFromJsonAsync(url, cancellationToken); if (data is null) throw new Exception("VATSIM status data is empty"); diff --git a/source/CPDLCServer/VatsimStatus/VatsimStatusServiceCollectionExtensions.cs b/source/CPDLCServer/VatsimStatus/VatsimStatusServiceCollectionExtensions.cs new file mode 100644 index 0000000..ad512a1 --- /dev/null +++ b/source/CPDLCServer/VatsimStatus/VatsimStatusServiceCollectionExtensions.cs @@ -0,0 +1,12 @@ +namespace CPDLCServer.VatsimStatus; + +public static class VatsimStatusServiceCollectionExtensions +{ + public static IServiceCollection AddVatsimStatus(this IServiceCollection services) + { + services.AddSingleton(); + services.AddHostedService(); + + return services; + } +} diff --git a/source/CPDLCServer/Hubs/ControllerHub.cs b/source/CPDLCServer/Web/ControllerHub.cs similarity index 92% rename from source/CPDLCServer/Hubs/ControllerHub.cs rename to source/CPDLCServer/Web/ControllerHub.cs index c45a8fd..9bde418 100644 --- a/source/CPDLCServer/Hubs/ControllerHub.cs +++ b/source/CPDLCServer/Web/ControllerHub.cs @@ -1,18 +1,24 @@ using CPDLCServer.Contracts; -using CPDLCServer.Messages; -using CPDLCServer.Model; -using CPDLCServer.Persistence; -using MediatR; +using CPDLCServer.AcarsConnections; +using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Infrastructure; using Microsoft.AspNetCore.SignalR; using CpdlcUplinkResponseType = CPDLCServer.Contracts.CpdlcUplinkResponseType; -namespace CPDLCServer.Hubs; +namespace CPDLCServer.Web; public class ControllerHub( IControllerRepository controllerRepository, IDialogueRepository dialogueRepository, IAcarsStationRepository acarsConnectedCallsignsRepository, - IMediator mediator, + IUnitOfWorkMediator mediator, ILogger logger) : Hub { @@ -85,10 +91,10 @@ public async Task BeginDialogue( var modelResponseType = responseType switch { - CpdlcUplinkResponseType.NoResponse => Model.CpdlcUplinkResponseType.NoResponse, - CpdlcUplinkResponseType.WilcoUnable => Model.CpdlcUplinkResponseType.WilcoUnable, - CpdlcUplinkResponseType.AffirmativeNegative => Model.CpdlcUplinkResponseType.AffirmativeNegative, - CpdlcUplinkResponseType.Roger => Model.CpdlcUplinkResponseType.Roger, + CpdlcUplinkResponseType.NoResponse => Cpdlc.Uplinks.CpdlcUplinkResponseType.NoResponse, + CpdlcUplinkResponseType.WilcoUnable => Cpdlc.Uplinks.CpdlcUplinkResponseType.WilcoUnable, + CpdlcUplinkResponseType.AffirmativeNegative => Cpdlc.Uplinks.CpdlcUplinkResponseType.AffirmativeNegative, + CpdlcUplinkResponseType.Roger => Cpdlc.Uplinks.CpdlcUplinkResponseType.Roger, _ => throw new ArgumentOutOfRangeException(nameof(responseType), responseType, null) }; @@ -114,10 +120,10 @@ public async Task ReplyToDownlink( var modelResponseType = responseType switch { - CpdlcUplinkResponseType.NoResponse => Model.CpdlcUplinkResponseType.NoResponse, - CpdlcUplinkResponseType.WilcoUnable => Model.CpdlcUplinkResponseType.WilcoUnable, - CpdlcUplinkResponseType.AffirmativeNegative => Model.CpdlcUplinkResponseType.AffirmativeNegative, - CpdlcUplinkResponseType.Roger => Model.CpdlcUplinkResponseType.Roger, + CpdlcUplinkResponseType.NoResponse => Cpdlc.Uplinks.CpdlcUplinkResponseType.NoResponse, + CpdlcUplinkResponseType.WilcoUnable => Cpdlc.Uplinks.CpdlcUplinkResponseType.WilcoUnable, + CpdlcUplinkResponseType.AffirmativeNegative => Cpdlc.Uplinks.CpdlcUplinkResponseType.AffirmativeNegative, + CpdlcUplinkResponseType.Roger => Cpdlc.Uplinks.CpdlcUplinkResponseType.Roger, _ => throw new ArgumentOutOfRangeException(nameof(responseType), responseType, null) }; diff --git a/source/CPDLCServer/Web/Pages/Account/Login.cshtml b/source/CPDLCServer/Web/Pages/Account/Login.cshtml new file mode 100644 index 0000000..e732754 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Account/Login.cshtml @@ -0,0 +1,38 @@ +@page "/login" +@model LoginModel +@{ + ViewData["Title"] = "Log in"; +} + +
+
+

Log in

+

Log in as the administrator to open the Settings and Logs pages.

+ + + +
+ + +
+
+
+ + + +
+ +
+ + + +
+
+
+ +
+ +
+
+
+
diff --git a/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs b/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs new file mode 100644 index 0000000..9dac8bc --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs @@ -0,0 +1,64 @@ +using System.ComponentModel.DataAnnotations; +using CPDLCServer.Auth.Login; +using CPDLCServer.Infrastructure; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.AspNetCore.RateLimiting; + +namespace CPDLCServer.Web.Pages.Account; + +[EnableRateLimiting(PasswordRateLimit.PolicyName)] +public class LoginModel : PageModel +{ + private readonly IUnitOfWorkMediator _mediator; + + public LoginModel(IUnitOfWorkMediator mediator) + { + _mediator = mediator; + } + + [BindProperty] + public LoginInput Input { get; set; } = new(); + + // The page to open after the login + [BindProperty(SupportsGet = true)] + public string? ReturnUrl { get; set; } + + public void OnGet() + { + } + + public async Task OnPostAsync(CancellationToken cancellationToken) + { + if (!ModelState.IsValid) + return Page(); + + var result = await _mediator.Send(new LoginCommand(Input.Username, Input.Password, ClientIpAddress.Get(HttpContext)), cancellationToken); + if (result is null) + { + // The same message for an unknown user, a wrong password and a lockout + ModelState.AddModelError( + string.Empty, + "The username or password is not correct, or the login is locked because of too many failed logins. " + + "If the login is locked, try again after 15 minutes."); + return Page(); + } + + await AdminAuthentication.SignIn(HttpContext, result.UserId, result.Username); + + // Open only pages on this server, so that a link cannot send the user to a different site + return Url.IsLocalUrl(ReturnUrl) ? LocalRedirect(ReturnUrl) : Redirect("/"); + } + + public class LoginInput + { + [Required] + [Display(Name = "Username")] + public string Username { get; set; } = string.Empty; + + [Required] + [DataType(DataType.Password)] + [Display(Name = "Password")] + public string Password { get; set; } = string.Empty; + } +} diff --git a/source/CPDLCServer/Web/Pages/Account/Logout.cshtml b/source/CPDLCServer/Web/Pages/Account/Logout.cshtml new file mode 100644 index 0000000..e957fc3 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Account/Logout.cshtml @@ -0,0 +1,2 @@ +@page "/logout" +@model LogoutModel diff --git a/source/CPDLCServer/Web/Pages/Account/Logout.cshtml.cs b/source/CPDLCServer/Web/Pages/Account/Logout.cshtml.cs new file mode 100644 index 0000000..465b7c3 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Account/Logout.cshtml.cs @@ -0,0 +1,20 @@ +using CPDLCServer.Auth.Login; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Account; + +// Only a form post logs out, so that a link on a different site cannot log the user out +public class LogoutModel : PageModel +{ + public IActionResult OnGet() + { + return Redirect("/"); + } + + public async Task OnPostAsync() + { + await AdminAuthentication.SignOut(HttpContext); + return Redirect("/"); + } +} diff --git a/source/CPDLCServer/Pages/Adsc/Index.cshtml b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml similarity index 97% rename from source/CPDLCServer/Pages/Adsc/Index.cshtml rename to source/CPDLCServer/Web/Pages/Adsc/Index.cshtml index c56ffa0..9a16633 100644 --- a/source/CPDLCServer/Pages/Adsc/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml @@ -1,6 +1,7 @@ @page "/adsc" -@using CPDLCServer.Model -@model CPDLCServer.Pages.Dashboard.Adsc.IndexModel +@using CPDLCServer.AdscContracts +@using CPDLCServer.AdscContracts.MessageLog +@model IndexModel @{ ViewData["Title"] = "ADS-C"; @@ -100,7 +101,7 @@ { @entry.Time.ToString("yyyy-MM-dd HH:mm:ss") - @entry.AcarsClientId + @entry.AcarsConnectionId @(entry.Direction == AdscMessageDirection.Uplink ? "↑" : "↓") @entry.StationId @entry.Callsign diff --git a/source/CPDLCServer/Pages/Adsc/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml.cs similarity index 89% rename from source/CPDLCServer/Pages/Adsc/Index.cshtml.cs rename to source/CPDLCServer/Web/Pages/Adsc/Index.cshtml.cs index 45e08bc..4519e0c 100644 --- a/source/CPDLCServer/Pages/Adsc/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml.cs @@ -1,9 +1,10 @@ -using CPDLCServer.Model; -using CPDLCServer.Persistence; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.AdscContracts.Reports; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace CPDLCServer.Pages.Dashboard.Adsc; +namespace CPDLCServer.Web.Pages.Adsc; public class IndexModel : PageModel { @@ -40,7 +41,7 @@ public async Task OnGetAsync(CancellationToken cancellationToken) .ThenBy(c => c.StationId) .ToArray(); - var reports = await _adscReportRepository.All(cancellationToken); + var reports = await _adscReportRepository.AllLatest(cancellationToken); ReportSources = reports.ToDictionary(r => r.Callsign, r => r.Report.Source); var logEntries = await _adscMessageLogRepository.All(cancellationToken); diff --git a/source/CPDLCServer/Pages/Atsu/Index.cshtml b/source/CPDLCServer/Web/Pages/Atsu/Index.cshtml similarity index 92% rename from source/CPDLCServer/Pages/Atsu/Index.cshtml rename to source/CPDLCServer/Web/Pages/Atsu/Index.cshtml index 75d8142..7af055a 100644 --- a/source/CPDLCServer/Pages/Atsu/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Atsu/Index.cshtml @@ -1,5 +1,5 @@ @page "/atsu/{stationId}" -@model CPDLCServer.Pages.Dashboard.Atsu.IndexModel +@model IndexModel @{ ViewData["Title"] = $"ATSU {Model.StationId}"; } @@ -7,7 +7,6 @@ diff --git a/source/CPDLCServer/Pages/Atsu/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Atsu/Index.cshtml.cs similarity index 86% rename from source/CPDLCServer/Pages/Atsu/Index.cshtml.cs rename to source/CPDLCServer/Web/Pages/Atsu/Index.cshtml.cs index 70825ac..b9c4490 100644 --- a/source/CPDLCServer/Pages/Atsu/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Atsu/Index.cshtml.cs @@ -1,10 +1,11 @@ -using CPDLCServer.Model; -using CPDLCServer.Pages.ViewModels; -using CPDLCServer.Persistence; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Web.Pages.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace CPDLCServer.Pages.Dashboard.Atsu; +namespace CPDLCServer.Web.Pages.Atsu; public class IndexModel : PageModel { @@ -44,7 +45,7 @@ public async Task OnGetAsync(string stationId, CancellationToken Messages = dialogues .Where(d => aircraftAtStation.Contains(d.AircraftCallsign)) - .SelectMany(d => d.Messages.Select(m => Dashboard.Messages.IndexModel.ToViewModel(d, m, aircraftLookup))) + .SelectMany(d => d.Messages.Select(m => MessageRowViewModel.From(d, m, aircraftLookup))) .OrderByDescending(m => m.Timestamp) .ToList(); diff --git a/source/CPDLCServer/Pages/Dialogue/Index.cshtml b/source/CPDLCServer/Web/Pages/Dialogue/Index.cshtml similarity index 93% rename from source/CPDLCServer/Pages/Dialogue/Index.cshtml rename to source/CPDLCServer/Web/Pages/Dialogue/Index.cshtml index 97701af..ea734fe 100644 --- a/source/CPDLCServer/Pages/Dialogue/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Dialogue/Index.cshtml @@ -1,5 +1,5 @@ @page "/dialogue/{id:guid}" -@model CPDLCServer.Pages.Dashboard.Dialogue.IndexModel +@model IndexModel @{ ViewData["Title"] = $"Dialogue {Model.Dialogue?.Id.ToString()[..8]}..."; } @@ -7,7 +7,6 @@ diff --git a/source/CPDLCServer/Pages/Dialogue/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Dialogue/Index.cshtml.cs similarity index 78% rename from source/CPDLCServer/Pages/Dialogue/Index.cshtml.cs rename to source/CPDLCServer/Web/Pages/Dialogue/Index.cshtml.cs index ee7eb68..4b0621e 100644 --- a/source/CPDLCServer/Pages/Dialogue/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Dialogue/Index.cshtml.cs @@ -1,10 +1,10 @@ -using CPDLCServer.Model; -using CPDLCServer.Pages.ViewModels; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Web.Pages.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace CPDLCServer.Pages.Dashboard.Dialogue; +namespace CPDLCServer.Web.Pages.Dialogue; public class IndexModel : PageModel { @@ -19,7 +19,7 @@ public IndexModel( _aircraftRepository = aircraftRepository; } - public Model.Dialogue? Dialogue { get; private set; } + public Cpdlc.Dialogues.Dialogue? Dialogue { get; private set; } public List Messages { get; private set; } = []; public string AcarsNetwork { get; private set; } = "Unknown"; public string StationId { get; private set; } = "Unknown"; @@ -35,14 +35,14 @@ public async Task OnGetAsync(Guid id, CancellationToken cancellat var aircraft = await _aircraftRepository.All(cancellationToken); var match = aircraft.FirstOrDefault(a => a.Callsign == Dialogue.AircraftCallsign); - AcarsNetwork = match?.AcarsClientId ?? "Unknown"; + AcarsNetwork = match?.AcarsConnectionId ?? "Unknown"; StationId = match?.StationId ?? "Unknown"; var aircraftLookup = aircraft.ToDictionary(a => a.Callsign, a => a); Messages = Dialogue.Messages .OrderBy(m => m.Time) - .Select(m => Dashboard.Messages.IndexModel.ToViewModel(Dialogue, m, aircraftLookup)) + .Select(m => MessageRowViewModel.From(Dialogue, m, aircraftLookup)) .ToList(); return Page(); diff --git a/source/CPDLCServer/Web/Pages/Index.cshtml b/source/CPDLCServer/Web/Pages/Index.cshtml new file mode 100644 index 0000000..5cf01cb --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Index.cshtml @@ -0,0 +1,196 @@ +@page "/" +@model IndexModel +@{ + ViewData["Title"] = "CPDLC Server"; +} + +

Dashboard

+ + + +

Connections

+ +
+
+
+
+
ATC Connections
+
+
+ @if (Model.Controllers.Length == 0) + { +

No ATC connections.

+ } + else + { +
+ + + + + + + + + + @foreach (var controller in Model.Controllers) + { + + + + + + } + +
CallsignATSU CodeConnection ID
@controller.Callsign@controller.StationId@controller.ConnectionId
+
+ } +
+
+
+ +
+
+
+
Pilot Connections
+
+
+ @if (Model.Aircraft.Length == 0) + { +

No pilot connections.

+ } + else + { +
+ + + + + + + + + + + + @foreach (var aircraft in Model.Aircraft) + { + + + + + + + + } + +
CallsignATSU CodeData AuthorityACARS NetworkLast Seen
@aircraft.Callsign@aircraft.StationId@aircraft.DataAuthorityState@aircraft.AcarsConnectionId@aircraft.LastSeen.ToString("yyyy-MM-dd HH:mm:ss")
+
+ } +
+
+
+
+ +

Messages

+ +
+ +
+ +@if (Model.TotalPages > 1) +{ + +} diff --git a/source/CPDLCServer/Web/Pages/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Index.cshtml.cs new file mode 100644 index 0000000..30d39b9 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Index.cshtml.cs @@ -0,0 +1,64 @@ +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Web.Pages.ViewModels; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages; + +public class IndexModel : PageModel +{ + private const int PageSize = 50; + + private readonly IControllerRepository _controllerRepository; + private readonly IAircraftRepository _aircraftRepository; + private readonly IDialogueRepository _dialogueRepository; + + public IndexModel( + IControllerRepository controllerRepository, + IAircraftRepository aircraftRepository, + IDialogueRepository dialogueRepository) + { + _controllerRepository = controllerRepository; + _aircraftRepository = aircraftRepository; + _dialogueRepository = dialogueRepository; + } + + [BindProperty(SupportsGet = true)] + public int PageNumber { get; set; } = 1; + + public ControllerInfo[] Controllers { get; private set; } = []; + public AircraftConnection[] Aircraft { get; private set; } = []; + + public int TotalMessageCount { get; private set; } + public int OpenDialogueCount { get; private set; } + + public List Messages { get; private set; } = []; + public int TotalPages { get; private set; } + public int CurrentPage => PageNumber; + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + Controllers = await _controllerRepository.All(cancellationToken); + Aircraft = await _aircraftRepository.All(cancellationToken); + var dialogues = await _dialogueRepository.All(cancellationToken); + + TotalMessageCount = dialogues.Sum(d => d.Messages.Count); + OpenDialogueCount = dialogues.Count(d => !d.IsClosed); + + var aircraftLookup = Aircraft.ToDictionary(a => a.Callsign, a => a); + var allMessages = dialogues + .SelectMany(d => d.Messages.Select(m => MessageRowViewModel.From(d, m, aircraftLookup))) + .OrderByDescending(m => m.Timestamp) + .ToList(); + + TotalPages = (int)Math.Ceiling(allMessages.Count / (double)PageSize); + PageNumber = Math.Clamp(PageNumber, 1, Math.Max(1, TotalPages)); + + Messages = allMessages + .Skip((PageNumber - 1) * PageSize) + .Take(PageSize) + .ToList(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Logs/Index.cshtml b/source/CPDLCServer/Web/Pages/Logs/Index.cshtml new file mode 100644 index 0000000..04a9e53 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Logs/Index.cshtml @@ -0,0 +1,174 @@ +@page "/logs" +@model IndexModel +@{ + ViewData["Title"] = "Logs"; +} + + + + + +
+

Logs

+ Connecting +
+

The live log of the server. When the page opens, it shows the recent entries. Then it adds each new entry. The logging level of the server (Logging__Level) sets which entries the server writes.

+ +
+
+ + +
+
+ + +
+ + +
+ +
+ +@section Scripts { + +} diff --git a/source/CPDLCServer/Web/Pages/Logs/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Logs/Index.cshtml.cs new file mode 100644 index 0000000..b83970a --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Logs/Index.cshtml.cs @@ -0,0 +1,11 @@ +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Logs; + +// The page gets the log entries from /logs/stream with JavaScript +public class IndexModel : PageModel +{ + public void OnGet() + { + } +} diff --git a/source/CPDLCServer/Pages/Pilot/Index.cshtml b/source/CPDLCServer/Web/Pages/Pilot/Index.cshtml similarity index 87% rename from source/CPDLCServer/Pages/Pilot/Index.cshtml rename to source/CPDLCServer/Web/Pages/Pilot/Index.cshtml index 1570ff1..071931f 100644 --- a/source/CPDLCServer/Pages/Pilot/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Pilot/Index.cshtml @@ -1,5 +1,5 @@ @page "/pilot/{callsign}" -@model CPDLCServer.Pages.Dashboard.Pilot.IndexModel +@model IndexModel @{ ViewData["Title"] = $"Pilot {Model.Callsign}"; } @@ -7,7 +7,6 @@ @@ -26,7 +25,7 @@
@Model.Aircraft.StationId
ACARS Network
-
@Model.Aircraft.AcarsClientId
+
@Model.Aircraft.AcarsConnectionId
Data Authority
@Model.Aircraft.DataAuthorityState
diff --git a/source/CPDLCServer/Pages/Pilot/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Pilot/Index.cshtml.cs similarity index 83% rename from source/CPDLCServer/Pages/Pilot/Index.cshtml.cs rename to source/CPDLCServer/Web/Pages/Pilot/Index.cshtml.cs index 0df50ca..6650944 100644 --- a/source/CPDLCServer/Pages/Pilot/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Pilot/Index.cshtml.cs @@ -1,10 +1,10 @@ -using CPDLCServer.Model; -using CPDLCServer.Pages.ViewModels; -using CPDLCServer.Persistence; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Web.Pages.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace CPDLCServer.Pages.Dashboard.Pilot; +namespace CPDLCServer.Web.Pages.Pilot; public class IndexModel : PageModel { @@ -34,7 +34,7 @@ public async Task OnGetAsync(string callsign, CancellationToken c Messages = dialogues .Where(d => d.AircraftCallsign == callsign) - .SelectMany(d => d.Messages.Select(m => Dashboard.Messages.IndexModel.ToViewModel(d, m, aircraftLookup))) + .SelectMany(d => d.Messages.Select(m => MessageRowViewModel.From(d, m, aircraftLookup))) .OrderByDescending(m => m.Timestamp) .ToList(); diff --git a/source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml b/source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml new file mode 100644 index 0000000..4c5a9ef --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml @@ -0,0 +1,156 @@ +@page "/settings/acars/edit/{id:guid?}" +@using CPDLCServer.AcarsConnections.ConnectionSettings +@model EditModel +@{ + ViewData["Title"] = Model.IsNew ? "Add ACARS Connection" : "Edit ACARS Connection"; +} + + + +

@ViewData["Title"]

+

+ @if (Model.IsNew) + { + When you save an enabled connection, the server connects to the ACARS network immediately. + } + else + { + When you save, the server disconnects the connection, then connects it again with the new settings. + } +

+ + + +
+
+
+
+
+ +
The server connects to the ACARS network only with an enabled connection.
+
+
+
+ +
+
+
+ +
+
+ +
The type of the ACARS network.
+
+
+ + +
+
+ +
+
+ +
The callsign of the ATSU on the ACARS network, for example YBBB. Only one connection can use a station identifier.
+
+
+ + +
+
+ +
+
+ +
The network that the ACARS messages are for, for example VATSIM or IVAO.
+
+
+ + +
+
Default: @Model.Defaults.FlightSimulationNetwork
+
+ +
+
+ +
The URL of the ACARS network.
+
+
+ + +
+
Default: @Model.Defaults.Url
+
+ +
+
+ +
+ The logon code of the station on the ACARS network. The server keeps it encrypted. + @if (!Model.IsNew) + { + Leave it empty to keep the current code. + } +
+
+
+ + +
+
+ +
+
+ +
The reporting interval of the ADS-C contract that the server requests when an aircraft logs on with CPDLC.
+
+
+
+ + minutes +
+ +
+
Default: @Model.Defaults.DefaultAdscReportingInterval minutes
+
+ +
+
+ +
The time from the request of a selected ADS-C contract to its end. Then the server requests the default contract again.
+
+
+
+ + minutes +
+ +
+
Default: @Model.Defaults.SelectedAdscContractDuration minutes
+
+ +
+
+ +
Information for the administrators, for example who owns the station. The server does not use it.
+
+
+ + +
+
+
+
+ +
+ Cancel + +
+
diff --git a/source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml.cs b/source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml.cs new file mode 100644 index 0000000..6f95def --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml.cs @@ -0,0 +1,109 @@ +using CPDLCServer.AcarsConnections.ConnectionSettings; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Web.Pages.Settings.Acars; + +public class EditModel : PageModel +{ + private readonly CpdlcDbContext _dbContext; + private readonly IUnitOfWorkMediator _mediator; + private readonly ILogger _logger; + + public EditModel( + CpdlcDbContext dbContext, + IUnitOfWorkMediator mediator, + ILogger logger) + { + _dbContext = dbContext; + _mediator = mediator; + _logger = logger; + } + + [BindProperty] + public AcarsConnectionSettings Connection { get; set; } = new(); + + // Plain text. It is not shown. For an existing connection, an empty value keeps the current code. + [BindProperty] + public string? AuthenticationCode { get; set; } + + public AcarsConnectionSettings Defaults { get; } = new(); + + // Null for a new connection + public Guid? Id { get; private set; } + + public bool IsNew => Id is null; + + [TempData] + public string? StatusMessage { get; set; } + + [TempData] + public string? ErrorMessage { get; set; } + + public async Task OnGetAsync(Guid? id, CancellationToken cancellationToken) + { + Id = id; + if (id is null) + return Page(); + + var connection = await _dbContext.AcarsConnections + .AsNoTracking() + .SingleOrDefaultAsync(c => c.Id == id.Value, cancellationToken); + if (connection is null) + return NotFound(); + + Connection = connection; + return Page(); + } + + public async Task OnPostAsync(Guid? id, CancellationToken cancellationToken) + { + Id = id; + + if (id is null && string.IsNullOrWhiteSpace(AuthenticationCode)) + ModelState.AddModelError(nameof(AuthenticationCode), "Enter the authentication code."); + + if (Connection.Url is { IsAbsoluteUri: false }) + ModelState.AddModelError($"{nameof(Connection)}.{nameof(Connection.Url)}", "Enter an absolute URL."); + + // The ACARS connection ID comes from the station identifier, so only one connection can use a station identifier + var stationIdentifier = Connection.StationIdentifier.ToUpperInvariant(); + var otherId = id ?? Guid.Empty; + if (await _dbContext.AcarsConnections.AnyAsync(c => c.Id != otherId && c.StationIdentifier == stationIdentifier, cancellationToken)) + ModelState.AddModelError($"{nameof(Connection)}.{nameof(Connection.StationIdentifier)}", "Another ACARS connection uses this station identifier."); + + if (!ModelState.IsValid) + return Page(); + + try + { + if (id is null) + { + await _mediator.Send(new CreateAcarsConnectionCommand(Connection, AuthenticationCode), cancellationToken); + } + else + { + await _mediator.Send(new UpdateAcarsConnectionCommand(id.Value, Connection, AuthenticationCode), cancellationToken); + } + } + catch (AggregateException ex) + { + // The unit of work saved the settings, but the connection did not start + _logger.Error(ex, "ACARS connection for {StationId} was saved, but did not start", stationIdentifier); + ErrorMessage = $"The ACARS connection for {stationIdentifier} was saved, but it did not start: {ex.InnerException?.Message}"; + return RedirectToPage("Index"); + } + catch (Exception ex) + { + _logger.Error(ex, "Failed to save ACARS connection for {StationId}", stationIdentifier); + ModelState.AddModelError(string.Empty, $"The ACARS connection was not saved: {ex.Message}"); + return Page(); + } + + StatusMessage = $"The ACARS connection for {stationIdentifier} was saved."; + return RedirectToPage("Index"); + } +} diff --git a/source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml b/source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml new file mode 100644 index 0000000..1d833a1 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml @@ -0,0 +1,92 @@ +@page "/settings/acars" +@model IndexModel +@{ + ViewData["Title"] = "ACARS Connections"; +} + + + +
+

ACARS Connections

+ Add ACARS connection +
+

The server connects to the upstream ACARS network with each enabled connection. A change takes effect immediately. A restart is not necessary.

+ +@if (Model.StatusMessage is not null) +{ + +} + +@if (Model.ErrorMessage is not null) +{ + +} + +
+
+ @if (Model.Connections.Length == 0) + { +

There are no ACARS connections. Add one to connect to an ACARS network.

+ } + else + { +
+ + + + + + + + + + + + + @foreach (var connection in Model.Connections) + { + + + + + + + + + } + +
StationTypeNetworkURLStatus
+ @connection.StationIdentifier + @if (!string.IsNullOrWhiteSpace(connection.Notes)) + { +
@connection.Notes
+ } +
@connection.Type@connection.FlightSimulationNetwork@connection.Url + @if (!connection.Enabled) + { + Disabled + } + else if (Model.IsRunning(connection)) + { + Running + } + else + { + Not running + } + + Edit +
+ +
+
+
+ } +
+
diff --git a/source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml.cs new file mode 100644 index 0000000..25a54a1 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml.cs @@ -0,0 +1,63 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.AcarsConnections.ConnectionSettings; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Web.Pages.Settings.Acars; + +public class IndexModel : PageModel +{ + private readonly CpdlcDbContext _dbContext; + private readonly IAcarsConnectionManager _acarsConnectionManager; + private readonly IUnitOfWorkMediator _mediator; + private readonly ILogger _logger; + + public IndexModel( + CpdlcDbContext dbContext, + IAcarsConnectionManager acarsConnectionManager, + IUnitOfWorkMediator mediator, + ILogger logger) + { + _dbContext = dbContext; + _acarsConnectionManager = acarsConnectionManager; + _mediator = mediator; + _logger = logger; + } + + public AcarsConnectionSettings[] Connections { get; private set; } = []; + + [TempData] + public string? StatusMessage { get; set; } + + [TempData] + public string? ErrorMessage { get; set; } + + public bool IsRunning(AcarsConnectionSettings settings) => _acarsConnectionManager.IsRunning(settings.Id); + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + Connections = await _dbContext.AcarsConnections + .AsNoTracking() + .OrderBy(c => c.StationIdentifier) + .ToArrayAsync(cancellationToken); + } + + public async Task OnPostDeleteAsync(Guid id, CancellationToken cancellationToken) + { + try + { + await _mediator.Send(new DeleteAcarsConnectionCommand(id), cancellationToken); + StatusMessage = "The ACARS connection was deleted."; + } + catch (Exception ex) + { + _logger.Error(ex, "Failed to delete ACARS connection {Id}", id); + ErrorMessage = $"The ACARS connection was not deleted: {ex.Message}"; + } + + return RedirectToPage(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Settings/Index.cshtml b/source/CPDLCServer/Web/Pages/Settings/Index.cshtml new file mode 100644 index 0000000..7aaa1c1 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/Index.cshtml @@ -0,0 +1,213 @@ +@page "/settings" +@model IndexModel +@{ + ViewData["Title"] = "Global Settings"; +} + + + +

Global Settings

+

The server applies the changes immediately. A restart is not necessary.

+ +@if (Model.Saved) +{ + +} + + + +
+
+
+
Connections
+
+
+ @if (Model.OneFailedCheckCausesTimeout) + { + + } + +
+
+ +
The time between checks of the connected callsigns on the ACARS network.
+
+
+
+ + minutes + +
+ +
+
Default: @Model.Defaults.ConnectivityCheckIntervalMinutes minutes
+
+ +
+
+ +
The time without contact from an aircraft before its connection times out. Use a value of more than two times the connectivity check interval. If not, one failed check will cause connections to time out.
+
+
+
+ + minutes + +
+ +
+
Default: @Model.Defaults.AircraftConnectionTimeoutMinutes minutes
+
+
+
+ +
+
+
ADS-C
+
+
+
+
+ +
The time without ADS-C activity from an aircraft before the server cancels the ADS-C contract.
+
+
+
+ + minutes + +
+ +
+
Default: @Model.Defaults.AdscContractTimeoutMinutes minutes
+
+ +
+
+ +
The time that the server keeps the history of ADS-C reports.
+
+
+
+ + hours + +
+ +
+
Default: @Model.Defaults.AdscReportRetentionHours hours
+
+
+
+ +
+
+
Handoff
+
+
+
+
+ +
The time before the expected transfer time to send the NEXT DATA AUTHORITY message.
+
+
+
+ + minutes + +
+ +
+
Default: @Model.Defaults.HandoffNotificationLeadTimeMinutes minutes
+
+
+
+ +
+
+
ADS-C from VATSIM status data
+
+
+
+
+ +
Make ADS-C reports from the VATSIM status data for aircraft that do not support ADS-C over Hoppie.
+
+
+
+ +
+
+
Default: @(Model.Defaults.VatsimStatusEnabled ? "On" : "Off")
+
+ +
+
+ +
The URL of the VATSIM status data.
+
+
+
+ + +
+ +
+
Default: @Model.Defaults.VatsimStatusUrl
+
+ +
+
+ +
The time between downloads of the VATSIM status data.
+
+
+
+ + seconds + +
+ +
+
Default: @Model.Defaults.VatsimStatusPollingIntervalSeconds seconds
+
+ +
+
+ +
Also make reports for aircraft that do not have D1 or G1 in Item 10b of the flight plan.
+
+
+
+ +
+
+
Default: @(Model.Defaults.VatsimStatusAllowNonEquippedAircraft ? "On" : "Off")
+
+
+
+ +
+ Discard changes + +
+
+ +@section Scripts { + +} diff --git a/source/CPDLCServer/Web/Pages/Settings/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Settings/Index.cshtml.cs new file mode 100644 index 0000000..1f00f49 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/Index.cshtml.cs @@ -0,0 +1,49 @@ +using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Settings; + +public class IndexModel : PageModel +{ + private readonly IServerSettingsProvider _settingsProvider; + private readonly IUnitOfWorkMediator _mediator; + + public IndexModel(IServerSettingsProvider settingsProvider, IUnitOfWorkMediator mediator) + { + _settingsProvider = settingsProvider; + _mediator = mediator; + } + + [BindProperty] + public ServerSettings Settings { get; set; } = new(); + + public ServerSettings Defaults { get; } = new(); + + [TempData] + public bool Saved { get; set; } + + // If one connectivity check fails, the time between two updates of the last seen time is two check intervals + public bool OneFailedCheckCausesTimeout => + Settings.AircraftConnectionTimeoutMinutes <= Settings.ConnectivityCheckIntervalMinutes * 2; + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + Settings = await _settingsProvider.Load(cancellationToken); + } + + public async Task OnPostAsync(CancellationToken cancellationToken) + { + if (Settings.VatsimStatusUrl is { IsAbsoluteUri: false }) + ModelState.AddModelError($"{nameof(Settings)}.{nameof(Settings.VatsimStatusUrl)}", "Enter an absolute URL."); + + if (!ModelState.IsValid) + return Page(); + + await _mediator.Send(new SaveServerSettingsCommand(Settings), cancellationToken); + + Saved = true; + return RedirectToPage(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml b/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml new file mode 100644 index 0000000..194848e --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml @@ -0,0 +1,44 @@ +@page "/settings/users/{id:guid}/password" +@model ChangePasswordModel +@{ + ViewData["Title"] = "Change password"; +} + + + +

Change password

+

Set a new password for @Model.Username. The current password is not necessary.

+ + + +
+
+
+ + +
+ + +
Use 12 characters or more.
+ +
+ +
+ + + +
+
+
+ +
+ Cancel + +
+
diff --git a/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml.cs b/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml.cs new file mode 100644 index 0000000..b162e81 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml.cs @@ -0,0 +1,71 @@ +using System.ComponentModel.DataAnnotations; +using CPDLCServer.Auth.Users; +using CPDLCServer.Infrastructure; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Settings.Users; + +public class ChangePasswordModel : PageModel +{ + private readonly IUserRepository _userRepository; + private readonly IUnitOfWorkMediator _mediator; + + public ChangePasswordModel(IUserRepository userRepository, IUnitOfWorkMediator mediator) + { + _userRepository = userRepository; + _mediator = mediator; + } + + [BindProperty(SupportsGet = true)] + public Guid Id { get; set; } + + [BindProperty] + public ChangePasswordInput Input { get; set; } = new(); + + public string Username { get; private set; } = string.Empty; + + [TempData] + public string? StatusMessage { get; set; } + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + var user = await _userRepository.FindById(Id, cancellationToken); + if (user is null) + return NotFound(); + + Username = user.Username; + return Page(); + } + + public async Task OnPostAsync(CancellationToken cancellationToken) + { + var user = await _userRepository.FindById(Id, cancellationToken); + if (user is null) + return NotFound(); + + Username = user.Username; + if (!ModelState.IsValid) + return Page(); + + await _mediator.Send(new ChangePasswordCommand(Id, Input.NewPassword), cancellationToken); + + StatusMessage = $"The password of {Username} was changed."; + return RedirectToPage("Index"); + } + + public class ChangePasswordInput + { + [Required] + [StringLength(200, MinimumLength = 12, ErrorMessage = "Use a password of 12 characters or more.")] + [DataType(DataType.Password)] + [Display(Name = "New password")] + public string NewPassword { get; set; } = string.Empty; + + [Required] + [Compare(nameof(NewPassword), ErrorMessage = "The passwords are not the same.")] + [DataType(DataType.Password)] + [Display(Name = "Confirm new password")] + public string ConfirmNewPassword { get; set; } = string.Empty; + } +} diff --git a/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml b/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml new file mode 100644 index 0000000..d4eeaeb --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml @@ -0,0 +1,54 @@ +@page "/settings/users" +@model IndexModel +@{ + ViewData["Title"] = "Users"; +} + + + +

Users

+

The users that can log in to the dashboard.

+ +@if (Model.StatusMessage is not null) +{ + +} + +
+
+
+ + + + + + + + + + @foreach (var user in Model.Users) + { + + + + + + } + +
UsernameCreated
+ @user.Username + @if (Model.IsCurrentUser(user)) + { + (you) + } + @user.Created.ToString("yyyy-MM-dd HH:mm") UTC + Change password +
+
+
+
diff --git a/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml.cs new file mode 100644 index 0000000..a55e5f5 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml.cs @@ -0,0 +1,28 @@ +using System.Security.Claims; +using CPDLCServer.Auth.Users; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Settings.Users; + +public class IndexModel : PageModel +{ + private readonly IUserRepository _userRepository; + + public IndexModel(IUserRepository userRepository) + { + _userRepository = userRepository; + } + + public User[] Users { get; private set; } = []; + + [TempData] + public string? StatusMessage { get; set; } + + public bool IsCurrentUser(User user) => User.FindFirstValue(ClaimTypes.NameIdentifier) == user.Id.ToString(); + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + Users = await _userRepository.All(cancellationToken); + } +} diff --git a/source/CPDLCServer/Web/Pages/Settings/_SettingsLayout.cshtml b/source/CPDLCServer/Web/Pages/Settings/_SettingsLayout.cshtml new file mode 100644 index 0000000..ff5f4b4 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/_SettingsLayout.cshtml @@ -0,0 +1,25 @@ +@{ + Layout = "_Layout"; + + var path = Context.Request.Path; + var isAcars = path.StartsWithSegments("/settings/acars"); + var isUsers = path.StartsWithSegments("/settings/users"); + var isGlobal = !isAcars && !isUsers; +} + +
+ +
+ @RenderBody() +
+
+ +@section Scripts { + @await RenderSectionAsync("Scripts", required: false) +} diff --git a/source/CPDLCServer/Web/Pages/Settings/_ViewStart.cshtml b/source/CPDLCServer/Web/Pages/Settings/_ViewStart.cshtml new file mode 100644 index 0000000..ff2cb3f --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Settings/_ViewStart.cshtml @@ -0,0 +1,3 @@ +@{ + Layout = "_SettingsLayout"; +} diff --git a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml new file mode 100644 index 0000000..e400c01 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml @@ -0,0 +1,64 @@ +@page "/setup" +@model IndexModel +@{ + ViewData["Title"] = "Setup"; +} + +
+
+

Set up the server

+

Create the first user

+ + @if (!Model.IsTokenValid) + { + + } + else + { +

+ The administrator can open the Settings and Logs pages. + Keep the password in a safe place. The server cannot show it again. +

+ + + +
+ + +
+
+
+ + + +
+ +
+ + +
Use 12 characters or more.
+ +
+ +
+ + + +
+
+
+ +
+ +
+
+ } +
+
diff --git a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs new file mode 100644 index 0000000..23a4328 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs @@ -0,0 +1,94 @@ +using System.ComponentModel.DataAnnotations; +using CPDLCServer.Auth.Login; +using CPDLCServer.Auth.Users; +using CPDLCServer.Infrastructure; +using CPDLCServer.Setup; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Setup; + +// The setup: create the first user +public class IndexModel : PageModel +{ + private readonly SetupState _setupState; + private readonly IUnitOfWorkMediator _mediator; + private readonly ILogger _logger; + + public IndexModel( + SetupState setupState, + IUnitOfWorkMediator mediator, + ILogger logger) + { + _setupState = setupState; + _mediator = mediator; + _logger = logger; + } + + // The token from the setup URL in the server log + [BindProperty(SupportsGet = true)] + public string? Token { get; set; } + + [BindProperty] + public CreateAdminInput Input { get; set; } = new(); + + public bool IsTokenValid { get; private set; } + + public IActionResult OnGet() + { + if (_setupState.IsConfigured) + return Redirect("/"); + + IsTokenValid = _setupState.IsValidSetupToken(Token); + return Page(); + } + + public async Task OnPostAsync(CancellationToken cancellationToken) + { + if (_setupState.IsConfigured) + return Redirect("/"); + + IsTokenValid = _setupState.IsValidSetupToken(Token); + if (!IsTokenValid) + return Page(); + + if (!ModelState.IsValid) + return Page(); + + Guid userId; + try + { + userId = await _mediator.Send(new CreateUserCommand(Input.Username, Input.Password), cancellationToken); + } + catch (InvalidOperationException ex) + { + // Another person completed this step first + _logger.Warning(ex, "Failed to create the administrator"); + return RedirectToPage("/Account/Login"); + } + + await AdminAuthentication.SignIn(HttpContext, userId, Input.Username.Trim()); + + return Redirect("/"); + } + + public class CreateAdminInput + { + [Required] + [StringLength(64)] + [Display(Name = "Username")] + public string Username { get; set; } = string.Empty; + + [Required] + [StringLength(200, MinimumLength = 12, ErrorMessage = "Use a password of 12 characters or more.")] + [DataType(DataType.Password)] + [Display(Name = "Password")] + public string Password { get; set; } = string.Empty; + + [Required] + [Compare(nameof(Password), ErrorMessage = "The passwords are not the same.")] + [DataType(DataType.Password)] + [Display(Name = "Confirm password")] + public string ConfirmPassword { get; set; } = string.Empty; + } +} diff --git a/source/CPDLCServer/Pages/Shared/_Layout.cshtml b/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml similarity index 63% rename from source/CPDLCServer/Pages/Shared/_Layout.cshtml rename to source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml index 145d41a..7c80b1d 100644 --- a/source/CPDLCServer/Pages/Shared/_Layout.cshtml +++ b/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml @@ -12,12 +12,26 @@ -
-public class AdscContract(string callsign, string stationId) +public class AdscContract(string callsign, string stationId, TimeSpan defaultReportingInterval) { // The ACARS connections poll for messages every 20 to 75 seconds. A shorter interval gives no more data. public static readonly TimeSpan MinimumReportingInterval = TimeSpan.FromSeconds(60); @@ -17,6 +17,9 @@ public class AdscContract(string callsign, string stationId) public string Callsign { get; } = callsign; public string StationId { get; } = stationId; + // The default reporting interval of the ATSU. The controller sees it as the default period. + public TimeSpan DefaultReportingInterval { get; private set; } = defaultReportingInterval; + // The interval of the latest periodic request. Null when no periodic contract was requested. public TimeSpan? ReportingInterval { get; private set; } @@ -53,15 +56,17 @@ public void LogActivity(DateTimeOffset now) /// public void RequestDefaultContract(TimeSpan reportingInterval) { + // The default reporting interval of the ATSU can change while the server is running + DefaultReportingInterval = reportingInterval; ReportingInterval = reportingInterval; DefaultContractState = AdscContractState.Sent; - if (SelectedContractState is AdscContractState.Sent or AdscContractState.Accepted) - { - SelectedReportingInterval = null; - SelectedContractState = null; - SelectedContractEnds = null; - } + if (SelectedContractState is not (AdscContractState.Sent or AdscContractState.Accepted)) + return; + + SelectedReportingInterval = null; + SelectedContractState = null; + SelectedContractEnds = null; } public void RequestSelectedContract(TimeSpan reportingInterval, DateTimeOffset ends) diff --git a/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs b/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs index b9addff..d13c0c4 100644 --- a/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs @@ -17,6 +17,7 @@ public void Configure(EntityTypeBuilder builder) builder.Property(c => c.Callsign); builder.Property(c => c.StationId); + builder.Property(c => c.DefaultReportingInterval); builder.Property(c => c.ReportingInterval); builder.Property(c => c.DefaultContractState); builder.Property(c => c.SelectedReportingInterval); diff --git a/source/CPDLCServer/AdscContracts/AdscContractConverter.cs b/source/CPDLCServer/AdscContracts/AdscContractConverter.cs index 9191757..7dd9cb0 100644 --- a/source/CPDLCServer/AdscContracts/AdscContractConverter.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractConverter.cs @@ -11,6 +11,7 @@ public static AdscContractDto ToDto(AdscContract contract) contract.Callsign, contract.StationId, contract.ReportingInterval, + contract.DefaultReportingInterval, ToDto(contract.DefaultContractState), contract.SelectedReportingInterval, ToDto(contract.SelectedContractState), diff --git a/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs b/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs index 4a6299f..5eecc9c 100644 --- a/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs @@ -1,24 +1,16 @@ using CPDLCServer.Infrastructure; -using CPDLCServer.Settings; namespace CPDLCServer.AdscContracts; -public class AdscContractExpiryService : IHostedService, IDisposable +public class AdscContractExpiryService(IUnitOfWorkMediator mediator, ILogger logger) : IHostedService, IDisposable { readonly TimeSpan _checkInterval = TimeSpan.FromMinutes(1); - readonly IUnitOfWorkMediator _mediator; - readonly ILogger _logger; + readonly ILogger _logger = logger.ForContext(); CancellationTokenSource? _cancellationTokenSource; Task? _task; - public AdscContractExpiryService(IUnitOfWorkMediator mediator, ILogger logger) - { - _mediator = mediator; - _logger = logger.ForContext(); - } - public Task StartAsync(CancellationToken cancellationToken) { if (_cancellationTokenSource is not null || _task is not null) @@ -57,12 +49,8 @@ async Task DoWork(CancellationToken stoppingToken) using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); - var settings = await _mediator.Send(new GetServerSettingsRequest(), timeoutCts.Token); - var contractTimeout = TimeSpan.FromMinutes(settings.AdscContractTimeoutMinutes); - await _mediator.Send(new EndExpiredAdscContractsRequest(contractTimeout), timeoutCts.Token); - - var adscReportRetention = TimeSpan.FromHours(settings.AdscReportRetentionHours); - await _mediator.Send(new PurgeExpiredAdscDataRequest(adscReportRetention), timeoutCts.Token); + await mediator.Send(new EndExpiredAdscContractsRequest(), timeoutCts.Token); + await mediator.Send(new PurgeExpiredAdscDataRequest(), timeoutCts.Token); await Task.Delay(_checkInterval, stoppingToken); } diff --git a/source/CPDLCServer/AdscContracts/AdscContractsServiceCollectionExtensions.cs b/source/CPDLCServer/AdscContracts/AdscContractsServiceCollectionExtensions.cs index a0f9c53..28af032 100644 --- a/source/CPDLCServer/AdscContracts/AdscContractsServiceCollectionExtensions.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractsServiceCollectionExtensions.cs @@ -5,7 +5,7 @@ namespace CPDLCServer.AdscContracts; public static class AdscContractsServiceCollectionExtensions { - public static IServiceCollection AddAdscContracts(this IServiceCollection services) + public static IServiceCollection AddAdsContracts(this IServiceCollection services) { services.AddScoped(); services.AddHostedService(); diff --git a/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs index 03991b8..f5855d1 100644 --- a/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs +++ b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs @@ -1,9 +1,11 @@ +using CPDLCServer.AcarsConnections; using CPDLCServer.AdscContracts.Reports; using MediatR; namespace CPDLCServer.AdscContracts; public class AdscMessageReceivedNotificationHandler( + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, ILogger logger) @@ -73,8 +75,12 @@ await mediator.Publish( // Re-establish the default contract if (selectedContractRejected) { + var configuration = await acarsConnectionManager.GetConfigurationForStation(notification.StationId, cancellationToken); await mediator.Send( - new RequestDefaultAdscContractCommand(notification.StationId, message.Sender), + new RequestPeriodicAdscContractCommand( + notification.StationId, + message.Sender, + TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval)), cancellationToken); } break; diff --git a/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequest.cs b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequest.cs index 1d6e199..503d114 100644 --- a/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequest.cs +++ b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequest.cs @@ -2,4 +2,4 @@ namespace CPDLCServer.AdscContracts; -public record EndExpiredAdscContractsRequest(TimeSpan ContractTimeout) : IRequest; +public record EndExpiredAdscContractsRequest : IRequest; diff --git a/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequestHandler.cs b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequestHandler.cs index 3c75324..38d7fc1 100644 --- a/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequestHandler.cs +++ b/source/CPDLCServer/AdscContracts/EndExpiredAdscContractsRequestHandler.cs @@ -1,6 +1,7 @@ using CPDLCServer.AcarsConnections; using CPDLCServer.Infrastructure; using CPDLCServer.Persistence; +using CPDLCServer.Settings; using MediatR; namespace CPDLCServer.AdscContracts; @@ -8,6 +9,7 @@ namespace CPDLCServer.AdscContracts; public class EndExpiredAdscContractsRequestHandler( IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, + IServerSettingsProvider settingsProvider, IClock clock, ServerStartTime serverStartTime, IMediator mediator, @@ -17,15 +19,17 @@ public class EndExpiredAdscContractsRequestHandler( { public async Task Handle(EndExpiredAdscContractsRequest request, CancellationToken cancellationToken) { + var settings = await settingsProvider.Load(cancellationToken); + var contractTimeout = TimeSpan.FromMinutes(settings.AdscContractTimeoutMinutes); var contracts = await adscContractRepository.All(cancellationToken); var now = clock.UtcNow(); // The last activity times do not change while the server is stopped - var canApplyContractTimeout = now - serverStartTime.Started > request.ContractTimeout; + var canApplyContractTimeout = now - serverStartTime.Started > contractTimeout; foreach (var contract in contracts) { - if (canApplyContractTimeout && now - contract.LastActivity > request.ContractTimeout) + if (canApplyContractTimeout && now - contract.LastActivity > contractTimeout) { // A failure for one aircraft must not stop the other aircraft try @@ -55,8 +59,12 @@ public async Task Handle(EndExpiredAdscContractsRequest request, CancellationTok // A failure for one aircraft must not stop the other aircraft try { + var configuration = await acarsConnectionManager.GetConfigurationForStation(contract.StationId, cancellationToken); await mediator.Send( - new RequestDefaultAdscContractCommand(contract.StationId, contract.Callsign), + new RequestPeriodicAdscContractCommand( + contract.StationId, + contract.Callsign, + TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval)), cancellationToken); } catch (Exception ex) when (!cancellationToken.IsCancellationRequested) diff --git a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequest.cs b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequest.cs index baad90c..c7b8d8d 100644 --- a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequest.cs +++ b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequest.cs @@ -2,4 +2,4 @@ namespace CPDLCServer.AdscContracts; -public record PurgeExpiredAdscDataRequest(TimeSpan AdscReportRetention) : IRequest; +public record PurgeExpiredAdscDataRequest : IRequest; diff --git a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs index 342c55c..283f34f 100644 --- a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs +++ b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs @@ -1,6 +1,7 @@ using CPDLCServer.AdscContracts.MessageLog; using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; using MediatR; namespace CPDLCServer.AdscContracts; @@ -8,6 +9,7 @@ namespace CPDLCServer.AdscContracts; public class PurgeExpiredAdscDataRequestHandler( IAdscMessageLogRepository adscMessageLogRepository, IAdscReportRepository adscReportRepository, + IServerSettingsProvider settingsProvider, IClock clock) : IRequestHandler { @@ -15,9 +17,11 @@ public class PurgeExpiredAdscDataRequestHandler( public async Task Handle(PurgeExpiredAdscDataRequest request, CancellationToken cancellationToken) { + var settings = await settingsProvider.Load(cancellationToken); + var adscReportRetention = TimeSpan.FromHours(settings.AdscReportRetentionHours); var now = clock.UtcNow(); await adscMessageLogRepository.RemoveOlderThan(now - _messageLogRetention, cancellationToken); - await adscReportRepository.RemoveOlderThan(now - request.AdscReportRetention, cancellationToken); + await adscReportRepository.RemoveOlderThan(now - adscReportRetention, cancellationToken); } } diff --git a/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs index 85642c4..ee70900 100644 --- a/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs +++ b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs @@ -30,7 +30,8 @@ public async Task Handle(RequestAdscDemandReportCommand request, CancellationTok var contract = await adscContractRepository.Find(contractKey, cancellationToken); if (contract is null) { - contract = new AdscContract(request.Callsign, request.StationId); + var configuration = await acarsConnectionManager.GetConfigurationForStation(request.StationId, cancellationToken); + contract = new AdscContract(request.Callsign, request.StationId, TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval)); await adscContractRepository.Add(contractKey, contract, cancellationToken); } diff --git a/source/CPDLCServer/AdscContracts/RequestAdscContractOnConnectionEstablishedHandler.cs b/source/CPDLCServer/AdscContracts/RequestAdscContractOnConnectionEstablishedHandler.cs index d01fa9f..3923d00 100644 --- a/source/CPDLCServer/AdscContracts/RequestAdscContractOnConnectionEstablishedHandler.cs +++ b/source/CPDLCServer/AdscContracts/RequestAdscContractOnConnectionEstablishedHandler.cs @@ -1,9 +1,11 @@ +using CPDLCServer.AcarsConnections; using CPDLCServer.Cpdlc.Connections; using MediatR; namespace CPDLCServer.AdscContracts; public class RequestAdscContractOnConnectionEstablishedHandler( + IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, ILogger logger) @@ -27,8 +29,12 @@ public async Task Handle(AircraftConnectionEstablished notification, Cancellatio return; } + var configuration = await acarsConnectionManager.GetConfigurationForStation(notification.StationId, cancellationToken); await mediator.Send( - new RequestDefaultAdscContractCommand(notification.StationId, notification.Callsign), + new RequestPeriodicAdscContractCommand( + notification.StationId, + notification.Callsign, + TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval)), cancellationToken); } catch (Exception ex) when (!cancellationToken.IsCancellationRequested) diff --git a/source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommand.cs b/source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommand.cs deleted file mode 100644 index 2ee14cf..0000000 --- a/source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommand.cs +++ /dev/null @@ -1,8 +0,0 @@ -using MediatR; - -namespace CPDLCServer.AdscContracts; - -public record RequestDefaultAdscContractCommand( - string StationId, - string Callsign) - : IRequest; diff --git a/source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommandHandler.cs b/source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommandHandler.cs deleted file mode 100644 index 9f60f7e..0000000 --- a/source/CPDLCServer/AdscContracts/RequestDefaultAdscContractCommandHandler.cs +++ /dev/null @@ -1,44 +0,0 @@ -using CPDLCServer.AcarsConnections; -using CPDLCServer.Infrastructure; -using CPDLCServer.Persistence; -using MediatR; - -namespace CPDLCServer.AdscContracts; - -public class RequestDefaultAdscContractCommandHandler( - IAcarsConnectionManager acarsConnectionManager, - IAdscContractRepository adscContractRepository, - IMediator mediator, - IClock clock, - IUnitOfWork unitOfWork, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(RequestDefaultAdscContractCommand request, CancellationToken cancellationToken) - { - var configuration = await acarsConnectionManager.GetConfigurationForStation(request.StationId, cancellationToken); - var reportingInterval = TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval); - - logger.Information( - "Requesting default ADS-C contract with {Callsign} from {StationId} (Interval: {ReportingInterval})", - request.Callsign, - request.StationId, - reportingInterval); - - var acarsConnection = await acarsConnectionManager.GetAcarsConnectionForStation(request.StationId, cancellationToken); - unitOfWork.AfterCommit(ct => acarsConnection.RequestPeriodicAdscContract(request.Callsign, reportingInterval, ct)); - - var contractKey = new AdscContractKey(request.Callsign, request.StationId); - var contract = await adscContractRepository.Find(contractKey, cancellationToken); - if (contract is null) - { - contract = new AdscContract(request.Callsign, request.StationId); - await adscContractRepository.Add(contractKey, contract, cancellationToken); - } - - contract.RequestDefaultContract(reportingInterval); - contract.LogActivity(clock.UtcNow()); - - await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); - } -} diff --git a/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommand.cs b/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommand.cs new file mode 100644 index 0000000..99617e2 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommand.cs @@ -0,0 +1,11 @@ +using MediatR; + +namespace CPDLCServer.AdscContracts; + +// A reporting interval that is the same as the default reporting interval of the ATSU requests the default contract. +// Any other reporting interval requests a selected contract. +public record RequestPeriodicAdscContractCommand( + string StationId, + string Callsign, + TimeSpan ReportingInterval) + : IRequest; diff --git a/source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommandHandler.cs b/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommandHandler.cs similarity index 61% rename from source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommandHandler.cs rename to source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommandHandler.cs index 48eb81e..d38a947 100644 --- a/source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommandHandler.cs +++ b/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommandHandler.cs @@ -5,16 +5,16 @@ namespace CPDLCServer.AdscContracts; -public class RequestSelectedAdscContractCommandHandler( +public class RequestPeriodicAdscContractCommandHandler( IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, IClock clock, IUnitOfWork unitOfWork, ILogger logger) - : IRequestHandler + : IRequestHandler { - public async Task Handle(RequestSelectedAdscContractCommand request, CancellationToken cancellationToken) + public async Task Handle(RequestPeriodicAdscContractCommand request, CancellationToken cancellationToken) { if (request.ReportingInterval < AdscContract.MinimumReportingInterval) throw new ArgumentOutOfRangeException( @@ -22,8 +22,13 @@ public async Task Handle(RequestSelectedAdscContractCommand request, Cancellatio request.ReportingInterval, $"Reporting interval must be {AdscContract.MinimumReportingInterval.TotalSeconds} seconds or more"); + var configuration = await acarsConnectionManager.GetConfigurationForStation(request.StationId, cancellationToken); + var defaultReportingInterval = TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval); + var isDefaultContract = request.ReportingInterval == defaultReportingInterval; + logger.Information( - "Requesting selected ADS-C contract with {Callsign} from {StationId} (Interval: {ReportingInterval})", + "Requesting {ContractType} ADS-C contract with {Callsign} from {StationId} (Interval: {ReportingInterval})", + isDefaultContract ? "default" : "selected", request.Callsign, request.StationId, request.ReportingInterval); @@ -31,20 +36,27 @@ public async Task Handle(RequestSelectedAdscContractCommand request, Cancellatio var acarsConnection = await acarsConnectionManager.GetAcarsConnectionForStation(request.StationId, cancellationToken); unitOfWork.AfterCommit(ct => acarsConnection.RequestPeriodicAdscContract(request.Callsign, request.ReportingInterval, ct)); - // The selected contract ends at a fixed time after the request is sent - var configuration = await acarsConnectionManager.GetConfigurationForStation(request.StationId, cancellationToken); - var ends = clock.UtcNow() + TimeSpan.FromMinutes(configuration.SelectedAdscContractDuration); - var contractKey = new AdscContractKey(request.Callsign, request.StationId); var contract = await adscContractRepository.Find(contractKey, cancellationToken); if (contract is null) { - contract = new AdscContract(request.Callsign, request.StationId); + contract = new AdscContract(request.Callsign, request.StationId, defaultReportingInterval); await adscContractRepository.Add(contractKey, contract, cancellationToken); } - contract.RequestSelectedContract(request.ReportingInterval, ends); - contract.LogActivity(clock.UtcNow()); + var now = clock.UtcNow(); + if (isDefaultContract) + { + contract.RequestDefaultContract(request.ReportingInterval); + } + else + { + // The selected contract ends at a fixed time after the request is sent + var ends = now + TimeSpan.FromMinutes(configuration.SelectedAdscContractDuration); + contract.RequestSelectedContract(request.ReportingInterval, ends); + } + + contract.LogActivity(now); await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); } diff --git a/source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommand.cs b/source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommand.cs deleted file mode 100644 index 0bce216..0000000 --- a/source/CPDLCServer/AdscContracts/RequestSelectedAdscContractCommand.cs +++ /dev/null @@ -1,9 +0,0 @@ -using MediatR; - -namespace CPDLCServer.AdscContracts; - -public record RequestSelectedAdscContractCommand( - string StationId, - string Callsign, - TimeSpan ReportingInterval) - : IRequest; diff --git a/source/CPDLCServer/Auth/Login/LoginCommandHandler.cs b/source/CPDLCServer/Auth/Login/LoginCommandHandler.cs index e1c195b..c2a9553 100644 --- a/source/CPDLCServer/Auth/Login/LoginCommandHandler.cs +++ b/source/CPDLCServer/Auth/Login/LoginCommandHandler.cs @@ -31,9 +31,15 @@ public class LoginCommandHandler( { var lockoutEnd = loginLockout.RecordFailure(request.IpAddress); if (lockoutEnd is not null) - logger.Warning("Failed login for {Username} from {IpAddress}: the IP address is locked out until {LockoutEnd}", request.Username, request.IpAddress, lockoutEnd); + { + logger.Warning( + "Failed login for {Username} from {IpAddress}: the IP address is locked out until {LockoutEnd}", + request.Username, request.IpAddress, lockoutEnd); + } else + { logger.Warning("Failed login for {Username} from {IpAddress}", request.Username, request.IpAddress); + } return null; } diff --git a/source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs b/source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs index 08b17e9..a1ca693 100644 --- a/source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs +++ b/source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs @@ -27,6 +27,7 @@ public async Task Handle(CreateUserCommand request, CancellationToken canc Username = request.Username.Trim(), Created = clock.UtcNow() }; + user.PasswordHash = passwordHasher.HashPassword(user, request.Password); await userRepository.Add(user, cancellationToken); diff --git a/source/CPDLCServer/CPDLCServer.csproj b/source/CPDLCServer/CPDLCServer.csproj index f43dbd9..2a5b15a 100644 --- a/source/CPDLCServer/CPDLCServer.csproj +++ b/source/CPDLCServer/CPDLCServer.csproj @@ -16,6 +16,7 @@ + diff --git a/source/CPDLCServer/Controllers/ControllerConnectedNotificationHandler.cs b/source/CPDLCServer/Controllers/ControllerConnectedNotificationHandler.cs index 0f342d9..6b874ab 100644 --- a/source/CPDLCServer/Controllers/ControllerConnectedNotificationHandler.cs +++ b/source/CPDLCServer/Controllers/ControllerConnectedNotificationHandler.cs @@ -32,10 +32,7 @@ public async Task Handle(ControllerConnectedNotification notification, Cancellat } // Notify all other controllers that a peer controller has connected - var controllerDto = new ControllerConnectionDto( - notification.StationId, - notification.Callsign, - controllers.First(c => c.UserId == notification.UserId).VatsimCid); + var controllerDto = new ControllerConnectionDto(notification.StationId, notification.Callsign); unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(otherControllers.Select(c => c.ConnectionId)) diff --git a/source/CPDLCServer/Controllers/ControllerInfo.cs b/source/CPDLCServer/Controllers/ControllerInfo.cs index 63028f0..ba8e104 100644 --- a/source/CPDLCServer/Controllers/ControllerInfo.cs +++ b/source/CPDLCServer/Controllers/ControllerInfo.cs @@ -4,12 +4,10 @@ public class ControllerInfo( Guid userId, string connectionId, string stationId, - string callsign, - string vatsimCid) + string callsign) { public Guid UserId { get; } = userId; public string ConnectionId { get; } = connectionId; public string StationId { get; } = stationId; public string Callsign { get; } = callsign; - public string VatsimCid { get; } = vatsimCid; } diff --git a/source/CPDLCServer/Controllers/GetConnectedControllersRequestHandler.cs b/source/CPDLCServer/Controllers/GetConnectedControllersRequestHandler.cs index 49785ad..67674fa 100644 --- a/source/CPDLCServer/Controllers/GetConnectedControllersRequestHandler.cs +++ b/source/CPDLCServer/Controllers/GetConnectedControllersRequestHandler.cs @@ -13,7 +13,7 @@ public async Task Handle( var controllers = await controllerRepository.All(cancellationToken); var controllerInfo = controllers - .Select(c => new ControllerConnectionDto(c.StationId, c.Callsign, c.VatsimCid)) + .Select(c => new ControllerConnectionDto(c.StationId, c.Callsign)) .ToArray(); return new GetConnectedControllersResult(controllerInfo); diff --git a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandler.cs index 9e8ba6b..b67f4b3 100644 --- a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandler.cs @@ -25,7 +25,6 @@ public async Task Handle(AircraftConnectionEstablished notification, Cancellatio // Find all controllers on the same network and station var controllers = await controllerRepository.All(cancellationToken); - if (!controllers.Any()) { logger.Information( diff --git a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs index 0a34aba..17d44f5 100644 --- a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs @@ -48,7 +48,6 @@ await aircraftRepository.Remove( // Find all controllers on the same network and station var controllers = await controllerRepository.All(cancellationToken); - if (!controllers.Any()) { logger.Information( @@ -63,7 +62,6 @@ await aircraftRepository.Remove( .ToArray(); var openDialogues = aircraftDialogues.Where(d => !d.IsClosed).ToArray(); - if (openDialogues.Any()) { // Add error message to each open dialogue diff --git a/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequest.cs b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequest.cs index 232b345..7baf587 100644 --- a/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequest.cs +++ b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequest.cs @@ -2,4 +2,4 @@ namespace CPDLCServer.Cpdlc.Connections; -public record CheckLostAircraftConnectionsRequest(TimeSpan ConnectionTimeout) : IRequest; +public record CheckLostAircraftConnectionsRequest : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandler.cs b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandler.cs index cdc5110..290969d 100644 --- a/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/CheckLostAircraftConnectionsRequestHandler.cs @@ -1,10 +1,12 @@ using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; using MediatR; namespace CPDLCServer.Cpdlc.Connections; public class CheckLostAircraftConnectionsRequestHandler( IAircraftRepository aircraftRepository, + IServerSettingsProvider settingsProvider, IClock clock, ServerStartTime serverStartTime, IMediator mediator, @@ -12,10 +14,12 @@ public class CheckLostAircraftConnectionsRequestHandler( { public async Task Handle(CheckLostAircraftConnectionsRequest request, CancellationToken cancellationToken) { + var settings = await settingsProvider.Load(cancellationToken); + var connectionTimeout = TimeSpan.FromMinutes(settings.AircraftConnectionTimeoutMinutes); var now = clock.UtcNow(); // The last seen times do not change while the server is stopped - if (now - serverStartTime.Started <= request.ConnectionTimeout) + if (now - serverStartTime.Started <= connectionTimeout) { logger.Debug("Server has not been online for longer than the connection timeout, not checking for lost connections"); return; @@ -26,7 +30,7 @@ public async Task Handle(CheckLostAircraftConnectionsRequest request, Cancellati foreach (var connection in connections) { var timeSinceLastSeen = now - connection.LastSeen; - if (timeSinceLastSeen <= request.ConnectionTimeout) + if (timeSinceLastSeen <= connectionTimeout) { continue; } diff --git a/source/CPDLCServer/Cpdlc/Connections/LostConnectionService.cs b/source/CPDLCServer/Cpdlc/Connections/LostConnectionService.cs index 1179e14..2b531b7 100644 --- a/source/CPDLCServer/Cpdlc/Connections/LostConnectionService.cs +++ b/source/CPDLCServer/Cpdlc/Connections/LostConnectionService.cs @@ -1,24 +1,16 @@ using CPDLCServer.Infrastructure; -using CPDLCServer.Settings; namespace CPDLCServer.Cpdlc.Connections; -public class LostConnectionService : IHostedService, IDisposable +public class LostConnectionService(IUnitOfWorkMediator mediator, ILogger logger) : IHostedService, IDisposable { readonly TimeSpan _checkInterval = TimeSpan.FromMinutes(1); - readonly IUnitOfWorkMediator _mediator; - readonly ILogger _logger; + readonly ILogger _logger = logger.ForContext(); CancellationTokenSource? _cancellationTokenSource; Task? _task; - public LostConnectionService(IUnitOfWorkMediator mediator, ILogger logger) - { - _mediator = mediator; - _logger = logger.ForContext(); - } - public Task StartAsync(CancellationToken cancellationToken) { if (_cancellationTokenSource is not null || _task is not null) @@ -57,9 +49,7 @@ async Task DoWork(CancellationToken stoppingToken) using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); - var settings = await _mediator.Send(new GetServerSettingsRequest(), timeoutCts.Token); - var connectionTimeout = TimeSpan.FromMinutes(settings.AircraftConnectionTimeoutMinutes); - await _mediator.Send(new CheckLostAircraftConnectionsRequest(connectionTimeout), timeoutCts.Token); + await mediator.Send(new CheckLostAircraftConnectionsRequest(), timeoutCts.Token); await Task.Delay(_checkInterval, stoppingToken); } diff --git a/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs index 94b9b93..021622f 100644 --- a/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs @@ -19,7 +19,7 @@ public async Task Handle(DialogueChangedNotification notification, CancellationT // Check if any uplink in the dialogue contains END SERVICE var hasEndService = notification.Dialogue.Messages .OfType() - .Any(m => ControlMessages.IsEndServiceUplink(m)); + .Any(ControlMessages.IsEndServiceUplink); if (!hasEndService) return; diff --git a/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommandHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommandHandler.cs index 9da98ec..2ff6213 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/ArchiveDialogueCommandHandler.cs @@ -13,7 +13,6 @@ public class ArchiveDialogueCommandHandler( public async Task Handle(ArchiveDialogueCommand request, CancellationToken cancellationToken) { var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); - if (dialogue is null) { logger.Warning("Dialogue not found for archival: {DialogueId}", request.DialogueId); diff --git a/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandler.cs index d35d9a2..40f917b 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandler.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandler.cs @@ -60,7 +60,7 @@ bool CheckUplinkTimeout(UplinkMessage uplink, DateTimeOffset now) // Skip if already closed, in timeout/failed state, or doesn't require response if (uplink.IsClosed || uplink.IsPilotLate || - uplink.IsTransmissionFailed || + uplink.DidTransmissionFail || uplink.ResponseType == CpdlcUplinkResponseType.NoResponse) return false; diff --git a/source/CPDLCServer/Cpdlc/Dialogues/ControlMessages.cs b/source/CPDLCServer/Cpdlc/Dialogues/ControlMessages.cs index cacf49b..f4f083c 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/ControlMessages.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/ControlMessages.cs @@ -6,12 +6,14 @@ public static class ControlMessages { public static bool IsLogonRequest(ReceivedDownlink downlink) { - return downlink.Content.Contains("REQUEST LOGON"); + return downlink.Content.Contains("REQUEST LOGON") || + downlink.Content.Contains("REQUEST LOG ON"); } public static bool IsLogoffNotice(ReceivedDownlink downlink) { - return downlink.Content.Contains("LOGOFF"); + return downlink.Content.Contains("LOGOFF") || + downlink.Content.Contains("LOG OFF"); } public static bool IsEndServiceUplink(UplinkMessage uplink) diff --git a/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessage.cs b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessage.cs index 3ac5d3c..8ae1b59 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessage.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessage.cs @@ -1,3 +1,5 @@ +using System.Diagnostics.CodeAnalysis; + namespace CPDLCServer.Cpdlc.Dialogues; public abstract class CpdlcMessage( @@ -17,9 +19,13 @@ public abstract class CpdlcMessage( public int Position { get; internal set; } public DateTimeOffset? Closed { get; protected set; } + + [MemberNotNullWhen(true, nameof(Closed))] public bool IsClosed => Closed is not null; public DateTimeOffset? Acknowledged { get; protected set; } + + [MemberNotNullWhen(true, nameof(Acknowledged))] public bool IsAcknowledged => Acknowledged is not null; public abstract void Close(DateTimeOffset time); diff --git a/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessageConfiguration.cs b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessageConfiguration.cs index 26c868d..665bb3f 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessageConfiguration.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/CpdlcMessageConfiguration.cs @@ -44,7 +44,7 @@ public void Configure(EntityTypeBuilder builder) builder.Property(m => m.Sent); builder.Property(m => m.ClosedManually); builder.Property(m => m.IsPilotLate); - builder.Property(m => m.IsTransmissionFailed); + builder.Property(m => m.DidTransmissionFail); } } diff --git a/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotificationHandler.cs index 1acc221..ded5769 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueChangedNotificationHandler.cs @@ -37,9 +37,9 @@ public async Task Handle(DialogueChangedNotification notification, CancellationT // Convert to DTO and broadcast var dialogueDto = DialogueConverter.ToDto(dialogue); - unitOfWork.AfterCommit(ct => hubContext.Clients + await hubContext.Clients .Clients(controllers.Select(c => c.ConnectionId)) - .SendAsync("DialogueChanged", dialogueDto, ct)); + .SendAsync("DialogueChanged", dialogueDto, cancellationToken); logger.Information( "Notified {ControllerCount} controller(s) about dialogue {DialogueId} change for {Callsign}", diff --git a/source/CPDLCServer/Cpdlc/Dialogues/DialogueConverter.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConverter.cs index a57c970..cc6b8f2 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/DialogueConverter.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConverter.cs @@ -78,7 +78,7 @@ public static UplinkMessageDto ToDto(UplinkMessage uplink) Content = uplink.Content, Sent = uplink.Sent, IsPilotLate = uplink.IsPilotLate, - IsTransmissionFailed = uplink.IsTransmissionFailed + IsTransmissionFailed = uplink.DidTransmissionFail }; } diff --git a/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs index d24613f..47da523 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs @@ -20,7 +20,7 @@ public async Task Handle(PurgeExpiredCpdlcDataRequest request, CancellationToken foreach (var dialogue in oldDialogues) { await dialogueRepository.Remove(dialogue, cancellationToken); - logger.Information("Purging dialogue"); // TODO: Dialogue identifier + logger.Information("Purging dialogue {DialogueId}", dialogue.Id); } } } diff --git a/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandler.cs b/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandler.cs index fbe2018..47082e7 100644 --- a/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandler.cs @@ -14,7 +14,6 @@ public class AcknowledgeDownlinkCommandHandler( public async Task Handle(AcknowledgeDownlinkCommand request, CancellationToken cancellationToken) { var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); - if (dialogue is null) { logger.Warning("Dialogue not found for downlink acknowledgment: {DialogueId}", request.DialogueId); @@ -22,7 +21,6 @@ public async Task Handle(AcknowledgeDownlinkCommand request, CancellationToken c } dialogue.AcknowledgeDownlink(request.DownlinkMessageId, clock.UtcNow()); - logger.Information( "Acknowledged downlink {MessageId} in dialogue {DialogueId} for {AircraftCallsign}", request.DownlinkMessageId, diff --git a/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs index 3035a3f..90f333b 100644 --- a/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs @@ -26,6 +26,7 @@ public async Task Handle(DownlinkReceivedNotification notification, Cancellation logger.Information("Downlink message received from {Callsign}", downlink.Sender); // Scenario 1: Logon request + // TODO: Handle this in hoppies if (ControlMessages.IsLogonRequest(downlink)) { await mediator.Send( @@ -56,6 +57,7 @@ await mediator.Send( // Scenario 3: Logoff notice // Show the logoff to the controller, then terminate the connection. // Return early so that the terminated connection is not promoted to CurrentDataAuthority. + // TODO: Handle this in hoppies if (ControlMessages.IsLogoffNotice(downlink)) { var logoffDialogue = new Dialogue(downlink.Sender); diff --git a/source/CPDLCServer/Cpdlc/Uplinks/UplinkMessage.cs b/source/CPDLCServer/Cpdlc/Uplinks/UplinkMessage.cs index b11f2e7..bc05507 100644 --- a/source/CPDLCServer/Cpdlc/Uplinks/UplinkMessage.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/UplinkMessage.cs @@ -40,7 +40,7 @@ public UplinkMessage( // public bool CanAction { get; set; } // public bool Actioned { get; set; } public bool IsPilotLate { get; set; } - public bool IsTransmissionFailed { get; set; } + public bool DidTransmissionFail { get; set; } public override DateTimeOffset Time => Sent; diff --git a/source/CPDLCServer/Infrastructure/InfrastructureServiceCollectionExtensions.cs b/source/CPDLCServer/Infrastructure/InfrastructureServiceCollectionExtensions.cs index 00fdafa..0fc584b 100644 --- a/source/CPDLCServer/Infrastructure/InfrastructureServiceCollectionExtensions.cs +++ b/source/CPDLCServer/Infrastructure/InfrastructureServiceCollectionExtensions.cs @@ -9,7 +9,7 @@ public static IServiceCollection AddInfrastructure(this IServiceCollection servi services.AddSingleton(clock); services.AddSingleton(new ServerStartTime(clock.UtcNow())); - services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(InfrastructureServiceCollectionExtensions).Assembly)); + services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly)); services.AddSingleton(); return services; diff --git a/source/CPDLCServer/Infrastructure/ServerStartTime.cs b/source/CPDLCServer/Infrastructure/ServerStartTime.cs index a483356..26365f5 100644 --- a/source/CPDLCServer/Infrastructure/ServerStartTime.cs +++ b/source/CPDLCServer/Infrastructure/ServerStartTime.cs @@ -1,8 +1,11 @@ namespace CPDLCServer.Infrastructure; -// The time that the server started. -// The server does not update the saved data while it is stopped, so a timeout applies only when the server has been -// online for longer than the timeout. +/// +/// The time that the server started. +/// The server does not update the saved data while it is stopped, so a timeout applies only when the server has been +/// online for longer than the timeout. +/// +/// public class ServerStartTime(DateTimeOffset started) { public DateTimeOffset Started { get; } = started; diff --git a/source/CPDLCServer/Logging/LogBufferSink.cs b/source/CPDLCServer/Logging/InMemoryLogBufferSink.cs similarity index 89% rename from source/CPDLCServer/Logging/LogBufferSink.cs rename to source/CPDLCServer/Logging/InMemoryLogBufferSink.cs index 8ca4b5f..42332da 100644 --- a/source/CPDLCServer/Logging/LogBufferSink.cs +++ b/source/CPDLCServer/Logging/InMemoryLogBufferSink.cs @@ -4,8 +4,10 @@ namespace CPDLCServer.Logging; -// Writes the log events to the LogBuffer, for the Logs page -public class LogBufferSink(LogBuffer logBuffer) : ILogEventSink +/// +/// A log sink that stores log events in-memory. +/// +public class InMemoryLogBufferSink(LogBuffer logBuffer) : ILogEventSink { // The same text as the console output, without the timestamp, the level and the exception readonly MessageTemplateTextFormatter _messageFormatter = new("{Message:lj}"); diff --git a/source/CPDLCServer/Logging/LogBuffer.cs b/source/CPDLCServer/Logging/LogBuffer.cs index d59022b..caebbe8 100644 --- a/source/CPDLCServer/Logging/LogBuffer.cs +++ b/source/CPDLCServer/Logging/LogBuffer.cs @@ -2,7 +2,9 @@ namespace CPDLCServer.Logging; -// Keeps the most recent log entries in memory, and sends each new entry to the subscribers +/// +/// Keeps the most recent log entries in memory, and sends each new entry to the subscribers +/// public class LogBuffer(int capacity = 1000) { readonly object _lock = new(); @@ -25,8 +27,10 @@ public void Add(LogEntry entry) } } - // The subscription gets the recent entries, then each new entry. - // A slow subscriber loses its oldest entries, so that it cannot use too much memory. + /// + /// The subscription gets the recent entries, then each new entry. + /// A slow subscriber loses its oldest entries, so that it cannot use too much memory. + /// public LogSubscription Subscribe() { lock (_lock) diff --git a/source/CPDLCServer/Logging/LogStreamEndpoint.cs b/source/CPDLCServer/Logging/LogStreamEndpoint.cs index 6f05d5e..7fe7efc 100644 --- a/source/CPDLCServer/Logging/LogStreamEndpoint.cs +++ b/source/CPDLCServer/Logging/LogStreamEndpoint.cs @@ -26,7 +26,9 @@ public static async Task Handle(HttpContext context, LogBuffer logBuffer, IHostA try { foreach (var entry in subscription.RecentEntries) + { await WriteEvent(context.Response, entry, cancellationToken); + } await context.Response.Body.FlushAsync(cancellationToken); diff --git a/source/CPDLCServer/Persistence/UnitOfWork.cs b/source/CPDLCServer/Persistence/UnitOfWork.cs index 2ce6b8e..dafea06 100644 --- a/source/CPDLCServer/Persistence/UnitOfWork.cs +++ b/source/CPDLCServer/Persistence/UnitOfWork.cs @@ -1,14 +1,18 @@ namespace CPDLCServer.Persistence; +/// +/// One unit of work for each service scope. +/// The changes in all of the repositories are saved together. Then the messages are sent in the order that they were added. +/// public interface IUnitOfWork { - // Runs the action after the changes are saved. - // Use this for all messages to controllers and aircraft, so that they do not see changes that were not saved. + /// + /// Runs the action after the changes are saved. + /// Use this for all messages to controllers and aircraft, so that they do not see changes that were not saved. + /// void AfterCommit(Func action); } -// One unit of work for each service scope. -// The changes in all of the repositories are saved together. Then the messages are sent in the order that they were added. public class UnitOfWork(CpdlcDbContext dbContext) : IUnitOfWork { readonly List> _afterCommitActions = []; diff --git a/source/CPDLCServer/Persistence/UtcTicksConverter.cs b/source/CPDLCServer/Persistence/UtcTicksConverter.cs index b2dbbe8..2e10254 100644 --- a/source/CPDLCServer/Persistence/UtcTicksConverter.cs +++ b/source/CPDLCServer/Persistence/UtcTicksConverter.cs @@ -2,7 +2,9 @@ namespace CPDLCServer.Persistence; -// Stores a DateTimeOffset as the number of ticks in UTC. The offset is not kept. +/// +/// Stores a DateTimeOffset as the number of ticks in UTC. The offset is not kept. +/// public class UtcTicksConverter() : ValueConverter( value => value.UtcTicks, value => new DateTimeOffset(value, TimeSpan.Zero)); diff --git a/source/CPDLCServer/Program.cs b/source/CPDLCServer/Program.cs index 3e7c00d..9323476 100644 --- a/source/CPDLCServer/Program.cs +++ b/source/CPDLCServer/Program.cs @@ -39,18 +39,19 @@ var databaseProvider = GetDatabaseProvider(builder); var databasePath = Path.Combine(dataPath, "cpdlc.db"); -builder.Services.AddInfrastructure(); -builder.Services.AddPersistence(builder.Configuration, databaseProvider, databasePath); -builder.Services.AddSecurity(builder.Configuration); -builder.Services.AddSetup(); -builder.Services.AddAuth(); -builder.Services.AddSettings(); -builder.Services.AddAcarsConnections(); -builder.Services.AddAirTrafficControllers(); -builder.Services.AddCpdlc(); -builder.Services.AddAdscContracts(); -builder.Services.AddVatsimStatus(); -builder.Services.AddWeb(); +builder.Services + .AddInfrastructure() + .AddPersistence(builder.Configuration, databaseProvider, databasePath) + .AddSecurity(builder.Configuration) + .AddSetup() + .AddAuth() + .AddSettings() + .AddAcarsConnections() + .AddAirTrafficControllers() + .AddCpdlc() + .AddAdsContracts() + .AddVatsimStatus() + .AddWeb(); var app = builder.Build(); @@ -59,7 +60,7 @@ var setupState = app.Services.GetRequiredService(); await setupState.Load(CancellationToken.None); -app.Lifetime.ApplicationStarted.Register(() => LogSetupUrl(app, setupState)); +app.Lifetime.ApplicationStarted.Register(() => TryLogSetupUrl(app, setupState)); app.UseHttpsRedirection(); app.UseRouting(); @@ -72,8 +73,8 @@ app.MapRazorPages(); app.MapHub("/hubs/controller"); -app.MapGet("/health", () => Results.Ok()); app.MapGet("/logs/stream", LogStreamEndpoint.Handle).RequireAuthorization(); +app.MapGet("/health", () => Results.Ok()); app.Run(); return; @@ -112,7 +113,7 @@ DatabaseProvider GetDatabaseProvider(WebApplicationBuilder builder) return DatabaseProvider.Sqlite; if (!Enum.TryParse(configuredProvider, ignoreCase: true, out var provider)) - throw new Exception($"The database provider {configuredProvider} is not supported. Use Sqlite or PostgreSql."); + throw new Exception($"The database provider {configuredProvider} is not supported. Use {nameof(DatabaseProvider.Sqlite)} or {nameof(DatabaseProvider.PostgreSql)}."); return provider; } @@ -144,7 +145,7 @@ string GetDataPath(WebApplicationBuilder builder) return null; } -void LogSetupUrl(WebApplication app, SetupState setupState) +void TryLogSetupUrl(WebApplication app, SetupState setupState) { if (setupState.IsConfigured) return; @@ -200,7 +201,7 @@ async Task MigrateDatabase(WebApplication app, DatabaseProvider provider, string async Task SeedServerSettings(WebApplication app) { await using var scope = app.Services.CreateAsyncScope(); - await scope.ServiceProvider.GetRequiredService().SeedDefaults(CancellationToken.None); + await scope.ServiceProvider.GetRequiredService().SeedDefaults(CancellationToken.None); await scope.ServiceProvider.GetRequiredService().Commit(CancellationToken.None); } @@ -220,7 +221,7 @@ void ConfigureSerilog(WebApplicationBuilder builder) .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.Sink(new LogBufferSink(logBuffer)) + .WriteTo.Sink(new InMemoryLogBufferSink(logBuffer)) .CreateLogger(); builder.Host.UseSerilog(); diff --git a/source/CPDLCServer/Security/MasterKeyEncryption.cs b/source/CPDLCServer/Security/MasterKeyEncryption.cs index 25fa341..880cbc3 100644 --- a/source/CPDLCServer/Security/MasterKeyEncryption.cs +++ b/source/CPDLCServer/Security/MasterKeyEncryption.cs @@ -3,11 +3,12 @@ namespace CPDLCServer.Security; -// Encrypts secrets with AES-GCM and the master key, so that the database does not contain them as plain text. -// The encrypted value is the nonce, the tag and the ciphertext, as Base64 text. -// If the master key changes, the server cannot decrypt the secrets that were encrypted with the old key. -// -// The key comes from the MasterKey environment variable. A missing or invalid key stops the server at startup. +/// +/// Encrypts data with AES-GCM and the master key, so that the database does not contain them as plain text. +/// The encrypted value is the nonce, the tag and the ciphertext, as Base64 text. +/// If the master key changes, the server cannot decrypt the secrets that were encrypted with the old key. +/// The key comes from the MasterKey environment variable. A missing or invalid key stops the server at startup. +/// public class MasterKeyEncryption(string masterKey) { const int KeySize = 32; diff --git a/source/CPDLCServer/Settings/GetServerSettingsRequest.cs b/source/CPDLCServer/Settings/GetServerSettingsRequest.cs deleted file mode 100644 index d8bca9f..0000000 --- a/source/CPDLCServer/Settings/GetServerSettingsRequest.cs +++ /dev/null @@ -1,5 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Settings; - -public record GetServerSettingsRequest : IRequest; diff --git a/source/CPDLCServer/Settings/GetServerSettingsRequestHandler.cs b/source/CPDLCServer/Settings/GetServerSettingsRequestHandler.cs deleted file mode 100644 index f27825b..0000000 --- a/source/CPDLCServer/Settings/GetServerSettingsRequestHandler.cs +++ /dev/null @@ -1,12 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Settings; - -public class GetServerSettingsRequestHandler(IServerSettingsProvider settingsProvider) - : IRequestHandler -{ - public Task Handle(GetServerSettingsRequest request, CancellationToken cancellationToken) - { - return settingsProvider.Load(cancellationToken); - } -} diff --git a/source/CPDLCServer/Settings/ServerSettings.cs b/source/CPDLCServer/Settings/ServerSettings.cs index 5ec7292..7afe588 100644 --- a/source/CPDLCServer/Settings/ServerSettings.cs +++ b/source/CPDLCServer/Settings/ServerSettings.cs @@ -2,8 +2,9 @@ namespace CPDLCServer.Settings; -// The settings that can be changed while the server is running. They are kept in the database. -// The initial values are the default values. +/// +/// Settings that can be changed while the server is running. +/// public record ServerSettings { [Range(1, int.MaxValue)] diff --git a/source/CPDLCServer/Settings/ServerSettingsProvider.cs b/source/CPDLCServer/Settings/ServerSettingsProvider.cs index ff8d24f..d38cbee 100644 --- a/source/CPDLCServer/Settings/ServerSettingsProvider.cs +++ b/source/CPDLCServer/Settings/ServerSettingsProvider.cs @@ -5,15 +5,16 @@ namespace CPDLCServer.Settings; public interface IServerSettingsProvider { + /// + /// Adds the default settings when the database has no settings, for example at the first start + /// + Task SeedDefaults(CancellationToken cancellationToken); Task Load(CancellationToken cancellationToken); Task Save(ServerSettings settings, CancellationToken cancellationToken); } -// Reads and changes the settings with the database context of the current lifetime scope. -// The changes are saved when the unit of work of the scope is committed. public class ServerSettingsProvider(CpdlcDbContext dbContext) : IServerSettingsProvider { - // Adds the default settings when the database has no settings, for example at the first start public async Task SeedDefaults(CancellationToken cancellationToken) { if (await dbContext.ServerSettings.AnyAsync(cancellationToken)) diff --git a/source/CPDLCServer/Settings/SettingsServiceCollectionExtensions.cs b/source/CPDLCServer/Settings/SettingsServiceCollectionExtensions.cs index 3066fab..0c2f7d4 100644 --- a/source/CPDLCServer/Settings/SettingsServiceCollectionExtensions.cs +++ b/source/CPDLCServer/Settings/SettingsServiceCollectionExtensions.cs @@ -4,9 +4,7 @@ public static class SettingsServiceCollectionExtensions { public static IServiceCollection AddSettings(this IServiceCollection services) { - services.AddScoped(); - services.AddScoped(sp => sp.GetRequiredService()); - + services.AddScoped(); return services; } } diff --git a/source/CPDLCServer/Setup/SetupServiceCollectionExtensions.cs b/source/CPDLCServer/Setup/SetupServiceCollectionExtensions.cs index 6faa6a0..02b232b 100644 --- a/source/CPDLCServer/Setup/SetupServiceCollectionExtensions.cs +++ b/source/CPDLCServer/Setup/SetupServiceCollectionExtensions.cs @@ -5,7 +5,6 @@ public static class SetupServiceCollectionExtensions public static IServiceCollection AddSetup(this IServiceCollection services) { services.AddSingleton(); - return services; } } diff --git a/source/CPDLCServer/VatsimStatus/IVatsimPilotRepository.cs b/source/CPDLCServer/VatsimStatus/IVatsimPilotRepository.cs index 88469d0..9461e87 100644 --- a/source/CPDLCServer/VatsimStatus/IVatsimPilotRepository.cs +++ b/source/CPDLCServer/VatsimStatus/IVatsimPilotRepository.cs @@ -1,9 +1,7 @@ namespace CPDLCServer.VatsimStatus; -// Holds the pilots from the latest download of the VATSIM status data public interface IVatsimPilotRepository { - // Replaces all the pilots Task Replace(VatsimPilot[] pilots, CancellationToken cancellationToken); Task Find(string callsign, CancellationToken cancellationToken); } diff --git a/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequest.cs b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequest.cs index a3bffb5..0a7da94 100644 --- a/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequest.cs +++ b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequest.cs @@ -2,5 +2,7 @@ namespace CPDLCServer.VatsimStatus; -// Makes the ADS-C reports that are due from the latest VATSIM status data +/// +/// Creates an ADS-C position report using VATSIM status data. +/// public record ProduceVatsimAdscReportsRequest : IRequest; diff --git a/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs index 875e121..257e116 100644 --- a/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs +++ b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs @@ -7,7 +7,7 @@ namespace CPDLCServer.VatsimStatus; /// -/// Makes ADS-C reports from the VATSIM status data, for aircraft that do not support ADS-C over Hoppie's network. +/// Creates an ADS-C position report using VATSIM status data. /// /// A report from Hoppie stops the VATSIM reports. The VATSIM reports start again when the Hoppie reports are more than two reporting intervals late. /// A rejected contract stops the VATSIM reports. @@ -71,7 +71,7 @@ async Task ProduceReport(AdscContract contract, ServerSettings settings, DateTim } logger.Information( - "Made ADS-C report from VATSIM data for {Callsign} to {StationId}", + "Faking ADS-C report from VATSIM data for {Callsign} to {StationId}", contract.Callsign, contract.StationId); @@ -109,7 +109,8 @@ static bool CanUseVatsimData(AdscContract contract, AircraftAdscReport? latestRe if (!contract.HasPeriodicContract || contract.ReportingInterval is null) return false; - return now - latestReport.Received > contract.ReportingInterval.Value * 2; + var timeSinceLastReport = now - latestReport.Received; + return timeSinceLastReport > contract.ReportingInterval.Value * 2; } static bool IsReportDue(AdscContract contract, AircraftAdscReport? latestReport, DateTimeOffset now) @@ -120,6 +121,10 @@ static bool IsReportDue(AdscContract contract, AircraftAdscReport? latestReport, if (!contract.HasPeriodicContract || contract.ReportingInterval is null) return false; - return latestReport is null || now - latestReport.Received >= contract.ReportingInterval.Value; + if (latestReport is null) + return true; + + var timeSinceLastReport = now - latestReport.Received; + return timeSinceLastReport >= contract.ReportingInterval.Value; } } diff --git a/source/CPDLCServer/VatsimStatus/VatsimPilot.cs b/source/CPDLCServer/VatsimStatus/VatsimPilot.cs index 7bd5736..086e548 100644 --- a/source/CPDLCServer/VatsimStatus/VatsimPilot.cs +++ b/source/CPDLCServer/VatsimStatus/VatsimPilot.cs @@ -1,6 +1,8 @@ namespace CPDLCServer.VatsimStatus; -// A pilot from the VATSIM status data. Altitude is in feet. +/// +/// A pilot from the VATSIM status data +/// public record VatsimPilot( string Callsign, double Latitude, diff --git a/source/CPDLCServer/VatsimStatus/VatsimStatusService.cs b/source/CPDLCServer/VatsimStatus/VatsimStatusService.cs index 43d7824..4abbf39 100644 --- a/source/CPDLCServer/VatsimStatus/VatsimStatusService.cs +++ b/source/CPDLCServer/VatsimStatus/VatsimStatusService.cs @@ -1,4 +1,3 @@ -using System.Net.Http.Json; using System.Text.Json.Serialization; using CPDLCServer.Infrastructure; using CPDLCServer.Settings; @@ -7,30 +6,22 @@ namespace CPDLCServer.VatsimStatus; /// /// Downloads the VATSIM status data, then makes the ADS-C reports that are due. -/// Not all aircraft support ADS-C over Hoppie's network, so the server uses the VATSIM data for these aircraft. /// -public class VatsimStatusService : IHostedService, IDisposable +public class VatsimStatusService( + IVatsimPilotRepository vatsimPilotRepository, + IUnitOfWorkMediator mediator, + IServiceScopeFactory serviceScopeFactory, + ILogger logger) + : IHostedService, IDisposable { readonly TimeSpan _errorInterval = TimeSpan.FromMinutes(1); - readonly IVatsimPilotRepository _vatsimPilotRepository; - readonly IUnitOfWorkMediator _mediator; - readonly ILogger _logger; + readonly ILogger _logger = logger.ForContext(); readonly HttpClient _httpClient = new(); CancellationTokenSource? _cancellationTokenSource; Task? _task; - public VatsimStatusService( - IVatsimPilotRepository vatsimPilotRepository, - IUnitOfWorkMediator mediator, - ILogger logger) - { - _vatsimPilotRepository = vatsimPilotRepository; - _mediator = mediator; - _logger = logger.ForContext(); - } - public Task StartAsync(CancellationToken cancellationToken) { if (_cancellationTokenSource is not null || _task is not null) @@ -65,7 +56,7 @@ async Task DoWork(CancellationToken stoppingToken) try { // The settings can change while the server is running, so read them each time - var settings = await _mediator.Send(new GetServerSettingsRequest(), stoppingToken); + var settings = await LoadSettings(stoppingToken); var pollingInterval = TimeSpan.FromSeconds(settings.VatsimStatusPollingIntervalSeconds); if (!settings.VatsimStatusEnabled) @@ -79,7 +70,7 @@ async Task DoWork(CancellationToken stoppingToken) timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); await DownloadPilots(settings.VatsimStatusUrl, timeoutCts.Token); - await _mediator.Send(new ProduceVatsimAdscReportsRequest(), timeoutCts.Token); + await mediator.Send(new ProduceVatsimAdscReportsRequest(), timeoutCts.Token); await Task.Delay(pollingInterval, stoppingToken); } @@ -106,6 +97,14 @@ async Task DoWork(CancellationToken stoppingToken) _logger.Information("Stopped VATSIM status service"); } + // The settings provider is scoped, and this service is a singleton + async Task LoadSettings(CancellationToken cancellationToken) + { + await using var scope = serviceScopeFactory.CreateAsyncScope(); + var settingsProvider = scope.ServiceProvider.GetRequiredService(); + return await settingsProvider.Load(cancellationToken); + } + async Task DownloadPilots(Uri url, CancellationToken cancellationToken) { _logger.Debug("Downloading VATSIM status data"); @@ -124,7 +123,7 @@ async Task DownloadPilots(Uri url, CancellationToken cancellationToken) VatsimPilot.HasAdscEquipment(p.FlightPlan?.Aircraft))) .ToArray(); - await _vatsimPilotRepository.Replace(pilots, cancellationToken); + await vatsimPilotRepository.Replace(pilots, cancellationToken); _logger.Debug("Downloaded {PilotCount} pilot(s) from VATSIM status data", pilots.Length); } diff --git a/source/CPDLCServer/Web/ControllerHub.cs b/source/CPDLCServer/Web/ControllerHub.cs index 9bde418..32eb377 100644 --- a/source/CPDLCServer/Web/ControllerHub.cs +++ b/source/CPDLCServer/Web/ControllerHub.cs @@ -1,5 +1,4 @@ using CPDLCServer.Contracts; -using CPDLCServer.AcarsConnections; using CPDLCServer.AcarsConnections.Stations; using CPDLCServer.AdscContracts; using CPDLCServer.AdscContracts.Reports; @@ -46,7 +45,7 @@ public override async Task OnConnectedAsync() throw new HubException("callsign must be provided"); } - // Validate API key + // TODO: Validate API key // var validationResult = await _apiKeyValidator.ValidateAsync(apiKey); // if (validationResult is null) // { @@ -58,15 +57,13 @@ public override async Task OnConnectedAsync() Guid.NewGuid(), Context.ConnectionId, stationId, - callsign, - "TEST"); - // validationResult.VatsimCid); + callsign); await controllerRepository.Add(controller, Context.GetHttpContext()?.RequestAborted ?? CancellationToken.None); _logger.Information( - "Controller connected: {Callsign} (VATSIM CID: {VatsimCid}; ConnectionId: {ConnectionId})", - callsign, "TEST", Context.ConnectionId); + "Controller connected: {Callsign}. ConnectionId: {ConnectionId}", + callsign, Context.ConnectionId); await mediator.Publish( new ControllerConnectedNotification( @@ -98,11 +95,12 @@ public async Task BeginDialogue( _ => throw new ArgumentOutOfRangeException(nameof(responseType), responseType, null) }; - await mediator.Send(new BeginDialogueCommand( - controller.Callsign, - recipient, - modelResponseType, - content)); + await mediator.Send( + new BeginDialogueCommand( + controller.Callsign, + recipient, + modelResponseType, + content)); } public async Task ReplyToDownlink( @@ -127,12 +125,13 @@ public async Task ReplyToDownlink( _ => throw new ArgumentOutOfRangeException(nameof(responseType), responseType, null) }; - await mediator.Send(new ReplyToDownlinkCommand( - controller.Callsign, - dialogueId, - downlinkMessageId, - modelResponseType, - content)); + await mediator.Send( + new ReplyToDownlinkCommand( + controller.Callsign, + dialogueId, + downlinkMessageId, + modelResponseType, + content)); } public async Task RequestConnection(string callsign, string stationId) @@ -145,12 +144,6 @@ public async Task RequestConnection(string callsign, string stationId) } await mediator.Send(new SendConnectionRequestCommand(callsign, stationId)); - - _logger.Information( - "Controller {Callsign} requested a connection between {AircraftCallsign} and {StationId}", - controller.Callsign, - callsign, - stationId); } public async Task GetConnectedAircraft() @@ -162,9 +155,7 @@ public async Task GetConnectedAircraft() throw new InvalidOperationException($"Controller not found for connection {Context.ConnectionId}"); } - var query = new GetConnectedAircraftRequest(); - var result = await mediator.Send(query); - + var result = await mediator.Send(new GetConnectedAircraftRequest()); return result.Aircraft; } @@ -177,9 +168,7 @@ public async Task GetConnectedControllers() throw new InvalidOperationException($"Controller not found for connection {Context.ConnectionId}"); } - var query = new GetConnectedControllersRequest(); - var result = await mediator.Send(query); - + var result = await mediator.Send(new GetConnectedControllersRequest()); return result.Controllers; } @@ -190,34 +179,17 @@ public async Task GetAcarsStations() public async Task AcknowledgeDownlink(Guid dialogueId, int downlinkMessageId) { - var command = new AcknowledgeDownlinkCommand(dialogueId, downlinkMessageId); - await mediator.Send(command); - - _logger.Information( - "Controller acknowledged downlink {MessageId} in dialogue {DialogueId}", - downlinkMessageId, - dialogueId); + await mediator.Send(new AcknowledgeDownlinkCommand(dialogueId, downlinkMessageId)); } public async Task AcknowledgeUplink(Guid dialogueId, int uplinkMessageId) { - var command = new AcknowledgeUplinkCommand(dialogueId, uplinkMessageId); - await mediator.Send(command); - - _logger.Information( - "Controller acknowledged uplink {MessageId} in dialogue {DialogueId}", - uplinkMessageId, - dialogueId); + await mediator.Send(new AcknowledgeUplinkCommand(dialogueId, uplinkMessageId)); } public async Task ArchiveDialogue(Guid dialogueId) { - var command = new ArchiveDialogueCommand(dialogueId); - await mediator.Send(command); - - _logger.Information( - "Controller manually archived dialogue {DialogueId}", - dialogueId); + await mediator.Send(new ArchiveDialogueCommand(dialogueId)); } public async Task UpdateNextDataAuthority( @@ -232,35 +204,16 @@ public async Task UpdateNextDataAuthority( throw new InvalidOperationException($"Controller not found for connection {Context.ConnectionId}"); } - var command = new UpdateNextDataAuthorityCommand( - controller.StationId, - callsign, - nextDataAuthority, - expectedTransferTime); - - await mediator.Send(command); - - _logger.Information( - "Controller {Callsign} updated next data authority for {AircraftCallsign} to {NextDataAuthority}", - controller.Callsign, - callsign, - nextDataAuthority ?? "(none)"); - } - - public async Task GetAtsuSettings() - { - var controller = await controllerRepository.FindByConnectionId(Context.ConnectionId, CancellationToken.None); - if (controller is null) - { - _logger.Warning("Controller not found for connection {ConnectionId}", Context.ConnectionId); - throw new InvalidOperationException($"Controller not found for connection {Context.ConnectionId}"); - } - - return await mediator.Send(new GetAtsuSettingsRequest(controller.StationId)); + await mediator.Send( + new UpdateNextDataAuthorityCommand( + controller.StationId, + callsign, + nextDataAuthority, + expectedTransferTime)); } - // A null reporting interval ends the selected contract and requests the default contract again - public async Task RequestPeriodicAdscContract(string callsign, TimeSpan? reportingInterval) + // The default reporting interval of the ATSU requests the default contract. Any other interval requests a selected contract. + public async Task RequestPeriodicAdscContract(string callsign, TimeSpan reportingInterval) { var controller = await controllerRepository.FindByConnectionId(Context.ConnectionId, CancellationToken.None); if (controller is null) @@ -269,23 +222,7 @@ public async Task RequestPeriodicAdscContract(string callsign, TimeSpan? reporti throw new InvalidOperationException($"Controller not found for connection {Context.ConnectionId}"); } - if (reportingInterval is null) - { - await mediator.Send(new RequestDefaultAdscContractCommand(controller.StationId, callsign)); - } - else - { - await mediator.Send(new RequestSelectedAdscContractCommand( - controller.StationId, - callsign, - reportingInterval.Value)); - } - - _logger.Information( - "Controller {Callsign} requested periodic ADS-C contract with {AircraftCallsign} (Interval: {ReportingInterval})", - controller.Callsign, - callsign, - reportingInterval?.ToString() ?? "Default"); + await mediator.Send(new RequestPeriodicAdscContractCommand(controller.StationId, callsign, reportingInterval)); } public async Task RequestAdscDemandReport(string callsign) @@ -298,11 +235,6 @@ public async Task RequestAdscDemandReport(string callsign) } await mediator.Send(new RequestAdscDemandReportCommand(controller.StationId, callsign)); - - _logger.Information( - "Controller {Callsign} requested ADS-C demand report from {AircraftCallsign}", - controller.Callsign, - callsign); } public async Task CancelAdscContract(string callsign) @@ -315,11 +247,6 @@ public async Task CancelAdscContract(string callsign) } await mediator.Send(new CancelAdscContractCommand(controller.StationId, callsign)); - - _logger.Information( - "Controller {Callsign} cancelled ADS-C contract with {AircraftCallsign}", - controller.Callsign, - callsign); } public async Task GetAdscContracts() @@ -365,12 +292,6 @@ public async Task GetAllDialogues() async Task GetAllDialoguesFor(ControllerInfo controller, CancellationToken cancellationToken) { var dialogues = await dialogueRepository.All(cancellationToken); - - _logger.Information( - "Sending {DialogueCount} dialogues to controller {Callsign}", - dialogues.Length, - controller.Callsign); - return dialogues.Select(DialogueConverter.ToDto).ToArray(); } From 75f6cbc119c90ec9221e37cb60193866f6657357 Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:54:52 +0800 Subject: [PATCH 03/18] Fix build error --- .../CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs b/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs index e70bb59..ee6d27a 100644 --- a/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs +++ b/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs @@ -6,6 +6,12 @@ public class TestServerSettingsProvider(ServerSettings settings) : IServerSettin { ServerSettings _settings = settings; + // The settings are given in the constructor, so there are always settings + public Task SeedDefaults(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + public Task Load(CancellationToken cancellationToken) { return Task.FromResult(_settings); From 323d7dfb810c23c5f39bf9d284859e7a1c19be2c Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:02:55 +0800 Subject: [PATCH 04/18] Fix build error --- ...cReportReceivedNotificationHandlerTests.cs | 4 ++-- ...tionEstablishedNotificationHandlerTests.cs | 6 ++---- ...tConnectionLostNotificationHandlerTests.cs | 12 ++++------- ...ctionTerminatedNotificationHandlerTests.cs | 6 ++---- .../Connections/LogonCommandHandlerTests.cs | 15 +++++-------- ...ownlinkReceivedNotificationHandlerTests.cs | 21 +++++++------------ 6 files changed, 22 insertions(+), 42 deletions(-) diff --git a/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs index 5863dd1..8b3e036 100644 --- a/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs @@ -17,10 +17,10 @@ public async Task Handle_NotifiesAllConnectedControllers() // Arrange var controllerRepository = new TestControllerRepository(); await controllerRepository.Add( - new ControllerInfo(Guid.NewGuid(), "ConnectionId-1", "YBBB", "BN-TSN_FSS", "1234567"), + new ControllerInfo(Guid.NewGuid(), "ConnectionId-1", "YBBB", "BN-TSN_FSS"), CancellationToken.None); await controllerRepository.Add( - new ControllerInfo(Guid.NewGuid(), "ConnectionId-2", "YMMM", "ML-ASP_CTR", "7654321"), + new ControllerInfo(Guid.NewGuid(), "ConnectionId-2", "YMMM", "ML-ASP_CTR"), CancellationToken.None); var hubContext = Substitute.For>(); diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs index 0c4670d..0d78668 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs @@ -20,14 +20,12 @@ public async Task Handle_NotifiesAllConnectedControllers() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", - "BN-OCN_CTR", - "7654321"); + "BN-OCN_CTR"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs index 6cab381..a49ed7f 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs @@ -68,14 +68,12 @@ public async Task Handle_CreatesDialogueWithErrorMessageAndNotifiesControllers() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", - "BN-OCN_CTR", - "7654321"); + "BN-OCN_CTR"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); @@ -219,8 +217,7 @@ public async Task Handle_AddsErrorMessageToExistingOpenDialogue() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); await controllerManager.Add(controller, CancellationToken.None); var dialogueRepository = new TestDialogueRepository(); @@ -288,8 +285,7 @@ public async Task Handle_ClosesOpenDialogue_SoItCanBeArchived() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); await controllerManager.Add(controller, CancellationToken.None); var dialogueRepository = new TestDialogueRepository(); diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs index eef7153..72e2f87 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs @@ -19,14 +19,12 @@ public async Task Handle_NotifiesAllConnectedControllers() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", - "BN-OCN_CTR", - "7654321"); + "BN-OCN_CTR"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs index cd6a35b..0689b54 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs @@ -106,8 +106,7 @@ public async Task Handle_NewConnection_AcceptsLogon() Guid.NewGuid(), "Connection-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); @@ -140,8 +139,7 @@ public async Task Handle_NewConnection_TracksConnection() Guid.NewGuid(), "Connection-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); @@ -175,8 +173,7 @@ public async Task Handle_NewConnection_PersistsDialogueWithDownlinkAndUplink() Guid.NewGuid(), "Connection-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); @@ -218,8 +215,7 @@ public async Task Handle_ExistingConnection_AcceptsLogon_AndDoesNotDuplicateConn Guid.NewGuid(), "Connection-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); await controllerRepository.Add(controller, CancellationToken.None); var existing = new AircraftConnection("QFA1", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); @@ -259,8 +255,7 @@ public async Task Handle_NotifiesATC() Guid.NewGuid(), "Connection-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); diff --git a/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs index e09a6c1..949d27e 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs @@ -47,14 +47,12 @@ public async Task Handle_PublishesDialogueChangedNotification() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", - "BN-OCN_CTR", - "7654321"); + "BN-OCN_CTR"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); @@ -111,8 +109,7 @@ public async Task Handle_StillCreatesDialogueWhenNoControllersMatch() Guid.NewGuid(), "ConnectionId-1", "YMMM", - "ML-IND_FSS", - "1234567"); + "ML-IND_FSS"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -164,8 +161,7 @@ public async Task Handle_PromotesAircraftToCurrentDataAuthorityOnFirstDownlink() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -236,8 +232,7 @@ public async Task Handle_DoesNotPromoteToCurrentDataAuthority_WhenNotCurrentData Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -299,8 +294,7 @@ public async Task Handle_UpdatesLastSeen() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -605,8 +599,7 @@ public async Task Handle_LogoffMessage_FromNextDataAuthority_DoesNotPromoteOrNot Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS", - "1234567"); + "BN-TSN_FSS"); await controllerRepository.Add(controller, CancellationToken.None); var dialogueRepository = new TestDialogueRepository(); From 7aafc0483d1ba76cee2adf29073b81b04ac5a67c Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:06:27 +0800 Subject: [PATCH 05/18] Force version --- build/Build.cs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/build/Build.cs b/build/Build.cs index fd3083c..a0abde4 100644 --- a/build/Build.cs +++ b/build/Build.cs @@ -60,6 +60,9 @@ class Build : FalloutBuild [Parameter("Name of the migration to add")] readonly string MigrationName; + [Parameter("Version to use instead of the GitVersion version, for example 1.0.0-rc1")] + readonly string ForceVersion; + [GitRepository] readonly GitRepository GitRepository; @@ -167,8 +170,8 @@ class Build : FalloutBuild .SetConfiguration(Configuration) .SetOutputDirectory(PluginBuildOutputDirectory) .SetVersion(version) - .SetAssemblyVersion(GitVersion.MajorMinorPatch) - .SetFileVersion(GitVersion.MajorMinorPatch) + .SetAssemblyVersion(GetMajorMinorPatch()) + .SetFileVersion(GetMajorMinorPatch()) .SetInformationalVersion(version) .SetProperty("VatSysPath", VatSysExePath.Parent.Parent)); }); @@ -368,8 +371,8 @@ class Build : FalloutBuild .SetConfiguration(Configuration) .SetOutput(ServerBuildOutputDirectory) .SetVersion(version) - .SetAssemblyVersion(GitVersion.MajorMinorPatch) - .SetFileVersion(GitVersion.MajorMinorPatch) + .SetAssemblyVersion(GetMajorMinorPatch()) + .SetFileVersion(GetMajorMinorPatch()) .SetInformationalVersion(version)); Log.Information("Server published to {OutputDirectory}", ServerBuildOutputDirectory); @@ -496,8 +499,20 @@ static AbsolutePath GetVatSysProfilePath(string profileName) return Path.Combine(documentsPath, "vatSys Files", "Profiles", profileName); } + // The assembly and file versions cannot have a pre-release label or build metadata + string GetMajorMinorPatch() + { + if (!string.IsNullOrEmpty(ForceVersion)) + return ForceVersion.Split('-', '+')[0]; + + return GitVersion?.MajorMinorPatch ?? "0.0.0"; + } + string GetSemanticVersion() { + if (!string.IsNullOrEmpty(ForceVersion)) + return ForceVersion; + // For main/master branch, or if we're on a detached head (building from a tag) // use major.minor.patch (e.g., "1.2.3") if (string.IsNullOrEmpty(GitVersion.BranchName) || GitVersion.BranchName is "main" or "master") From 8603903683080631f88fd3c0c62535e176dc3b2d Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:44:01 +0800 Subject: [PATCH 06/18] Reduce and discourage usage of IGuiInvoker --- source/CPDLCPlugin/GuiInvoker.cs | 42 +++++++++++++++++++ source/CPDLCPlugin/Plugin.cs | 4 +- .../ViewModels/ADSContractViewModel.cs | 5 ++- .../ViewModels/CurrentMessagesViewModel.cs | 14 +++++-- .../CPDLCPlugin/ViewModels/EditorViewModel.cs | 6 +++ .../ViewModels/HistoryViewModel.cs | 5 ++- source/CPDLCPlugin/Windows/WindowManager.cs | 12 ++++++ 7 files changed, 82 insertions(+), 6 deletions(-) diff --git a/source/CPDLCPlugin/GuiInvoker.cs b/source/CPDLCPlugin/GuiInvoker.cs index 6ecafb3..b5330b0 100644 --- a/source/CPDLCPlugin/GuiInvoker.cs +++ b/source/CPDLCPlugin/GuiInvoker.cs @@ -3,6 +3,48 @@ namespace CPDLCPlugin; +/// +/// Does an action on the vatSys UI thread. Do not use this interface unless you must. +/// +/// +/// +/// You must use this interface only if both of these conditions are true: +/// +/// +/// +/// The code can run on a thread that is not the vatSys UI thread. For example: OnFDRUpdate and +/// OnRadarTrackUpdate, the Network events, the MediatR handlers, the work queue, Task.Run, and code after +/// ConfigureAwait(false). Some vatSys events (for example, MMI.SelectedTrackChanged) can occur on any +/// thread. +/// +/// +/// The code changes something that must change on the UI thread: a WinForms form or control, a WPF element (for +/// example, it makes, shows, or closes a window), or the state that a WPF view binds to (for example, a view model +/// property or collection). +/// +/// +/// +/// Do not use this interface in these cases: +/// +/// +/// +/// The code always runs on the UI thread. For example: WinForms and WPF event handlers, menu item clicks, form events, +/// and a DispatcherTimer. The action then runs immediately, thus the call does nothing. Call the code directly, +/// and catch the exceptions, because an exception that is not caught on the UI thread stops vatSys. +/// +/// The code does not change the UI. +/// A method that you call already goes to the UI thread. For example, the window manager. +/// +/// The UI does not change. Do the checks on the background thread first. For example, if a window shows one aircraft, +/// do not post the updates of the other aircraft. +/// +/// +/// +/// On a thread that is not the UI thread, each call posts one message to the UI thread. vatSys and all the plugins use +/// the same UI thread, and a thread can have a maximum of 10,000 posted messages. If the queue becomes full, the WPF +/// content in vatSys can stop. Thus, do not call this method for each radar track update or each flight plan update. +/// +/// public interface IGuiInvoker { void InvokeOnGUI(Action
action); diff --git a/source/CPDLCPlugin/Plugin.cs b/source/CPDLCPlugin/Plugin.cs index 55b986c..7a53bc8 100644 --- a/source/CPDLCPlugin/Plugin.cs +++ b/source/CPDLCPlugin/Plugin.cs @@ -617,7 +617,9 @@ public void OnFDRUpdate(FDP2.FDR updated) .Where(d => d.AircraftCallsign == updated.Callsign) .Any(d => !d.IsArchived && jurisdictionChecker.ShouldDisplayDialogue(d)); - if (hasDialoguesToDisplay) + // vatSys updates the FDRs often. If the window is open, do not post to the UI thread to open it again. + var windowManager = ServiceProvider.GetRequiredService(); + if (hasDialoguesToDisplay && !windowManager.IsWindowOpen(WindowKeys.CurrentMessages)) { var mediator = ServiceProvider.GetRequiredService(); await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: true)); diff --git a/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs b/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs index 670cc1c..9c214d8 100644 --- a/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs @@ -226,9 +226,12 @@ public void Receive(AdscReportReceivedNotification notification) void ReloadIfShown(string callsign) { - if (_disposed) + // The ADS-C reports come for all the aircraft. Do not post to the UI thread for an aircraft that this window + // does not show. The UI thread checks again, because the callsign can change before the action runs. + if (_disposed || callsign != Callsign) return; + // LoadContractAsync changes the properties that the view binds to _guiInvoker.InvokeOnGUI(mainForm => { if (_disposed) diff --git a/source/CPDLCPlugin/ViewModels/CurrentMessagesViewModel.cs b/source/CPDLCPlugin/ViewModels/CurrentMessagesViewModel.cs index 8362b2b..d506c66 100644 --- a/source/CPDLCPlugin/ViewModels/CurrentMessagesViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/CurrentMessagesViewModel.cs @@ -25,7 +25,8 @@ public partial class CurrentMessagesViewModel : readonly IErrorReporter _errorReporter; readonly IWindowHandle _windowHandle; readonly IJurisdictionChecker _jurisdictionChecker; - bool _closeWhenEmpty; + // The UI thread reads this field. Another thread can set it to false (see Receive(OpenCurrentMessagesWindowRequest)). + volatile bool _closeWhenEmpty; bool _disposed; public CurrentMessagesViewModel( @@ -590,6 +591,8 @@ public void Receive(DialogueChangedNotification message) if (_disposed) return; + // The message comes on a background thread. LoadDialoguesAsync changes Dialogues, which the view binds to, and it + // can close the window. Both must be on the UI thread. _guiInvoker.InvokeOnGUI(async _ => { if (_disposed) @@ -605,6 +608,8 @@ public void Receive(FdrOwnerChanged message) if (_disposed) return; + // The message comes on a background thread. LoadDialoguesAsync changes Dialogues, which the view binds to, and it + // can close the window. Both must be on the UI thread. _guiInvoker.InvokeOnGUI(async _ => { if (_disposed) @@ -620,6 +625,8 @@ public void Receive(ConnectedNotification message) if (_disposed) return; + // The message comes on a background thread. LoadDialoguesAsync changes Dialogues, which the view binds to, and it + // can close the window. Both must be on the UI thread. _guiInvoker.InvokeOnGUI(async _ => { if (_disposed) @@ -629,13 +636,14 @@ public void Receive(ConnectedNotification message) }); } - // The window must not close automatically after the controller opens it manually + // The window must not close automatically after the controller opens it manually. The view does not bind to this + // field. Thus, set it on this thread. public void Receive(OpenCurrentMessagesWindowRequest message) { if (_disposed || message.OpenedAutomatically) return; - _guiInvoker.InvokeOnGUI(_ => _closeWhenEmpty = false); + _closeWhenEmpty = false; } [RelayCommand] diff --git a/source/CPDLCPlugin/ViewModels/EditorViewModel.cs b/source/CPDLCPlugin/ViewModels/EditorViewModel.cs index 050edd5..46c682a 100644 --- a/source/CPDLCPlugin/ViewModels/EditorViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/EditorViewModel.cs @@ -747,6 +747,12 @@ IUplinkMessageElementComponentViewModel[] ConvertToViewModel(UplinkMessageRefere public void Receive(DialogueChangedNotification message) { + // The dialogues change for all the aircraft. The editor shows the dialogues of one aircraft only. Do not post to + // the UI thread for the other aircraft. + if (message.Dialogue.AircraftCallsign != Callsign) + return; + + // LoadDownlinkMessagesAsync changes the downlink messages, which the view binds to _guiInvoker.InvokeOnGUI(async _ => await LoadDownlinkMessagesAsync()); } diff --git a/source/CPDLCPlugin/ViewModels/HistoryViewModel.cs b/source/CPDLCPlugin/ViewModels/HistoryViewModel.cs index be06a1d..4f1581d 100644 --- a/source/CPDLCPlugin/ViewModels/HistoryViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/HistoryViewModel.cs @@ -105,9 +105,12 @@ async Task LoadMessages() public void Receive(DialogueChangedNotification notification) { - if (_disposed) + // The dialogues change for all the aircraft. Do not post to the UI thread for an aircraft that this window does + // not show. The UI thread checks again, because the callsign can change before the action runs. + if (_disposed || notification.Dialogue.AircraftCallsign != Callsign) return; + // LoadDialoguesAsync changes Dialogues, which the view binds to _guiInvoker.InvokeOnGUI(mainForm => { if (_disposed) diff --git a/source/CPDLCPlugin/Windows/WindowManager.cs b/source/CPDLCPlugin/Windows/WindowManager.cs index 2a8bd7b..d956325 100644 --- a/source/CPDLCPlugin/Windows/WindowManager.cs +++ b/source/CPDLCPlugin/Windows/WindowManager.cs @@ -48,8 +48,20 @@ public void FocusOrCreateWindow( }); } + public bool IsWindowOpen(string key) + { + lock (_gate) + { + return _forms.ContainsKey(key); + } + } + public void TryRemoveWindow(string key) { + // Do not post to the UI thread if the window is not open + if (!IsWindowOpen(key)) + return; + guiInvoker.InvokeOnGUI(_ => { lock (_gate) From b7f3f33ecb205f956f4dbd253a67c810650cc223 Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:12:28 +0800 Subject: [PATCH 07/18] Fix plugin perf issues --- source/CPDLCPlugin/Plugin.cs | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/source/CPDLCPlugin/Plugin.cs b/source/CPDLCPlugin/Plugin.cs index 7a53bc8..d8130c3 100644 --- a/source/CPDLCPlugin/Plugin.cs +++ b/source/CPDLCPlugin/Plugin.cs @@ -40,6 +40,10 @@ public class Plugin : ILabelPlugin, IStripPlugin, IRecipient RebuildCpdlcStatusLabelItems()); + QueueLabelRebuild(); // If this flight has any dialogues that we have jurisdiction over, open the current messages window // Ensures flights handed off to us open the window so we can see their requests @@ -682,6 +686,21 @@ public void OnRadarTrackUpdate(RDP.RadarTrack updated) {} public CustomColour? SelectGroundTrackColour(Track track) => null; + // vatSys updates the FDRs often, and each rebuild reads all the FDRs. A rebuild reads the state when it runs. Thus, + // if a rebuild is already in the work queue, do not queue another one. + void QueueLabelRebuild() + { + if (Interlocked.Exchange(ref _isLabelRebuildQueued, 1) == 1) + return; + + _workQueue.Enqueue(() => + { + // Clear the flag before the rebuild reads the state. Then a change during the rebuild queues a new rebuild. + Interlocked.Exchange(ref _isLabelRebuildQueued, 0); + return RebuildCpdlcStatusLabelItems(); + }); + } + async Task RebuildCpdlcStatusLabelItems(CancellationToken cancellationToken = default) { try @@ -699,7 +718,7 @@ public void Receive(ConnectedAircraftChanged _) { try { - _workQueue.Enqueue(() => RebuildCpdlcStatusLabelItems()); + QueueLabelRebuild(); } catch (Exception ex) { @@ -711,10 +730,12 @@ public void Receive(DialogueChangedNotification dialogueChangedNotification) { try { + // The rebuild is in the work queue before the next work item. Thus, the labels are rebuilt before the window + // opens. + QueueLabelRebuild(); + _workQueue.Enqueue(async () => { - await RebuildCpdlcStatusLabelItems().ConfigureAwait(false); - // Try to open the Current Messages Window if this dialogue is relevant to the controller var jurisdictionChecker = ServiceProvider.GetRequiredService(); if (dialogueChangedNotification.Dialogue.IsArchived || @@ -723,6 +744,11 @@ public void Receive(DialogueChangedNotification dialogueChangedNotification) return; } + // If the window is open, do not post to the UI thread to open and activate it again + var windowManager = ServiceProvider.GetRequiredService(); + if (windowManager.IsWindowOpen(WindowKeys.CurrentMessages)) + return; + var mediator = ServiceProvider.GetRequiredService(); await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: true)); }); From 2490d6484029870368792702bddfa936dd7f1153 Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:49:52 +0800 Subject: [PATCH 08/18] Expire stale ADS-C reports and delay VATSIM reports Each contract keeps one report. A report expires after two reporting intervals plus three minutes, and the plugin then shows the flight plan track again. VATSIM reports start only after a configurable delay, or after a Hoppie report times out. Co-Authored-By: Claude Opus 5.5 --- .fallout/build.schema.json | 4 + docs/docs/server/index.md | 6 +- source/CPDLCPlugin/AdscReportStore.cs | 20 ++ source/CPDLCPlugin/AdscTrackDisplay.cs | 16 ++ .../Messages/AdscReportExpiredNotification.cs | 25 +++ .../Server/IDownlinkHandlerDelegate.cs | 1 + .../Server/MediatorMessageHandler.cs | 16 ++ .../Server/SignalRConnectionManager.cs | 2 + .../ViewModels/ADSContractViewModel.cs | 8 + .../AdscContractRepositoryTests.cs | 10 +- .../AdscContracts/AdscContractTests.cs | 76 ++++--- ...MessageReceivedNotificationHandlerTests.cs | 11 +- .../CancelAdscContractCommandHandlerTests.cs | 6 +- ...scContractOnConnectionEndedHandlerTests.cs | 8 +- ...ExpiredAdscContractsRequestHandlerTests.cs | 20 +- .../Reports/AdscReportRepositoryTests.cs | 116 +++++----- .../ExpireAdscReportsRequestHandlerTests.cs | 202 ++++++++++++++++++ ...uestAdscDemandReportCommandHandlerTests.cs | 6 +- ...ractOnConnectionEstablishedHandlerTests.cs | 6 +- ...PeriodicAdscContractCommandHandlerTests.cs | 11 +- .../Mocks/TestAdscReportRepository.cs | 50 +++-- ...uceVatsimAdscReportsRequestHandlerTests.cs | 119 +++++++---- .../CPDLCServer/AdscContracts/AdscContract.cs | 42 +++- .../AdscContractConfiguration.cs | 3 + .../AdscContractExpiryService.cs | 4 + .../AdscMessageReceivedNotificationHandler.cs | 11 +- .../Reports/AdscReportExpiredNotification.cs | 5 + .../AdscReportExpiredNotificationHandler.cs | 36 ++++ .../Reports/AdscReportRepository.cs | 66 +++--- .../AircraftAdscReportConfiguration.cs | 7 +- .../Reports/ExpireAdscReportsRequest.cs | 5 + .../ExpireAdscReportsRequestHandler.cs | 49 +++++ .../Reports/IAdscReportRepository.cs | 12 +- .../RequestAdscDemandReportCommandHandler.cs | 2 +- ...questPeriodicAdscContractCommandHandler.cs | 4 +- ... 20261115024457_InitialCreate.Designer.cs} | 32 ++- ...ate.cs => 20261115024457_InitialCreate.cs} | 19 +- .../PostgreSqlCpdlcDbContextModelSnapshot.cs | 30 ++- ... 20261115024453_InitialCreate.Designer.cs} | 30 ++- ...ate.cs => 20261115024453_InitialCreate.cs} | 19 +- .../SqliteCpdlcDbContextModelSnapshot.cs | 28 ++- source/CPDLCServer/Settings/ServerSettings.cs | 3 + .../ProduceVatsimAdscReportsRequestHandler.cs | 43 ++-- .../Web/Pages/Settings/Index.cshtml | 16 ++ 44 files changed, 882 insertions(+), 323 deletions(-) create mode 100644 source/CPDLCPlugin/Messages/AdscReportExpiredNotification.cs create mode 100644 source/CPDLCServer.Tests/AdscContracts/Reports/ExpireAdscReportsRequestHandlerTests.cs create mode 100644 source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotification.cs create mode 100644 source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotificationHandler.cs create mode 100644 source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequest.cs create mode 100644 source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequestHandler.cs rename source/CPDLCServer/Persistence/Migrations/PostgreSql/{20261107042236_InitialCreate.Designer.cs => 20261115024457_InitialCreate.Designer.cs} (95%) rename source/CPDLCServer/Persistence/Migrations/PostgreSql/{20261107042236_InitialCreate.cs => 20261115024457_InitialCreate.cs} (93%) rename source/CPDLCServer/Persistence/Migrations/Sqlite/{20261107042233_InitialCreate.Designer.cs => 20261115024453_InitialCreate.Designer.cs} (95%) rename source/CPDLCServer/Persistence/Migrations/Sqlite/{20261107042233_InitialCreate.cs => 20261115024453_InitialCreate.cs} (93%) diff --git a/.fallout/build.schema.json b/.fallout/build.schema.json index 45a5342..7bddb3a 100644 --- a/.fallout/build.schema.json +++ b/.fallout/build.schema.json @@ -127,6 +127,10 @@ ], "description": "Configuration to build - Default is 'Debug' (local) or 'Release' (server)" }, + "ForceVersion": { + "type": "string", + "description": "Version to use instead of the GitVersion version, for example 1.0.0-rc1" + }, "GitHubToken": { "type": "string", "description": "GitHub token for creating releases", diff --git a/docs/docs/server/index.md b/docs/docs/server/index.md index a9a35c9..e003e26 100644 --- a/docs/docs/server/index.md +++ b/docs/docs/server/index.md @@ -121,7 +121,9 @@ A controller can select a different reporting interval for an aircraft. The sele The aircraft does not acknowledge a request. The first report after a request accepts it. If the aircraft rejects a selected contract, the server requests the default contract again. If the aircraft rejects the default contract, the server does not send it again. -The server keeps a history of the reports for the ADS-C report retention period. When a controller connects, the plugin loads the latest report for each aircraft, so that the controller sees the ADS-C tracks immediately. +The server keeps one report for each contract. A new report replaces the previous report. When a controller connects, the plugin loads the latest report for each aircraft, so that the controller sees the ADS-C tracks immediately. + +A report expires when the next two periodic reports do not arrive. The expiry time is two reporting intervals plus three minutes, from the time in the report. A contract with only a demand request uses the default reporting interval. When a report expires, or when its contract is removed, the server deletes the report and the plugin shows the flight plan track again. The ADS-C page of the dashboard (`/adsc`) shows all the contracts and their states, and a log of all the ADS-C messages that the server sent and received. @@ -129,7 +131,7 @@ The ADS-C page of the dashboard (`/adsc`) shows all the contracts and their stat Not all aircraft support ADS-C over Hoppie's network. When the "ADS-C from VATSIM status data" setting is on, the server fakes ADS-C reports using data from the [VATSIM status API](https://data.vatsim.net/v3/vatsim-data.json). -This is only done for aircraft that have `D1` or `G1` in Item 10b of the flight plan, unless the "allow aircraft without ADS-C equipment" setting is on. A report from Hoppie always has priority. If the Hoppie reports stop for more than two reporting intervals, the server uses the VATSIM status data again. +This is only done for aircraft that have `D1` or `G1` in Item 10b of the flight plan, unless the "allow aircraft without ADS-C equipment" setting is on. The server waits for the "report delay" after it makes a contract before it uses the VATSIM status data, so that the aircraft can send its first report through Hoppie. A report from Hoppie always has priority, and it stops the VATSIM reports for that contract. When the Hoppie report expires, the server uses the VATSIM status data again. ## Running diff --git a/source/CPDLCPlugin/AdscReportStore.cs b/source/CPDLCPlugin/AdscReportStore.cs index c9c20df..5d13726 100644 --- a/source/CPDLCPlugin/AdscReportStore.cs +++ b/source/CPDLCPlugin/AdscReportStore.cs @@ -82,6 +82,26 @@ public async Task> All(CancellationToken canc } } + /// + /// Removes the report of the aircraft, if it is from the ATSU. + /// + /// True if the report was removed. + public async Task Remove(string callsign, string stationId, CancellationToken cancellationToken = default) + { + await _semaphore.WaitAsync(cancellationToken); + try + { + if (!_latestReports.TryGetValue(callsign, out var report) || report.StationId != stationId) + return false; + + return _latestReports.Remove(callsign); + } + finally + { + _semaphore.Release(); + } + } + public async Task Clear(CancellationToken cancellationToken = default) { await _semaphore.WaitAsync(cancellationToken); diff --git a/source/CPDLCPlugin/AdscTrackDisplay.cs b/source/CPDLCPlugin/AdscTrackDisplay.cs index 395c33b..3efe501 100644 --- a/source/CPDLCPlugin/AdscTrackDisplay.cs +++ b/source/CPDLCPlugin/AdscTrackDisplay.cs @@ -55,6 +55,22 @@ public void Show(AdscReportDto report) fdr.PredictedPosition.Location = new Coordinate(report.Latitude, report.Longitude); } + /// + /// Removes the ADS-C track of the aircraft, if it shows a report from the ATSU. + /// The track goes back to its flight plan position. + /// + public void Remove(string callsign, string stationId) + { + if (!_tracks.TryGetValue(callsign, out var track) || track.Report.StationId != stationId) + return; + + // Do not remove a newer report that arrived after the check + if (!((ICollection>)_tracks).Remove(new KeyValuePair(callsign, track))) + return; + + RestoreFlightPlanPosition(callsign); + } + public void Clear() { var callsigns = _tracks.Keys.ToArray(); diff --git a/source/CPDLCPlugin/Messages/AdscReportExpiredNotification.cs b/source/CPDLCPlugin/Messages/AdscReportExpiredNotification.cs new file mode 100644 index 0000000..d742765 --- /dev/null +++ b/source/CPDLCPlugin/Messages/AdscReportExpiredNotification.cs @@ -0,0 +1,25 @@ +using CommunityToolkit.Mvvm.Messaging; +using MediatR; +using Serilog; + +namespace CPDLCPlugin.Messages; + +public record AdscReportExpiredNotification(string Callsign, string StationId) : INotification; + +public class AdscReportExpiredNotificationHandler( + AdscReportStore adscReportStore, + AdscTrackDisplay adscTrackDisplay, + ILogger logger) + : INotificationHandler +{ + public async Task Handle(AdscReportExpiredNotification notification, CancellationToken cancellationToken) + { + logger.Information("ADS-C report from {Callsign} via {StationId} expired", notification.Callsign, notification.StationId); + + // The aircraft can have a newer report from a different ATSU. Then the ADS-C track stays. + await adscReportStore.Remove(notification.Callsign, notification.StationId, cancellationToken); + adscTrackDisplay.Remove(notification.Callsign, notification.StationId); + + WeakReferenceMessenger.Default.Send(notification); + } +} diff --git a/source/CPDLCPlugin/Server/IDownlinkHandlerDelegate.cs b/source/CPDLCPlugin/Server/IDownlinkHandlerDelegate.cs index 8e9b134..eaf5030 100644 --- a/source/CPDLCPlugin/Server/IDownlinkHandlerDelegate.cs +++ b/source/CPDLCPlugin/Server/IDownlinkHandlerDelegate.cs @@ -11,5 +11,6 @@ public interface IDownlinkHandlerDelegate Task AdscContractUpdated(AdscContractDto adscContractDto, CancellationToken cancellationToken); Task AdscContractRemoved(string callsign, string stationId, CancellationToken cancellationToken); Task AdscReportReceived(AdscReportDto adscReportDto, CancellationToken cancellationToken); + Task AdscReportExpired(string callsign, string stationId, CancellationToken cancellationToken); void Error(Exception exception); } diff --git a/source/CPDLCPlugin/Server/MediatorMessageHandler.cs b/source/CPDLCPlugin/Server/MediatorMessageHandler.cs index 3cb9099..682e811 100644 --- a/source/CPDLCPlugin/Server/MediatorMessageHandler.cs +++ b/source/CPDLCPlugin/Server/MediatorMessageHandler.cs @@ -120,6 +120,22 @@ public async Task AdscReportReceived(AdscReportDto adscReportDto, CancellationTo } } + public async Task AdscReportExpired(string callsign, string stationId, CancellationToken cancellationToken) + { + try + { + await mediator.Publish(new AdscReportExpiredNotification(callsign, stationId), cancellationToken); + } + catch (OperationCanceledException) + { + // Expected when cancellation is requested + } + catch (Exception ex) + { + Plugin.AddError(ex, "Failed to handle AdscReportExpired notification"); + } + } + public void Error(Exception error) { Plugin.AddError(error, "Error from SignalR connection"); diff --git a/source/CPDLCPlugin/Server/SignalRConnectionManager.cs b/source/CPDLCPlugin/Server/SignalRConnectionManager.cs index 3cd54c2..2080c49 100644 --- a/source/CPDLCPlugin/Server/SignalRConnectionManager.cs +++ b/source/CPDLCPlugin/Server/SignalRConnectionManager.cs @@ -128,6 +128,8 @@ void RegisterHandlers() WithCancellationToken(downlinkHandlerDelegate.AdscContractRemoved)(callsign, stationId)); _connection.On("AdscReportReceived", adscReport => WithCancellationToken(downlinkHandlerDelegate.AdscReportReceived)(adscReport)); + _connection.On("AdscReportExpired", (callsign, stationId) => + WithCancellationToken(downlinkHandlerDelegate.AdscReportExpired)(callsign, stationId)); } Func WithCancellationToken(Func action) diff --git a/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs b/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs index 9c214d8..5891b22 100644 --- a/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/ADSContractViewModel.cs @@ -11,6 +11,7 @@ public partial class ADSContractViewModel : ObservableObject, IRecipient, IRecipient, IRecipient, + IRecipient, IDisposable { readonly Plugin _plugin; @@ -42,6 +43,7 @@ public ADSContractViewModel( WeakReferenceMessenger.Default.Register(this); WeakReferenceMessenger.Default.Register(this); WeakReferenceMessenger.Default.Register(this); + WeakReferenceMessenger.Default.Register(this); if (!string.IsNullOrWhiteSpace(initialCallsign)) { @@ -224,6 +226,11 @@ public void Receive(AdscReportReceivedNotification notification) ReloadIfShown(notification.AdscReportDto.Callsign); } + public void Receive(AdscReportExpiredNotification notification) + { + ReloadIfShown(notification.Callsign); + } + void ReloadIfShown(string callsign) { // The ADS-C reports come for all the aircraft. Do not post to the UI thread for an aircraft that this window @@ -259,6 +266,7 @@ public void Dispose() WeakReferenceMessenger.Default.Unregister(this); WeakReferenceMessenger.Default.Unregister(this); WeakReferenceMessenger.Default.Unregister(this); + WeakReferenceMessenger.Default.Unregister(this); _disposed = true; } } diff --git a/source/CPDLCServer.Tests/AdscContracts/AdscContractRepositoryTests.cs b/source/CPDLCServer.Tests/AdscContracts/AdscContractRepositoryTests.cs index 1ab47e7..cc4e4b6 100644 --- a/source/CPDLCServer.Tests/AdscContracts/AdscContractRepositoryTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/AdscContractRepositoryTests.cs @@ -1,4 +1,5 @@ using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Tests.Mocks; namespace CPDLCServer.Tests.AdscContracts; @@ -12,9 +13,9 @@ public async Task Find_ReturnsSavedContract() { // Arrange using var database = new TestDatabase(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(15)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(15), Start.AddMinutes(-10)); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); - contract.ReportReceived(); + contract.ReportReceived(new AdscReport(Start.AddMinutes(-5), -33.9461, 151.1772, 37000, AdscReportSource.VATSIM)); contract.RequestSelectedContract(TimeSpan.FromMinutes(2), Start.AddHours(1)); contract.RequestDemandReport(); contract.LogActivity(Start); @@ -38,7 +39,10 @@ public async Task Find_ReturnsSavedContract() Assert.Equal(AdscContractState.Sent, saved.SelectedContractState); Assert.Equal(Start.AddHours(1), saved.SelectedContractEnds); Assert.Equal(AdscContractState.Sent, saved.DemandContractState); + Assert.Equal(Start.AddMinutes(-10), saved.Created); Assert.Equal(Start, saved.LastActivity); + Assert.Equal(Start.AddMinutes(-5), saved.LastReportReceived); + Assert.Equal(AdscReportSource.VATSIM, saved.ReportingSource); } [Fact] @@ -48,7 +52,7 @@ public async Task Remove_DeletesContract() using var database = new TestDatabase(); await using (var dbContext = database.CreateDbContext()) { - await new AdscContractRepository(dbContext).Add(new("UAL123", "YBBB"), new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)), CancellationToken.None); + await new AdscContractRepository(dbContext).Add(new("UAL123", "YBBB"), new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue), CancellationToken.None); await dbContext.SaveChangesAsync(); } diff --git a/source/CPDLCServer.Tests/AdscContracts/AdscContractTests.cs b/source/CPDLCServer.Tests/AdscContracts/AdscContractTests.cs index 83a0b1e..89b5590 100644 --- a/source/CPDLCServer.Tests/AdscContracts/AdscContractTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/AdscContractTests.cs @@ -1,4 +1,5 @@ using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; namespace CPDLCServer.Tests.AdscContracts; @@ -7,12 +8,13 @@ public class AdscContractTests static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(10); static readonly TimeSpan SelectedInterval = TimeSpan.FromMinutes(2); static readonly DateTimeOffset Ends = new(2026, 1, 1, 1, 0, 0, TimeSpan.Zero); + static readonly AdscReport Report = new(Ends.AddHours(-1), -33.9461, 151.1772, 37000, AdscReportSource.Hoppie); [Fact] public void RequestDefaultContract_SendsDefaultContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); // Act contract.RequestDefaultContract(DefaultInterval); @@ -28,7 +30,7 @@ public void RequestDefaultContract_SendsDefaultContract() public void RequestDefaultContract_UpdatesDefaultReportingInterval() { // Arrange - the default reporting interval of the ATSU changed after the contract was made - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(15)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(15), DateTimeOffset.MinValue); // Act contract.RequestDefaultContract(DefaultInterval); @@ -41,9 +43,9 @@ public void RequestDefaultContract_UpdatesDefaultReportingInterval() public void RequestDefaultContract_WhenSelectedContractIsAccepted_EndsSelectedContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestSelectedContract(SelectedInterval, Ends); - contract.ReportReceived(); + contract.ReportReceived(Report); // Act contract.RequestDefaultContract(DefaultInterval); @@ -60,7 +62,7 @@ public void RequestDefaultContract_WhenSelectedContractIsAccepted_EndsSelectedCo public void RequestDefaultContract_WhenSelectedContractIsRejected_KeepsRejection() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestSelectedContract(SelectedInterval, Ends); contract.Reject(); @@ -77,9 +79,9 @@ public void RequestDefaultContract_WhenSelectedContractIsRejected_KeepsRejection public void RequestSelectedContract_SendsSelectedContractAndKeepsDefaultContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); - contract.ReportReceived(); + contract.ReportReceived(Report); // Act contract.RequestSelectedContract(SelectedInterval, Ends); @@ -96,14 +98,13 @@ public void RequestSelectedContract_SendsSelectedContractAndKeepsDefaultContract public void ReportReceived_WhenDefaultContractIsSent_AcceptsDefaultContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); // Act - var changed = contract.ReportReceived(); + contract.ReportReceived(Report); // Assert - Assert.True(changed); Assert.Equal(AdscContractState.Accepted, contract.DefaultContractState); } @@ -111,15 +112,14 @@ public void ReportReceived_WhenDefaultContractIsSent_AcceptsDefaultContract() public void ReportReceived_WhenSelectedContractIsSent_AcceptsSelectedContractAndEndsDefaultContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); contract.RequestSelectedContract(SelectedInterval, Ends); // Act - var changed = contract.ReportReceived(); + contract.ReportReceived(Report); // Assert - Assert.True(changed); Assert.Equal(AdscContractState.Accepted, contract.SelectedContractState); Assert.Null(contract.DefaultContractState); } @@ -128,32 +128,48 @@ public void ReportReceived_WhenSelectedContractIsSent_AcceptsSelectedContractAnd public void ReportReceived_WhenDemandReportIsSent_AcceptsDemandReport() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDemandReport(); // Act - var changed = contract.ReportReceived(); + contract.ReportReceived(Report); // Assert - Assert.True(changed); Assert.Equal(AdscContractState.Accepted, contract.DemandContractState); Assert.False(contract.HasPeriodicContract); Assert.True(contract.IsActive); } [Fact] - public void ReportReceived_WhenNothingIsSent_ReturnsFalse() + public void ReportReceived_RecordsTimestampAndSource() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); - contract.ReportReceived(); + var report = Report with { Source = AdscReportSource.VATSIM }; // Act - var changed = contract.ReportReceived(); + contract.ReportReceived(report); // Assert - Assert.False(changed); + Assert.Equal(report.Timestamp, contract.LastReportReceived); + Assert.Equal(AdscReportSource.VATSIM, contract.ReportingSource); + } + + [Fact] + public void ReportTimedOut_RemovesSourceAndKeepsTimestamp() + { + // Arrange + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + contract.RequestDefaultContract(DefaultInterval); + contract.ReportReceived(Report); + + // Act + contract.ReportTimedOut(); + + // Assert + Assert.Null(contract.ReportingSource); + Assert.Equal(Report.Timestamp, contract.LastReportReceived); Assert.Equal(AdscContractState.Accepted, contract.DefaultContractState); } @@ -161,9 +177,9 @@ public void ReportReceived_WhenNothingIsSent_ReturnsFalse() public void Reject_WhenSelectedContractIsSent_RejectsSelectedContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); - contract.ReportReceived(); + contract.ReportReceived(Report); contract.RequestSelectedContract(SelectedInterval, Ends); // Act @@ -180,9 +196,9 @@ public void Reject_WhenSelectedContractIsSent_RejectsSelectedContract() public void Reject_WhenSelectedContractIsAccepted_RejectsSelectedContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestSelectedContract(SelectedInterval, Ends); - contract.ReportReceived(); + contract.ReportReceived(Report); // Act var selectedContractRejected = contract.Reject(); @@ -197,7 +213,7 @@ public void Reject_WhenSelectedContractIsAccepted_RejectsSelectedContract() public void Reject_WhenDefaultContractIsSent_RejectsDefaultContract() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); // Act @@ -213,9 +229,9 @@ public void Reject_WhenDefaultContractIsSent_RejectsDefaultContract() public void Reject_WhenDemandReportIsSent_RejectsDemandReport() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(DefaultInterval); - contract.ReportReceived(); + contract.ReportReceived(Report); contract.RequestDemandReport(); // Act @@ -230,9 +246,9 @@ public void Reject_WhenDemandReportIsSent_RejectsDemandReport() public void Reject_WhenDemandReportIsAccepted_KeepsDemandReport() { // Arrange - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDemandReport(); - contract.ReportReceived(); + contract.ReportReceived(Report); contract.RequestDefaultContract(DefaultInterval); // Act diff --git a/source/CPDLCServer.Tests/AdscContracts/AdscMessageReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/AdscMessageReceivedNotificationHandlerTests.cs index d3370a6..0536ad1 100644 --- a/source/CPDLCServer.Tests/AdscContracts/AdscMessageReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/AdscMessageReceivedNotificationHandlerTests.cs @@ -9,6 +9,7 @@ namespace CPDLCServer.Tests.AdscContracts; public class AdscMessageReceivedNotificationHandlerTests { + static readonly AdscReport Report = new(DateTimeOffset.UtcNow, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie); static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(10); static readonly TimeSpan SelectedInterval = TimeSpan.FromMinutes(2); @@ -101,13 +102,13 @@ await mediator.Received(1).Publish( } [Fact] - public async Task Handle_Report_WhenContractIsAccepted_DoesNotPublishContractChange() + public async Task Handle_Report_WhenContractIsAccepted_PublishesContractChange() { // Arrange var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository, "YBBB"); contract.RequestDefaultContract(DefaultInterval); - contract.ReportReceived(); + contract.ReportReceived(Report); var mediator = Substitute.For(); var handler = new AdscMessageReceivedNotificationHandler(new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); @@ -116,8 +117,8 @@ public async Task Handle_Report_WhenContractIsAccepted_DoesNotPublishContractCha await handler.Handle(CreateReport("YBBB"), CancellationToken.None); // Assert - await mediator.DidNotReceive().Publish( - Arg.Any(), + await mediator.Received(1).Publish( + Arg.Is(n => n.Contract == contract), Arg.Any()); await mediator.Received(1).Publish( Arg.Any(), @@ -250,7 +251,7 @@ public async Task Handle_Rejection_LogsActivity() static async Task AddContract(TestAdscContractRepository contractRepository, string stationId) { - var contract = new AdscContract("UAL123", stationId, TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", stationId, TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", stationId), contract, CancellationToken.None); return contract; } diff --git a/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractCommandHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractCommandHandlerTests.cs index 99d0219..b35c5ec 100644 --- a/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractCommandHandlerTests.cs @@ -14,7 +14,7 @@ public async Task Handle_WhenContractExists_SendsCancelAndRemovesContract() // Arrange var acarsConnectionManager = new TestAcarsConnectionManager(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); @@ -59,8 +59,8 @@ public async Task Handle_OnlyRemovesContractForStation() { // Arrange var contractRepository = new TestAdscContractRepository(); - var ybbbContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); - var ymmmContract = new AdscContract("UAL123", "YMMM", TimeSpan.FromMinutes(10)); + var ybbbContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + var ymmmContract = new AdscContract("UAL123", "YMMM", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), ybbbContract, CancellationToken.None); await contractRepository.Add(new AdscContractKey("UAL123", "YMMM"), ymmmContract, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs index a397863..e637658 100644 --- a/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs @@ -14,7 +14,7 @@ public async Task Handle_ConnectionTerminated_CancelsContract() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); @@ -37,7 +37,7 @@ public async Task Handle_ConnectionLost_CancelsContractForStationOfAcarsConnecti { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YMMM", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YMMM", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YMMM"), contract, CancellationToken.None); var mediator = Substitute.For(); @@ -77,7 +77,7 @@ public async Task Handle_WhenContractIsWithOtherStation_DoesNotCancel() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YMMM", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YMMM", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YMMM"), contract, CancellationToken.None); var mediator = Substitute.For(); @@ -98,7 +98,7 @@ public async Task Handle_WhenCancelFails_DoesNotThrow() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); var mediator = Substitute.For(); diff --git a/source/CPDLCServer.Tests/AdscContracts/EndExpiredAdscContractsRequestHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/EndExpiredAdscContractsRequestHandlerTests.cs index e97a2a6..680fafe 100644 --- a/source/CPDLCServer.Tests/AdscContracts/EndExpiredAdscContractsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/EndExpiredAdscContractsRequestHandlerTests.cs @@ -22,7 +22,7 @@ public async Task Handle_WhenSelectedContractHasEnded_RequestsDefaultContract() // Arrange var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestSelectedContract(TimeSpan.FromMinutes(2), clock.UtcNow()); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); @@ -46,7 +46,7 @@ public async Task Handle_WhenSelectedContractHasNotEnded_DoesNothing() // Arrange var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestSelectedContract(TimeSpan.FromMinutes(2), clock.UtcNow().AddSeconds(1)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); @@ -68,7 +68,7 @@ public async Task Handle_WhenNoSelectedContract_DoesNothing() // Arrange var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); @@ -92,7 +92,7 @@ public async Task Handle_WhenRequestFails_ContinuesWithOtherContracts() var contractRepository = new TestAdscContractRepository(); foreach (var callsign in new[] { "UAL123", "QFA1" }) { - var contract = new AdscContract(callsign, "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract(callsign, "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestSelectedContract(TimeSpan.FromMinutes(2), clock.UtcNow()); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey(callsign, "YBBB"), contract, CancellationToken.None); @@ -121,7 +121,7 @@ public async Task Handle_WhenContractIsInactive_CancelsAndRemovesContract() // Arrange var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); @@ -150,7 +150,7 @@ public async Task Handle_WhenServerOnlineForLessThanTimeout_KeepsInactiveContrac // Arrange - the last activity was long before the server started var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); @@ -178,7 +178,7 @@ public async Task Handle_WhenServerOnlineForLessThanTimeout_StillEndsSelectedCon // Arrange var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestSelectedContract(TimeSpan.FromMinutes(2), clock.UtcNow()); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); @@ -202,7 +202,7 @@ public async Task Handle_WhenContractIsInactiveAndAcarsCancelFails_RemovesContra // Arrange - TestAcarsConnectionManager has no ACARS connection for YSSY, so the cancel fails var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YSSY", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YSSY", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YSSY"), contract, CancellationToken.None); @@ -228,7 +228,7 @@ public async Task Handle_WhenContractHasRecentActivity_KeepsContract() // Arrange var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); @@ -252,7 +252,7 @@ public async Task Handle_WhenSelectedContractIsInactive_CancelsInsteadOfRequesti // Arrange var clock = new TestClock(); var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestSelectedContract(TimeSpan.FromMinutes(2), clock.UtcNow().AddMinutes(60)); contract.LogActivity(clock.UtcNow()); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs index 3ed2def..6a25f58 100644 --- a/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs @@ -9,26 +9,30 @@ public class AdscReportRepositoryTests static readonly DateTimeOffset Start = new(2026, 10, 13, 12, 0, 0, TimeSpan.Zero); [Fact] - public async Task Add_KeepsLatestReportForEachAircraft() + public async Task Add_KeepsOneReportForEachContract() { // Arrange using var database = new TestDatabase(); var first = CreateReport("UAL123", "YBBB", 0); var second = CreateReport("UAL123", "YBBB", 5); - var other = CreateReport("QFA1", "YBBB", 0); + var otherStation = CreateReport("UAL123", "YMMM", 0); + var otherAircraft = CreateReport("QFA1", "YBBB", 0); // Act - await AddAndSave(database, first, second, other); + await AddAndSave(database, first, otherStation, otherAircraft); + await AddAndSave(database, second); // Assert - var reports = await AllLatest(database); - Assert.Equal(2, reports.Length); + await using var dbContext = database.CreateDbContext(); + var reports = await dbContext.AdscReports.ToArrayAsync(); + Assert.Equal(3, reports.Length); Assert.Contains(second, reports); - Assert.Contains(other, reports); + Assert.Contains(otherStation, reports); + Assert.Contains(otherAircraft, reports); } [Fact] - public async Task Add_KeepsHistoryOfReports() + public async Task Add_InSameUnitOfWork_KeepsOneReportForEachContract() { // Arrange using var database = new TestDatabase(); @@ -36,82 +40,87 @@ public async Task Add_KeepsHistoryOfReports() var second = CreateReport("UAL123", "YBBB", 5); // Act - await AddAndSave(database, first); - await AddAndSave(database, second); + await AddAndSave(database, first, second); // Assert await using var dbContext = database.CreateDbContext(); - var history = await dbContext.AdscReports.ToArrayAsync(); - Assert.Equal(2, history.Length); - Assert.Contains(first, history); - Assert.Contains(second, history); + Assert.Equal([second], await dbContext.AdscReports.ToArrayAsync()); } [Fact] - public async Task Add_WhenReportIsOlder_KeepsNewerReport() + public async Task AllLatest_ReturnsLatestReportForEachAircraft() { // Arrange using var database = new TestDatabase(); - var newer = CreateReport("UAL123", "YBBB", 5); - var older = CreateReport("UAL123", "YMMM", 0); + var older = CreateReport("UAL123", "YBBB", 0); + var newer = CreateReport("UAL123", "YMMM", 5); + var other = CreateReport("QFA1", "YBBB", 0); + await AddAndSave(database, older, newer, other); // Act - await AddAndSave(database, newer); - await AddAndSave(database, older); + var reports = await AllLatest(database); // Assert - Assert.Equal([newer], await AllLatest(database)); + Assert.Equal(2, reports.Length); + Assert.Contains(newer, reports); + Assert.Contains(other, reports); } [Fact] - public async Task Add_InSameUnitOfWork_KeepsOneLatestReport() + public async Task AllLatest_WhenVatsimReportIsNewerThanHoppieReport_ReturnsHoppieReport() { // Arrange using var database = new TestDatabase(); - var first = CreateReport("UAL123", "YBBB", 0); - var second = CreateReport("UAL123", "YMMM", 5); - - // Act - await AddAndSave(database, first, second); + var hoppieReport = CreateReport("UAL123", "YBBB", 0); + var vatsimReport = CreateReport("UAL123", "YMMM", 5, AdscReportSource.VATSIM); + await AddAndSave(database, hoppieReport, vatsimReport); - // Assert - Assert.Equal([second], await AllLatest(database)); + // Act & Assert + Assert.Equal([hoppieReport], await AllLatest(database)); } [Fact] - public async Task Add_WhenHoppieReportIsOlderThanVatsimReport_ReplacesVatsimReport() + public async Task FindLatest_ReturnsLatestReportForAircraft() { // Arrange using var database = new TestDatabase(); - var vatsimReport = CreateReport("UAL123", "YBBB", 5, AdscReportSource.VATSIM); - var hoppieReport = CreateReport("UAL123", "YBBB", 0); - - // Act - await AddAndSave(database, vatsimReport); - await AddAndSave(database, hoppieReport); + var report = CreateReport("UAL123", "YBBB", 0); + await AddAndSave(database, report); - // Assert - Assert.Equal([hoppieReport], await AllLatest(database)); + // Act & Assert + await using var dbContext = database.CreateDbContext(); + var repository = new AdscReportRepository(dbContext); + Assert.Equal(report, await repository.FindLatest("UAL123", CancellationToken.None)); + Assert.Null(await repository.FindLatest("QFA1", CancellationToken.None)); } [Fact] - public async Task Add_WhenVatsimReportIsOlderThanHoppieReport_KeepsHoppieReport() + public async Task RemoveOlderThan_RemovesOnlyOlderReports() { // Arrange using var database = new TestDatabase(); - var hoppieReport = CreateReport("UAL123", "YBBB", 5); - var vatsimReport = CreateReport("UAL123", "YBBB", 0, AdscReportSource.VATSIM); + var older = CreateReport("UAL123", "YBBB", 0); + var atCutoff = CreateReport("QFA1", "YBBB", 5); + var newer = CreateReport("VOZ1", "YBBB", 10); + await AddAndSave(database, older, atCutoff, newer); // Act - await AddAndSave(database, hoppieReport); - await AddAndSave(database, vatsimReport); + await using (var dbContext = database.CreateDbContext()) + { + var repository = new AdscReportRepository(dbContext); + await repository.RemoveOlderThan(atCutoff.Received, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } // Assert - Assert.Equal([hoppieReport], await AllLatest(database)); + var reports = await AllLatest(database); + Assert.Equal(2, reports.Length); + Assert.Contains(atCutoff, reports); + Assert.Contains(newer, reports); } [Fact] - public async Task FindLatest_ReturnsLatestReportForAircraft() + public async Task Find_ReturnsReportForContract() { // Arrange using var database = new TestDatabase(); @@ -121,33 +130,30 @@ public async Task FindLatest_ReturnsLatestReportForAircraft() // Act & Assert await using var dbContext = database.CreateDbContext(); var repository = new AdscReportRepository(dbContext); - Assert.Equal(report, await repository.FindLatest("UAL123", CancellationToken.None)); - Assert.Null(await repository.FindLatest("QFA1", CancellationToken.None)); + Assert.Equal(report, await repository.Find("UAL123", "YBBB", CancellationToken.None)); + Assert.Null(await repository.Find("UAL123", "YMMM", CancellationToken.None)); } [Fact] - public async Task RemoveOlderThan_RemovesOnlyOlderReports() + public async Task Remove_RemovesReport() { // Arrange using var database = new TestDatabase(); - var older = CreateReport("UAL123", "YBBB", 0); - var atCutoff = CreateReport("QFA1", "YBBB", 5); - var newer = CreateReport("VOZ1", "YBBB", 10); - await AddAndSave(database, older, atCutoff, newer); + var removed = CreateReport("UAL123", "YBBB", 0); + var kept = CreateReport("QFA1", "YBBB", 0); + await AddAndSave(database, removed, kept); // Act await using (var dbContext = database.CreateDbContext()) { var repository = new AdscReportRepository(dbContext); - await repository.RemoveOlderThan(atCutoff.Received, CancellationToken.None); + var report = await repository.Find("UAL123", "YBBB", CancellationToken.None); + await repository.Remove(report!, CancellationToken.None); await dbContext.SaveChangesAsync(); } // Assert - var reports = await AllLatest(database); - Assert.Equal(2, reports.Length); - Assert.Contains(atCutoff, reports); - Assert.Contains(newer, reports); + Assert.Equal([kept], await AllLatest(database)); } static async Task AddAndSave(TestDatabase database, params AircraftAdscReport[] reports) diff --git a/source/CPDLCServer.Tests/AdscContracts/Reports/ExpireAdscReportsRequestHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/ExpireAdscReportsRequestHandlerTests.cs new file mode 100644 index 0000000..78c4f31 --- /dev/null +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/ExpireAdscReportsRequestHandlerTests.cs @@ -0,0 +1,202 @@ +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Tests.Mocks; +using MediatR; +using NSubstitute; +using Serilog.Core; + +namespace CPDLCServer.Tests.AdscContracts.Reports; + +public class ExpireAdscReportsRequestHandlerTests +{ + static readonly TimeSpan ReportingInterval = TimeSpan.FromMinutes(10); + + // Two reporting intervals and the delivery tolerance + static readonly TimeSpan ReportExpiry = TimeSpan.FromMinutes(23); + + [Fact] + public async Task Handle_WhenLastReportIsOlderThanReportExpiry_RemovesReportAndPublishesNotification() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDefaultContract(ReportingInterval); + + var reportRepository = new TestAdscReportRepository(); + await ReceiveReport(reportRepository, contract, clock.UtcNow() - ReportExpiry - TimeSpan.FromSeconds(1)); + + var mediator = Substitute.For(); + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, mediator, Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Empty(await reportRepository.All(CancellationToken.None)); + await mediator.Received(1).Publish( + Arg.Is(n => n.Callsign == "UAL123" && n.StationId == "YBBB"), + Arg.Any()); + } + + [Fact] + public async Task Handle_WhenLastReportIsOlderThanReportExpiry_TimesOutContractReport() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDefaultContract(ReportingInterval); + + var reportRepository = new TestAdscReportRepository(); + var report = await ReceiveReport(reportRepository, contract, clock.UtcNow() - ReportExpiry - TimeSpan.FromSeconds(1)); + + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, Substitute.For(), Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Null(contract.ReportingSource); + Assert.Equal(report.Report.Timestamp, contract.LastReportReceived); + } + + [Fact] + public async Task Handle_WhenLastReportIsNotOlderThanReportExpiry_KeepsReport() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDefaultContract(ReportingInterval); + + var reportRepository = new TestAdscReportRepository(); + var report = await ReceiveReport(reportRepository, contract, clock.UtcNow() - ReportExpiry); + + var mediator = Substitute.For(); + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, mediator, Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Equal([report], await reportRepository.All(CancellationToken.None)); + await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_WhenSelectedContractHasShorterInterval_UsesSelectedInterval() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDefaultContract(ReportingInterval); + contract.RequestSelectedContract(TimeSpan.FromMinutes(2), clock.UtcNow().AddHours(1)); + + // Two selected intervals and the delivery tolerance is 7 minutes + var reportRepository = new TestAdscReportRepository(); + await ReceiveReport(reportRepository, contract, clock.UtcNow() - TimeSpan.FromMinutes(7) - TimeSpan.FromSeconds(1)); + + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, Substitute.For(), Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Empty(await reportRepository.All(CancellationToken.None)); + } + + [Fact] + public async Task Handle_WhenContractHasOnlyDemandRequest_UsesDefaultInterval() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDemandReport(); + + var reportRepository = new TestAdscReportRepository(); + var report = await ReceiveReport(reportRepository, contract, clock.UtcNow() - ReportExpiry); + + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, Substitute.For(), Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Equal([report], await reportRepository.All(CancellationToken.None)); + } + + [Fact] + public async Task Handle_WhenContractHasNoLastReport_RemovesReport() + { + // Arrange + var clock = new TestClock(); + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + contract.RequestDefaultContract(ReportingInterval); + + var reportRepository = new TestAdscReportRepository(); + await AddReport(reportRepository, clock.UtcNow()); + + var handler = new ExpireAdscReportsRequestHandler(reportRepository, contractRepository, clock, Substitute.For(), Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Empty(await reportRepository.All(CancellationToken.None)); + } + + [Fact] + public async Task Handle_WhenReportHasNoContract_RemovesReportAndPublishesNotification() + { + // Arrange + var clock = new TestClock(); + var reportRepository = new TestAdscReportRepository(); + await AddReport(reportRepository, clock.UtcNow()); + + var mediator = Substitute.For(); + var handler = new ExpireAdscReportsRequestHandler( + reportRepository, new TestAdscContractRepository(), clock, mediator, Logger.None); + + // Act + await handler.Handle(new ExpireAdscReportsRequest(), CancellationToken.None); + + // Assert + Assert.Empty(await reportRepository.All(CancellationToken.None)); + await mediator.Received(1).Publish( + Arg.Is(n => n.Callsign == "UAL123" && n.StationId == "YBBB"), + Arg.Any()); + } + + static async Task AddContract(TestAdscContractRepository contractRepository) + { + var contract = new AdscContract("UAL123", "YBBB", ReportingInterval, DateTimeOffset.MinValue); + await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); + return contract; + } + + // Adds the report to the repository and gives it to the contract, as the server does when a report arrives + static async Task ReceiveReport( + TestAdscReportRepository reportRepository, + AdscContract contract, + DateTimeOffset timestamp) + { + var report = await AddReport(reportRepository, timestamp); + contract.ReportReceived(report.Report); + return report; + } + + static async Task AddReport(TestAdscReportRepository reportRepository, DateTimeOffset timestamp) + { + var report = new AircraftAdscReport( + "UAL123", + "YBBB", + new AdscReport(timestamp, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie), + timestamp); + await reportRepository.Add(report, CancellationToken.None); + return report; + } +} diff --git a/source/CPDLCServer.Tests/AdscContracts/Reports/RequestAdscDemandReportCommandHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/RequestAdscDemandReportCommandHandlerTests.cs index ae7f96d..a0c131a 100644 --- a/source/CPDLCServer.Tests/AdscContracts/Reports/RequestAdscDemandReportCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/RequestAdscDemandReportCommandHandlerTests.cs @@ -9,6 +9,8 @@ namespace CPDLCServer.Tests.AdscContracts.Reports; public class RequestAdscDemandReportCommandHandlerTests { + static readonly AdscReport Report = new(DateTimeOffset.UtcNow, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie); + [Fact] public async Task Handle_SendsRequestViaAcarsConnectionForStation() { @@ -56,9 +58,9 @@ public async Task Handle_WhenPeriodicContractExists_KeepsPeriodicContractAndSend { // Arrange var contractRepository = new TestAdscContractRepository(); - var existingContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var existingContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); existingContract.RequestDefaultContract(TimeSpan.FromMinutes(10)); - existingContract.ReportReceived(); + existingContract.ReportReceived(Report); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), existingContract, CancellationToken.None); var mediator = Substitute.For(); diff --git a/source/CPDLCServer.Tests/AdscContracts/RequestAdscContractOnConnectionEstablishedHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/RequestAdscContractOnConnectionEstablishedHandlerTests.cs index c19a6e5..1c1a067 100644 --- a/source/CPDLCServer.Tests/AdscContracts/RequestAdscContractOnConnectionEstablishedHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/RequestAdscContractOnConnectionEstablishedHandlerTests.cs @@ -34,7 +34,7 @@ public async Task Handle_WhenSelectedContractExists_DoesNotRequestContract() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestSelectedContract(TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow.AddHours(1)); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); @@ -56,7 +56,7 @@ public async Task Handle_WhenOnlyDemandReportExists_RequestsDefaultContract() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDemandReport(); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); @@ -80,7 +80,7 @@ public async Task Handle_WhenDefaultContractIsRejected_RequestsDefaultContract() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); contract.RequestDefaultContract(TimeSpan.FromMinutes(10)); contract.Reject(); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/AdscContracts/RequestPeriodicAdscContractCommandHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/RequestPeriodicAdscContractCommandHandlerTests.cs index 05d9118..c8a58b6 100644 --- a/source/CPDLCServer.Tests/AdscContracts/RequestPeriodicAdscContractCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/RequestPeriodicAdscContractCommandHandlerTests.cs @@ -1,4 +1,5 @@ using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Tests.Mocks; using MediatR; using NSubstitute; @@ -8,6 +9,8 @@ namespace CPDLCServer.Tests.AdscContracts; public class RequestPeriodicAdscContractCommandHandlerTests { + static readonly AdscReport Report = new(DateTimeOffset.UtcNow, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie); + [Fact] public async Task Handle_SendsDefaultIntervalViaAcarsConnectionForStation() { @@ -74,9 +77,9 @@ public async Task Handle_WithDefaultInterval_WhenSelectedContractIsInUse_EndsSel { // Arrange var contractRepository = new TestAdscContractRepository(); - var existingContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var existingContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); existingContract.RequestSelectedContract(TimeSpan.FromMinutes(2), DateTimeOffset.UtcNow.AddHours(1)); - existingContract.ReportReceived(); + existingContract.ReportReceived(Report); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), existingContract, CancellationToken.None); var handler = new RequestPeriodicAdscContractCommandHandler( @@ -171,9 +174,9 @@ public async Task Handle_WhenDefaultContractExists_KeepsDefaultContractUntilAcce { // Arrange var contractRepository = new TestAdscContractRepository(); - var existingContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var existingContract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); existingContract.RequestDefaultContract(TimeSpan.FromMinutes(10)); - existingContract.ReportReceived(); + existingContract.ReportReceived(Report); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), existingContract, CancellationToken.None); var handler = new RequestPeriodicAdscContractCommandHandler( diff --git a/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs index 8713f8d..d54ac22 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs @@ -4,43 +4,53 @@ namespace CPDLCServer.Tests.Mocks; public class TestAdscReportRepository : IAdscReportRepository { - private readonly List _history = []; - private readonly Dictionary _latest = new(); + private readonly List _reports = []; public Task Add(AircraftAdscReport report, CancellationToken cancellationToken) { - _history.Add(report); - - if (_latest.TryGetValue(report.Callsign, out var latest)) - { - var replacesVatsimReport = report.Report.Source == AdscReportSource.Hoppie && - latest.Report.Source == AdscReportSource.VATSIM; - - if (!replacesVatsimReport && latest.Report.Timestamp > report.Report.Timestamp) - return Task.CompletedTask; - } - - _latest[report.Callsign] = report; + _reports.RemoveAll(r => r.Callsign == report.Callsign && r.StationId == report.StationId); + _reports.Add(report); return Task.CompletedTask; } + public Task Find(string callsign, string stationId, CancellationToken cancellationToken) + { + return Task.FromResult(_reports.FirstOrDefault(r => r.Callsign == callsign && r.StationId == stationId)); + } + public Task FindLatest(string callsign, CancellationToken cancellationToken) { - return Task.FromResult(_latest.GetValueOrDefault(callsign)); + var reports = _reports.Where(r => r.Callsign == callsign).ToArray(); + return Task.FromResult(reports.Length == 0 ? null : SelectLatest(reports)); } public Task AllLatest(CancellationToken cancellationToken) { - return Task.FromResult(_latest.Values.ToArray()); + return Task.FromResult(_reports.GroupBy(r => r.Callsign).Select(SelectLatest).ToArray()); } - public Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken) + public Task All(CancellationToken cancellationToken) { - _history.RemoveAll(r => r.Received < cutoff); + return Task.FromResult(_reports.ToArray()); + } - foreach (var report in _latest.Values.Where(r => r.Received < cutoff).ToArray()) - _latest.Remove(report.Callsign); + public Task Remove(AircraftAdscReport report, CancellationToken cancellationToken) + { + _reports.Remove(report); + return Task.CompletedTask; + } + public Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken) + { + _reports.RemoveAll(r => r.Received < cutoff); return Task.CompletedTask; } + + static AircraftAdscReport SelectLatest(IEnumerable reports) + { + return reports + .OrderByDescending(r => r.Report.Source == AdscReportSource.Hoppie) + .ThenByDescending(r => r.Report.Timestamp) + .First(); + } } diff --git a/source/CPDLCServer.Tests/VatsimStatus/ProduceVatsimAdscReportsRequestHandlerTests.cs b/source/CPDLCServer.Tests/VatsimStatus/ProduceVatsimAdscReportsRequestHandlerTests.cs index 3d24f9e..a7c9a04 100644 --- a/source/CPDLCServer.Tests/VatsimStatus/ProduceVatsimAdscReportsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/VatsimStatus/ProduceVatsimAdscReportsRequestHandlerTests.cs @@ -14,6 +14,7 @@ public class ProduceVatsimAdscReportsRequestHandlerTests static readonly TimeSpan DefaultInterval = TimeSpan.FromMinutes(10); static readonly DateTimeOffset Now = new(2026, 10, 17, 12, 0, 0, TimeSpan.Zero); static readonly DateTimeOffset LastUpdated = Now.AddSeconds(-10); + static readonly TimeSpan ReportDelay = TimeSpan.FromMinutes(5); [Fact] public async Task Handle_WhenNoReport_PublishesVatsimReportAndAcceptsContract() @@ -24,7 +25,7 @@ public async Task Handle_WhenNoReport_PublishesVatsimReportAndAcceptsContract() contract.RequestDefaultContract(DefaultInterval); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, new TestAdscReportRepository(), mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -42,18 +43,33 @@ await mediator.Received(1).Publish( } [Fact] - public async Task Handle_WhenVatsimReportIsDue_PublishesVatsimReport() + public async Task Handle_WhenContractIsNewerThanReportDelay_PublishesNothing() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = await AddContract(contractRepository); + var contract = await AddContract(contractRepository, Now - ReportDelay + TimeSpan.FromSeconds(1)); contract.RequestDefaultContract(DefaultInterval); - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.VATSIM, Now - DefaultInterval); + var mediator = Substitute.For(); + var handler = await CreateHandler(contractRepository, mediator); + + // Act + await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); + + // Assert + await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_WhenContractIsReportDelayOld_PublishesVatsimReport() + { + // Arrange + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository, Now - ReportDelay); + contract.RequestDefaultContract(DefaultInterval); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -63,39 +79,37 @@ public async Task Handle_WhenVatsimReportIsDue_PublishesVatsimReport() } [Fact] - public async Task Handle_WhenVatsimReportIsNotDue_PublishesNothing() + public async Task Handle_WhenVatsimReportIsDue_PublishesVatsimReport() { // Arrange var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository); contract.RequestDefaultContract(DefaultInterval); - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.VATSIM, Now.AddMinutes(-5)); + ReceiveReport(contract, AdscReportSource.VATSIM, Now - DefaultInterval); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); // Assert - await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); + await mediator.Received(1).Publish(Arg.Any(), Arg.Any()); } [Fact] - public async Task Handle_WhenHoppieReportIsTwoIntervalsLate_PublishesNothing() + public async Task Handle_WhenVatsimReportIsNotDue_PublishesNothing() { // Arrange var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository); contract.RequestDefaultContract(DefaultInterval); - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.Hoppie, Now - DefaultInterval * 2); + ReceiveReport(contract, AdscReportSource.VATSIM, Now.AddMinutes(-5)); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -105,24 +119,24 @@ public async Task Handle_WhenHoppieReportIsTwoIntervalsLate_PublishesNothing() } [Fact] - public async Task Handle_WhenHoppieReportIsMoreThanTwoIntervalsLate_PublishesVatsimReport() + public async Task Handle_WhenSourceIsHoppie_PublishesNothing() { // Arrange var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository); contract.RequestDefaultContract(DefaultInterval); - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.Hoppie, Now - DefaultInterval * 2 - TimeSpan.FromSeconds(1)); + // The periodic report is due, but the report must come from Hoppie + ReceiveReport(contract, AdscReportSource.Hoppie, Now - DefaultInterval * 2 - TimeSpan.FromSeconds(1)); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); // Assert - await mediator.Received(1).Publish(Arg.Any(), Arg.Any()); + await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); } [Fact] @@ -135,7 +149,7 @@ public async Task Handle_WhenContractIsRejected_PublishesNothing() contract.Reject(); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, new TestAdscReportRepository(), mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -151,14 +165,13 @@ public async Task Handle_WhenDemandRequestIsSent_PublishesVatsimReportAndAccepts var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository); contract.RequestDefaultContract(DefaultInterval); - contract.RequestDemandReport(); // The periodic report is not due - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.VATSIM, Now.AddMinutes(-1)); + ReceiveReport(contract, AdscReportSource.VATSIM, Now.AddMinutes(-1)); + contract.RequestDemandReport(); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -174,13 +187,11 @@ public async Task Handle_WhenDemandOnlyContractHasHoppieReport_PublishesNothing( // Arrange var contractRepository = new TestAdscContractRepository(); var contract = await AddContract(contractRepository); + ReceiveReport(contract, AdscReportSource.Hoppie, Now.AddHours(-1)); contract.RequestDemandReport(); - var reportRepository = new TestAdscReportRepository(); - await AddReport(reportRepository, AdscReportSource.Hoppie, Now.AddHours(-1)); - var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, reportRepository, mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -189,6 +200,26 @@ public async Task Handle_WhenDemandOnlyContractHasHoppieReport_PublishesNothing( await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); } + [Fact] + public async Task Handle_WhenHoppieReportTimedOut_PublishesVatsimReport() + { + // Arrange + var contractRepository = new TestAdscContractRepository(); + var contract = await AddContract(contractRepository); + ReceiveReport(contract, AdscReportSource.Hoppie, Now.AddHours(-1)); + contract.ReportTimedOut(); + contract.RequestDemandReport(); + + var mediator = Substitute.For(); + var handler = await CreateHandler(contractRepository, mediator); + + // Act + await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); + + // Assert + await mediator.Received(1).Publish(Arg.Any(), Arg.Any()); + } + [Fact] public async Task Handle_WhenPilotIsNotEquipped_PublishesNothing() { @@ -200,7 +231,6 @@ public async Task Handle_WhenPilotIsNotEquipped_PublishesNothing() var mediator = Substitute.For(); var handler = await CreateHandler( contractRepository, - new TestAdscReportRepository(), mediator, isAdscEquipped: false); @@ -222,7 +252,6 @@ public async Task Handle_WhenPilotIsNotEquippedAndNonEquippedAircraftAreAllowed_ var mediator = Substitute.For(); var handler = await CreateHandler( contractRepository, - new TestAdscReportRepository(), mediator, isAdscEquipped: false, allowNonEquippedAircraft: true); @@ -239,12 +268,12 @@ public async Task Handle_WhenPilotIsNotInVatsimData_PublishesNothing() { // Arrange var contractRepository = new TestAdscContractRepository(); - var contract = new AdscContract("QFA1", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("QFA1", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("QFA1", "YBBB"), contract, CancellationToken.None); contract.RequestDefaultContract(DefaultInterval); var mediator = Substitute.For(); - var handler = await CreateHandler(contractRepository, new TestAdscReportRepository(), mediator); + var handler = await CreateHandler(contractRepository, mediator); // Act await handler.Handle(new ProduceVatsimAdscReportsRequest(), CancellationToken.None); @@ -255,7 +284,6 @@ public async Task Handle_WhenPilotIsNotInVatsimData_PublishesNothing() static async Task CreateHandler( IAdscContractRepository contractRepository, - IAdscReportRepository reportRepository, IMediator mediator, bool isAdscEquipped = true, bool allowNonEquippedAircraft = false) @@ -270,29 +298,28 @@ [new VatsimPilot("UAL123", -33.9461, 151.1772, 37000, LastUpdated, isAdscEquippe return new ProduceVatsimAdscReportsRequestHandler( contractRepository, - reportRepository, pilotRepository, - new TestServerSettingsProvider(new ServerSettings { VatsimStatusEnabled = true, VatsimStatusAllowNonEquippedAircraft = allowNonEquippedAircraft }), + new TestServerSettingsProvider(new ServerSettings + { + VatsimStatusEnabled = true, + VatsimStatusAllowNonEquippedAircraft = allowNonEquippedAircraft, + VatsimStatusReportDelayMinutes = (int)ReportDelay.TotalMinutes + }), clock, mediator, Logger.None); } - static async Task AddContract(IAdscContractRepository contractRepository) + // The contract was made before the report delay, unless the test gives a different time + static async Task AddContract(IAdscContractRepository contractRepository, DateTimeOffset? created = null) { - var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10)); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), created ?? DateTimeOffset.MinValue); await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); return contract; } - static async Task AddReport(IAdscReportRepository reportRepository, AdscReportSource source, DateTimeOffset received) + static void ReceiveReport(AdscContract contract, AdscReportSource source, DateTimeOffset timestamp) { - await reportRepository.Add( - new AircraftAdscReport( - "UAL123", - "YBBB", - new AdscReport(received.AddSeconds(-30), -33.9461, 151.1772, 37000, source), - received), - CancellationToken.None); + contract.ReportReceived(new AdscReport(timestamp, -33.9461, 151.1772, 37000, source)); } } diff --git a/source/CPDLCServer/AdscContracts/AdscContract.cs b/source/CPDLCServer/AdscContracts/AdscContract.cs index 00b94d6..ae13708 100644 --- a/source/CPDLCServer/AdscContracts/AdscContract.cs +++ b/source/CPDLCServer/AdscContracts/AdscContract.cs @@ -1,3 +1,5 @@ +using CPDLCServer.AdscContracts.Reports; + namespace CPDLCServer.AdscContracts; /// @@ -9,18 +11,22 @@ namespace CPDLCServer.AdscContracts; /// A demand request asks for one report. /// /// -public class AdscContract(string callsign, string stationId, TimeSpan defaultReportingInterval) +public class AdscContract(string callsign, string stationId, TimeSpan defaultReportingInterval, DateTimeOffset created) { // The ACARS connections poll for messages every 20 to 75 seconds. A shorter interval gives no more data. public static readonly TimeSpan MinimumReportingInterval = TimeSpan.FromSeconds(60); + // The maximum delivery time of a report + static readonly TimeSpan ReportDeliveryTolerance = TimeSpan.FromMinutes(3); + public string Callsign { get; } = callsign; public string StationId { get; } = stationId; - // The default reporting interval of the ATSU. The controller sees it as the default period. + // The time that the ATSU made the contract + public DateTimeOffset Created { get; } = created; + public TimeSpan DefaultReportingInterval { get; private set; } = defaultReportingInterval; - // The interval of the latest periodic request. Null when no periodic contract was requested. public TimeSpan? ReportingInterval { get; private set; } public AdscContractState? DefaultContractState { get; private set; } @@ -30,12 +36,15 @@ public class AdscContract(string callsign, string stationId, TimeSpan defaultRep // Null when no selected contract is in use public DateTimeOffset? SelectedContractEnds { get; private set; } - public AdscContractState? DemandContractState { get; private set; } // The latest time that a request was sent, or that a message was received from the aircraft public DateTimeOffset LastActivity { get; private set; } + public DateTimeOffset? LastReportReceived { get; private set; } + + public AdscReportSource? ReportingSource { get; private set; } + public bool HasPeriodicContract => DefaultContractState is AdscContractState.Sent or AdscContractState.Accepted || SelectedContractState is AdscContractState.Sent or AdscContractState.Accepted; @@ -45,6 +54,10 @@ DefaultContractState is AdscContractState.Sent or AdscContractState.Accepted || HasPeriodicContract || DemandContractState is AdscContractState.Sent or AdscContractState.Accepted; + // A report expires when the next two periodic reports do not arrive. + // A contract with only a demand request uses the default reporting interval. + public TimeSpan ReportExpiry => (ReportingInterval ?? DefaultReportingInterval) * 2 + ReportDeliveryTolerance; + public void LogActivity(DateTimeOffset now) { LastActivity = now; @@ -86,30 +99,35 @@ public void RequestDemandReport() /// The aircraft does not acknowledge a request, so a report accepts the latest periodic request and the demand request. /// When the selected contract is accepted, it replaces the default contract on the aircraft. ///
- /// True if the state of a request changed. - public bool ReportReceived() + public void ReportReceived(AdscReport report) { - var changed = false; + ReportingSource = report.Source; + LastReportReceived = report.Timestamp; if (SelectedContractState == AdscContractState.Sent) { SelectedContractState = AdscContractState.Accepted; DefaultContractState = null; - changed = true; } else if (DefaultContractState == AdscContractState.Sent) { DefaultContractState = AdscContractState.Accepted; - changed = true; } if (DemandContractState == AdscContractState.Sent) { DemandContractState = AdscContractState.Accepted; - changed = true; } + } - return changed; + /// + /// The last report is too old to show the position of the aircraft. + /// The time of the last report stays, so that the next periodic report is due immediately. + /// The source is removed, so that reports from VATSIM can replace the reports from Hoppie. + /// + public void ReportTimedOut() + { + ReportingSource = null; } /// @@ -133,7 +151,9 @@ public bool Reject() } if (DemandContractState == AdscContractState.Sent) + { DemandContractState = AdscContractState.Rejected; + } return selectedContractRejected; } diff --git a/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs b/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs index d13c0c4..b7b4c56 100644 --- a/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs @@ -17,6 +17,7 @@ public void Configure(EntityTypeBuilder builder) builder.Property(c => c.Callsign); builder.Property(c => c.StationId); + builder.Property(c => c.Created); builder.Property(c => c.DefaultReportingInterval); builder.Property(c => c.ReportingInterval); builder.Property(c => c.DefaultContractState); @@ -25,6 +26,8 @@ public void Configure(EntityTypeBuilder builder) builder.Property(c => c.SelectedContractEnds); builder.Property(c => c.DemandContractState); builder.Property(c => c.LastActivity); + builder.Property(c => c.LastReportReceived); + builder.Property(c => c.ReportingSource); builder.HasIndex(c => new { c.Callsign, c.StationId }); } diff --git a/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs b/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs index 5eecc9c..d1b5f28 100644 --- a/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractExpiryService.cs @@ -1,3 +1,4 @@ +using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Infrastructure; namespace CPDLCServer.AdscContracts; @@ -50,6 +51,9 @@ async Task DoWork(CancellationToken stoppingToken) timeoutCts.CancelAfter(TimeSpan.FromMinutes(1)); await mediator.Send(new EndExpiredAdscContractsRequest(), timeoutCts.Token); + + // After the contracts, so that the reports of removed contracts expire immediately + await mediator.Send(new ExpireAdscReportsRequest(), timeoutCts.Token); await mediator.Send(new PurgeExpiredAdscDataRequest(), timeoutCts.Token); await Task.Delay(_checkInterval, stoppingToken); diff --git a/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs index f5855d1..1bb1225 100644 --- a/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs +++ b/source/CPDLCServer/AdscContracts/AdscMessageReceivedNotificationHandler.cs @@ -44,15 +44,8 @@ public async Task Handle(AdscMessageReceivedNotification notification, Cancellat "ADS-C report received from {Callsign}", message.Sender); - if (contract.ReportReceived()) - { - logger.Information( - "{Callsign} accepted the ADS-C contract with {StationId}", - message.Sender, - notification.StationId); - - await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); - } + contract.ReportReceived(reportMessage.Report); + await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); await mediator.Publish( new AdscReportReceivedNotification( diff --git a/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotification.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotification.cs new file mode 100644 index 0000000..9b868d0 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotification.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.AdscContracts.Reports; + +public record AdscReportExpiredNotification(string Callsign, string StationId) : INotification; diff --git a/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotificationHandler.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotificationHandler.cs new file mode 100644 index 0000000..3371a1d --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportExpiredNotificationHandler.cs @@ -0,0 +1,36 @@ +using CPDLCServer.Controllers; +using CPDLCServer.Persistence; +using CPDLCServer.Web; +using MediatR; +using Microsoft.AspNetCore.SignalR; + +namespace CPDLCServer.AdscContracts.Reports; + +public class AdscReportExpiredNotificationHandler( + IControllerRepository controllerRepository, + IHubContext hubContext, + IUnitOfWork unitOfWork, + ILogger logger) + : INotificationHandler +{ + public async Task Handle(AdscReportExpiredNotification notification, CancellationToken cancellationToken) + { + var controllers = await controllerRepository.All(cancellationToken); + if (controllers.Length == 0) + { + logger.Verbose( + "No controllers to notify about expired ADS-C report from {Callsign}", + notification.Callsign); + return; + } + + unitOfWork.AfterCommit(ct => hubContext.Clients + .Clients(controllers.Select(c => c.ConnectionId)) + .SendAsync("AdscReportExpired", notification.Callsign, notification.StationId, ct)); + + logger.Information( + "Notified {ControllerCount} controller(s) about expired ADS-C report from {Callsign}", + controllers.Length, + notification.Callsign); + } +} diff --git a/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs index 44613b2..ba4b13c 100644 --- a/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs @@ -10,61 +10,69 @@ public class AdscReportRepository(CpdlcDbContext dbContext) : IAdscReportReposit { public async Task Add(AircraftAdscReport report, CancellationToken cancellationToken) { - var latest = await FindLatest(report.Callsign, cancellationToken); - - var isLatest = latest is null || ReplacesLatest(report, latest); - if (isLatest && latest is not null) - SetIsLatest(latest, false); + var previous = await Find(report.Callsign, report.StationId, cancellationToken); + if (previous is not null) + dbContext.AdscReports.Remove(previous); dbContext.AdscReports.Add(report); - SetIsLatest(report, isLatest); } - public async Task FindLatest(string callsign, CancellationToken cancellationToken) + public async Task Find(string callsign, string stationId, CancellationToken cancellationToken) { await dbContext.AdscReports - .Where(r => r.Callsign == callsign && EF.Property(r, AircraftAdscReportConfiguration.IsLatestProperty)) + .Where(r => r.Callsign == callsign && r.StationId == stationId) .LoadAsync(cancellationToken); - return dbContext.AdscReports.Local.FirstOrDefault(r => r.Callsign == callsign && IsLatest(r)); + return dbContext.AdscReports.Local.FirstOrDefault(r => r.Callsign == callsign && r.StationId == stationId); } - public async Task AllLatest(CancellationToken cancellationToken) + public async Task FindLatest(string callsign, CancellationToken cancellationToken) { await dbContext.AdscReports - .Where(r => EF.Property(r, AircraftAdscReportConfiguration.IsLatestProperty)) + .Where(r => r.Callsign == callsign) .LoadAsync(cancellationToken); - return dbContext.AdscReports.Local.Where(IsLatest).ToArray(); + var reports = dbContext.AdscReports.Local.Where(r => r.Callsign == callsign).ToArray(); + return reports.Length == 0 ? null : SelectLatest(reports); } - public async Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken) + public async Task AllLatest(CancellationToken cancellationToken) { - await dbContext.AdscReports - .Where(r => r.Received < cutoff) - .LoadAsync(cancellationToken); - - var oldReports = dbContext.AdscReports.Local.Where(r => r.Received < cutoff).ToArray(); - dbContext.AdscReports.RemoveRange(oldReports); + var reports = await All(cancellationToken); + return reports + .GroupBy(r => r.Callsign) + .Select(SelectLatest) + .ToArray(); } - static bool ReplacesLatest(AircraftAdscReport report, AircraftAdscReport latest) + public async Task All(CancellationToken cancellationToken) { - // A report from Hoppie always replaces a report from VATSIM - if (report.Report.Source == AdscReportSource.Hoppie && latest.Report.Source == AdscReportSource.VATSIM) - return true; + await dbContext.AdscReports.LoadAsync(cancellationToken); + return dbContext.AdscReports.Local.ToArray(); + } - // An aircraft can report to more than one ATSU, so reports can arrive out of order - return report.Report.Timestamp >= latest.Report.Timestamp; + public Task Remove(AircraftAdscReport report, CancellationToken cancellationToken) + { + dbContext.AdscReports.Remove(report); + return Task.CompletedTask; } - bool IsLatest(AircraftAdscReport report) + public async Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken) { - return dbContext.Entry(report).Property(AircraftAdscReportConfiguration.IsLatestProperty).CurrentValue; + await dbContext.AdscReports + .Where(r => r.Received < cutoff) + .LoadAsync(cancellationToken); + + var oldReports = dbContext.AdscReports.Local.Where(r => r.Received < cutoff).ToArray(); + dbContext.AdscReports.RemoveRange(oldReports); } - void SetIsLatest(AircraftAdscReport report, bool isLatest) + // An aircraft can report to more than one ATSU, so the reports can arrive out of order + static AircraftAdscReport SelectLatest(IEnumerable reports) { - dbContext.Entry(report).Property(AircraftAdscReportConfiguration.IsLatestProperty).CurrentValue = isLatest; + return reports + .OrderByDescending(r => r.Report.Source == AdscReportSource.Hoppie) + .ThenByDescending(r => r.Report.Timestamp) + .First(); } } diff --git a/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs index 016b11a..ce084ab 100644 --- a/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs @@ -7,9 +7,6 @@ public class AircraftAdscReportConfiguration : IEntityTypeConfiguration builder) { builder.ToTable("AdscReports"); @@ -18,8 +15,6 @@ public void Configure(EntityTypeBuilder builder) builder.Property(IdProperty); builder.HasKey(IdProperty); - builder.Property(IsLatestProperty); - builder.Property(r => r.Callsign); builder.Property(r => r.StationId); builder.Property(r => r.Received); @@ -33,7 +28,7 @@ public void Configure(EntityTypeBuilder builder) report.Property(r => r.Source).HasColumnName("Source"); }); - builder.HasIndex(r => r.Callsign); + builder.HasIndex(r => new { r.Callsign, r.StationId }).IsUnique(); builder.HasIndex(r => r.Received); } } diff --git a/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequest.cs b/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequest.cs new file mode 100644 index 0000000..58cb32d --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequest.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.AdscContracts.Reports; + +public record ExpireAdscReportsRequest : IRequest; diff --git a/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequestHandler.cs b/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequestHandler.cs new file mode 100644 index 0000000..a1644b9 --- /dev/null +++ b/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequestHandler.cs @@ -0,0 +1,49 @@ +using CPDLCServer.Infrastructure; +using MediatR; + +namespace CPDLCServer.AdscContracts.Reports; + +/// +/// Removes the ADS-C reports that are too old to show the position of the aircraft. +/// +/// A report expires when the time since the last report of its contract is more than the report expiry of the contract. +/// A report without a contract expires immediately, because the aircraft does not send more reports. +/// +/// +public class ExpireAdscReportsRequestHandler( + IAdscReportRepository adscReportRepository, + IAdscContractRepository adscContractRepository, + IClock clock, + IMediator mediator, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(ExpireAdscReportsRequest request, CancellationToken cancellationToken) + { + var reports = await adscReportRepository.All(cancellationToken); + var now = clock.UtcNow(); + + foreach (var report in reports) + { + var contract = await adscContractRepository.Find( + new AdscContractKey(report.Callsign, report.StationId), + cancellationToken); + + if (contract?.LastReportReceived is not null && now - contract.LastReportReceived.Value <= contract.ReportExpiry) + continue; + + logger.Information( + "ADS-C report from {Callsign} to {StationId} at {Timestamp} has expired", + report.Callsign, + report.StationId, + report.Report.Timestamp); + + contract?.ReportTimedOut(); + await adscReportRepository.Remove(report, cancellationToken); + + await mediator.Publish( + new AdscReportExpiredNotification(report.Callsign, report.StationId), + cancellationToken); + } + } +} diff --git a/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs b/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs index 58989a3..1e4a363 100644 --- a/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs +++ b/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs @@ -1,14 +1,18 @@ namespace CPDLCServer.AdscContracts.Reports; -// Holds the history of ADS-C reports, and the latest report for each aircraft +// Holds one report for each ADS-C contract (aircraft and ATSU) public interface IAdscReportRepository { - // Adds the report to the history. - // The report becomes the latest report, unless the repository has a newer report for the same aircraft. - // A report from Hoppie always replaces a report from VATSIM as the latest report. + // Adds the report. The report replaces the previous report of the same aircraft and ATSU. Task Add(AircraftAdscReport report, CancellationToken cancellationToken); + Task Find(string callsign, string stationId, CancellationToken cancellationToken); + + // The latest report of an aircraft, from all the ATSUs. + // A report from Hoppie is used before a report from VATSIM. Then the report with the latest timestamp is used. Task FindLatest(string callsign, CancellationToken cancellationToken); Task AllLatest(CancellationToken cancellationToken); + Task All(CancellationToken cancellationToken); + Task Remove(AircraftAdscReport report, CancellationToken cancellationToken); Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken); } diff --git a/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs index ee70900..9e075dd 100644 --- a/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs +++ b/source/CPDLCServer/AdscContracts/Reports/RequestAdscDemandReportCommandHandler.cs @@ -31,7 +31,7 @@ public async Task Handle(RequestAdscDemandReportCommand request, CancellationTok if (contract is null) { var configuration = await acarsConnectionManager.GetConfigurationForStation(request.StationId, cancellationToken); - contract = new AdscContract(request.Callsign, request.StationId, TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval)); + contract = new AdscContract(request.Callsign, request.StationId, TimeSpan.FromMinutes(configuration.DefaultAdscReportingInterval), clock.UtcNow()); await adscContractRepository.Add(contractKey, contract, cancellationToken); } diff --git a/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommandHandler.cs b/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommandHandler.cs index d38a947..5bf8e00 100644 --- a/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommandHandler.cs +++ b/source/CPDLCServer/AdscContracts/RequestPeriodicAdscContractCommandHandler.cs @@ -38,13 +38,13 @@ public async Task Handle(RequestPeriodicAdscContractCommand request, Cancellatio var contractKey = new AdscContractKey(request.Callsign, request.StationId); var contract = await adscContractRepository.Find(contractKey, cancellationToken); + var now = clock.UtcNow(); if (contract is null) { - contract = new AdscContract(request.Callsign, request.StationId, defaultReportingInterval); + contract = new AdscContract(request.Callsign, request.StationId, defaultReportingInterval, now); await adscContractRepository.Add(contractKey, contract, cancellationToken); } - var now = clock.UtcNow(); if (isDefaultContract) { contract.RequestDefaultContract(request.ReportingInterval); diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.Designer.cs similarity index 95% rename from source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.Designer.cs rename to source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.Designer.cs index 2e43b38..4c60b09 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.Designer.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.Designer.cs @@ -13,7 +13,7 @@ namespace CPDLCServer.Persistence.Migrations.PostgreSql { [DbContext(typeof(PostgreSqlCpdlcDbContext))] - [Migration("20261107042236_InitialCreate")] + [Migration("20261115024457_InitialCreate")] partial class InitialCreate { /// @@ -46,7 +46,8 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasColumnType("text"); b.Property("Notes") - .HasColumnType("text"); + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); b.Property("SelectedAdscContractDuration") .HasColumnType("integer"); @@ -83,18 +84,30 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Created") + .HasColumnType("bigint"); + b.Property("DefaultContractState") .HasColumnType("text"); + b.Property("DefaultReportingInterval") + .HasColumnType("bigint"); + b.Property("DemandContractState") .HasColumnType("text"); b.Property("LastActivity") .HasColumnType("bigint"); + b.Property("LastReportReceived") + .HasColumnType("bigint"); + b.Property("ReportingInterval") .HasColumnType("bigint"); + b.Property("ReportingSource") + .HasColumnType("text"); + b.Property("SelectedContractEnds") .HasColumnType("bigint"); @@ -127,9 +140,6 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); - b.Property("IsLatest") - .HasColumnType("boolean"); - b.Property("Received") .HasColumnType("bigint"); @@ -165,10 +175,11 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("Callsign"); - b.HasIndex("Received"); + b.HasIndex("Callsign", "StationId") + .IsUnique(); + b.ToTable("AdscReports", (string)null); }); @@ -368,6 +379,9 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("VatsimStatusPollingIntervalSeconds") .HasColumnType("integer"); + b.Property("VatsimStatusReportDelayMinutes") + .HasColumnType("integer"); + b.Property("VatsimStatusUrl") .IsRequired() .HasColumnType("text"); @@ -418,10 +432,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasColumnType("text") .HasColumnName("Content"); - b.Property("IsPilotLate") + b.Property("DidTransmissionFail") .HasColumnType("boolean"); - b.Property("IsTransmissionFailed") + b.Property("IsPilotLate") .HasColumnType("boolean"); b.Property("Recipient") diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.cs similarity index 93% rename from source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.cs rename to source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.cs index 31c11a2..00cf2dd 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261107042236_InitialCreate.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.cs @@ -25,7 +25,7 @@ protected override void Up(MigrationBuilder migrationBuilder) EncryptedAuthenticationCode = table.Column(type: "text", nullable: false), DefaultAdscReportingInterval = table.Column(type: "integer", nullable: false), SelectedAdscContractDuration = table.Column(type: "integer", nullable: false), - Notes = table.Column(type: "text", nullable: true) + Notes = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true) }, constraints: table => { @@ -40,13 +40,17 @@ protected override void Up(MigrationBuilder migrationBuilder) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), Callsign = table.Column(type: "text", nullable: false), StationId = table.Column(type: "text", nullable: false), + Created = table.Column(type: "bigint", nullable: false), + DefaultReportingInterval = table.Column(type: "bigint", nullable: false), ReportingInterval = table.Column(type: "bigint", nullable: true), DefaultContractState = table.Column(type: "text", nullable: true), SelectedReportingInterval = table.Column(type: "bigint", nullable: true), SelectedContractState = table.Column(type: "text", nullable: true), SelectedContractEnds = table.Column(type: "bigint", nullable: true), DemandContractState = table.Column(type: "text", nullable: true), - LastActivity = table.Column(type: "bigint", nullable: false) + LastActivity = table.Column(type: "bigint", nullable: false), + LastReportReceived = table.Column(type: "bigint", nullable: true), + ReportingSource = table.Column(type: "text", nullable: true) }, constraints: table => { @@ -62,7 +66,6 @@ protected override void Up(MigrationBuilder migrationBuilder) Callsign = table.Column(type: "text", nullable: false), StationId = table.Column(type: "text", nullable: false), Received = table.Column(type: "bigint", nullable: false), - IsLatest = table.Column(type: "boolean", nullable: false), Altitude = table.Column(type: "integer", nullable: false), Latitude = table.Column(type: "double precision", nullable: false), Longitude = table.Column(type: "double precision", nullable: false), @@ -139,7 +142,8 @@ protected override void Up(MigrationBuilder migrationBuilder) VatsimStatusEnabled = table.Column(type: "boolean", nullable: false), VatsimStatusUrl = table.Column(type: "text", nullable: false), VatsimStatusPollingIntervalSeconds = table.Column(type: "integer", nullable: false), - VatsimStatusAllowNonEquippedAircraft = table.Column(type: "boolean", nullable: false) + VatsimStatusAllowNonEquippedAircraft = table.Column(type: "boolean", nullable: false), + VatsimStatusReportDelayMinutes = table.Column(type: "integer", nullable: false) }, constraints: table => { @@ -185,7 +189,7 @@ protected override void Up(MigrationBuilder migrationBuilder) Sent = table.Column(type: "bigint", nullable: true), ClosedManually = table.Column(type: "boolean", nullable: true), IsPilotLate = table.Column(type: "boolean", nullable: true), - IsTransmissionFailed = table.Column(type: "boolean", nullable: true) + DidTransmissionFail = table.Column(type: "boolean", nullable: true) }, constraints: table => { @@ -210,9 +214,10 @@ protected override void Up(MigrationBuilder migrationBuilder) columns: new[] { "Callsign", "StationId" }); migrationBuilder.CreateIndex( - name: "IX_AdscReports_Callsign", + name: "IX_AdscReports_Callsign_StationId", table: "AdscReports", - column: "Callsign"); + columns: new[] { "Callsign", "StationId" }, + unique: true); migrationBuilder.CreateIndex( name: "IX_AdscReports_Received", diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs index e2e3d59..fb489c9 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs @@ -43,7 +43,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("text"); b.Property("Notes") - .HasColumnType("text"); + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); b.Property("SelectedAdscContractDuration") .HasColumnType("integer"); @@ -80,18 +81,30 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Created") + .HasColumnType("bigint"); + b.Property("DefaultContractState") .HasColumnType("text"); + b.Property("DefaultReportingInterval") + .HasColumnType("bigint"); + b.Property("DemandContractState") .HasColumnType("text"); b.Property("LastActivity") .HasColumnType("bigint"); + b.Property("LastReportReceived") + .HasColumnType("bigint"); + b.Property("ReportingInterval") .HasColumnType("bigint"); + b.Property("ReportingSource") + .HasColumnType("text"); + b.Property("SelectedContractEnds") .HasColumnType("bigint"); @@ -124,9 +137,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); - b.Property("IsLatest") - .HasColumnType("boolean"); - b.Property("Received") .HasColumnType("bigint"); @@ -162,10 +172,11 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("Callsign"); - b.HasIndex("Received"); + b.HasIndex("Callsign", "StationId") + .IsUnique(); + b.ToTable("AdscReports", (string)null); }); @@ -365,6 +376,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("VatsimStatusPollingIntervalSeconds") .HasColumnType("integer"); + b.Property("VatsimStatusReportDelayMinutes") + .HasColumnType("integer"); + b.Property("VatsimStatusUrl") .IsRequired() .HasColumnType("text"); @@ -415,10 +429,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("text") .HasColumnName("Content"); - b.Property("IsPilotLate") + b.Property("DidTransmissionFail") .HasColumnType("boolean"); - b.Property("IsTransmissionFailed") + b.Property("IsPilotLate") .HasColumnType("boolean"); b.Property("Recipient") diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.Designer.cs similarity index 95% rename from source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.Designer.cs rename to source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.Designer.cs index 8e3c78b..8394737 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.Designer.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ namespace CPDLCServer.Persistence.Migrations.Sqlite { [DbContext(typeof(SqliteCpdlcDbContext))] - [Migration("20261107042233_InitialCreate")] + [Migration("20261115024453_InitialCreate")] partial class InitialCreate { /// @@ -41,6 +41,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasColumnType("TEXT"); b.Property("Notes") + .HasMaxLength(2000) .HasColumnType("TEXT"); b.Property("SelectedAdscContractDuration") @@ -76,18 +77,30 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Created") + .HasColumnType("INTEGER"); + b.Property("DefaultContractState") .HasColumnType("TEXT"); + b.Property("DefaultReportingInterval") + .HasColumnType("INTEGER"); + b.Property("DemandContractState") .HasColumnType("TEXT"); b.Property("LastActivity") .HasColumnType("INTEGER"); + b.Property("LastReportReceived") + .HasColumnType("INTEGER"); + b.Property("ReportingInterval") .HasColumnType("INTEGER"); + b.Property("ReportingSource") + .HasColumnType("TEXT"); + b.Property("SelectedContractEnds") .HasColumnType("INTEGER"); @@ -118,9 +131,6 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); - b.Property("IsLatest") - .HasColumnType("INTEGER"); - b.Property("Received") .HasColumnType("INTEGER"); @@ -156,10 +166,11 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("Callsign"); - b.HasIndex("Received"); + b.HasIndex("Callsign", "StationId") + .IsUnique(); + b.ToTable("AdscReports", (string)null); }); @@ -353,6 +364,9 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("VatsimStatusPollingIntervalSeconds") .HasColumnType("INTEGER"); + b.Property("VatsimStatusReportDelayMinutes") + .HasColumnType("INTEGER"); + b.Property("VatsimStatusUrl") .IsRequired() .HasColumnType("TEXT"); @@ -403,10 +417,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasColumnType("TEXT") .HasColumnName("Content"); - b.Property("IsPilotLate") + b.Property("DidTransmissionFail") .HasColumnType("INTEGER"); - b.Property("IsTransmissionFailed") + b.Property("IsPilotLate") .HasColumnType("INTEGER"); b.Property("Recipient") diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.cs similarity index 93% rename from source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.cs rename to source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.cs index 887bdd3..4c0b95d 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261107042233_InitialCreate.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.cs @@ -24,7 +24,7 @@ protected override void Up(MigrationBuilder migrationBuilder) EncryptedAuthenticationCode = table.Column(type: "TEXT", nullable: false), DefaultAdscReportingInterval = table.Column(type: "INTEGER", nullable: false), SelectedAdscContractDuration = table.Column(type: "INTEGER", nullable: false), - Notes = table.Column(type: "TEXT", nullable: true) + Notes = table.Column(type: "TEXT", maxLength: 2000, nullable: true) }, constraints: table => { @@ -39,13 +39,17 @@ protected override void Up(MigrationBuilder migrationBuilder) .Annotation("Sqlite:Autoincrement", true), Callsign = table.Column(type: "TEXT", nullable: false), StationId = table.Column(type: "TEXT", nullable: false), + Created = table.Column(type: "INTEGER", nullable: false), + DefaultReportingInterval = table.Column(type: "INTEGER", nullable: false), ReportingInterval = table.Column(type: "INTEGER", nullable: true), DefaultContractState = table.Column(type: "TEXT", nullable: true), SelectedReportingInterval = table.Column(type: "INTEGER", nullable: true), SelectedContractState = table.Column(type: "TEXT", nullable: true), SelectedContractEnds = table.Column(type: "INTEGER", nullable: true), DemandContractState = table.Column(type: "TEXT", nullable: true), - LastActivity = table.Column(type: "INTEGER", nullable: false) + LastActivity = table.Column(type: "INTEGER", nullable: false), + LastReportReceived = table.Column(type: "INTEGER", nullable: true), + ReportingSource = table.Column(type: "TEXT", nullable: true) }, constraints: table => { @@ -61,7 +65,6 @@ protected override void Up(MigrationBuilder migrationBuilder) Callsign = table.Column(type: "TEXT", nullable: false), StationId = table.Column(type: "TEXT", nullable: false), Received = table.Column(type: "INTEGER", nullable: false), - IsLatest = table.Column(type: "INTEGER", nullable: false), Altitude = table.Column(type: "INTEGER", nullable: false), Latitude = table.Column(type: "REAL", nullable: false), Longitude = table.Column(type: "REAL", nullable: false), @@ -138,7 +141,8 @@ protected override void Up(MigrationBuilder migrationBuilder) VatsimStatusEnabled = table.Column(type: "INTEGER", nullable: false), VatsimStatusUrl = table.Column(type: "TEXT", nullable: false), VatsimStatusPollingIntervalSeconds = table.Column(type: "INTEGER", nullable: false), - VatsimStatusAllowNonEquippedAircraft = table.Column(type: "INTEGER", nullable: false) + VatsimStatusAllowNonEquippedAircraft = table.Column(type: "INTEGER", nullable: false), + VatsimStatusReportDelayMinutes = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { @@ -184,7 +188,7 @@ protected override void Up(MigrationBuilder migrationBuilder) Sent = table.Column(type: "INTEGER", nullable: true), ClosedManually = table.Column(type: "INTEGER", nullable: true), IsPilotLate = table.Column(type: "INTEGER", nullable: true), - IsTransmissionFailed = table.Column(type: "INTEGER", nullable: true) + DidTransmissionFail = table.Column(type: "INTEGER", nullable: true) }, constraints: table => { @@ -209,9 +213,10 @@ protected override void Up(MigrationBuilder migrationBuilder) columns: new[] { "Callsign", "StationId" }); migrationBuilder.CreateIndex( - name: "IX_AdscReports_Callsign", + name: "IX_AdscReports_Callsign_StationId", table: "AdscReports", - column: "Callsign"); + columns: new[] { "Callsign", "StationId" }, + unique: true); migrationBuilder.CreateIndex( name: "IX_AdscReports_Received", diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs index ffdc58d..7a00aba 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs @@ -38,6 +38,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("TEXT"); b.Property("Notes") + .HasMaxLength(2000) .HasColumnType("TEXT"); b.Property("SelectedAdscContractDuration") @@ -73,18 +74,30 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Created") + .HasColumnType("INTEGER"); + b.Property("DefaultContractState") .HasColumnType("TEXT"); + b.Property("DefaultReportingInterval") + .HasColumnType("INTEGER"); + b.Property("DemandContractState") .HasColumnType("TEXT"); b.Property("LastActivity") .HasColumnType("INTEGER"); + b.Property("LastReportReceived") + .HasColumnType("INTEGER"); + b.Property("ReportingInterval") .HasColumnType("INTEGER"); + b.Property("ReportingSource") + .HasColumnType("TEXT"); + b.Property("SelectedContractEnds") .HasColumnType("INTEGER"); @@ -115,9 +128,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); - b.Property("IsLatest") - .HasColumnType("INTEGER"); - b.Property("Received") .HasColumnType("INTEGER"); @@ -153,10 +163,11 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("Callsign"); - b.HasIndex("Received"); + b.HasIndex("Callsign", "StationId") + .IsUnique(); + b.ToTable("AdscReports", (string)null); }); @@ -350,6 +361,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("VatsimStatusPollingIntervalSeconds") .HasColumnType("INTEGER"); + b.Property("VatsimStatusReportDelayMinutes") + .HasColumnType("INTEGER"); + b.Property("VatsimStatusUrl") .IsRequired() .HasColumnType("TEXT"); @@ -400,10 +414,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("TEXT") .HasColumnName("Content"); - b.Property("IsPilotLate") + b.Property("DidTransmissionFail") .HasColumnType("INTEGER"); - b.Property("IsTransmissionFailed") + b.Property("IsPilotLate") .HasColumnType("INTEGER"); b.Property("Recipient") diff --git a/source/CPDLCServer/Settings/ServerSettings.cs b/source/CPDLCServer/Settings/ServerSettings.cs index 7afe588..8cc31bc 100644 --- a/source/CPDLCServer/Settings/ServerSettings.cs +++ b/source/CPDLCServer/Settings/ServerSettings.cs @@ -31,4 +31,7 @@ public record ServerSettings public int VatsimStatusPollingIntervalSeconds { get; init; } = 120; public bool VatsimStatusAllowNonEquippedAircraft { get; init; } + + [Range(0, int.MaxValue)] + public int VatsimStatusReportDelayMinutes { get; init; } = 5; } diff --git a/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs index 257e116..94b2131 100644 --- a/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs +++ b/source/CPDLCServer/VatsimStatus/ProduceVatsimAdscReportsRequestHandler.cs @@ -9,14 +9,14 @@ namespace CPDLCServer.VatsimStatus; /// /// Creates an ADS-C position report using VATSIM status data. /// -/// A report from Hoppie stops the VATSIM reports. The VATSIM reports start again when the Hoppie reports are more than two reporting intervals late. +/// The VATSIM reports start after the report delay from when the contract was made, so that the aircraft can send its first report through Hoppie. +/// A report from Hoppie stops the VATSIM reports. The VATSIM reports start again when the Hoppie report times out. /// A rejected contract stops the VATSIM reports. /// A report is made only when the contract needs one: a demand request, or a periodic report that is due. /// /// public class ProduceVatsimAdscReportsRequestHandler( IAdscContractRepository adscContractRepository, - IAdscReportRepository adscReportRepository, IVatsimPilotRepository vatsimPilotRepository, IServerSettingsProvider settingsProvider, IClock clock, @@ -53,8 +53,8 @@ async Task ProduceReport(AdscContract contract, ServerSettings settings, DateTim if (!contract.IsActive) return; - var latestReport = await adscReportRepository.FindLatest(contract.Callsign, cancellationToken); - if (!CanUseVatsimData(contract, latestReport, now) || !IsReportDue(contract, latestReport, now)) + var reportDelay = TimeSpan.FromMinutes(settings.VatsimStatusReportDelayMinutes); + if (!CanUseVatsimData(contract, reportDelay, now) || !IsReportDue(contract, now)) return; var pilot = await vatsimPilotRepository.Find(contract.Callsign, cancellationToken); @@ -75,18 +75,6 @@ async Task ProduceReport(AdscContract contract, ServerSettings settings, DateTim contract.Callsign, contract.StationId); - contract.LogActivity(now); - - if (contract.ReportReceived()) - { - logger.Information( - "{Callsign} accepted the ADS-C contract with {StationId}", - contract.Callsign, - contract.StationId); - - await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); - } - var report = new AdscReport( pilot.LastUpdated, pilot.Latitude, @@ -94,26 +82,25 @@ async Task ProduceReport(AdscContract contract, ServerSettings settings, DateTim pilot.Altitude, AdscReportSource.VATSIM); + contract.LogActivity(now); + contract.ReportReceived(report); + await mediator.Publish(new AdscContractChangedNotification(contract), cancellationToken); + await mediator.Publish( new AdscReportReceivedNotification(contract.Callsign, contract.StationId, report, now), cancellationToken); } - // VATSIM data is used only when there is no report from Hoppie, or when the Hoppie reports are late - static bool CanUseVatsimData(AdscContract contract, AircraftAdscReport? latestReport, DateTimeOffset now) + static bool CanUseVatsimData(AdscContract contract, TimeSpan reportDelay, DateTimeOffset now) { - if (latestReport is null || latestReport.Report.Source == AdscReportSource.VATSIM) - return true; - - // Only a periodic contract makes the reports late - if (!contract.HasPeriodicContract || contract.ReportingInterval is null) + if (now - contract.Created < reportDelay) return false; - var timeSinceLastReport = now - latestReport.Received; - return timeSinceLastReport > contract.ReportingInterval.Value * 2; + // The source is null when there is no report, or when the last report timed out + return contract.ReportingSource is null or AdscReportSource.VATSIM; } - static bool IsReportDue(AdscContract contract, AircraftAdscReport? latestReport, DateTimeOffset now) + static bool IsReportDue(AdscContract contract, DateTimeOffset now) { if (contract.DemandContractState == AdscContractState.Sent) return true; @@ -121,10 +108,10 @@ static bool IsReportDue(AdscContract contract, AircraftAdscReport? latestReport, if (!contract.HasPeriodicContract || contract.ReportingInterval is null) return false; - if (latestReport is null) + if (contract.LastReportReceived is null) return true; - var timeSinceLastReport = now - latestReport.Received; + var timeSinceLastReport = now - contract.LastReportReceived.Value; return timeSinceLastReport >= contract.ReportingInterval.Value; } } diff --git a/source/CPDLCServer/Web/Pages/Settings/Index.cshtml b/source/CPDLCServer/Web/Pages/Settings/Index.cshtml index 7aaa1c1..201243a 100644 --- a/source/CPDLCServer/Web/Pages/Settings/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Settings/Index.cshtml @@ -179,6 +179,22 @@
Default: @Model.Defaults.VatsimStatusPollingIntervalSeconds seconds
+
+
+ +
The time after a new ADS-C contract before VATSIM reports are made. During this time, the aircraft can send its first report through Hoppie.
+
+
+
+ + minutes + +
+ +
+
Default: @Model.Defaults.VatsimStatusReportDelayMinutes minutes
+
+
From 543fe1e3590a95f12d518be36db144eccd968574 Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:37:21 +0800 Subject: [PATCH 09/18] Reset CPDLC connections on a new logon and replace the global lock A new logon resets the connection and closes its open dialogues. Dialogues have a station ID. The unit of work uses optimistic concurrency, failed uplinks are marked, message IDs are deleted when a connection ends, and dialogue retention is a setting. Co-Authored-By: Claude Opus 5.5 --- docs/docs/concepts/index.md | 20 ++- docs/docs/server/index.md | 16 ++- ...scContractOnConnectionEndedHandlerTests.cs | 23 ++++ ...PurgeExpiredAdscDataRequestHandlerTests.cs | 39 +----- .../Reports/AdscReportRepositoryTests.cs | 25 ---- ...tConnectionLostNotificationHandlerTests.cs | 44 ++++++- .../Connections/LogonCommandHandlerTests.cs | 123 +++++++++++++++--- .../TerminateConnectionHandlerTests.cs | 28 +++- ...eConnectionOnDialogueClosedHandlerTests.cs | 12 +- ...veCompletedDialoguesRequestHandlerTests.cs | 8 +- .../ArchiveDialogueCommandHandlerTests.cs | 8 +- ...CheckMessageTimeoutsRequestHandlerTests.cs | 16 +-- .../Dialogues/DialogueRepositoryTests.cs | 70 ++++++++-- .../Cpdlc/Dialogues/DialogueTests.cs | 30 ++--- ...urgeExpiredCpdlcDataRequestHandlerTests.cs | 33 ++++- .../AcknowledgeDownlinkCommandHandlerTests.cs | 8 +- ...ownlinkReceivedNotificationHandlerTests.cs | 4 +- .../AcknowledgeUplinkCommandHandlerTests.cs | 12 +- .../BeginDialogueCommandHandlerTests.cs | 10 +- ...nkTransmissionFailedCommandHandlerTests.cs | 45 +++++++ .../Cpdlc/Uplinks/MessageIdProviderTests.cs | 26 ++++ .../ReplyToDownlinkCommandHandlerTests.cs | 28 ++-- .../Cpdlc/Uplinks/UplinkTransmitterTests.cs | 63 +++++++++ .../Mocks/TestAdscReportRepository.cs | 6 - .../Mocks/TestDialogueRepository.cs | 13 +- .../Mocks/TestMessageIdProvider.cs | 10 +- .../Mocks/TestUplinkTransmitter.cs | 13 ++ .../Persistence/CpdlcDbContextTests.cs | 116 +++++++++++++++++ .../Persistence/UnitOfWorkTests.cs | 2 +- .../Settings/ServerSettingsProviderTests.cs | 12 +- .../AdscContractConfiguration.cs | 4 +- ...celAdscContractOnConnectionEndedHandler.cs | 16 ++- .../PurgeExpiredAdscDataRequestHandler.cs | 9 +- .../Reports/AdscReportRepository.cs | 10 -- .../AircraftAdscReportConfiguration.cs | 1 - .../ExpireAdscReportsRequestHandler.cs | 8 +- .../Reports/IAdscReportRepository.cs | 1 - .../AircraftConnectionConfiguration.cs | 4 +- ...rcraftConnectionLostNotificationHandler.cs | 60 +++------ .../Connections/AircraftConnectionReset.cs | 10 ++ .../Cpdlc/Connections/LogonCommandHandler.cs | 64 ++++++--- .../Connections/TerminateConnectionHandler.cs | 12 +- ...minateConnectionOnDialogueClosedHandler.cs | 3 +- .../Cpdlc/CpdlcServiceCollectionExtensions.cs | 1 + .../CPDLCServer/Cpdlc/Dialogues/Dialogue.cs | 35 ++++- .../Cpdlc/Dialogues/DialogueConfiguration.cs | 6 +- .../Cpdlc/Dialogues/DialogueRepository.cs | 23 +++- .../Cpdlc/Dialogues/IDialogueRepository.cs | 7 +- .../Cpdlc/Dialogues/MessageMonitorService.cs | 13 +- .../PurgeExpiredCpdlcDataRequestHandler.cs | 17 ++- .../DownlinkReceivedNotificationHandler.cs | 7 +- .../Uplinks/BeginDialogueCommandHandler.cs | 11 +- .../MarkUplinkTransmissionFailedCommand.cs | 5 + ...kUplinkTransmissionFailedCommandHandler.cs | 33 +++++ .../Cpdlc/Uplinks/MessageIdProvider.cs | 16 +++ .../Uplinks/ReplyToDownlinkCommandHandler.cs | 14 +- .../Cpdlc/Uplinks/UplinkTransmitter.cs | 44 +++++++ .../Infrastructure/UnitOfWorkMediator.cs | 39 ++++-- .../CPDLCServer/Persistence/CpdlcDbContext.cs | 57 ++++++++ ... 20261115043637_InitialCreate.Designer.cs} | 56 ++++++-- ...ate.cs => 20261115043637_InitialCreate.cs} | 45 ++++--- .../PostgreSqlCpdlcDbContextModelSnapshot.cs | 54 ++++++-- ... 20261115043633_InitialCreate.Designer.cs} | 56 ++++++-- ...ate.cs => 20261115043633_InitialCreate.cs} | 45 ++++--- .../SqliteCpdlcDbContextModelSnapshot.cs | 54 ++++++-- source/CPDLCServer/Settings/ServerSettings.cs | 2 +- .../Web/Pages/Atsu/Index.cshtml.cs | 7 +- .../Web/Pages/Dialogue/Index.cshtml.cs | 4 +- .../Web/Pages/Settings/Index.cshtml | 39 +++--- 69 files changed, 1334 insertions(+), 421 deletions(-) create mode 100644 source/CPDLCServer.Tests/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandlerTests.cs create mode 100644 source/CPDLCServer.Tests/Cpdlc/Uplinks/UplinkTransmitterTests.cs create mode 100644 source/CPDLCServer.Tests/Mocks/TestUplinkTransmitter.cs create mode 100644 source/CPDLCServer.Tests/Persistence/CpdlcDbContextTests.cs create mode 100644 source/CPDLCServer/Cpdlc/Connections/AircraftConnectionReset.cs create mode 100644 source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommand.cs create mode 100644 source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandler.cs create mode 100644 source/CPDLCServer/Cpdlc/Uplinks/UplinkTransmitter.cs rename source/CPDLCServer/Persistence/Migrations/PostgreSql/{20261115024457_InitialCreate.Designer.cs => 20261115043637_InitialCreate.Designer.cs} (90%) rename source/CPDLCServer/Persistence/Migrations/PostgreSql/{20261115024457_InitialCreate.cs => 20261115043637_InitialCreate.cs} (90%) rename source/CPDLCServer/Persistence/Migrations/Sqlite/{20261115024453_InitialCreate.Designer.cs => 20261115043633_InitialCreate.Designer.cs} (90%) rename source/CPDLCServer/Persistence/Migrations/Sqlite/{20261115024453_InitialCreate.cs => 20261115043633_InitialCreate.cs} (90%) diff --git a/docs/docs/concepts/index.md b/docs/docs/concepts/index.md index 54315e5..884808a 100644 --- a/docs/docs/concepts/index.md +++ b/docs/docs/concepts/index.md @@ -42,6 +42,17 @@ Connections can be initiated by: In both cases, the server automatically accepts valid logon requests. +### Connection Reset + +If an aircraft that is already connected sends `REQUEST LOGON` again, the new logon replaces the existing connection. +Hoppie's network identifies an aircraft only by its callsign, so the new logon can be from a different pilot with the same callsign. + +When the server resets a connection: + +- It closes all open dialogues of the previous connection, and adds the message `CPDLC CONNECTION RESET` to each dialogue +- The aircraft connects as Next Data Authority (NDA) again +- It cancels the ADS-C contract of the previous connection, then requests a new contract + ## Data Authority Data authority determines which ground station is responsible for communicating with an aircraft. @@ -241,9 +252,12 @@ Controllers use ADS-C to see aircraft that are outside radar coverage, such as a The aircraft sends reports automatically. The pilot does not have to do anything. Each report has the position, the altitude, and the time of the report. -:::note -ADS-C and CPDLC are separate systems. An aircraft can have an ADS-C contract with a ground station without a CPDLC connection. -For convenience, this plugin connects ADS-C to CPDLC. The server requests an ADS-C contract when an aircraft logs on with CPDLC, and cancels the contract when the CPDLC connection ends. +:::note[VATSIM accommodation] +ADS-C and CPDLC are separate systems. In real operations, an aircraft can have an ADS-C contract with a ground station without a CPDLC connection. +The aircraft makes ADS-C contracts after an AFN logon, and an ATSU usually keeps its ADS-C contract after it transfers the CPDLC connection to the next ATSU, until the aircraft is clear of its airspace. + +Hoppie's network has no AFN logon, so the CPDLC connection is the only signal that an aircraft is online. +Thus this plugin connects ADS-C to CPDLC. The server requests an ADS-C contract when an aircraft logs on with CPDLC, and cancels the contract when the CPDLC connection ends or is reset. ::: ### Contracts diff --git a/docs/docs/server/index.md b/docs/docs/server/index.md index e003e26..48af96c 100644 --- a/docs/docs/server/index.md +++ b/docs/docs/server/index.md @@ -88,7 +88,15 @@ The server can use SQLite or PostgreSQL (`DatabaseProvider`): The server applies the migrations when it starts. With SQLite, it also makes the database file. -The server deletes dialogues 24 hours after they open. It deletes ADS-C reports after the configured ADS-C report retention period. These periods start when the dialogue opens or the report is received, not when the server starts. Thus, after a restart, the server immediately deletes the data that is older than the period. +The server deletes a dialogue when the dialogue retention period ends (default: 24 hours). The period starts when the dialogue opens, not when the server starts. Thus, after a restart, the server deletes the dialogues that are older than the period within a few minutes. The server keeps the dialogues after the aircraft disconnects. + +The server keeps only the latest ADS-C report for each contract. The report expires soon after the next periodic reports do not arrive (see [ADS-C](#ads-c)). + +When a CPDLC connection ends, the server deletes the CPDLC message IDs of the aircraft. The next connection starts again at the first message ID. + +### Concurrent Changes + +The server processes the requests from controllers, the ACARS connections and the background tasks at the same time. Each changed record has a version. If two requests change the same record at the same time, the second request fails and the server runs it again with the new data, up to three times. ### ACARS Connections @@ -113,7 +121,11 @@ You can show only the entries at or above a level, pause the log, and clear the ### ADS-C -When an aircraft logs on with CPDLC, the server requests the default ADS-C contract with the aircraft. When the CPDLC connection ends, the server cancels the contract. +When an aircraft logs on with CPDLC, the server requests the default ADS-C contract with the aircraft. When the CPDLC connection ends or is reset, the server cancels the contract. + +:::note[VATSIM accommodation] +In real operations, ADS-C does not depend on CPDLC, and an ATSU usually keeps its ADS-C contract after a CPDLC transfer. Hoppie's network has no AFN logon, so the server uses the CPDLC connection as the signal that an aircraft is online. +::: Each ATSU has its own default reporting interval, set on its ACARS connection. Controllers can read this value. diff --git a/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs index e637658..bfe6513 100644 --- a/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/CancelAdscContractOnConnectionEndedHandlerTests.cs @@ -114,4 +114,27 @@ await handler.Handle( new AircraftConnectionTerminated("hoppies-ybbb", "YBBB", "UAL123"), CancellationToken.None); } + + [Fact] + public async Task Handle_ConnectionReset_CancelsContract() + { + // Arrange + var contractRepository = new TestAdscContractRepository(); + var contract = new AdscContract("UAL123", "YBBB", TimeSpan.FromMinutes(10), DateTimeOffset.MinValue); + await contractRepository.Add(new AdscContractKey("UAL123", "YBBB"), contract, CancellationToken.None); + + var mediator = Substitute.For(); + var handler = new CancelAdscContractOnConnectionEndedHandler( + new TestAcarsConnectionManager(), contractRepository, mediator, Logger.None); + + // Act + await handler.Handle( + new AircraftConnectionReset("hoppies-ybbb", "YBBB", "UAL123"), + CancellationToken.None); + + // Assert + await mediator.Received(1).Send( + Arg.Is(c => c.StationId == "YBBB" && c.Callsign == "UAL123"), + Arg.Any()); + } } diff --git a/source/CPDLCServer.Tests/AdscContracts/PurgeExpiredAdscDataRequestHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/PurgeExpiredAdscDataRequestHandlerTests.cs index ffecd8d..3899b55 100644 --- a/source/CPDLCServer.Tests/AdscContracts/PurgeExpiredAdscDataRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/PurgeExpiredAdscDataRequestHandlerTests.cs @@ -1,15 +1,11 @@ using CPDLCServer.AdscContracts; using CPDLCServer.AdscContracts.MessageLog; -using CPDLCServer.AdscContracts.Reports; -using CPDLCServer.Settings; using CPDLCServer.Tests.Mocks; namespace CPDLCServer.Tests.AdscContracts; public class PurgeExpiredAdscDataRequestHandlerTests { - static readonly TestServerSettingsProvider Settings = new(new ServerSettings { AdscReportRetentionHours = 24 }); - [Fact] public async Task Handle_RemovesAdscMessagesOlderThan24Hours() { @@ -37,7 +33,7 @@ public async Task Handle_RemovesAdscMessagesOlderThan24Hours() await adscMessageLogRepository.Add(oldEntry, CancellationToken.None); await adscMessageLogRepository.Add(newEntry, CancellationToken.None); - var handler = new PurgeExpiredAdscDataRequestHandler(adscMessageLogRepository, new TestAdscReportRepository(), Settings, clock); + var handler = new PurgeExpiredAdscDataRequestHandler(adscMessageLogRepository, clock); // Act - advance time beyond the purge timeout (24 hours) for the old entry only clock.SetUtcNow(startTime.AddHours(25)); @@ -46,37 +42,4 @@ public async Task Handle_RemovesAdscMessagesOlderThan24Hours() // Assert Assert.Equal([newEntry], await adscMessageLogRepository.All(CancellationToken.None)); } - - [Fact] - public async Task Handle_RemovesAdscReportsOlderThanRetention() - { - // Arrange - var clock = new TestClock(); - var adscReportRepository = new TestAdscReportRepository(); - - var startTime = DateTimeOffset.UtcNow; - clock.SetUtcNow(startTime); - - var oldReport = new AircraftAdscReport( - "UAL123", - "YBBB", - new AdscReport(startTime, -33.9461, 151.1772, 37000, AdscReportSource.Hoppie), - startTime); - var newReport = new AircraftAdscReport( - "QFA1", - "YBBB", - new AdscReport(startTime.AddHours(2), -33.9461, 151.1772, 37000, AdscReportSource.Hoppie), - startTime.AddHours(2)); - await adscReportRepository.Add(oldReport, CancellationToken.None); - await adscReportRepository.Add(newReport, CancellationToken.None); - - var handler = new PurgeExpiredAdscDataRequestHandler(new TestAdscMessageLogRepository(), adscReportRepository, Settings, clock); - - // Act - advance time beyond the retention (24 hours) for the old report only - clock.SetUtcNow(startTime.AddHours(25)); - await handler.Handle(new PurgeExpiredAdscDataRequest(), CancellationToken.None); - - // Assert - Assert.Equal([newReport], await adscReportRepository.AllLatest(CancellationToken.None)); - } } diff --git a/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs index 6a25f58..09c4e0c 100644 --- a/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportRepositoryTests.cs @@ -94,31 +94,6 @@ public async Task FindLatest_ReturnsLatestReportForAircraft() Assert.Null(await repository.FindLatest("QFA1", CancellationToken.None)); } - [Fact] - public async Task RemoveOlderThan_RemovesOnlyOlderReports() - { - // Arrange - using var database = new TestDatabase(); - var older = CreateReport("UAL123", "YBBB", 0); - var atCutoff = CreateReport("QFA1", "YBBB", 5); - var newer = CreateReport("VOZ1", "YBBB", 10); - await AddAndSave(database, older, atCutoff, newer); - - // Act - await using (var dbContext = database.CreateDbContext()) - { - var repository = new AdscReportRepository(dbContext); - await repository.RemoveOlderThan(atCutoff.Received, CancellationToken.None); - await dbContext.SaveChangesAsync(); - } - - // Assert - var reports = await AllLatest(database); - Assert.Equal(2, reports.Length); - Assert.Contains(atCutoff, reports); - Assert.Contains(newer, reports); - } - [Fact] public async Task Find_ReturnsReportForContract() { diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs index a49ed7f..ce41b8d 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs @@ -2,6 +2,7 @@ using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Web; using CPDLCServer.Tests.Mocks; using Microsoft.AspNetCore.SignalR; @@ -202,6 +203,42 @@ await clientProxy.DidNotReceive().SendCoreAsync( Arg.Any()); } + [Fact] + public async Task Handle_ClosesOpenDialoguesWhenNoControllersConnected() + { + // Arrange + var aircraftManager = new TestAircraftRepository(); + var aircraft = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); + aircraft.RequestLogon(DateTimeOffset.UtcNow); + aircraft.AcceptLogon(DateTimeOffset.UtcNow); + await aircraftManager.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); + + var clock = new TestClock(); + var dialogueRepository = new TestDialogueRepository(); + var openDialogue = new Dialogue("UAL123", "YBBB"); + openDialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", clock.UtcNow()); + await dialogueRepository.Add(openDialogue, CancellationToken.None); + + var messageIdProvider = new TestMessageIdProvider(); + var handler = new AircraftConnectionLostNotificationHandler( + aircraftManager, + new TestControllerRepository(), + dialogueRepository, + Substitute.For>(), + messageIdProvider, + new TestPublisher(), + clock, + new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new AircraftConnectionLost("hoppies-ybbb", "UAL123"), CancellationToken.None); + + // Assert - the dialogue is closed with the error message, and the message IDs are removed + Assert.True(openDialogue.IsClosed); + Assert.Equal("ERROR CONNECTION TIMED OUT", Assert.IsType(openDialogue.Messages.Last()).Content); + Assert.Equal([("hoppies-ybbb", "UAL123")], messageIdProvider.Removed); + } + [Fact] public async Task Handle_AddsErrorMessageToExistingOpenDialogue() { @@ -224,7 +261,7 @@ public async Task Handle_AddsErrorMessageToExistingOpenDialogue() var clock = new TestClock(); // Create an existing dialogue with an open downlink message - var existingDialogue = new Dialogue("UAL123"); + var existingDialogue = new Dialogue("UAL123", "YBBB"); existingDialogue.AddDownlink( 1, null, @@ -268,6 +305,9 @@ public async Task Handle_AddsErrorMessageToExistingOpenDialogue() Assert.Equal("ERROR CONNECTION TIMED OUT", errorMessage.Content); Assert.Equal(AlertType.Medium, errorMessage.AlertType); Assert.Equal(1, errorMessage.MessageReference); // References the open downlink + + // Assert - the message IDs of the connection are removed after the error message + Assert.Equal([("hoppies-ybbb", "UAL123")], messageIdProvider.Removed); } [Fact] @@ -292,7 +332,7 @@ public async Task Handle_ClosesOpenDialogue_SoItCanBeArchived() var clock = new TestClock(); // Create an existing dialogue with an open downlink message - var existingDialogue = new Dialogue("UAL123"); + var existingDialogue = new Dialogue("UAL123", "YBBB"); var openDownlink = existingDialogue.AddDownlink( 1, null, diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs index 0689b54..2ed02d5 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs @@ -38,7 +38,7 @@ static LogonCommandHandler BuildHandler( messageIdProvider, clock, mediator, - new TestUnitOfWork(), + new TestUplinkTransmitter(), Logger.None); [Fact] @@ -199,8 +199,28 @@ public async Task Handle_NewConnection_PersistsDialogueWithDownlinkAndUplink() await mediator.Received(1).Publish(Arg.Any(), Arg.Any()); } + static async Task AddExistingConnection(TestAircraftRepository aircraftRepository, TestClock clock) + { + var existing = new AircraftConnection("QFA1", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); + existing.RequestLogon(clock.UtcNow()); + existing.AcceptLogon(clock.UtcNow()); + existing.SetNextDataAuthority("YMMM", clock.UtcNow().AddMinutes(30)); + await aircraftRepository.Add(new("QFA1", "hoppies-ybbb"), existing, CancellationToken.None); + return existing; + } + + static async Task AddController(TestControllerRepository controllerRepository) + { + var controller = new ControllerInfo( + Guid.NewGuid(), + "Connection-1", + "YBBB", + "BN-TSN_FSS"); + await controllerRepository.Add(controller, CancellationToken.None); + } + [Fact] - public async Task Handle_ExistingConnection_AcceptsLogon_AndDoesNotDuplicateConnection() + public async Task Handle_ExistingConnection_ReplacesConnection() { // Arrange var clock = new TestClock(); @@ -211,17 +231,45 @@ public async Task Handle_ExistingConnection_AcceptsLogon_AndDoesNotDuplicateConn var messageIdProvider = new TestMessageIdProvider(); var mediator = Substitute.For(); - var controller = new ControllerInfo( - Guid.NewGuid(), - "Connection-1", - "YBBB", - "BN-TSN_FSS"); - await controllerRepository.Add(controller, CancellationToken.None); + await AddController(controllerRepository); + var existing = await AddExistingConnection(aircraftRepository, clock); - var existing = new AircraftConnection("QFA1", "hoppies-ybbb", "YBBB", DataAuthorityState.CurrentDataAuthority); - existing.RequestLogon(clock.UtcNow()); - existing.AcceptLogon(clock.UtcNow()); - await aircraftRepository.Add(new("QFA1", "hoppies-ybbb"), existing, CancellationToken.None); + var command = BuildLogonCommand(clock); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert - the logon is accepted + var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); + Assert.Equal("LOGON ACCEPTED", Assert.Single(acarsConnection.SentMessages).Content); + + // Assert - a new connection replaces the existing connection, and does not keep its state + var connection = Assert.Single(await aircraftRepository.All(CancellationToken.None)); + Assert.NotSame(existing, connection); + Assert.Equal(DataAuthorityState.NextDataAuthority, connection.DataAuthorityState); + Assert.False(connection.HasNextDataAuthority); + + // Assert - the new connection is established, so that a new ADS-C contract is requested + await mediator.Received(1).Publish( + new AircraftConnectionEstablished("hoppies-ybbb", "YBBB", "QFA1", DataAuthorityState.NextDataAuthority), + Arg.Any()); + } + + [Fact] + public async Task Handle_ExistingConnection_PublishesReset() + { + // Arrange + var clock = new TestClock(); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var aircraftRepository = new TestAircraftRepository(); + var controllerRepository = new TestControllerRepository(); + var dialogueRepository = new TestDialogueRepository(); + var messageIdProvider = new TestMessageIdProvider(); + var mediator = Substitute.For(); + + await AddController(controllerRepository); + await AddExistingConnection(aircraftRepository, clock); var command = BuildLogonCommand(clock); var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); @@ -230,13 +278,52 @@ public async Task Handle_ExistingConnection_AcceptsLogon_AndDoesNotDuplicateConn await handler.Handle(command, CancellationToken.None); // Assert - var acarsConnection = (TestAcarsConnection)await acarsConnectionManager.GetAcarsConnection("hoppies-ybbb", CancellationToken.None); - Assert.Single(acarsConnection.SentMessages); - Assert.Equal("LOGON ACCEPTED", acarsConnection.SentMessages[0].Content); + await mediator.Received(1).Publish( + new AircraftConnectionReset("hoppies-ybbb", "YBBB", "QFA1"), + Arg.Any()); + } + + [Fact] + public async Task Handle_ExistingConnection_ClosesOpenDialoguesWithResetMessage() + { + // Arrange + var clock = new TestClock(); + var acarsConnectionManager = new TestAcarsConnectionManager(); + var aircraftRepository = new TestAircraftRepository(); + var controllerRepository = new TestControllerRepository(); + var dialogueRepository = new TestDialogueRepository(); + var messageIdProvider = new TestMessageIdProvider(); + messageIdProvider.SetNextId(10); + var mediator = Substitute.For(); + + await AddController(controllerRepository); + await AddExistingConnection(aircraftRepository, clock); + + var openDialogue = new Dialogue("QFA1", "YBBB"); + openDialogue.AddUplink(5, null, "QFA1", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", clock.UtcNow()); + await dialogueRepository.Add(openDialogue, CancellationToken.None); + + // A dialogue with a different ATSU is not part of the connection + var otherStationDialogue = new Dialogue("QFA1", "YMMM"); + otherStationDialogue.AddUplink(6, null, "QFA1", "ML-IND_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL390", clock.UtcNow()); + await dialogueRepository.Add(otherStationDialogue, CancellationToken.None); + + var command = BuildLogonCommand(clock); + var handler = BuildHandler(acarsConnectionManager, aircraftRepository, controllerRepository, dialogueRepository, messageIdProvider, clock, mediator); + + // Act + await handler.Handle(command, CancellationToken.None); + + // Assert - the open dialogue is closed with the reset message + Assert.True(openDialogue.IsClosed); + var resetMessage = Assert.IsType(openDialogue.Messages.Last()); + Assert.Equal("CPDLC CONNECTION RESET", resetMessage.Content); + Assert.Equal(10, resetMessage.MessageId); + Assert.Equal(5, resetMessage.MessageReference); - var allTrackedAircraft = await aircraftRepository.All(CancellationToken.None); - Assert.Same(existing, Assert.Single(allTrackedAircraft)); - Assert.Equal(DataAuthorityState.CurrentDataAuthority, existing.DataAuthorityState); + // Assert - the dialogue with the other ATSU does not change + Assert.False(otherStationDialogue.IsClosed); + Assert.Single(otherStationDialogue.Messages); } [Fact] diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionHandlerTests.cs index d6d626f..209fdc1 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionHandlerTests.cs @@ -14,10 +14,12 @@ static TerminateConnectionHandler BuildHandler( TestAircraftRepository aircraftRepository, TestDialogueRepository dialogueRepository, TestClock clock, - IMediator mediator) => + IMediator mediator, + TestMessageIdProvider? messageIdProvider = null) => new( aircraftRepository, dialogueRepository, + messageIdProvider ?? new TestMessageIdProvider(), clock, mediator, Logger.None); @@ -33,7 +35,7 @@ static async Task AddConnectedAircraft(TestAircraftRepositor static async Task AddOpenDialogue(TestDialogueRepository dialogueRepository, TestClock clock, string callsign) { - var dialogue = new Dialogue(callsign); + var dialogue = new Dialogue(callsign, "YBBB"); dialogue.AddDownlink( 1, null, @@ -108,7 +110,7 @@ public async Task Handle_DoesNotChangeClosedOrArchivedDialogues() var mediator = Substitute.For(); await AddConnectedAircraft(aircraftRepository, clock, "UAL123"); - var closedDialogue = new Dialogue("UAL123"); + var closedDialogue = new Dialogue("UAL123", "YBBB"); closedDialogue.AddDownlink( 1, null, @@ -177,4 +179,24 @@ public async Task Handle_UnknownAircraft_DoesNothing() await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); await mediator.DidNotReceive().Publish(Arg.Any(), Arg.Any()); } + + [Fact] + public async Task Handle_RemovesMessageIdSequence() + { + // Arrange + var clock = new TestClock(); + var aircraftRepository = new TestAircraftRepository(); + var dialogueRepository = new TestDialogueRepository(); + var messageIdProvider = new TestMessageIdProvider(); + var mediator = Substitute.For(); + await AddConnectedAircraft(aircraftRepository, clock, "UAL123"); + + var handler = BuildHandler(aircraftRepository, dialogueRepository, clock, mediator, messageIdProvider); + + // Act + await handler.Handle(new TerminateConnectionRequest("UAL123", "hoppies-ybbb"), CancellationToken.None); + + // Assert + Assert.Equal([("hoppies-ybbb", "UAL123")], messageIdProvider.Removed); + } } diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandlerTests.cs index 5817024..d81d89c 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandlerTests.cs @@ -31,7 +31,7 @@ public async Task Handle_ClosedDialogueWithEndService_TerminatesConnection() Logger.None); // Create a closed dialogue with END SERVICE - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -76,7 +76,7 @@ public async Task Handle_OpenDialogueWithEndService_DoesNotTerminateConnection() Logger.None); // Create an open dialogue with END SERVICE (requires response) - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -119,7 +119,7 @@ public async Task Handle_ClosedDialogueWithoutEndService_DoesNotTerminateConnect Logger.None); // Create a closed dialogue WITHOUT END SERVICE - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -162,7 +162,7 @@ public async Task Handle_ClosedDialogueWithMultipleMessages_TerminatesWhenEndSer Logger.None); // Create a dialogue with multiple messages including END SERVICE - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Pilot request dialogue.AddDownlink( @@ -225,7 +225,7 @@ public async Task Handle_AircraftConnectionNotFound_LogsWarningAndDoesNotCrash() Logger.None); // Create a closed dialogue with END SERVICE - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -268,7 +268,7 @@ public async Task Handle_AircraftConnectionNotCDA_DoesNotTerminate() Logger.None); // Create a closed dialogue with END SERVICE - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandlerTests.cs index c3fe365..f3e44b5 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveCompletedDialoguesRequestHandlerTests.cs @@ -20,7 +20,7 @@ public async Task Handle_ArchivesDialogue_WhenAllMessagesAcknowledgedAndDelayPas clock.SetUtcNow(startTime); // Create a closed dialogue with acknowledged message - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -56,7 +56,7 @@ public async Task Handle_DoesNotArchive_WhenDelayNotPassed() var startTime = DateTimeOffset.UtcNow; clock.SetUtcNow(startTime); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -91,7 +91,7 @@ public async Task Handle_IgnoresOpenDialogues() clock.SetUtcNow(startTime); // Create an open dialogue (requires response) - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -127,7 +127,7 @@ public async Task Handle_IgnoresDialoguesWithoutAcknowledgements() clock.SetUtcNow(startTime); // Create a downlink that's closed but not acknowledged - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink( 1, null, diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveDialogueCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveDialogueCommandHandlerTests.cs index 99fb760..ec5ea10 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveDialogueCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/ArchiveDialogueCommandHandlerTests.cs @@ -16,7 +16,7 @@ public async Task Handle_ArchivesClosedDialogue() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.NoResponse, @@ -43,7 +43,7 @@ public async Task Handle_AcknowledgesUnacknowledgedDownlinks_WhenArchiving() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, @@ -78,7 +78,7 @@ public async Task Handle_DoesNotArchive_WhenDialogueIsOpen() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, @@ -107,7 +107,7 @@ public async Task Handle_IsIdempotent_WhenAlreadyArchived() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.NoResponse, diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandlerTests.cs index 5ab96c7..fc20f17 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/CheckMessageTimeoutsRequestHandlerTests.cs @@ -20,7 +20,7 @@ public async Task Handle_MarksPilotLate_WhenUplinkTimesOut() clock.SetUtcNow(startTime); // Create an uplink that requires a response - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -56,7 +56,7 @@ public async Task Handle_DoesNotMarkPilotLate_WhenTimeoutNotReached() var startTime = DateTimeOffset.UtcNow; clock.SetUtcNow(startTime); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -91,7 +91,7 @@ public async Task Handle_IgnoresNoResponseUplinks() clock.SetUtcNow(startTime); // Create an uplink that doesn't require a response - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -126,7 +126,7 @@ public async Task Handle_MarksControllerLate_WhenDownlinkTimesOut() clock.SetUtcNow(startTime); // Create a downlink that requires a response - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -161,7 +161,7 @@ public async Task Handle_IgnoresClosedMessages() var startTime = DateTimeOffset.UtcNow; clock.SetUtcNow(startTime); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -200,7 +200,7 @@ public async Task Handle_IgnoresClosedDialogues() clock.SetUtcNow(startTime); // Create a self-closing uplink (NoResponse) - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -235,10 +235,10 @@ public async Task Handle_HandlesMultipleDialogues() clock.SetUtcNow(startTime); // Create multiple dialogues with different aircraft - var dialogue1 = new Dialogue("UAL123"); + var dialogue1 = new Dialogue("UAL123", "YBBB"); var uplink1 = dialogue1.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB", startTime); - var dialogue2 = new Dialogue("DAL456"); + var dialogue2 = new Dialogue("DAL456", "YBBB"); var uplink2 = dialogue2.AddUplink(2, null, "DAL456", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "DESCEND", startTime); await repository.Add(dialogue1, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueRepositoryTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueRepositoryTests.cs index e779a23..154f961 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueRepositoryTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueRepositoryTests.cs @@ -14,7 +14,7 @@ public async Task FindById_ReturnsSavedDialogueWithMessagesInOrder() { // Arrange using var database = new TestDatabase(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", Start); dialogue.AddUplink(1, 7, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "DESCEND TO FL350", Start.AddMinutes(1)); dialogue.AddDownlink(8, 1, "UAL123", CpdlcDownlinkResponseType.NoResponse, AlertType.None, "WILCO", Start.AddMinutes(2)); @@ -55,7 +55,7 @@ public async Task Add_MessageToSavedDialogue_SavesMessage() { // Arrange using var database = new TestDatabase(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); await using (var dbContext = database.CreateDbContext()) @@ -88,12 +88,12 @@ public async Task FindOpenDialogueByUplink_FindsDialogueAddedInSameUnitOfWork() await using var dbContext = database.CreateDbContext(); var repository = new DialogueRepository(dbContext); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); await repository.Add(dialogue, CancellationToken.None); // Act - var result = await repository.FindOpenDialogueByUplink("UAL123", 1, CancellationToken.None); + var result = await repository.FindOpenDialogueByUplink("UAL123", "YBBB", 1, CancellationToken.None); // Assert Assert.Same(dialogue, result); @@ -136,7 +136,46 @@ public async Task FindClosedAndNotArchived_ReturnsOnlyClosedDialoguesThatAreNotA } [Fact] - public async Task FindOpenedBefore_ReturnsOnlyOlderDialogues() + public async Task FindOpenDialogueByUplink_DoesNotFindDialogueWithDifferentStation() + { + // Arrange + using var database = new TestDatabase(); + await using var dbContext = database.CreateDbContext(); + var repository = new DialogueRepository(dbContext); + + var dialogue = new Dialogue("UAL123", "YMMM"); + dialogue.AddUplink(1, null, "UAL123", "ML-IND_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); + await repository.Add(dialogue, CancellationToken.None); + + // Act + var result = await repository.FindOpenDialogueByUplink("UAL123", "YBBB", 1, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task FindOpenForAircraft_ReturnsOnlyOpenDialoguesOfAircraftAndStation() + { + // Arrange + using var database = new TestDatabase(); + var open = CreateOpenDialogue("UAL123", Start); + var closed = CreateClosedDialogue("UAL123", Start); + var otherAircraft = CreateOpenDialogue("QFA1", Start); + var otherStation = new Dialogue("UAL123", "YMMM"); + otherStation.AddUplink(1, null, "UAL123", "ML-IND_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); + await AddAndSave(database, open, closed, otherAircraft, otherStation); + + // Act + await using var dbContext = database.CreateDbContext(); + var result = await new DialogueRepository(dbContext).FindOpenForAircraft("UAL123", "YBBB", CancellationToken.None); + + // Assert + Assert.Equal([open.Id], result.Select(d => d.Id)); + } + + [Fact] + public async Task RemoveOpenedBefore_DeletesOnlyOlderDialoguesAndTheirMessages() { // Arrange using var database = new TestDatabase(); @@ -145,11 +184,18 @@ public async Task FindOpenedBefore_ReturnsOnlyOlderDialogues() await AddAndSave(database, older, newer); // Act - await using var dbContext = database.CreateDbContext(); - var result = await new DialogueRepository(dbContext).FindOpenedBefore(Start.AddHours(1), CancellationToken.None); + int removedCount; + await using (var dbContext = database.CreateDbContext()) + { + removedCount = await new DialogueRepository(dbContext).RemoveOpenedBefore(Start.AddHours(1), CancellationToken.None); + await dbContext.SaveChangesAsync(); + } - // Assert - Assert.Equal([older.Id], result.Select(d => d.Id)); + // Assert - the messages of the removed dialogue are deleted by the database + Assert.Equal(1, removedCount); + await using var readDbContext = database.CreateDbContext(); + Assert.Equal([newer.Id], (await new DialogueRepository(readDbContext).All(CancellationToken.None)).Select(d => d.Id)); + Assert.All(readDbContext.Set(), m => Assert.Equal(newer.Id, m.DialogueId)); } [Fact] @@ -157,7 +203,7 @@ public async Task Remove_DeletesDialogueAndMessages() { // Arrange using var database = new TestDatabase(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", Start); await using (var dbContext = database.CreateDbContext()) @@ -194,14 +240,14 @@ static async Task AddAndSave(TestDatabase database, params Dialogue[] dialogues) static Dialogue CreateOpenDialogue(string callsign, DateTimeOffset time) { - var dialogue = new Dialogue(callsign); + var dialogue = new Dialogue(callsign, "YBBB"); dialogue.AddUplink(1, null, callsign, "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", time); return dialogue; } static Dialogue CreateClosedDialogue(string callsign, DateTimeOffset time) { - var dialogue = new Dialogue(callsign); + var dialogue = new Dialogue(callsign, "YBBB"); dialogue.AddUplink(1, null, callsign, "BN-TSN_FSS", CpdlcUplinkResponseType.NoResponse, AlertType.None, "MONITOR BRISBANE CENTRE 128.6", time); return dialogue; } diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueTests.cs index e03fb92..2f0da2c 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/DialogueTests.cs @@ -11,7 +11,7 @@ public void Constructor_AddsFirstMessage() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Act var downlink = dialogue.AddDownlink( @@ -33,7 +33,7 @@ public void Constructor_SetsOpenedTimeToFirstMessageTime() { // Arrange var time = new DateTimeOffset(2025, 1, 15, 10, 30, 0, TimeSpan.Zero); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Act dialogue.AddDownlink( @@ -53,7 +53,7 @@ public void Constructor_SetsOpenedTimeToFirstMessageTime() public void Constructor_SetsCallsignFromParameter() { // Arrange - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Act dialogue.AddDownlink( @@ -74,7 +74,7 @@ public void AddMessage_UplinkResponseClosesReferencedDownlink() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -105,7 +105,7 @@ public void AddMessage_DownlinkResponseClosesReferencedUplink() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -136,7 +136,7 @@ public void AddMessage_StandbyDownlinkDoesNotCloseUplink() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -166,7 +166,7 @@ public void AddMessage_StandbyUplinkDoesNotCloseDownlink() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -197,7 +197,7 @@ public void AddMessage_RequestDeferredUplinkDoesNotCloseDownlink() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -228,7 +228,7 @@ public void Dialogue_ClosesWhenAllMessagesAreClosed() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink( 1, null, @@ -259,7 +259,7 @@ public void Dialogue_RemainsOpenWhenSomeMessagesAreOpen() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -291,7 +291,7 @@ public void Dialogue_MessageRequiringNoResponseIsSelfClosing() { // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Act var downlink = dialogue.AddDownlink( @@ -315,7 +315,7 @@ public void Dialogue_MultipleMessagesAndResponses() // Arrange - Simulate a realistic CPDLC exchange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Pilot requests climb var downlink1 = dialogue.AddDownlink( @@ -380,7 +380,7 @@ public void Dialogue_LogonRequestAndAcceptanceClosesImmediately() // Arrange var time = DateTimeOffset.UtcNow; - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); // Pilot sends logon request var logonRequest = dialogue.AddDownlink( @@ -420,7 +420,7 @@ public void AddMessage_WithEarlierTime_IsPlacedByTime() { // Arrange var time = new DateTimeOffset(2025, 1, 15, 10, 30, 0, TimeSpan.Zero); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB FL410", time); dialogue.AddDownlink(3, null, "UAL123", CpdlcDownlinkResponseType.NoResponse, AlertType.None, "FREE TEXT", time.AddMinutes(2)); @@ -437,7 +437,7 @@ public void AddMessage_WithEarlierTimeThanReferencedMessage_IsPlacedAfterReferen { // Arrange - the reply has an earlier time than the request, for example because of a clock difference var time = new DateTimeOffset(2025, 1, 15, 10, 30, 0, TimeSpan.Zero); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB FL410", time); // Act diff --git a/source/CPDLCServer.Tests/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandlerTests.cs index 62ed9db..ff9d242 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandlerTests.cs @@ -1,5 +1,6 @@ using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Settings; using CPDLCServer.Tests.Mocks; using Serilog.Core; @@ -13,18 +14,19 @@ public async Task Handle_RemovesDialoguesOpenedMoreThan24HoursAgo() // Arrange var clock = new TestClock(); var dialogueRepository = new TestDialogueRepository(); + var settingsProvider = new TestServerSettingsProvider(new ServerSettings { DialogueRetentionHours = 24 }); var startTime = DateTimeOffset.UtcNow; clock.SetUtcNow(startTime); - var oldDialogue = new Dialogue("UAL123"); + var oldDialogue = new Dialogue("UAL123", "YBBB"); oldDialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", startTime); - var newDialogue = new Dialogue("QFA1"); + var newDialogue = new Dialogue("QFA1", "YBBB"); newDialogue.AddUplink(1, null, "QFA1", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", startTime.AddHours(2)); await dialogueRepository.Add(oldDialogue, CancellationToken.None); await dialogueRepository.Add(newDialogue, CancellationToken.None); - var handler = new PurgeExpiredCpdlcDataRequestHandler(dialogueRepository, clock, Logger.None); + var handler = new PurgeExpiredCpdlcDataRequestHandler(dialogueRepository, settingsProvider, clock, Logger.None); // Act - advance time beyond the purge timeout (24 hours) for the old dialogue only clock.SetUtcNow(startTime.AddHours(25)); @@ -33,4 +35,29 @@ public async Task Handle_RemovesDialoguesOpenedMoreThan24HoursAgo() // Assert Assert.Equal([newDialogue], await dialogueRepository.All(CancellationToken.None)); } + + [Fact] + public async Task Handle_UsesDialogueRetentionSetting() + { + // Arrange + var clock = new TestClock(); + var dialogueRepository = new TestDialogueRepository(); + var settingsProvider = new TestServerSettingsProvider(new ServerSettings { DialogueRetentionHours = 2 }); + + var startTime = DateTimeOffset.UtcNow; + clock.SetUtcNow(startTime); + + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddUplink(1, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", startTime); + await dialogueRepository.Add(dialogue, CancellationToken.None); + + var handler = new PurgeExpiredCpdlcDataRequestHandler(dialogueRepository, settingsProvider, clock, Logger.None); + + // Act - advance time beyond the configured retention (2 hours) + clock.SetUtcNow(startTime.AddHours(3)); + await handler.Handle(new PurgeExpiredCpdlcDataRequest(), CancellationToken.None); + + // Assert + Assert.Empty(await dialogueRepository.All(CancellationToken.None)); + } } diff --git a/source/CPDLCServer.Tests/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandlerTests.cs index 2ed656b..7b14b50 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Downlinks/AcknowledgeDownlinkCommandHandlerTests.cs @@ -15,7 +15,7 @@ public async Task Handle_AcknowledgesDownlinkMessage() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -53,7 +53,7 @@ public async Task Handle_PublishesDialogueChangedNotification() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink( 1, null, @@ -90,7 +90,7 @@ public async Task Handle_DoesNotCloseDialogueWhenMessagesAreStillOpen() var publisher = new TestPublisher(); // Create a downlink that requires a response - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var downlink = dialogue.AddDownlink( 1, null, @@ -151,7 +151,7 @@ public async Task Handle_ThrowsWhenDownlinkMessageNotFoundInDialogue() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink( 1, null, diff --git a/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs index 949d27e..d95f305 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs @@ -392,7 +392,7 @@ public async Task Handle_AppendsToExistingDialogue_ForDownlinkWithReference() var hubContext = Substitute.For>(); // Create existing dialogue with an uplink - var existingDialogue = new Dialogue("UAL123"); + var existingDialogue = new Dialogue("UAL123", "YBBB"); existingDialogue.AddUplink( 5, null, @@ -497,7 +497,7 @@ public async Task Handle_DoesNotAppendToClosedDialogue_WhenAircraftReusesMessage var hubContext = Substitute.For>(); // Prior session: uplink ID=5 was sent and fully replied to (dialogue is now closed) - var priorDialogue = new Dialogue("UAL123"); + var priorDialogue = new Dialogue("UAL123", "YBBB"); priorDialogue.AddUplink( 5, null, "UAL123", "YBBB", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB FL410", diff --git a/source/CPDLCServer.Tests/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandlerTests.cs index 349933e..b73a9d9 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/AcknowledgeUplinkCommandHandlerTests.cs @@ -16,7 +16,7 @@ public async Task Handle_ClosesUplinkMessageManually() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -57,7 +57,7 @@ public async Task Handle_PublishesDialogueChangedNotification() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -95,7 +95,7 @@ public async Task Handle_ClosesDialogueWhenAllMessagesAreClosed() var publisher = new TestPublisher(); // Create an uplink that requires a response - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink = dialogue.AddUplink( 1, null, @@ -135,7 +135,7 @@ public async Task Handle_KeepsDialogueOpenWhenOtherMessagesAreStillOpen() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); var uplink1 = dialogue.AddUplink( 1, null, @@ -211,7 +211,7 @@ public async Task Handle_ThrowsWhenUplinkMessageNotFoundInDialogue() var clock = new TestClock(); var publisher = new TestPublisher(); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddUplink( 1, null, @@ -246,7 +246,7 @@ public async Task Handle_OnlyFindsUplinkMessages() var publisher = new TestPublisher(); // Create a dialogue with a downlink (not an uplink) - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink( 1, null, diff --git a/source/CPDLCServer.Tests/Cpdlc/Uplinks/BeginDialogueCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/BeginDialogueCommandHandlerTests.cs index e82491b..b0bb757 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Uplinks/BeginDialogueCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/BeginDialogueCommandHandlerTests.cs @@ -27,7 +27,7 @@ public async Task Handle_CreatesNewDialogue() await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -60,7 +60,7 @@ public async Task Handle_UplinkHasNullMessageReference() await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -90,7 +90,7 @@ public async Task Handle_SendsUplinkViaAcarsConnection() await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -121,7 +121,7 @@ public async Task Handle_PublishesDialogueChangedNotification() await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); var handler = new BeginDialogueCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); @@ -146,7 +146,7 @@ public async Task Handle_ThrowsWhenAircraftNotConnected() // No aircraft added var handler = new BeginDialogueCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new BeginDialogueCommand("BN-TSN_FSS", "UAL123", CpdlcUplinkResponseType.WilcoUnable, "CLIMB TO FL410"); diff --git a/source/CPDLCServer.Tests/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandlerTests.cs new file mode 100644 index 0000000..77f0e27 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandlerTests.cs @@ -0,0 +1,45 @@ +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Uplinks; + +public class MarkUplinkTransmissionFailedCommandHandlerTests +{ + [Fact] + public async Task Handle_MarksUplinkAsFailedAndPublishesDialogueChanged() + { + // Arrange + var dialogueRepository = new TestDialogueRepository(); + var publisher = new TestPublisher(); + + var dialogue = new Dialogue("UAL123", "YBBB"); + var uplink = dialogue.AddUplink(3, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.WilcoUnable, AlertType.None, "CLIMB TO FL410", DateTimeOffset.UtcNow); + await dialogueRepository.Add(dialogue, CancellationToken.None); + + var handler = new MarkUplinkTransmissionFailedCommandHandler(dialogueRepository, publisher, Logger.None); + + // Act + await handler.Handle(new MarkUplinkTransmissionFailedCommand(dialogue.Id, 3), CancellationToken.None); + + // Assert + Assert.True(uplink.DidTransmissionFail); + var notification = Assert.Single(publisher.PublishedNotifications.OfType()); + Assert.Same(dialogue, notification.Dialogue); + } + + [Fact] + public async Task Handle_DialogueNotFound_DoesNothing() + { + // Arrange + var publisher = new TestPublisher(); + var handler = new MarkUplinkTransmissionFailedCommandHandler(new TestDialogueRepository(), publisher, Logger.None); + + // Act + await handler.Handle(new MarkUplinkTransmissionFailedCommand(Guid.NewGuid(), 3), CancellationToken.None); + + // Assert + Assert.Empty(publisher.PublishedNotifications); + } +} diff --git a/source/CPDLCServer.Tests/Cpdlc/Uplinks/MessageIdProviderTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/MessageIdProviderTests.cs index 80db06e..a3b9805 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Uplinks/MessageIdProviderTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/MessageIdProviderTests.cs @@ -103,4 +103,30 @@ public async Task GetNextMessageId_AfterRestart_ContinuesSequence() // Assert Assert.Equal(3, messageId); } + + [Fact] + public async Task Remove_NextConnectionStartsAtFirstId() + { + // Arrange + using var database = new TestDatabase(); + await using (var dbContext = database.CreateDbContext()) + { + var provider = new MessageIdProvider(dbContext); + await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + await provider.GetNextMessageId("YBBB", "UAL123", CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act + await using (var dbContext = database.CreateDbContext()) + { + await new MessageIdProvider(dbContext).Remove("YBBB", "UAL123", CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Assert + await using var readDbContext = database.CreateDbContext(); + Assert.Empty(readDbContext.MessageIdSequences); + Assert.Equal(1, await new MessageIdProvider(readDbContext).GetNextMessageId("YBBB", "UAL123", CancellationToken.None)); + } } diff --git a/source/CPDLCServer.Tests/Cpdlc/Uplinks/ReplyToDownlinkCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/ReplyToDownlinkCommandHandlerTests.cs index 5c33d9f..a79109a 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Uplinks/ReplyToDownlinkCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/ReplyToDownlinkCommandHandlerTests.cs @@ -30,7 +30,7 @@ public async Task Handle_AppendsUplinkToExistingDialogue_NotCreatingNew() aircraft.AcceptLogon(clock.UtcNow()); await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink( 7, null, @@ -42,7 +42,7 @@ public async Task Handle_AppendsUplinkToExistingDialogue_NotCreatingNew() await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); var command = new ReplyToDownlinkCommand("BN-TSN_FSS", dialogue.Id, 7, CpdlcUplinkResponseType.WilcoUnable, "DESCEND FL350"); @@ -77,12 +77,12 @@ public async Task Handle_UplinkMessageReferenceMatchesDownlinkId() aircraft.AcceptLogon(clock.UtcNow()); await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", clock.UtcNow()); await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Act await handler.Handle( @@ -115,16 +115,16 @@ public async Task Handle_UsesDialogueId_WhenMultipleDialoguesHaveSameDownlinkMes await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); // Both dialogues have a downlink with MessageId=1 (aircraft re-used the same ID) - var dialogueA = new Dialogue("UAL123"); + var dialogueA = new Dialogue("UAL123", "YBBB"); dialogueA.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB FL350", clock.UtcNow()); await dialogueRepository.Add(dialogueA, CancellationToken.None); - var dialogueB = new Dialogue("UAL123"); + var dialogueB = new Dialogue("UAL123", "YBBB"); dialogueB.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL250", clock.UtcNow()); await dialogueRepository.Add(dialogueB, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Controller explicitly replies to dialogueA await handler.Handle( @@ -152,12 +152,12 @@ public async Task Handle_SendsUplinkViaAcarsConnection() aircraft.AcceptLogon(clock.UtcNow()); await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", clock.UtcNow()); await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Act await handler.Handle( @@ -188,12 +188,12 @@ public async Task Handle_PublishesDialogueChangedNotification() aircraft.AcceptLogon(clock.UtcNow()); await aircraftRepository.Add(new(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink(7, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT FL350", clock.UtcNow()); await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Act await handler.Handle( @@ -218,7 +218,7 @@ public async Task Handle_ThrowsWhenDialogueNotFound() var aircraftRepository = new TestAircraftRepository(); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Act & Assert await Assert.ThrowsAsync(() => @@ -239,12 +239,12 @@ public async Task Handle_ThrowsWhenAircraftNotConnected() var aircraftRepository = new TestAircraftRepository(); // Dialogue exists but aircraft is not in the repository - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); dialogue.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DESCENT", clock.UtcNow()); await dialogueRepository.Add(dialogue, CancellationToken.None); var handler = new ReplyToDownlinkCommandHandler( - aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUnitOfWork(), Logger.None); + aircraftRepository, acarsConnectionManager, messageIdProvider, dialogueRepository, mediator, clock, new TestUplinkTransmitter(), Logger.None); // Act & Assert await Assert.ThrowsAsync(() => diff --git a/source/CPDLCServer.Tests/Cpdlc/Uplinks/UplinkTransmitterTests.cs b/source/CPDLCServer.Tests/Cpdlc/Uplinks/UplinkTransmitterTests.cs new file mode 100644 index 0000000..e10fad7 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Uplinks/UplinkTransmitterTests.cs @@ -0,0 +1,63 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Infrastructure; +using CPDLCServer.Tests.Mocks; +using MediatR; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Uplinks; + +public class UplinkTransmitterTests +{ + static UplinkMessage CreateUplink(Guid dialogueId) => new( + dialogueId, + 3, + null, + "UAL123", + "BN-TSN_FSS", + CpdlcUplinkResponseType.WilcoUnable, + AlertType.None, + "CLIMB TO FL410", + DateTimeOffset.UtcNow); + + [Fact] + public void TransmitAfterCommit_SendSucceeds_DoesNotMarkUplinkAsFailed() + { + // Arrange + var acarsConnection = new TestAcarsConnection("YBBB"); + var unitOfWorkMediator = Substitute.For(); + var transmitter = new UplinkTransmitter(new TestUnitOfWork(), unitOfWorkMediator, Logger.None); + var uplink = CreateUplink(Guid.NewGuid()); + + // Act + transmitter.TransmitAfterCommit(acarsConnection, uplink); + + // Assert + Assert.Equal([uplink], acarsConnection.SentMessages); + unitOfWorkMediator.DidNotReceive().Send(Arg.Any(), Arg.Any()); + } + + [Fact] + public void TransmitAfterCommit_SendFails_MarksUplinkAsFailedThenThrows() + { + // Arrange + var acarsConnection = Substitute.For(); + acarsConnection.Send(Arg.Any(), Arg.Any()) + .ThrowsAsync(new HttpRequestException("Hoppie is not available")); + + var unitOfWorkMediator = Substitute.For(); + var transmitter = new UplinkTransmitter(new TestUnitOfWork(), unitOfWorkMediator, Logger.None); + var dialogueId = Guid.NewGuid(); + + // Act + Assert.Throws(() => transmitter.TransmitAfterCommit(acarsConnection, CreateUplink(dialogueId))); + + // Assert + unitOfWorkMediator.Received(1).Send( + new MarkUplinkTransmissionFailedCommand(dialogueId, 3), + Arg.Any()); + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs index d54ac22..b08c7fa 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAdscReportRepository.cs @@ -40,12 +40,6 @@ public Task Remove(AircraftAdscReport report, CancellationToken cancellationToke return Task.CompletedTask; } - public Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken) - { - _reports.RemoveAll(r => r.Received < cutoff); - return Task.CompletedTask; - } - static AircraftAdscReport SelectLatest(IEnumerable reports) { return reports diff --git a/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs b/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs index 3aa8e9f..4e91c0e 100644 --- a/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs +++ b/source/CPDLCServer.Tests/Mocks/TestDialogueRepository.cs @@ -15,11 +15,13 @@ public Task Add(Dialogue dialogue, CancellationToken cancellationToken) public Task FindOpenDialogueByUplink( string aircraftCallsign, + string stationId, int uplinkMessageId, CancellationToken cancellationToken) { var dialogue = _dialogues.FirstOrDefault(d => d.AircraftCallsign == aircraftCallsign && + d.StationId == stationId && !d.IsClosed && d.Messages.OfType().Any(m => m.MessageId == uplinkMessageId)); @@ -41,9 +43,16 @@ public Task FindClosedAndNotArchived(CancellationToken cancellationT return Task.FromResult(_dialogues.Where(d => d.IsClosed && !d.IsArchived).ToArray()); } - public Task FindOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken) + public Task FindOpenForAircraft(string aircraftCallsign, string stationId, CancellationToken cancellationToken) { - return Task.FromResult(_dialogues.Where(d => d.Opened < cutoff).ToArray()); + return Task.FromResult(_dialogues + .Where(d => d.AircraftCallsign == aircraftCallsign && d.StationId == stationId && !d.IsClosed && !d.IsArchived) + .ToArray()); + } + + public Task RemoveOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken) + { + return Task.FromResult(_dialogues.RemoveAll(d => d.Opened < cutoff)); } public Task All(CancellationToken cancellationToken) diff --git a/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs b/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs index cec8d29..ebbce1a 100644 --- a/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs +++ b/source/CPDLCServer.Tests/Mocks/TestMessageIdProvider.cs @@ -6,13 +6,21 @@ public class TestMessageIdProvider : IMessageIdProvider { private int _nextId = 1; + public List<(string AcarsConnectionId, string Callsign)> Removed { get; } = []; + public Task GetNextMessageId(string stationId, string callsign, CancellationToken cancellationToken) { return Task.FromResult(_nextId++); } + public Task Remove(string acarsConnectionId, string callsign, CancellationToken cancellationToken) + { + Removed.Add((acarsConnectionId, callsign)); + return Task.CompletedTask; + } + public void SetNextId(int id) { _nextId = id; } -} \ No newline at end of file +} diff --git a/source/CPDLCServer.Tests/Mocks/TestUplinkTransmitter.cs b/source/CPDLCServer.Tests/Mocks/TestUplinkTransmitter.cs new file mode 100644 index 0000000..60dc89b --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestUplinkTransmitter.cs @@ -0,0 +1,13 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Uplinks; + +namespace CPDLCServer.Tests.Mocks; + +// Sends each uplink immediately, so that the handler tests can check the messages after the handler returns +public class TestUplinkTransmitter : IUplinkTransmitter +{ + public void TransmitAfterCommit(IAcarsConnection acarsConnection, UplinkMessage uplink) + { + acarsConnection.Send(uplink, CancellationToken.None).GetAwaiter().GetResult(); + } +} diff --git a/source/CPDLCServer.Tests/Persistence/CpdlcDbContextTests.cs b/source/CPDLCServer.Tests/Persistence/CpdlcDbContextTests.cs new file mode 100644 index 0000000..20588e3 --- /dev/null +++ b/source/CPDLCServer.Tests/Persistence/CpdlcDbContextTests.cs @@ -0,0 +1,116 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Downlinks; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Tests.Persistence; + +public class CpdlcDbContextTests +{ + static readonly DateTimeOffset Start = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task SaveChanges_WhenEntityChangedByDifferentUnitOfWork_Throws() + { + // Arrange + using var database = new TestDatabase(); + var connection = new AircraftConnection("UAL123", "hoppies-ybbb", "YBBB", DataAuthorityState.NextDataAuthority); + await using (var dbContext = database.CreateDbContext()) + { + await new AircraftRepository(dbContext).Add(new("UAL123", "hoppies-ybbb"), connection, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + await using var first = database.CreateDbContext(); + await using var second = database.CreateDbContext(); + var firstConnection = await new AircraftRepository(first).Find(new("UAL123", "hoppies-ybbb"), CancellationToken.None); + var secondConnection = await new AircraftRepository(second).Find(new("UAL123", "hoppies-ybbb"), CancellationToken.None); + + firstConnection!.PromoteToCurrentDataAuthority(); + secondConnection!.SetNextDataAuthority("YMMM", Start); + + // Act + await first.SaveChangesAsync(); + + // Assert + await Assert.ThrowsAsync(() => second.SaveChangesAsync()); + } + + [Fact] + public async Task SaveChanges_WhenMessagesOfSameDialogueChangedByDifferentUnitOfWork_Throws() + { + // Arrange + using var database = new TestDatabase(); + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB TO FL410", Start); + dialogue.AddDownlink(2, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST DIRECT TO BIXAD", Start); + await using (var dbContext = database.CreateDbContext()) + { + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + await using var first = database.CreateDbContext(); + await using var second = database.CreateDbContext(); + var firstDialogue = await new DialogueRepository(first).FindById(dialogue.Id, CancellationToken.None); + var secondDialogue = await new DialogueRepository(second).FindById(dialogue.Id, CancellationToken.None); + + // Each unit of work changes a different message. Only the messages change, not the dialogue. + firstDialogue!.AcknowledgeDownlink(1, Start.AddMinutes(1)); + secondDialogue!.AcknowledgeDownlink(2, Start.AddMinutes(1)); + + // Act + await first.SaveChangesAsync(); + + // Assert + await Assert.ThrowsAsync(() => second.SaveChangesAsync()); + } + + [Fact] + public async Task SaveChanges_WhenSameEntityAddedByDifferentUnitOfWork_Throws() + { + // Arrange + using var database = new TestDatabase(); + await using var first = database.CreateDbContext(); + await using var second = database.CreateDbContext(); + + await new MessageIdProvider(first).GetNextMessageId("hoppies-ybbb", "UAL123", CancellationToken.None); + await new MessageIdProvider(second).GetNextMessageId("hoppies-ybbb", "UAL123", CancellationToken.None); + + // Act + await first.SaveChangesAsync(); + + // Assert + await Assert.ThrowsAnyAsync(() => second.SaveChangesAsync()); + } + + [Fact] + public async Task SaveChanges_WhenNoConflict_Saves() + { + // Arrange + using var database = new TestDatabase(); + var dialogue = new Dialogue("UAL123", "YBBB"); + dialogue.AddDownlink(1, null, "UAL123", CpdlcDownlinkResponseType.ResponseRequired, AlertType.None, "REQUEST CLIMB TO FL410", Start); + await using (var dbContext = database.CreateDbContext()) + { + await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); + await dbContext.SaveChangesAsync(); + } + + // Act - two units of work, one after the other + foreach (var minutes in new[] { 1, 2 }) + { + await using var dbContext = database.CreateDbContext(); + var saved = await new DialogueRepository(dbContext).FindById(dialogue.Id, CancellationToken.None); + saved!.AddUplink(minutes + 10, null, "UAL123", "BN-TSN_FSS", CpdlcUplinkResponseType.NoResponse, AlertType.None, "STANDBY", Start.AddMinutes(minutes)); + await dbContext.SaveChangesAsync(); + } + + // Assert + await using var readDbContext = database.CreateDbContext(); + var result = await new DialogueRepository(readDbContext).FindById(dialogue.Id, CancellationToken.None); + Assert.Equal(3, result!.Messages.Count); + } +} diff --git a/source/CPDLCServer.Tests/Persistence/UnitOfWorkTests.cs b/source/CPDLCServer.Tests/Persistence/UnitOfWorkTests.cs index 6ca9a08..0452694 100644 --- a/source/CPDLCServer.Tests/Persistence/UnitOfWorkTests.cs +++ b/source/CPDLCServer.Tests/Persistence/UnitOfWorkTests.cs @@ -14,7 +14,7 @@ public async Task Commit_SavesChangesBeforeActions() await using var dbContext = database.CreateDbContext(); var unitOfWork = new UnitOfWork(dbContext); - var dialogue = new Dialogue("UAL123"); + var dialogue = new Dialogue("UAL123", "YBBB"); await new DialogueRepository(dbContext).Add(dialogue, CancellationToken.None); var savedWhenActionRan = false; diff --git a/source/CPDLCServer.Tests/Settings/ServerSettingsProviderTests.cs b/source/CPDLCServer.Tests/Settings/ServerSettingsProviderTests.cs index 6057f66..14a9c6c 100644 --- a/source/CPDLCServer.Tests/Settings/ServerSettingsProviderTests.cs +++ b/source/CPDLCServer.Tests/Settings/ServerSettingsProviderTests.cs @@ -27,7 +27,7 @@ public async Task SeedDefaults_WhenSettingsExist_DoesNotChangeThem() // Arrange using var database = new TestDatabase(); await Seed(database); - await SaveAndCommit(database, new ServerSettings { AdscReportRetentionHours = 48 }); + await SaveAndCommit(database, new ServerSettings { DialogueRetentionHours = 48 }); // Act await Seed(database); @@ -36,7 +36,7 @@ public async Task SeedDefaults_WhenSettingsExist_DoesNotChangeThem() await using var dbContext = database.CreateDbContext(); Assert.Equal(1, await dbContext.ServerSettings.CountAsync()); var settings = await new ServerSettingsProvider(dbContext).Load(CancellationToken.None); - Assert.Equal(48, settings.AdscReportRetentionHours); + Assert.Equal(48, settings.DialogueRetentionHours); } [Fact] @@ -72,14 +72,14 @@ public async Task Save_WithoutCommit_DoesNotChangeTheDatabase() await using (var dbContext = database.CreateDbContext()) { await new ServerSettingsProvider(dbContext).Save( - new ServerSettings { AdscReportRetentionHours = 48 }, + new ServerSettings { DialogueRetentionHours = 48 }, CancellationToken.None); } // Assert await using var otherDbContext = database.CreateDbContext(); var settings = await new ServerSettingsProvider(otherDbContext).Load(CancellationToken.None); - Assert.Equal(new ServerSettings().AdscReportRetentionHours, settings.AdscReportRetentionHours); + Assert.Equal(new ServerSettings().DialogueRetentionHours, settings.DialogueRetentionHours); } [Fact] @@ -92,10 +92,10 @@ public async Task Load_AfterSaveInTheSameScope_ReturnsTheUnsavedSettings() var provider = new ServerSettingsProvider(dbContext); // Act - await provider.Save(new ServerSettings { AdscReportRetentionHours = 48 }, CancellationToken.None); + await provider.Save(new ServerSettings { DialogueRetentionHours = 48 }, CancellationToken.None); // Assert - Assert.Equal(48, (await provider.Load(CancellationToken.None)).AdscReportRetentionHours); + Assert.Equal(48, (await provider.Load(CancellationToken.None)).DialogueRetentionHours); } static async Task Seed(TestDatabase database) diff --git a/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs b/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs index b7b4c56..da77094 100644 --- a/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs +++ b/source/CPDLCServer/AdscContracts/AdscContractConfiguration.cs @@ -29,6 +29,8 @@ public void Configure(EntityTypeBuilder builder) builder.Property(c => c.LastReportReceived); builder.Property(c => c.ReportingSource); - builder.HasIndex(c => new { c.Callsign, c.StationId }); + // One contract for each aircraft and ATSU. + // Two units of work that add the same contract at the same time cannot both commit. + builder.HasIndex(c => new { c.Callsign, c.StationId }).IsUnique(); } } diff --git a/source/CPDLCServer/AdscContracts/CancelAdscContractOnConnectionEndedHandler.cs b/source/CPDLCServer/AdscContracts/CancelAdscContractOnConnectionEndedHandler.cs index af4a5cb..b97dda6 100644 --- a/source/CPDLCServer/AdscContracts/CancelAdscContractOnConnectionEndedHandler.cs +++ b/source/CPDLCServer/AdscContracts/CancelAdscContractOnConnectionEndedHandler.cs @@ -4,12 +4,19 @@ namespace CPDLCServer.AdscContracts; +// VATSIM accommodation: in real operations, ADS-C does not depend on CPDLC. +// The aircraft makes ADS-C contracts after an AFN logon, and an ATSU usually keeps its contract after a CPDLC transfer, +// until the aircraft is clear of its airspace. +// Hoppie has no AFN logon, so the CPDLC connection is the only signal that an aircraft is online. +// Thus the server cancels the ADS-C contract when the CPDLC connection ends, and when a new logon resets it. public class CancelAdscContractOnConnectionEndedHandler( IAcarsConnectionManager acarsConnectionManager, IAdscContractRepository adscContractRepository, IMediator mediator, ILogger logger) - : INotificationHandler, INotificationHandler + : INotificationHandler, + INotificationHandler, + INotificationHandler { public async Task Handle(AircraftConnectionTerminated notification, CancellationToken cancellationToken) { @@ -22,6 +29,13 @@ public async Task Handle(AircraftConnectionLost notification, CancellationToken await CancelContract(notification.Callsign, acarsConnection.StationId, cancellationToken); } + // The contract was made with the previous logon. + // Cancel it, so that the server requests a new contract for the new logon. + public async Task Handle(AircraftConnectionReset notification, CancellationToken cancellationToken) + { + await CancelContract(notification.Callsign, notification.StationId, cancellationToken); + } + async Task CancelContract(string callsign, string stationId, CancellationToken cancellationToken) { // A failure here must not stop the other handlers for the ended CPDLC connection diff --git a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs index 283f34f..3d00e70 100644 --- a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs +++ b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs @@ -1,27 +1,22 @@ using CPDLCServer.AdscContracts.MessageLog; -using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Infrastructure; -using CPDLCServer.Settings; using MediatR; namespace CPDLCServer.AdscContracts; public class PurgeExpiredAdscDataRequestHandler( IAdscMessageLogRepository adscMessageLogRepository, - IAdscReportRepository adscReportRepository, - IServerSettingsProvider settingsProvider, IClock clock) : IRequestHandler { readonly TimeSpan _messageLogRetention = TimeSpan.FromHours(24); + // The ADS-C reports are not purged here. Each contract keeps only its latest report, and the report expires + // soon after the next periodic reports do not arrive (ExpireAdscReportsRequestHandler). public async Task Handle(PurgeExpiredAdscDataRequest request, CancellationToken cancellationToken) { - var settings = await settingsProvider.Load(cancellationToken); - var adscReportRetention = TimeSpan.FromHours(settings.AdscReportRetentionHours); var now = clock.UtcNow(); await adscMessageLogRepository.RemoveOlderThan(now - _messageLogRetention, cancellationToken); - await adscReportRepository.RemoveOlderThan(now - adscReportRetention, cancellationToken); } } diff --git a/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs b/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs index ba4b13c..9326ea7 100644 --- a/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AdscReportRepository.cs @@ -57,16 +57,6 @@ public Task Remove(AircraftAdscReport report, CancellationToken cancellationToke return Task.CompletedTask; } - public async Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken) - { - await dbContext.AdscReports - .Where(r => r.Received < cutoff) - .LoadAsync(cancellationToken); - - var oldReports = dbContext.AdscReports.Local.Where(r => r.Received < cutoff).ToArray(); - dbContext.AdscReports.RemoveRange(oldReports); - } - // An aircraft can report to more than one ATSU, so the reports can arrive out of order static AircraftAdscReport SelectLatest(IEnumerable reports) { diff --git a/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs index ce084ab..4bd1bbc 100644 --- a/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs +++ b/source/CPDLCServer/AdscContracts/Reports/AircraftAdscReportConfiguration.cs @@ -29,6 +29,5 @@ public void Configure(EntityTypeBuilder builder) }); builder.HasIndex(r => new { r.Callsign, r.StationId }).IsUnique(); - builder.HasIndex(r => r.Received); } } diff --git a/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequestHandler.cs b/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequestHandler.cs index a1644b9..bef048c 100644 --- a/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequestHandler.cs +++ b/source/CPDLCServer/AdscContracts/Reports/ExpireAdscReportsRequestHandler.cs @@ -23,11 +23,13 @@ public async Task Handle(ExpireAdscReportsRequest request, CancellationToken can var reports = await adscReportRepository.All(cancellationToken); var now = clock.UtcNow(); + // Load all of the contracts in one query, not one query for each report + var contracts = await adscContractRepository.All(cancellationToken); + var contractsByKey = contracts.ToDictionary(c => new AdscContractKey(c.Callsign, c.StationId)); + foreach (var report in reports) { - var contract = await adscContractRepository.Find( - new AdscContractKey(report.Callsign, report.StationId), - cancellationToken); + var contract = contractsByKey.GetValueOrDefault(new AdscContractKey(report.Callsign, report.StationId)); if (contract?.LastReportReceived is not null && now - contract.LastReportReceived.Value <= contract.ReportExpiry) continue; diff --git a/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs b/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs index 1e4a363..213a63d 100644 --- a/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs +++ b/source/CPDLCServer/AdscContracts/Reports/IAdscReportRepository.cs @@ -14,5 +14,4 @@ public interface IAdscReportRepository Task All(CancellationToken cancellationToken); Task Remove(AircraftAdscReport report, CancellationToken cancellationToken); - Task RemoveOlderThan(DateTimeOffset cutoff, CancellationToken cancellationToken); } diff --git a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionConfiguration.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionConfiguration.cs index b7061fe..02fa328 100644 --- a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionConfiguration.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionConfiguration.cs @@ -27,6 +27,8 @@ public void Configure(EntityTypeBuilder builder) builder.Property(c => c.ExpectedTransferTime); builder.Property(c => c.DidSentNextDataAuthorityMessage); - builder.HasIndex(c => new { c.Callsign, c.AcarsConnectionId }); + // One connection for each aircraft on an ACARS connection. + // Two units of work that add the same connection at the same time cannot both commit. + builder.HasIndex(c => new { c.Callsign, c.AcarsConnectionId }).IsUnique(); } } diff --git a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs index 17d44f5..8e74f8b 100644 --- a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionLostNotificationHandler.cs @@ -46,55 +46,23 @@ await aircraftRepository.Remove( notification.Callsign, notification.AcarsConnectionId); - // Find all controllers on the same network and station - var controllers = await controllerRepository.All(cancellationToken); - if (!controllers.Any()) - { - logger.Information( - "No controllers to notify about lost aircraft {Callsign}", - notification.Callsign); - return; - } - - var allDialogues = await dialogueRepository.All(cancellationToken); - var aircraftDialogues = allDialogues - .Where(d => d.AircraftCallsign == notification.Callsign && !d.IsArchived) - .ToArray(); + // Close the dialogues also when no controllers are online, so that no dialogue of the lost connection stays open + var openDialogues = await dialogueRepository.FindOpenForAircraft( + notification.Callsign, + aircraft.StationId, + cancellationToken); - var openDialogues = aircraftDialogues.Where(d => !d.IsClosed).ToArray(); if (openDialogues.Any()) { - // Add error message to each open dialogue + // Add error message to each open dialogue, then close the remaining open messages, because no response can arrive foreach (var dialogue in openDialogues) { - // Find an open message to reference - var openMessage = dialogue.Messages.FirstOrDefault(m => !m.IsClosed); - - if (openMessage is null) - { - logger.Warning( - "Dialogue {DialogueId} is marked as open but has no open messages", - dialogue.Id); - continue; - } - var messageId = await messageIdProvider.GetNextMessageId( notification.AcarsConnectionId, notification.Callsign, cancellationToken); - var now = clock.UtcNow(); - dialogue.AddDownlink( - messageId, - openMessage.MessageId, - notification.Callsign, - CpdlcDownlinkResponseType.NoResponse, - AlertType.Medium, - "ERROR CONNECTION TIMED OUT", - now); - - // No response can arrive, so close the remaining open messages - dialogue.Abort(now); + dialogue.AbortWithError(messageId, "ERROR CONNECTION TIMED OUT", clock.UtcNow()); // Publish DialogueChangedNotification await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); @@ -113,7 +81,7 @@ await aircraftRepository.Remove( notification.Callsign, cancellationToken); - var dialogue = new Dialogue(notification.Callsign); + var dialogue = new Dialogue(notification.Callsign, aircraft.StationId); dialogue.AddDownlink( messageId, null, @@ -134,7 +102,19 @@ await aircraftRepository.Remove( notification.Callsign); } + // After the error messages, because they use the message IDs of the connection + await messageIdProvider.Remove(notification.AcarsConnectionId, notification.Callsign, cancellationToken); + // Notify controllers that the aircraft has disconnected + var controllers = await controllerRepository.All(cancellationToken); + if (!controllers.Any()) + { + logger.Information( + "No controllers to notify about lost aircraft {Callsign}", + notification.Callsign); + return; + } + var controllerConnectionIds = controllers.Select(c => c.ConnectionId).ToArray(); unitOfWork.AfterCommit(ct => hubContext.Clients .Clients(controllerConnectionIds) diff --git a/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionReset.cs b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionReset.cs new file mode 100644 index 0000000..a624a3c --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Connections/AircraftConnectionReset.cs @@ -0,0 +1,10 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Connections; + +// A new logon replaced the connection of an aircraft. The pilot can be a different pilot with the same callsign. +public record AircraftConnectionReset( + string AcarsConnectionId, + string StationId, + string Callsign) + : INotification; diff --git a/source/CPDLCServer/Cpdlc/Connections/LogonCommandHandler.cs b/source/CPDLCServer/Cpdlc/Connections/LogonCommandHandler.cs index 7dfd7f7..12b7f13 100644 --- a/source/CPDLCServer/Cpdlc/Connections/LogonCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/LogonCommandHandler.cs @@ -3,7 +3,6 @@ using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Infrastructure; -using CPDLCServer.Persistence; using MediatR; namespace CPDLCServer.Cpdlc.Connections; @@ -16,7 +15,7 @@ public class LogonCommandHandler( IMessageIdProvider messageIdProvider, IClock clock, IMediator mediator, - IUnitOfWork unitOfWork, + IUplinkTransmitter uplinkTransmitter, ILogger logger) : IRequestHandler { @@ -24,22 +23,18 @@ public async Task Handle(LogonCommand request, CancellationToken cancellationTok { var acarsConnection = await acarsConnectionManager.GetAcarsConnection(request.AcarsConnectionId, cancellationToken); - // If the aircraft already exists, simply accept the connection again - // Likely an issue with the aircraft requiring a reconnect - var aircraft = await aircraftRepository.Find( + // A new logon replaces the existing connection. + // Hoppie identifies an aircraft only by its callsign, so the new logon can be from a different pilot. + var existingAircraft = await aircraftRepository.Find( new(request.Callsign, request.AcarsConnectionId), cancellationToken); - if (aircraft is not null) + if (existingAircraft is not null) { - logger.Verbose("Duplicate connection request received from {Callsign} on {AcarsConnectionId}. Accepting the request.", request.Callsign, request.AcarsConnectionId); - - await Reply(acarsConnection, request, "LOGON ACCEPTED", cancellationToken); - - return; + await ResetConnection(existingAircraft, cancellationToken); } - aircraft = new AircraftConnection( + var aircraft = new AircraftConnection( request.Callsign, request.AcarsConnectionId, acarsConnection.StationId, @@ -83,13 +78,50 @@ await mediator.Publish( cancellationToken); } + // No response to the messages of the previous connection can arrive, so close its open dialogues + async Task ResetConnection(AircraftConnection existingAircraft, CancellationToken cancellationToken) + { + logger.Information( + "Connection request received from {Callsign} on {AcarsConnectionId}, which is already connected. Resetting the connection.", + existingAircraft.Callsign, + existingAircraft.AcarsConnectionId); + + var openDialogues = await dialogueRepository.FindOpenForAircraft( + existingAircraft.Callsign, + existingAircraft.StationId, + cancellationToken); + + foreach (var dialogue in openDialogues) + { + var messageId = await messageIdProvider.GetNextMessageId( + existingAircraft.AcarsConnectionId, + existingAircraft.Callsign, + cancellationToken); + + dialogue.AbortWithError(messageId, "CPDLC CONNECTION RESET", clock.UtcNow()); + await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); + + logger.Information( + "Closed dialogue {DialogueId} for reset connection with {Callsign}", + dialogue.Id, + existingAircraft.Callsign); + } + + await mediator.Publish( + new AircraftConnectionReset( + existingAircraft.AcarsConnectionId, + existingAircraft.StationId, + existingAircraft.Callsign), + cancellationToken); + } + async Task Reply( IAcarsConnection acarsConnection, LogonCommand request, string content, CancellationToken cancellationToken) { - var dialogue = new Dialogue(request.Callsign); + var dialogue = new Dialogue(request.Callsign, acarsConnection.StationId); dialogue.AddDownlink( request.DownlinkId, request.DownlinkMessageReference, @@ -119,10 +151,6 @@ async Task Reply( await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - unitOfWork.AfterCommit(async ct => - { - await acarsConnection.Send(uplinkMessage, ct); - logger.Information("Sent CPDLC message from SYSTEM to {Callsign}", request.Callsign); - }); + uplinkTransmitter.TransmitAfterCommit(acarsConnection, uplinkMessage); } } diff --git a/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionHandler.cs b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionHandler.cs index 25ec7ed..2a7c966 100644 --- a/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionHandler.cs @@ -1,4 +1,5 @@ using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Infrastructure; using MediatR; @@ -7,6 +8,7 @@ namespace CPDLCServer.Cpdlc.Connections; public class TerminateConnectionHandler( IAircraftRepository aircraftRepository, IDialogueRepository dialogueRepository, + IMessageIdProvider messageIdProvider, IClock clock, IMediator mediator, ILogger logger) @@ -28,10 +30,10 @@ public async Task Handle(TerminateConnectionRequest request, CancellationToken c return; // No response can arrive after the connection ends, so close the open dialogues - var allDialogues = await dialogueRepository.All(cancellationToken); - var openDialogues = allDialogues - .Where(d => d.AircraftCallsign == request.Callsign && !d.IsClosed && !d.IsArchived) - .ToArray(); + var openDialogues = await dialogueRepository.FindOpenForAircraft( + request.Callsign, + aircraftConnection.StationId, + cancellationToken); foreach (var dialogue in openDialogues) { @@ -44,6 +46,8 @@ public async Task Handle(TerminateConnectionRequest request, CancellationToken c request.Callsign); } + await messageIdProvider.Remove(request.AcarsConnectionId, request.Callsign, cancellationToken); + await mediator.Publish( new AircraftConnectionTerminated( request.AcarsConnectionId, diff --git a/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs index 021622f..bf17135 100644 --- a/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs +++ b/source/CPDLCServer/Cpdlc/Connections/TerminateConnectionOnDialogueClosedHandler.cs @@ -24,10 +24,11 @@ public async Task Handle(DialogueChangedNotification notification, CancellationT if (!hasEndService) return; - // Find the aircraft connection (CDA state) + // Find the aircraft connection (CDA state) with the ATSU of the dialogue var aircraftConnections = await aircraftRepository.All(cancellationToken); var aircraftConnection = aircraftConnections.FirstOrDefault(c => c.Callsign == notification.Dialogue.AircraftCallsign && + c.StationId == notification.Dialogue.StationId && c.DataAuthorityState == DataAuthorityState.CurrentDataAuthority); if (aircraftConnection is null) diff --git a/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs b/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs index 39d9cdb..a9684b3 100644 --- a/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs +++ b/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs @@ -16,6 +16,7 @@ public static IServiceCollection AddCpdlc(this IServiceCollection services) services.AddHostedService(); services.AddScoped(); + services.AddScoped(); return services; } diff --git a/source/CPDLCServer/Cpdlc/Dialogues/Dialogue.cs b/source/CPDLCServer/Cpdlc/Dialogues/Dialogue.cs index bdd6ce4..6dddc32 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/Dialogue.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/Dialogue.cs @@ -20,14 +20,18 @@ public class Dialogue { readonly List _messages = []; - public Dialogue(string aircraftCallsign) + public Dialogue(string aircraftCallsign, string stationId) { AircraftCallsign = aircraftCallsign; + StationId = stationId; } public Guid Id { get; } = Guid.NewGuid(); public string AircraftCallsign { get; } + + // The ATSU of the dialogue + public string StationId { get; } public IReadOnlyList Messages => _messages.AsReadOnly(); public DateTimeOffset Opened { get; private set; } public DateTimeOffset? Closed { get; private set; } @@ -129,6 +133,24 @@ public void Abort(DateTimeOffset now) TryClose(now); } + // Adds an error message from the aircraft, then closes all open messages, because no response can arrive. + // The error message refers to the first open message. + public void AbortWithError(int messageId, string content, DateTimeOffset now) + { + var openMessage = _messages.FirstOrDefault(m => !m.IsClosed); + + AddDownlink( + messageId, + openMessage?.MessageId, + AircraftCallsign, + CpdlcDownlinkResponseType.NoResponse, + AlertType.Medium, + content, + now); + + Abort(now); + } + public void AcknowledgeDownlink(int downlinkMessageId, DateTimeOffset now) { var downlink = _messages.OfType() @@ -142,6 +164,17 @@ public void AcknowledgeDownlink(int downlinkMessageId, DateTimeOffset now) downlink.Acknowledge(now); } + public void MarkTransmissionFailed(int uplinkMessageId) + { + var uplink = _messages.OfType() + .FirstOrDefault(ul => ul.MessageId == uplinkMessageId); + + if (uplink is null) + throw new InvalidOperationException($"Uplink message {uplinkMessageId} not found in dialogue"); + + uplink.DidTransmissionFail = true; + } + void ProcessMessage(CpdlcMessage message) { switch (message) diff --git a/source/CPDLCServer/Cpdlc/Dialogues/DialogueConfiguration.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConfiguration.cs index 02de8cc..6bccd48 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/DialogueConfiguration.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueConfiguration.cs @@ -13,6 +13,7 @@ public void Configure(EntityTypeBuilder builder) builder.Property(d => d.Id).ValueGeneratedNever(); builder.Property(d => d.AircraftCallsign); + builder.Property(d => d.StationId); builder.Property(d => d.Opened); builder.Property(d => d.Closed); builder.Property(d => d.Archived); @@ -26,6 +27,9 @@ public void Configure(EntityTypeBuilder builder) .HasField("_messages") .UsePropertyAccessMode(PropertyAccessMode.Field); - builder.HasIndex(d => d.AircraftCallsign); + builder.HasIndex(d => new { d.AircraftCallsign, d.StationId }); + + // The purge finds the old dialogues by the time that they opened + builder.HasIndex(d => d.Opened); } } diff --git a/source/CPDLCServer/Cpdlc/Dialogues/DialogueRepository.cs b/source/CPDLCServer/Cpdlc/Dialogues/DialogueRepository.cs index e6733d4..90fa38a 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/DialogueRepository.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/DialogueRepository.cs @@ -17,11 +17,12 @@ public Task Add(Dialogue dialogue, CancellationToken cancellationToken) public async Task FindOpenDialogueByUplink( string aircraftCallsign, + string stationId, int uplinkMessageId, CancellationToken cancellationToken) { await DialoguesWithMessages() - .Where(d => d.AircraftCallsign == aircraftCallsign && d.Closed == null) + .Where(d => d.AircraftCallsign == aircraftCallsign && d.StationId == stationId && d.Closed == null) .LoadAsync(cancellationToken); // BUG: It's possible to have messageId collisions, since the server generates incrementing ids, and some @@ -36,6 +37,7 @@ await DialoguesWithMessages() return dbContext.Dialogues.Local .FirstOrDefault(d => d.AircraftCallsign == aircraftCallsign && + d.StationId == stationId && !d.IsClosed && d.Messages.OfType().Any(m => m.MessageId == uplinkMessageId)); } @@ -67,13 +69,26 @@ await DialoguesWithMessages() return dbContext.Dialogues.Local.Where(d => d.IsClosed && !d.IsArchived).ToArray(); } - public async Task FindOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken) + public async Task FindOpenForAircraft(string aircraftCallsign, string stationId, CancellationToken cancellationToken) { await DialoguesWithMessages() - .Where(d => d.Opened < cutoff) + .Where(d => d.AircraftCallsign == aircraftCallsign && d.StationId == stationId && d.Closed == null && d.Archived == null) .LoadAsync(cancellationToken); - return dbContext.Dialogues.Local.Where(d => d.Opened < cutoff).ToArray(); + return dbContext.Dialogues.Local + .Where(d => d.AircraftCallsign == aircraftCallsign && d.StationId == stationId && !d.IsClosed && !d.IsArchived) + .ToArray(); + } + + public async Task RemoveOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken) + { + // The messages are not loaded. The database deletes them with their dialogue (cascade delete). + var dialogues = await dbContext.Dialogues + .Where(d => d.Opened < cutoff) + .ToArrayAsync(cancellationToken); + + dbContext.Dialogues.RemoveRange(dialogues); + return dialogues.Length; } public async Task All(CancellationToken cancellationToken) diff --git a/source/CPDLCServer/Cpdlc/Dialogues/IDialogueRepository.cs b/source/CPDLCServer/Cpdlc/Dialogues/IDialogueRepository.cs index 9759966..c6592f0 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/IDialogueRepository.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/IDialogueRepository.cs @@ -8,6 +8,7 @@ public interface IDialogueRepository Task FindOpenDialogueByUplink( string aircraftCallsign, + string stationId, int uplinkMessageId, CancellationToken cancellationToken); @@ -17,7 +18,11 @@ public interface IDialogueRepository Task FindClosedAndNotArchived(CancellationToken cancellationToken); - Task FindOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken); + // The open dialogues of an aircraft with an ATSU + Task FindOpenForAircraft(string aircraftCallsign, string stationId, CancellationToken cancellationToken); + + // Removes the dialogues that opened before the cutoff, and returns the number of dialogues that were removed + Task RemoveOpenedBefore(DateTimeOffset cutoff, CancellationToken cancellationToken); Task All(CancellationToken cancellationToken); diff --git a/source/CPDLCServer/Cpdlc/Dialogues/MessageMonitorService.cs b/source/CPDLCServer/Cpdlc/Dialogues/MessageMonitorService.cs index 3bb34fa..303daa0 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/MessageMonitorService.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/MessageMonitorService.cs @@ -5,14 +5,19 @@ namespace CPDLCServer.Cpdlc.Dialogues; public class MessageMonitorService( IUnitOfWorkMediator mediator, + IClock clock, ILogger logger) : BackgroundService { readonly TimeSpan _timeoutCheckInterval = TimeSpan.FromSeconds(5); + // The retention period is in hours, so the purge does not need to run often + readonly TimeSpan _purgeInterval = TimeSpan.FromMinutes(5); + protected override async Task ExecuteAsync(CancellationToken stoppingToken) { logger.Information("Starting message monitor service"); + DateTimeOffset? lastPurge = null; try { while (!stoppingToken.IsCancellationRequested) @@ -20,7 +25,13 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) logger.Verbose("Running message monitor iteration"); // Each request is a separate unit of work, so that a failure in one does not stop the others - await Send(new PurgeExpiredCpdlcDataRequest(), stoppingToken); + var now = clock.UtcNow(); + if (lastPurge is null || now - lastPurge >= _purgeInterval) + { + await Send(new PurgeExpiredCpdlcDataRequest(), stoppingToken); + lastPurge = now; + } + await Send(new CheckMessageTimeoutsRequest(), stoppingToken); await Send(new ArchiveCompletedDialoguesRequest(), stoppingToken); diff --git a/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs index 47da523..cbaca88 100644 --- a/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs +++ b/source/CPDLCServer/Cpdlc/Dialogues/PurgeExpiredCpdlcDataRequestHandler.cs @@ -1,26 +1,25 @@ using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; using MediatR; namespace CPDLCServer.Cpdlc.Dialogues; public class PurgeExpiredCpdlcDataRequestHandler( IDialogueRepository dialogueRepository, + IServerSettingsProvider settingsProvider, IClock clock, ILogger logger) : IRequestHandler { - readonly TimeSpan _purgeTimeout = TimeSpan.FromHours(24); - public async Task Handle(PurgeExpiredCpdlcDataRequest request, CancellationToken cancellationToken) { + var settings = await settingsProvider.Load(cancellationToken); + var retention = TimeSpan.FromHours(settings.DialogueRetentionHours); var now = clock.UtcNow(); - // I don't care if it's closed or not. It's been long enough. - var oldDialogues = await dialogueRepository.FindOpenedBefore(now - _purgeTimeout, cancellationToken); - foreach (var dialogue in oldDialogues) - { - await dialogueRepository.Remove(dialogue, cancellationToken); - logger.Information("Purging dialogue {DialogueId}", dialogue.Id); - } + // The dialogue is purged when the retention period ends, also when it is open or the aircraft is connected + var purgedCount = await dialogueRepository.RemoveOpenedBefore(now - retention, cancellationToken); + if (purgedCount > 0) + logger.Information("Purging {DialogueCount} dialogue(s) older than {Retention}", purgedCount, retention); } } diff --git a/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs index 90f333b..69a123f 100644 --- a/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs +++ b/source/CPDLCServer/Cpdlc/Downlinks/DownlinkReceivedNotificationHandler.cs @@ -60,7 +60,7 @@ await mediator.Send( // TODO: Handle this in hoppies if (ControlMessages.IsLogoffNotice(downlink)) { - var logoffDialogue = new Dialogue(downlink.Sender); + var logoffDialogue = new Dialogue(downlink.Sender, notification.StationId); logoffDialogue.AddDownlink( downlink.MessageId, downlink.MessageReference, @@ -113,6 +113,7 @@ await mediator.Send( { var dialogue = await dialogueRepository.FindOpenDialogueByUplink( downlink.Sender, + notification.StationId, downlink.MessageReference.Value, cancellationToken); if (dialogue is not null) @@ -125,7 +126,7 @@ await mediator.Send( // TODO: This could lead to a bug if the Aircraft thinks we're still in the original message chain. // Consider returning an error here instead. logger.Warning("No open dialogue found for uplink reference {MessageReference} from {Callsign} - starting new dialogue", downlink.MessageReference.Value, downlink.Sender); - dialogue = new Dialogue(downlink.Sender); + dialogue = new Dialogue(downlink.Sender, notification.StationId); dialogue.AddDownlink( downlink.MessageId, downlink.MessageReference, @@ -142,7 +143,7 @@ await mediator.Send( } else // Scenario 5: Aircraft initiates a new dialogue { - var dialogue = new Dialogue(downlink.Sender); + var dialogue = new Dialogue(downlink.Sender, notification.StationId); dialogue.AddDownlink( downlink.MessageId, downlink.MessageReference, diff --git a/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommandHandler.cs b/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommandHandler.cs index 56bd6e1..d14fbda 100644 --- a/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/BeginDialogueCommandHandler.cs @@ -2,7 +2,6 @@ using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Infrastructure; -using CPDLCServer.Persistence; using MediatR; namespace CPDLCServer.Cpdlc.Uplinks; @@ -14,7 +13,7 @@ public class BeginDialogueCommandHandler( IDialogueRepository dialogueRepository, IMediator mediator, IClock clock, - IUnitOfWork unitOfWork, + IUplinkTransmitter uplinkTransmitter, ILogger logger) : IRequestHandler { @@ -37,7 +36,7 @@ public async Task Handle(BeginDialogueCommand request, CancellationToken cancell request.Recipient, cancellationToken); - var dialogue = new Dialogue(request.Recipient); + var dialogue = new Dialogue(request.Recipient, aircraftConnection.StationId); var uplinkMessage = dialogue.AddUplink( messageId, null, @@ -54,10 +53,6 @@ public async Task Handle(BeginDialogueCommand request, CancellationToken cancell await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - unitOfWork.AfterCommit(async ct => - { - await acarsConnection.Send(uplinkMessage, ct); - logger.Information("Sent CPDLC message from {Sender} to {Recipient}", request.Sender, request.Recipient); - }); + uplinkTransmitter.TransmitAfterCommit(acarsConnection, uplinkMessage); } } diff --git a/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommand.cs b/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommand.cs new file mode 100644 index 0000000..396419d --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Uplinks; + +public record MarkUplinkTransmissionFailedCommand(Guid DialogueId, int UplinkMessageId) : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandler.cs b/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandler.cs new file mode 100644 index 0000000..6e1680a --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/MarkUplinkTransmissionFailedCommandHandler.cs @@ -0,0 +1,33 @@ +using CPDLCServer.Cpdlc.Dialogues; +using MediatR; + +namespace CPDLCServer.Cpdlc.Uplinks; + +public class MarkUplinkTransmissionFailedCommandHandler( + IDialogueRepository dialogueRepository, + IPublisher publisher, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(MarkUplinkTransmissionFailedCommand request, CancellationToken cancellationToken) + { + var dialogue = await dialogueRepository.FindById(request.DialogueId, cancellationToken); + if (dialogue is null) + { + logger.Warning( + "Cannot mark uplink {MessageId} as failed: dialogue {DialogueId} not found", + request.UplinkMessageId, + request.DialogueId); + return; + } + + dialogue.MarkTransmissionFailed(request.UplinkMessageId); + + logger.Information( + "Marked uplink {MessageId} in dialogue {DialogueId} as failed", + request.UplinkMessageId, + request.DialogueId); + + await publisher.Publish(new DialogueChangedNotification(dialogue), cancellationToken); + } +} diff --git a/source/CPDLCServer/Cpdlc/Uplinks/MessageIdProvider.cs b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdProvider.cs index 46b2646..799dd71 100644 --- a/source/CPDLCServer/Cpdlc/Uplinks/MessageIdProvider.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/MessageIdProvider.cs @@ -8,6 +8,12 @@ Task GetNextMessageId( string acarsConnectionId, string callsign, CancellationToken cancellationToken); + + // Removes the message IDs of an aircraft when its connection ends. The next connection starts at the first ID. + Task Remove( + string acarsConnectionId, + string callsign, + CancellationToken cancellationToken); } // The last message ID is saved with the unit of work, so that the IDs continue after a restart @@ -27,4 +33,14 @@ public async Task GetNextMessageId( return sequence.Next(); } + + public async Task Remove( + string acarsConnectionId, + string callsign, + CancellationToken cancellationToken) + { + var sequence = await dbContext.MessageIdSequences.FindAsync([acarsConnectionId, callsign], cancellationToken); + if (sequence is not null) + dbContext.MessageIdSequences.Remove(sequence); + } } diff --git a/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommandHandler.cs b/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommandHandler.cs index a0f0696..ad9899e 100644 --- a/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommandHandler.cs +++ b/source/CPDLCServer/Cpdlc/Uplinks/ReplyToDownlinkCommandHandler.cs @@ -2,7 +2,6 @@ using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Infrastructure; -using CPDLCServer.Persistence; using MediatR; namespace CPDLCServer.Cpdlc.Uplinks; @@ -14,7 +13,7 @@ public class ReplyToDownlinkCommandHandler( IDialogueRepository dialogueRepository, IMediator mediator, IClock clock, - IUnitOfWork unitOfWork, + IUplinkTransmitter uplinkTransmitter, ILogger logger) : IRequestHandler { @@ -28,10 +27,9 @@ public async Task Handle(ReplyToDownlinkCommand request, CancellationToken cance logger.Information("Replying to downlink {DownlinkMessageId} in dialogue {DialogueId} for {Callsign}", request.DownlinkMessageId, request.DialogueId, callsign); + // The reply goes through the connection of the ATSU of the dialogue var allAircraft = await aircraftRepository.All(cancellationToken); - var aircraftConnection = - allAircraft.FirstOrDefault(a => a.Callsign == callsign && a.DataAuthorityState == DataAuthorityState.CurrentDataAuthority) - ?? allAircraft.FirstOrDefault(a => a.Callsign == callsign && a.DataAuthorityState == DataAuthorityState.NextDataAuthority); + var aircraftConnection = allAircraft.FirstOrDefault(a => a.Callsign == callsign && a.StationId == dialogue.StationId); if (aircraftConnection is null) throw new Exception($"{callsign} is not connected"); @@ -57,10 +55,6 @@ public async Task Handle(ReplyToDownlinkCommand request, CancellationToken cance await mediator.Publish(new DialogueChangedNotification(dialogue), cancellationToken); - unitOfWork.AfterCommit(async ct => - { - await acarsConnection.Send(uplinkMessage, ct); - logger.Information("Sent CPDLC message from {Sender} to {Callsign}", request.Sender, callsign); - }); + uplinkTransmitter.TransmitAfterCommit(acarsConnection, uplinkMessage); } } diff --git a/source/CPDLCServer/Cpdlc/Uplinks/UplinkTransmitter.cs b/source/CPDLCServer/Cpdlc/Uplinks/UplinkTransmitter.cs new file mode 100644 index 0000000..5ff5a5d --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Uplinks/UplinkTransmitter.cs @@ -0,0 +1,44 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; + +namespace CPDLCServer.Cpdlc.Uplinks; + +public interface IUplinkTransmitter +{ + /// + /// Sends the uplink after the unit of work is committed. + /// If the ACARS network does not accept the uplink, the uplink is marked as failed in a new unit of work. + /// + void TransmitAfterCommit(IAcarsConnection acarsConnection, UplinkMessage uplink); +} + +public class UplinkTransmitter( + IUnitOfWork unitOfWork, + IUnitOfWorkMediator unitOfWorkMediator, + ILogger logger) + : IUplinkTransmitter +{ + public void TransmitAfterCommit(IAcarsConnection acarsConnection, UplinkMessage uplink) + { + unitOfWork.AfterCommit(async ct => + { + try + { + await acarsConnection.Send(uplink, ct); + logger.Information("Sent CPDLC message from {Sender} to {Recipient}", uplink.SenderCallsign, uplink.Recipient); + } + catch (Exception ex) + { + logger.Error(ex, "Failed to send uplink {MessageId} to {Recipient}", uplink.MessageId, uplink.Recipient); + + // The unit of work of the uplink is already committed, so a new unit of work changes the uplink + await unitOfWorkMediator.Send( + new MarkUplinkTransmissionFailedCommand(uplink.DialogueId, uplink.MessageId), + ct); + + throw; + } + }); + } +} diff --git a/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs b/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs index 22e3ac3..e41aa06 100644 --- a/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs +++ b/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs @@ -1,5 +1,6 @@ using CPDLCServer.Persistence; using MediatR; +using Microsoft.EntityFrameworkCore; namespace CPDLCServer.Infrastructure; @@ -13,11 +14,15 @@ public interface IUnitOfWorkMediator Task Publish(INotification notification, CancellationToken cancellationToken = default); } -public class UnitOfWorkMediator(IServiceScopeFactory serviceScopeFactory) : IUnitOfWorkMediator, IDisposable +// The units of work run at the same time. The database prevents conflicts: +// - Each changed entity has a version (concurrency token). If a different unit of work changed the entity after it was +// read, the commit fails. +// - Unique indexes prevent two units of work from adding the same entity. +// When the commit fails, the unit of work runs again in a new scope, so that it reads the new data. +// The messages to controllers and aircraft are sent only after a successful commit, so a failed attempt sends nothing. +public class UnitOfWorkMediator(IServiceScopeFactory serviceScopeFactory, ILogger logger) : IUnitOfWorkMediator { - // Only one unit of work runs at a time. - // Two units of work cannot then change the same entity, and the messages are sent in the order of the changes. - readonly SemaphoreSlim _semaphore = new(1, 1); + const int MaxAttempts = 3; public async Task Send(IRequest request, CancellationToken cancellationToken = default) { @@ -48,21 +53,29 @@ await Run( async Task Run(Func> action, CancellationToken cancellationToken) { - using (await _semaphore.LockAsync(cancellationToken)) + for (var attempt = 1; ; attempt++) { await using var scope = serviceScopeFactory.CreateAsyncScope(); var mediator = scope.ServiceProvider.GetRequiredService(); var unitOfWork = scope.ServiceProvider.GetRequiredService(); - var result = await action(mediator); - await unitOfWork.Commit(cancellationToken); + try + { + var result = await action(mediator); + await unitOfWork.Commit(cancellationToken); - return result; + return result; + } + // DbUpdateConcurrencyException: a different unit of work changed or removed an entity. + // DbUpdateException: a different unit of work added an entity with the same unique key. + catch (DbUpdateException ex) when (attempt < MaxAttempts) + { + logger.Warning( + ex, + "Unit of work conflicted with a different unit of work (attempt {Attempt} of {MaxAttempts}), retrying", + attempt, + MaxAttempts); + } } } - - public void Dispose() - { - _semaphore.Dispose(); - } } diff --git a/source/CPDLCServer/Persistence/CpdlcDbContext.cs b/source/CPDLCServer/Persistence/CpdlcDbContext.cs index 65a8f0e..edaa75a 100644 --- a/source/CPDLCServer/Persistence/CpdlcDbContext.cs +++ b/source/CPDLCServer/Persistence/CpdlcDbContext.cs @@ -15,6 +15,11 @@ namespace CPDLCServer.Persistence; // because EF Core keeps one set of migrations for each context type public class CpdlcDbContext(DbContextOptions options) : DbContext(options) { + // A concurrency token on each entity that a unit of work can change. + // When two units of work change the same entity at the same time, the second commit fails, and the unit of work + // runs again with the new data (see UnitOfWorkMediator). + public const string VersionProperty = "Version"; + public DbSet AircraftConnections => Set(); public DbSet Dialogues => Set(); public DbSet AdscContracts => Set(); @@ -53,5 +58,57 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new ServerSettingsConfiguration()); modelBuilder.ApplyConfiguration(new AcarsConnectionSettingsConfiguration()); modelBuilder.ApplyConfiguration(new UserConfiguration()); + + // The messages have no version. A change to a message is a change to its dialogue (see SaveChangesAsync). + Type[] versionedEntityTypes = + [ + typeof(AircraftConnection), + typeof(Dialogue), + typeof(AdscContract), + typeof(AircraftAdscReport), + typeof(MessageIdSequence), + typeof(ServerSettings), + typeof(AcarsConnectionSettings), + typeof(User) + ]; + + foreach (var entityType in versionedEntityTypes) + { + modelBuilder.Entity(entityType) + .Property(VersionProperty) + .IsConcurrencyToken(); + } + } + + public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) + { + IncrementVersions(); + return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); + } + + // Increments the version of each changed entity. + // A dialogue is changed when one of its messages is added, changed or removed, so that two units of work cannot + // change the messages of the same dialogue at the same time. + void IncrementVersions() + { + ChangeTracker.DetectChanges(); + + var dialogueIdsWithChangedMessages = ChangeTracker.Entries() + .Where(e => e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted) + .Select(e => e.Entity.DialogueId) + .ToHashSet(); + + var changedEntries = ChangeTracker.Entries() + .Where(e => e.Metadata.FindProperty(VersionProperty) is not null) + .Where(e => + e.State == EntityState.Modified || + (e.State == EntityState.Unchanged && e.Entity is Dialogue dialogue && dialogueIdsWithChangedMessages.Contains(dialogue.Id))) + .ToArray(); + + foreach (var entry in changedEntries) + { + var version = entry.Property(VersionProperty); + version.CurrentValue = (int)version.OriginalValue! + 1; + } } } diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.Designer.cs similarity index 90% rename from source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.Designer.cs rename to source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.Designer.cs index 4c60b09..c82eadd 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.Designer.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.Designer.cs @@ -13,7 +13,7 @@ namespace CPDLCServer.Persistence.Migrations.PostgreSql { [DbContext(typeof(PostgreSqlCpdlcDbContext))] - [Migration("20261115024457_InitialCreate")] + [Migration("20261115043637_InitialCreate")] partial class InitialCreate { /// @@ -64,6 +64,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); b.HasIndex("StationIdentifier") @@ -121,9 +125,14 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); - b.HasIndex("Callsign", "StationId"); + b.HasIndex("Callsign", "StationId") + .IsUnique(); b.ToTable("AdscContracts", (string)null); }); @@ -147,6 +156,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => { b1.IsRequired(); @@ -175,8 +188,6 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("Received"); - b.HasIndex("Callsign", "StationId") .IsUnique(); @@ -199,6 +210,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); b.HasIndex("Username") @@ -253,9 +268,14 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); - b.HasIndex("Callsign", "AcarsConnectionId"); + b.HasIndex("Callsign", "AcarsConnectionId") + .IsUnique(); b.ToTable("AircraftConnections", (string)null); }); @@ -324,9 +344,19 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("Opened") .HasColumnType("bigint"); + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); - b.HasIndex("AircraftCallsign"); + b.HasIndex("Opened"); + + b.HasIndex("AircraftCallsign", "StationId"); b.ToTable("Dialogues", (string)null); }); @@ -342,6 +372,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("LastMessageId") .HasColumnType("integer"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("AcarsConnectionId", "Callsign"); b.ToTable("MessageIdSequences", (string)null); @@ -358,15 +392,15 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("AdscContractTimeoutMinutes") .HasColumnType("integer"); - b.Property("AdscReportRetentionHours") - .HasColumnType("integer"); - b.Property("AircraftConnectionTimeoutMinutes") .HasColumnType("integer"); b.Property("ConnectivityCheckIntervalMinutes") .HasColumnType("integer"); + b.Property("DialogueRetentionHours") + .HasColumnType("integer"); + b.Property("HandoffNotificationLeadTimeMinutes") .HasColumnType("integer"); @@ -386,6 +420,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); b.ToTable("ServerSettings", (string)null); diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.cs similarity index 90% rename from source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.cs rename to source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.cs index 00cf2dd..6fc25f8 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115024457_InitialCreate.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.cs @@ -25,7 +25,8 @@ protected override void Up(MigrationBuilder migrationBuilder) EncryptedAuthenticationCode = table.Column(type: "text", nullable: false), DefaultAdscReportingInterval = table.Column(type: "integer", nullable: false), SelectedAdscContractDuration = table.Column(type: "integer", nullable: false), - Notes = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true) + Notes = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true), + Version = table.Column(type: "integer", nullable: false) }, constraints: table => { @@ -50,7 +51,8 @@ protected override void Up(MigrationBuilder migrationBuilder) DemandContractState = table.Column(type: "text", nullable: true), LastActivity = table.Column(type: "bigint", nullable: false), LastReportReceived = table.Column(type: "bigint", nullable: true), - ReportingSource = table.Column(type: "text", nullable: true) + ReportingSource = table.Column(type: "text", nullable: true), + Version = table.Column(type: "integer", nullable: false) }, constraints: table => { @@ -66,6 +68,7 @@ protected override void Up(MigrationBuilder migrationBuilder) Callsign = table.Column(type: "text", nullable: false), StationId = table.Column(type: "text", nullable: false), Received = table.Column(type: "bigint", nullable: false), + Version = table.Column(type: "integer", nullable: false), Altitude = table.Column(type: "integer", nullable: false), Latitude = table.Column(type: "double precision", nullable: false), Longitude = table.Column(type: "double precision", nullable: false), @@ -93,7 +96,8 @@ protected override void Up(MigrationBuilder migrationBuilder) LastSeen = table.Column(type: "bigint", nullable: false), NextDataAuthority = table.Column(type: "text", nullable: true), ExpectedTransferTime = table.Column(type: "bigint", nullable: true), - DidSentNextDataAuthorityMessage = table.Column(type: "boolean", nullable: false) + DidSentNextDataAuthorityMessage = table.Column(type: "boolean", nullable: false), + Version = table.Column(type: "integer", nullable: false) }, constraints: table => { @@ -106,9 +110,11 @@ protected override void Up(MigrationBuilder migrationBuilder) { Id = table.Column(type: "uuid", nullable: false), AircraftCallsign = table.Column(type: "text", nullable: false), + StationId = table.Column(type: "text", nullable: false), Opened = table.Column(type: "bigint", nullable: false), Closed = table.Column(type: "bigint", nullable: true), - Archived = table.Column(type: "bigint", nullable: true) + Archived = table.Column(type: "bigint", nullable: true), + Version = table.Column(type: "integer", nullable: false) }, constraints: table => { @@ -121,7 +127,8 @@ protected override void Up(MigrationBuilder migrationBuilder) { AcarsConnectionId = table.Column(type: "text", nullable: false), Callsign = table.Column(type: "text", nullable: false), - LastMessageId = table.Column(type: "integer", nullable: false) + LastMessageId = table.Column(type: "integer", nullable: false), + Version = table.Column(type: "integer", nullable: false) }, constraints: table => { @@ -137,13 +144,14 @@ protected override void Up(MigrationBuilder migrationBuilder) ConnectivityCheckIntervalMinutes = table.Column(type: "integer", nullable: false), AircraftConnectionTimeoutMinutes = table.Column(type: "integer", nullable: false), AdscContractTimeoutMinutes = table.Column(type: "integer", nullable: false), - AdscReportRetentionHours = table.Column(type: "integer", nullable: false), + DialogueRetentionHours = table.Column(type: "integer", nullable: false), HandoffNotificationLeadTimeMinutes = table.Column(type: "integer", nullable: false), VatsimStatusEnabled = table.Column(type: "boolean", nullable: false), VatsimStatusUrl = table.Column(type: "text", nullable: false), VatsimStatusPollingIntervalSeconds = table.Column(type: "integer", nullable: false), VatsimStatusAllowNonEquippedAircraft = table.Column(type: "boolean", nullable: false), - VatsimStatusReportDelayMinutes = table.Column(type: "integer", nullable: false) + VatsimStatusReportDelayMinutes = table.Column(type: "integer", nullable: false), + Version = table.Column(type: "integer", nullable: false) }, constraints: table => { @@ -157,7 +165,8 @@ protected override void Up(MigrationBuilder migrationBuilder) Id = table.Column(type: "uuid", nullable: false), Username = table.Column(type: "text", nullable: false), PasswordHash = table.Column(type: "text", nullable: false), - Created = table.Column(type: "bigint", nullable: false) + Created = table.Column(type: "bigint", nullable: false), + Version = table.Column(type: "integer", nullable: false) }, constraints: table => { @@ -211,7 +220,8 @@ protected override void Up(MigrationBuilder migrationBuilder) migrationBuilder.CreateIndex( name: "IX_AdscContracts_Callsign_StationId", table: "AdscContracts", - columns: new[] { "Callsign", "StationId" }); + columns: new[] { "Callsign", "StationId" }, + unique: true); migrationBuilder.CreateIndex( name: "IX_AdscReports_Callsign_StationId", @@ -219,15 +229,11 @@ protected override void Up(MigrationBuilder migrationBuilder) columns: new[] { "Callsign", "StationId" }, unique: true); - migrationBuilder.CreateIndex( - name: "IX_AdscReports_Received", - table: "AdscReports", - column: "Received"); - migrationBuilder.CreateIndex( name: "IX_AircraftConnections_Callsign_AcarsConnectionId", table: "AircraftConnections", - columns: new[] { "Callsign", "AcarsConnectionId" }); + columns: new[] { "Callsign", "AcarsConnectionId" }, + unique: true); migrationBuilder.CreateIndex( name: "IX_CpdlcMessages_DialogueId", @@ -235,9 +241,14 @@ protected override void Up(MigrationBuilder migrationBuilder) column: "DialogueId"); migrationBuilder.CreateIndex( - name: "IX_Dialogues_AircraftCallsign", + name: "IX_Dialogues_AircraftCallsign_StationId", + table: "Dialogues", + columns: new[] { "AircraftCallsign", "StationId" }); + + migrationBuilder.CreateIndex( + name: "IX_Dialogues_Opened", table: "Dialogues", - column: "AircraftCallsign"); + column: "Opened"); migrationBuilder.CreateIndex( name: "IX_Users_Username", diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs index fb489c9..8662c94 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs @@ -61,6 +61,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); b.HasIndex("StationIdentifier") @@ -118,9 +122,14 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); - b.HasIndex("Callsign", "StationId"); + b.HasIndex("Callsign", "StationId") + .IsUnique(); b.ToTable("AdscContracts", (string)null); }); @@ -144,6 +153,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => { b1.IsRequired(); @@ -172,8 +185,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("Received"); - b.HasIndex("Callsign", "StationId") .IsUnique(); @@ -196,6 +207,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); b.HasIndex("Username") @@ -250,9 +265,14 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); - b.HasIndex("Callsign", "AcarsConnectionId"); + b.HasIndex("Callsign", "AcarsConnectionId") + .IsUnique(); b.ToTable("AircraftConnections", (string)null); }); @@ -321,9 +341,19 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("Opened") .HasColumnType("bigint"); + b.Property("StationId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); - b.HasIndex("AircraftCallsign"); + b.HasIndex("Opened"); + + b.HasIndex("AircraftCallsign", "StationId"); b.ToTable("Dialogues", (string)null); }); @@ -339,6 +369,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("LastMessageId") .HasColumnType("integer"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("AcarsConnectionId", "Callsign"); b.ToTable("MessageIdSequences", (string)null); @@ -355,15 +389,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("AdscContractTimeoutMinutes") .HasColumnType("integer"); - b.Property("AdscReportRetentionHours") - .HasColumnType("integer"); - b.Property("AircraftConnectionTimeoutMinutes") .HasColumnType("integer"); b.Property("ConnectivityCheckIntervalMinutes") .HasColumnType("integer"); + b.Property("DialogueRetentionHours") + .HasColumnType("integer"); + b.Property("HandoffNotificationLeadTimeMinutes") .HasColumnType("integer"); @@ -383,6 +417,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + b.HasKey("Id"); b.ToTable("ServerSettings", (string)null); diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.Designer.cs similarity index 90% rename from source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.Designer.cs rename to source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.Designer.cs index 8394737..8f91f06 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.Designer.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ namespace CPDLCServer.Persistence.Migrations.Sqlite { [DbContext(typeof(SqliteCpdlcDbContext))] - [Migration("20261115024453_InitialCreate")] + [Migration("20261115043633_InitialCreate")] partial class InitialCreate { /// @@ -59,6 +59,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); b.HasIndex("StationIdentifier") @@ -114,9 +118,14 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); - b.HasIndex("Callsign", "StationId"); + b.HasIndex("Callsign", "StationId") + .IsUnique(); b.ToTable("AdscContracts", (string)null); }); @@ -138,6 +147,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => { b1.IsRequired(); @@ -166,8 +179,6 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("Received"); - b.HasIndex("Callsign", "StationId") .IsUnique(); @@ -190,6 +201,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); b.HasIndex("Username") @@ -242,9 +257,14 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); - b.HasIndex("Callsign", "AcarsConnectionId"); + b.HasIndex("Callsign", "AcarsConnectionId") + .IsUnique(); b.ToTable("AircraftConnections", (string)null); }); @@ -311,9 +331,19 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("Opened") .HasColumnType("INTEGER"); + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); - b.HasIndex("AircraftCallsign"); + b.HasIndex("Opened"); + + b.HasIndex("AircraftCallsign", "StationId"); b.ToTable("Dialogues", (string)null); }); @@ -329,6 +359,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("LastMessageId") .HasColumnType("INTEGER"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("AcarsConnectionId", "Callsign"); b.ToTable("MessageIdSequences", (string)null); @@ -343,15 +377,15 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("AdscContractTimeoutMinutes") .HasColumnType("INTEGER"); - b.Property("AdscReportRetentionHours") - .HasColumnType("INTEGER"); - b.Property("AircraftConnectionTimeoutMinutes") .HasColumnType("INTEGER"); b.Property("ConnectivityCheckIntervalMinutes") .HasColumnType("INTEGER"); + b.Property("DialogueRetentionHours") + .HasColumnType("INTEGER"); + b.Property("HandoffNotificationLeadTimeMinutes") .HasColumnType("INTEGER"); @@ -371,6 +405,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); b.ToTable("ServerSettings", (string)null); diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.cs similarity index 90% rename from source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.cs rename to source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.cs index 4c0b95d..452d70c 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115024453_InitialCreate.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.cs @@ -24,7 +24,8 @@ protected override void Up(MigrationBuilder migrationBuilder) EncryptedAuthenticationCode = table.Column(type: "TEXT", nullable: false), DefaultAdscReportingInterval = table.Column(type: "INTEGER", nullable: false), SelectedAdscContractDuration = table.Column(type: "INTEGER", nullable: false), - Notes = table.Column(type: "TEXT", maxLength: 2000, nullable: true) + Notes = table.Column(type: "TEXT", maxLength: 2000, nullable: true), + Version = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { @@ -49,7 +50,8 @@ protected override void Up(MigrationBuilder migrationBuilder) DemandContractState = table.Column(type: "TEXT", nullable: true), LastActivity = table.Column(type: "INTEGER", nullable: false), LastReportReceived = table.Column(type: "INTEGER", nullable: true), - ReportingSource = table.Column(type: "TEXT", nullable: true) + ReportingSource = table.Column(type: "TEXT", nullable: true), + Version = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { @@ -65,6 +67,7 @@ protected override void Up(MigrationBuilder migrationBuilder) Callsign = table.Column(type: "TEXT", nullable: false), StationId = table.Column(type: "TEXT", nullable: false), Received = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false), Altitude = table.Column(type: "INTEGER", nullable: false), Latitude = table.Column(type: "REAL", nullable: false), Longitude = table.Column(type: "REAL", nullable: false), @@ -92,7 +95,8 @@ protected override void Up(MigrationBuilder migrationBuilder) LastSeen = table.Column(type: "INTEGER", nullable: false), NextDataAuthority = table.Column(type: "TEXT", nullable: true), ExpectedTransferTime = table.Column(type: "INTEGER", nullable: true), - DidSentNextDataAuthorityMessage = table.Column(type: "INTEGER", nullable: false) + DidSentNextDataAuthorityMessage = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { @@ -105,9 +109,11 @@ protected override void Up(MigrationBuilder migrationBuilder) { Id = table.Column(type: "TEXT", nullable: false), AircraftCallsign = table.Column(type: "TEXT", nullable: false), + StationId = table.Column(type: "TEXT", nullable: false), Opened = table.Column(type: "INTEGER", nullable: false), Closed = table.Column(type: "INTEGER", nullable: true), - Archived = table.Column(type: "INTEGER", nullable: true) + Archived = table.Column(type: "INTEGER", nullable: true), + Version = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { @@ -120,7 +126,8 @@ protected override void Up(MigrationBuilder migrationBuilder) { AcarsConnectionId = table.Column(type: "TEXT", nullable: false), Callsign = table.Column(type: "TEXT", nullable: false), - LastMessageId = table.Column(type: "INTEGER", nullable: false) + LastMessageId = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { @@ -136,13 +143,14 @@ protected override void Up(MigrationBuilder migrationBuilder) ConnectivityCheckIntervalMinutes = table.Column(type: "INTEGER", nullable: false), AircraftConnectionTimeoutMinutes = table.Column(type: "INTEGER", nullable: false), AdscContractTimeoutMinutes = table.Column(type: "INTEGER", nullable: false), - AdscReportRetentionHours = table.Column(type: "INTEGER", nullable: false), + DialogueRetentionHours = table.Column(type: "INTEGER", nullable: false), HandoffNotificationLeadTimeMinutes = table.Column(type: "INTEGER", nullable: false), VatsimStatusEnabled = table.Column(type: "INTEGER", nullable: false), VatsimStatusUrl = table.Column(type: "TEXT", nullable: false), VatsimStatusPollingIntervalSeconds = table.Column(type: "INTEGER", nullable: false), VatsimStatusAllowNonEquippedAircraft = table.Column(type: "INTEGER", nullable: false), - VatsimStatusReportDelayMinutes = table.Column(type: "INTEGER", nullable: false) + VatsimStatusReportDelayMinutes = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { @@ -156,7 +164,8 @@ protected override void Up(MigrationBuilder migrationBuilder) Id = table.Column(type: "TEXT", nullable: false), Username = table.Column(type: "TEXT", nullable: false), PasswordHash = table.Column(type: "TEXT", nullable: false), - Created = table.Column(type: "INTEGER", nullable: false) + Created = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false) }, constraints: table => { @@ -210,7 +219,8 @@ protected override void Up(MigrationBuilder migrationBuilder) migrationBuilder.CreateIndex( name: "IX_AdscContracts_Callsign_StationId", table: "AdscContracts", - columns: new[] { "Callsign", "StationId" }); + columns: new[] { "Callsign", "StationId" }, + unique: true); migrationBuilder.CreateIndex( name: "IX_AdscReports_Callsign_StationId", @@ -218,15 +228,11 @@ protected override void Up(MigrationBuilder migrationBuilder) columns: new[] { "Callsign", "StationId" }, unique: true); - migrationBuilder.CreateIndex( - name: "IX_AdscReports_Received", - table: "AdscReports", - column: "Received"); - migrationBuilder.CreateIndex( name: "IX_AircraftConnections_Callsign_AcarsConnectionId", table: "AircraftConnections", - columns: new[] { "Callsign", "AcarsConnectionId" }); + columns: new[] { "Callsign", "AcarsConnectionId" }, + unique: true); migrationBuilder.CreateIndex( name: "IX_CpdlcMessages_DialogueId", @@ -234,9 +240,14 @@ protected override void Up(MigrationBuilder migrationBuilder) column: "DialogueId"); migrationBuilder.CreateIndex( - name: "IX_Dialogues_AircraftCallsign", + name: "IX_Dialogues_AircraftCallsign_StationId", + table: "Dialogues", + columns: new[] { "AircraftCallsign", "StationId" }); + + migrationBuilder.CreateIndex( + name: "IX_Dialogues_Opened", table: "Dialogues", - column: "AircraftCallsign"); + column: "Opened"); migrationBuilder.CreateIndex( name: "IX_Users_Username", diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs index 7a00aba..018ccc0 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs @@ -56,6 +56,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); b.HasIndex("StationIdentifier") @@ -111,9 +115,14 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); - b.HasIndex("Callsign", "StationId"); + b.HasIndex("Callsign", "StationId") + .IsUnique(); b.ToTable("AdscContracts", (string)null); }); @@ -135,6 +144,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.ComplexProperty(typeof(Dictionary), "Report", "CPDLCServer.AdscContracts.Reports.AircraftAdscReport.Report#AdscReport", b1 => { b1.IsRequired(); @@ -163,8 +176,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); - b.HasIndex("Received"); - b.HasIndex("Callsign", "StationId") .IsUnique(); @@ -187,6 +198,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); b.HasIndex("Username") @@ -239,9 +254,14 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); - b.HasIndex("Callsign", "AcarsConnectionId"); + b.HasIndex("Callsign", "AcarsConnectionId") + .IsUnique(); b.ToTable("AircraftConnections", (string)null); }); @@ -308,9 +328,19 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("Opened") .HasColumnType("INTEGER"); + b.Property("StationId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); - b.HasIndex("AircraftCallsign"); + b.HasIndex("Opened"); + + b.HasIndex("AircraftCallsign", "StationId"); b.ToTable("Dialogues", (string)null); }); @@ -326,6 +356,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("LastMessageId") .HasColumnType("INTEGER"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("AcarsConnectionId", "Callsign"); b.ToTable("MessageIdSequences", (string)null); @@ -340,15 +374,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("AdscContractTimeoutMinutes") .HasColumnType("INTEGER"); - b.Property("AdscReportRetentionHours") - .HasColumnType("INTEGER"); - b.Property("AircraftConnectionTimeoutMinutes") .HasColumnType("INTEGER"); b.Property("ConnectivityCheckIntervalMinutes") .HasColumnType("INTEGER"); + b.Property("DialogueRetentionHours") + .HasColumnType("INTEGER"); + b.Property("HandoffNotificationLeadTimeMinutes") .HasColumnType("INTEGER"); @@ -368,6 +402,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + b.HasKey("Id"); b.ToTable("ServerSettings", (string)null); diff --git a/source/CPDLCServer/Settings/ServerSettings.cs b/source/CPDLCServer/Settings/ServerSettings.cs index 8cc31bc..3f15d25 100644 --- a/source/CPDLCServer/Settings/ServerSettings.cs +++ b/source/CPDLCServer/Settings/ServerSettings.cs @@ -17,7 +17,7 @@ public record ServerSettings public int AdscContractTimeoutMinutes { get; init; } = 120; [Range(1, int.MaxValue)] - public int AdscReportRetentionHours { get; init; } = 24; + public int DialogueRetentionHours { get; init; } = 24; [Range(0, int.MaxValue)] public int HandoffNotificationLeadTimeMinutes { get; init; } = 20; diff --git a/source/CPDLCServer/Web/Pages/Atsu/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Atsu/Index.cshtml.cs index b9c4490..e7eafc3 100644 --- a/source/CPDLCServer/Web/Pages/Atsu/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Atsu/Index.cshtml.cs @@ -38,13 +38,10 @@ public async Task OnGetAsync(string stationId, CancellationToken Controllers = controllers.Where(c => c.StationId == stationId).ToArray(); var aircraftLookup = aircraft.ToDictionary(a => a.Callsign, a => a); - var aircraftAtStation = aircraft - .Where(a => a.StationId == stationId) - .Select(a => a.Callsign) - .ToHashSet(); + // The dialogues stay after the aircraft disconnects, so find them by their own station Messages = dialogues - .Where(d => aircraftAtStation.Contains(d.AircraftCallsign)) + .Where(d => d.StationId == stationId) .SelectMany(d => d.Messages.Select(m => MessageRowViewModel.From(d, m, aircraftLookup))) .OrderByDescending(m => m.Timestamp) .ToList(); diff --git a/source/CPDLCServer/Web/Pages/Dialogue/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Dialogue/Index.cshtml.cs index 4b0621e..fcaf46b 100644 --- a/source/CPDLCServer/Web/Pages/Dialogue/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Dialogue/Index.cshtml.cs @@ -34,9 +34,9 @@ public async Task OnGetAsync(Guid id, CancellationToken cancellat } var aircraft = await _aircraftRepository.All(cancellationToken); - var match = aircraft.FirstOrDefault(a => a.Callsign == Dialogue.AircraftCallsign); + var match = aircraft.FirstOrDefault(a => a.Callsign == Dialogue.AircraftCallsign && a.StationId == Dialogue.StationId); AcarsNetwork = match?.AcarsConnectionId ?? "Unknown"; - StationId = match?.StationId ?? "Unknown"; + StationId = Dialogue.StationId; var aircraftLookup = aircraft.ToDictionary(a => a.Callsign, a => a); diff --git a/source/CPDLCServer/Web/Pages/Settings/Index.cshtml b/source/CPDLCServer/Web/Pages/Settings/Index.cshtml index 201243a..bb7c443 100644 --- a/source/CPDLCServer/Web/Pages/Settings/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Settings/Index.cshtml @@ -70,39 +70,46 @@
-
ADS-C
+
Dialogues
-
+
- -
The time without ADS-C activity from an aircraft before the server cancels the ADS-C contract.
+ +
The time from when a dialogue opens until the server deletes it. The server keeps the dialogues after the aircraft disconnects.
- - minutes - + + hours +
- +
-
Default: @Model.Defaults.AdscContractTimeoutMinutes minutes
+
Default: @Model.Defaults.DialogueRetentionHours hours
+
+
+
+
+
ADS-C
+
+
- -
The time that the server keeps the history of ADS-C reports.
+ +
The time without ADS-C activity from an aircraft before the server cancels the ADS-C contract.
- - hours - + + minutes +
- +
-
Default: @Model.Defaults.AdscReportRetentionHours hours
+
Default: @Model.Defaults.AdscContractTimeoutMinutes minutes
From 6034a456de1c2e0922d329db43c76525feffc9d7 Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:54:44 +0800 Subject: [PATCH 10/18] Don't open PRL menu for ADS-C tracks --- source/CPDLCPlugin/AdscTrackPatches.cs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/source/CPDLCPlugin/AdscTrackPatches.cs b/source/CPDLCPlugin/AdscTrackPatches.cs index 6854f1e..f6472e4 100644 --- a/source/CPDLCPlugin/AdscTrackPatches.cs +++ b/source/CPDLCPlugin/AdscTrackPatches.cs @@ -10,6 +10,7 @@ namespace CPDLCPlugin; /// /// When a report arrives, the track moves to the reported position and uses the ADSC symbol. /// Each time vatSys extrapolates the flight plan positions, the track moves along the route from the reported position and uses the ADSCExtrapolated symbol. +/// The controller cannot open the PRL menu, because the PRL comes from the reports. /// /// A coupled radar track always has priority over an ADS-C report. ///
@@ -44,6 +45,11 @@ public static void Apply(AdscTrackDisplay display) harmony.Patch( RequireMethod("vatsys.FDP2:GenerateTrackPosition"), postfix: new HarmonyMethod(typeof(AdscTrackPatches), nameof(GenerateTrackPositionPostfix))); + + // The PRL label item and the PRL strip item open this menu on a left click + harmony.Patch( + RequireMethod("vatsys.MMI:OpenPRLMenu"), + prefix: new HarmonyMethod(typeof(AdscTrackPatches), nameof(OpenPRLMenuPrefix))); } catch { @@ -89,6 +95,20 @@ static void PaintTrackGeometryRealisationPrefix(ref TrackSymbols.Types type, ref aircraftHeading = -1; } + static bool OpenPRLMenuPrefix(FDP2.FDR SourceFDR, ref bool __result) + { + if (!HasAdscTrack(SourceFDR)) + return true; + + __result = false; + return false; + } + + static bool HasAdscTrack(FDP2.FDR? fdr) + { + return _display is not null && fdr is not null && _display.TryGetTrack(fdr.Callsign, out _); + } + static void GenerateTrackPositionPostfix(FDP2.FDR fdr) { if (_display is null || fdr.CoupledTrack is not null) From 657a72fde87aa2b3878ee6c845260c74fc7b9ec5 Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:08:37 +1000 Subject: [PATCH 11/18] Add disclaimer --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 6512d98..6f544fa 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,9 @@ +> [!NOTE] +> Even though the development of this plugin was inspired by real ATM systems such as those from Thales Group, the plugin is absolutely NOT affiliated with or endorsed by said company. The plugin and all associated files shall be used solely for the purpose of simulation on the VATSIM network. + ## Overview This plugin enables CPDLC (Controller-Pilot Data Link Communications) functionality in vatSys, allowing controllers to send and receive datalink messages with aircraft on the VATSIM network. From 9c2336d2ea35523fe2f06aa42d7a7b3ce53b4ef8 Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:12:37 +1000 Subject: [PATCH 12/18] Re-do the dashboard and add VATSIM Connect authentication Co-Authored-By: Claude Opus 5.5 --- .do/deploy.template.yaml | 11 + CPDLC.json | 1 + docs/docs/server/index.md | 54 +- docs/docs/vatsys-plugin/configuration.md | 10 + docs/docs/vatsys-plugin/plugin.md | 4 + example.env | 11 +- source/CPDLCPlugin/CPDLCPlugin.csproj | 1 + .../Configuration/PluginConfiguration.cs | 4 + .../Messages/AuthenticateRequest.cs | 30 + .../AuthenticationChangedNotification.cs | 4 + .../Messages/CheckAuthenticationRequest.cs | 38 + source/CPDLCPlugin/Messages/ConnectRequest.cs | 124 +- source/CPDLCPlugin/Messages/LogOutRequest.cs | 42 + .../Messages/OpenSetupWindowRequest.cs | 7 +- source/CPDLCPlugin/Plugin.cs | 1549 +++++++++-------- .../CPDLCPlugin/Server/AuthenticationState.cs | 28 + .../CPDLCPlugin/Server/PluginAuthenticator.cs | 245 +++ source/CPDLCPlugin/Server/ServerAddress.cs | 14 + .../Server/SignalRConnectionManager.cs | 834 ++++----- source/CPDLCPlugin/Server/TokenStore.cs | 70 + .../CPDLCPlugin/ViewModels/SetupViewModel.cs | 74 +- source/CPDLCPlugin/Windows/SetupView.xaml | 48 +- source/CPDLCServer.Contracts/AcarsMessages.cs | 5 + .../Hoppie/HoppieAcarsConnectionTests.cs | 3 + .../Traffic/AcarsTrafficLogTests.cs | 85 + ...cReportReceivedNotificationHandlerTests.cs | 4 +- .../AdministratorCommandHandlerTests.cs | 132 ++ .../Auth/Login/ClientIpAddressTests.cs | 52 - .../Auth/Login/LoginCommandHandlerTests.cs | 163 -- .../Auth/Login/LoginLockoutTests.cs | 99 -- .../PluginAuthorizationCodesTests.cs | 109 ++ .../PluginTokens/PluginRedirectUriTests.cs | 23 + .../ChangePasswordCommandHandlerTests.cs | 59 - .../Users/CreateUserCommandHandlerTests.cs | 80 - ...tionEstablishedNotificationHandlerTests.cs | 8 +- ...tConnectionLostNotificationHandlerTests.cs | 16 +- ...ctionTerminatedNotificationHandlerTests.cs | 8 +- .../Connections/LogonCommandHandlerTests.cs | 20 +- ...ownlinkReceivedNotificationHandlerTests.cs | 28 +- .../Cpdlc/Motd/SendMotdCommandHandlerTests.cs | 83 + .../CPDLCServer.Tests/Logging/LogAreaTests.cs | 26 + .../Logging/LogBufferTests.cs | 30 +- .../Mocks/TestAcarsConnectionManager.cs | 6 +- .../Mocks/TestAdministratorRepository.cs | 35 + .../Mocks/TestServerSettingsProvider.cs | 20 +- .../Mocks/TestUserRepository.cs | 34 - .../Settings/BannerImageFormatTests.cs | 30 + .../Setup/SetupStateTests.cs | 29 +- .../AcarsConnectionManager.cs | 23 +- ...sConnectionsServiceCollectionExtensions.cs | 2 + .../AcarsConnectionSettings.cs | 28 + .../AcarsConnectionSettingsConfiguration.cs | 3 + .../CreateAcarsConnectionCommandHandler.cs | 1 + .../UpdateAcarsConnectionCommandHandler.cs | 2 + .../Hoppie/HoppieAcarsConnection.cs | 76 +- .../AcarsConnections/HoppiesConfiguration.cs | 6 + .../Traffic/AcarsTrafficEntry.cs | 16 + .../Traffic/AcarsTrafficLog.cs | 53 + .../Auth/AdministratorRequirement.cs | 25 + .../Administrators/AddAdministratorCommand.cs | 5 + .../AddAdministratorCommandHandler.cs | 29 + .../Auth/Administrators/Administrator.cs | 12 + .../AdministratorConfiguration.cs | 15 + .../Administrators/AdministratorRepository.cs | 39 + .../CreateFirstAdministratorCommand.cs | 6 + .../CreateFirstAdministratorCommandHandler.cs | 32 + .../IAdministratorRepository.cs | 10 + .../RemoveAdministratorCommand.cs | 6 + .../RemoveAdministratorCommandHandler.cs | 33 + .../UpdateAdministratorNameCommand.cs | 6 + .../UpdateAdministratorNameCommandHandler.cs | 16 + .../Auth/AuthServiceCollectionExtensions.cs | 94 +- source/CPDLCServer/Auth/CurrentUser.cs | 28 + .../Auth/Login/AdminAuthentication.cs | 25 - .../CPDLCServer/Auth/Login/ClientIpAddress.cs | 36 - source/CPDLCServer/Auth/Login/LoginCommand.cs | 8 - .../Auth/Login/LoginCommandHandler.cs | 56 - source/CPDLCServer/Auth/Login/LoginLockout.cs | 79 - .../Auth/Login/PasswordRateLimit.cs | 39 - .../PluginTokens/CreatePluginTokenCommand.cs | 6 + .../CreatePluginTokenCommandHandler.cs | 40 + .../PluginTokens/IPluginTokenRepository.cs | 8 + .../PluginTokens/PluginAuthorizationCodes.cs | 73 + .../Auth/PluginTokens/PluginEndpoints.cs | 62 + .../Auth/PluginTokens/PluginRedirectUri.cs | 19 + .../Auth/PluginTokens/PluginToken.cs | 14 + .../PluginTokenAuthenticationHandler.cs | 57 + .../PluginTokens/PluginTokenConfiguration.cs | 18 + .../Auth/PluginTokens/PluginTokenHash.cs | 23 + .../PluginTokens/PluginTokenRepository.cs | 25 + .../PluginTokens/RevokePluginTokenCommand.cs | 6 + .../RevokePluginTokenCommandHandler.cs | 26 + .../Auth/Users/ChangePasswordCommand.cs | 5 - .../Users/ChangePasswordCommandHandler.cs | 21 - .../Auth/Users/CreateUserCommand.cs | 5 - .../Auth/Users/CreateUserCommandHandler.cs | 44 - .../CPDLCServer/Auth/Users/IUserRepository.cs | 10 - source/CPDLCServer/Auth/Users/User.cs | 10 - .../Auth/Users/UserConfiguration.cs | 17 - .../CPDLCServer/Auth/Users/UserRepository.cs | 42 - .../VatsimConnect/VatsimConnectOptions.cs | 13 + .../Auth/VatsimConnect/VatsimUser.cs | 27 + .../CPDLCServer/Controllers/ControllerInfo.cs | 8 +- .../Cpdlc/CpdlcServiceCollectionExtensions.cs | 3 + .../CPDLCServer/Cpdlc/Motd/MotdScheduler.cs | 35 + .../CPDLCServer/Cpdlc/Motd/SendMotdCommand.cs | 5 + .../Cpdlc/Motd/SendMotdCommandHandler.cs | 42 + .../SendMotdOnConnectionEstablishedHandler.cs | 31 + .../Infrastructure/UnitOfWorkMediator.cs | 11 +- .../Logging/InMemoryLogBufferSink.cs | 9 + source/CPDLCServer/Logging/LogArea.cs | 40 + source/CPDLCServer/Logging/LogEntry.cs | 2 + .../CPDLCServer/Persistence/CpdlcDbContext.cs | 11 +- ... 20261121042342_InitialCreate.Designer.cs} | 69 +- ...ate.cs => 20261121042342_InitialCreate.cs} | 70 +- .../PostgreSqlCpdlcDbContextModelSnapshot.cs | 67 +- ... 20261121042339_InitialCreate.Designer.cs} | 69 +- ...ate.cs => 20261121042339_InitialCreate.cs} | 70 +- .../SqliteCpdlcDbContextModelSnapshot.cs | 67 +- source/CPDLCServer/Program.cs | 442 +++-- source/CPDLCServer/Settings/BannerEndpoint.cs | 19 + .../CPDLCServer/Settings/BannerImageFormat.cs | 28 + source/CPDLCServer/Settings/BrandingInfo.cs | 4 + .../SaveServerSettingsCommandHandler.cs | 3 +- source/CPDLCServer/Settings/ServerSettings.cs | 30 + .../Settings/ServerSettingsConfiguration.cs | 3 + .../Settings/ServerSettingsProvider.cs | 39 +- .../Settings/SetBannerImageCommand.cs | 6 + .../Settings/SetBannerImageCommandHandler.cs | 35 + .../Setup/RedirectToSetupMiddleware.cs | 2 +- source/CPDLCServer/Setup/SetupState.cs | 27 +- source/CPDLCServer/Web/ControllerHub.cs | 23 +- .../Web/Pages/Account/AccessDenied.cshtml | 8 + .../Web/Pages/Account/Login.cshtml | 38 +- .../Web/Pages/Account/Login.cshtml.cs | 60 +- .../Web/Pages/Account/Logout.cshtml.cs | 7 +- .../CPDLCServer/Web/Pages/Adsc/Index.cshtml | 142 +- .../Web/Pages/Adsc/Index.cshtml.cs | 23 +- .../Web/Pages/Adsc/Messages.cshtml | 49 + .../Web/Pages/Adsc/Messages.cshtml.cs | 38 + .../CPDLCServer/Web/Pages/Atsu/Index.cshtml | 54 - .../Acars/Edit.cshtml | 44 +- .../Acars/Edit.cshtml.cs | 2 +- .../Acars/Index.cshtml | 23 +- .../Acars/Index.cshtml.cs | 3 +- .../Pages/Configuration/Acars/Traffic.cshtml | 78 + .../Configuration/Acars/Traffic.cshtml.cs | 59 + .../Configuration/Acars/_TrafficRows.cshtml | 29 + .../Configuration/Administrators/Index.cshtml | 83 + .../Administrators/Index.cshtml.cs | 81 + .../Web/Pages/Configuration/Logs/Index.cshtml | 243 +++ .../Pages/Configuration/Logs/Index.cshtml.cs | 23 + .../{ => Configuration}/Settings/Index.cshtml | 101 +- .../Configuration/Settings/Index.cshtml.cs | 97 ++ .../Web/Pages/Cpdlc/Aircraft/Index.cshtml | 45 + .../{Pilot => Cpdlc/Aircraft}/Index.cshtml.cs | 2 +- .../Web/Pages/Cpdlc/Dialogues/Index.cshtml | 46 + .../Dialogues}/Index.cshtml.cs | 4 +- .../CPDLCServer/Web/Pages/Cpdlc/Index.cshtml | 124 ++ .../Web/Pages/Cpdlc/Index.cshtml.cs | 56 + .../Web/Pages/Cpdlc/Messages.cshtml | 14 + .../Web/Pages/Cpdlc/Messages.cshtml.cs | 48 + .../Web/Pages/Cpdlc/Stations/Index.cshtml | 46 + .../{Atsu => Cpdlc/Stations}/Index.cshtml.cs | 2 +- .../Web/Pages/Dialogue/Index.cshtml | 52 - source/CPDLCServer/Web/Pages/Index.cshtml | 194 --- source/CPDLCServer/Web/Pages/Index.cshtml.cs | 57 +- .../CPDLCServer/Web/Pages/Logs/Index.cshtml | 174 -- .../Web/Pages/Logs/Index.cshtml.cs | 11 - .../CPDLCServer/Web/Pages/Pilot/Index.cshtml | 47 - .../Web/Pages/Plugin/Authorize.cshtml | 30 + .../Web/Pages/Plugin/Authorize.cshtml.cs | 51 + .../Web/Pages/Settings/Index.cshtml.cs | 49 - .../Settings/Users/ChangePassword.cshtml | 44 - .../Settings/Users/ChangePassword.cshtml.cs | 71 - .../Web/Pages/Settings/Users/Index.cshtml | 54 - .../Web/Pages/Settings/Users/Index.cshtml.cs | 28 - .../Web/Pages/Settings/_SettingsLayout.cshtml | 25 - .../Web/Pages/Settings/_ViewStart.cshtml | 3 - .../CPDLCServer/Web/Pages/Setup/Index.cshtml | 70 +- .../Web/Pages/Setup/Index.cshtml.cs | 58 +- .../Web/Pages/Shared/_Branding.cshtml | 18 + .../Web/Pages/Shared/_CenteredLayout.cshtml | 31 + .../Web/Pages/Shared/_Layout.cshtml | 133 +- .../Web/Pages/Shared/_MessageTable.cshtml | 85 +- .../Web/Pages/Shared/_Pagination.cshtml | 44 + .../Pages/ViewModels/MessageRowViewModel.cs | 2 +- .../Pages/ViewModels/PaginationViewModel.cs | 7 + .../CPDLCServer/Web/Pages/_ViewImports.cshtml | 2 + .../Web/WebServiceCollectionExtensions.cs | 13 +- 190 files changed, 6159 insertions(+), 3906 deletions(-) create mode 100644 source/CPDLCPlugin/Messages/AuthenticateRequest.cs create mode 100644 source/CPDLCPlugin/Messages/AuthenticationChangedNotification.cs create mode 100644 source/CPDLCPlugin/Messages/CheckAuthenticationRequest.cs create mode 100644 source/CPDLCPlugin/Messages/LogOutRequest.cs create mode 100644 source/CPDLCPlugin/Server/AuthenticationState.cs create mode 100644 source/CPDLCPlugin/Server/PluginAuthenticator.cs create mode 100644 source/CPDLCPlugin/Server/ServerAddress.cs create mode 100644 source/CPDLCPlugin/Server/TokenStore.cs create mode 100644 source/CPDLCServer.Tests/AcarsConnections/Traffic/AcarsTrafficLogTests.cs create mode 100644 source/CPDLCServer.Tests/Auth/Administrators/AdministratorCommandHandlerTests.cs delete mode 100644 source/CPDLCServer.Tests/Auth/Login/ClientIpAddressTests.cs delete mode 100644 source/CPDLCServer.Tests/Auth/Login/LoginCommandHandlerTests.cs delete mode 100644 source/CPDLCServer.Tests/Auth/Login/LoginLockoutTests.cs create mode 100644 source/CPDLCServer.Tests/Auth/PluginTokens/PluginAuthorizationCodesTests.cs create mode 100644 source/CPDLCServer.Tests/Auth/PluginTokens/PluginRedirectUriTests.cs delete mode 100644 source/CPDLCServer.Tests/Auth/Users/ChangePasswordCommandHandlerTests.cs delete mode 100644 source/CPDLCServer.Tests/Auth/Users/CreateUserCommandHandlerTests.cs create mode 100644 source/CPDLCServer.Tests/Cpdlc/Motd/SendMotdCommandHandlerTests.cs create mode 100644 source/CPDLCServer.Tests/Logging/LogAreaTests.cs create mode 100644 source/CPDLCServer.Tests/Mocks/TestAdministratorRepository.cs delete mode 100644 source/CPDLCServer.Tests/Mocks/TestUserRepository.cs create mode 100644 source/CPDLCServer.Tests/Settings/BannerImageFormatTests.cs create mode 100644 source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficEntry.cs create mode 100644 source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficLog.cs create mode 100644 source/CPDLCServer/Auth/AdministratorRequirement.cs create mode 100644 source/CPDLCServer/Auth/Administrators/AddAdministratorCommand.cs create mode 100644 source/CPDLCServer/Auth/Administrators/AddAdministratorCommandHandler.cs create mode 100644 source/CPDLCServer/Auth/Administrators/Administrator.cs create mode 100644 source/CPDLCServer/Auth/Administrators/AdministratorConfiguration.cs create mode 100644 source/CPDLCServer/Auth/Administrators/AdministratorRepository.cs create mode 100644 source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommand.cs create mode 100644 source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommandHandler.cs create mode 100644 source/CPDLCServer/Auth/Administrators/IAdministratorRepository.cs create mode 100644 source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommand.cs create mode 100644 source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommandHandler.cs create mode 100644 source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommand.cs create mode 100644 source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommandHandler.cs create mode 100644 source/CPDLCServer/Auth/CurrentUser.cs delete mode 100644 source/CPDLCServer/Auth/Login/AdminAuthentication.cs delete mode 100644 source/CPDLCServer/Auth/Login/ClientIpAddress.cs delete mode 100644 source/CPDLCServer/Auth/Login/LoginCommand.cs delete mode 100644 source/CPDLCServer/Auth/Login/LoginCommandHandler.cs delete mode 100644 source/CPDLCServer/Auth/Login/LoginLockout.cs delete mode 100644 source/CPDLCServer/Auth/Login/PasswordRateLimit.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommand.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommandHandler.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/IPluginTokenRepository.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/PluginAuthorizationCodes.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/PluginEndpoints.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/PluginRedirectUri.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/PluginToken.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/PluginTokenAuthenticationHandler.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/PluginTokenConfiguration.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/PluginTokenHash.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/PluginTokenRepository.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommand.cs create mode 100644 source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommandHandler.cs delete mode 100644 source/CPDLCServer/Auth/Users/ChangePasswordCommand.cs delete mode 100644 source/CPDLCServer/Auth/Users/ChangePasswordCommandHandler.cs delete mode 100644 source/CPDLCServer/Auth/Users/CreateUserCommand.cs delete mode 100644 source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs delete mode 100644 source/CPDLCServer/Auth/Users/IUserRepository.cs delete mode 100644 source/CPDLCServer/Auth/Users/User.cs delete mode 100644 source/CPDLCServer/Auth/Users/UserConfiguration.cs delete mode 100644 source/CPDLCServer/Auth/Users/UserRepository.cs create mode 100644 source/CPDLCServer/Auth/VatsimConnect/VatsimConnectOptions.cs create mode 100644 source/CPDLCServer/Auth/VatsimConnect/VatsimUser.cs create mode 100644 source/CPDLCServer/Cpdlc/Motd/MotdScheduler.cs create mode 100644 source/CPDLCServer/Cpdlc/Motd/SendMotdCommand.cs create mode 100644 source/CPDLCServer/Cpdlc/Motd/SendMotdCommandHandler.cs create mode 100644 source/CPDLCServer/Cpdlc/Motd/SendMotdOnConnectionEstablishedHandler.cs create mode 100644 source/CPDLCServer/Logging/LogArea.cs rename source/CPDLCServer/Persistence/Migrations/PostgreSql/{20261115043637_InitialCreate.Designer.cs => 20261121042342_InitialCreate.Designer.cs} (90%) rename source/CPDLCServer/Persistence/Migrations/PostgreSql/{20261115043637_InitialCreate.cs => 20261121042342_InitialCreate.cs} (87%) rename source/CPDLCServer/Persistence/Migrations/Sqlite/{20261115043633_InitialCreate.Designer.cs => 20261121042339_InitialCreate.Designer.cs} (89%) rename source/CPDLCServer/Persistence/Migrations/Sqlite/{20261115043633_InitialCreate.cs => 20261121042339_InitialCreate.cs} (87%) create mode 100644 source/CPDLCServer/Settings/BannerEndpoint.cs create mode 100644 source/CPDLCServer/Settings/BannerImageFormat.cs create mode 100644 source/CPDLCServer/Settings/BrandingInfo.cs create mode 100644 source/CPDLCServer/Settings/SetBannerImageCommand.cs create mode 100644 source/CPDLCServer/Settings/SetBannerImageCommandHandler.cs create mode 100644 source/CPDLCServer/Web/Pages/Account/AccessDenied.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml.cs delete mode 100644 source/CPDLCServer/Web/Pages/Atsu/Index.cshtml rename source/CPDLCServer/Web/Pages/{Settings => Configuration}/Acars/Edit.cshtml (80%) rename source/CPDLCServer/Web/Pages/{Settings => Configuration}/Acars/Edit.cshtml.cs (98%) rename source/CPDLCServer/Web/Pages/{Settings => Configuration}/Acars/Index.cshtml (82%) rename source/CPDLCServer/Web/Pages/{Settings => Configuration}/Acars/Index.cshtml.cs (97%) create mode 100644 source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Configuration/Acars/_TrafficRows.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml.cs rename source/CPDLCServer/Web/Pages/{ => Configuration}/Settings/Index.cshtml (73%) create mode 100644 source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Cpdlc/Aircraft/Index.cshtml rename source/CPDLCServer/Web/Pages/{Pilot => Cpdlc/Aircraft}/Index.cshtml.cs (96%) create mode 100644 source/CPDLCServer/Web/Pages/Cpdlc/Dialogues/Index.cshtml rename source/CPDLCServer/Web/Pages/{Dialogue => Cpdlc/Dialogues}/Index.cshtml.cs (92%) create mode 100644 source/CPDLCServer/Web/Pages/Cpdlc/Index.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Cpdlc/Index.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Cpdlc/Messages.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Cpdlc/Messages.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Cpdlc/Stations/Index.cshtml rename source/CPDLCServer/Web/Pages/{Atsu => Cpdlc/Stations}/Index.cshtml.cs (97%) delete mode 100644 source/CPDLCServer/Web/Pages/Dialogue/Index.cshtml delete mode 100644 source/CPDLCServer/Web/Pages/Logs/Index.cshtml delete mode 100644 source/CPDLCServer/Web/Pages/Logs/Index.cshtml.cs delete mode 100644 source/CPDLCServer/Web/Pages/Pilot/Index.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml.cs delete mode 100644 source/CPDLCServer/Web/Pages/Settings/Index.cshtml.cs delete mode 100644 source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml delete mode 100644 source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml.cs delete mode 100644 source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml delete mode 100644 source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml.cs delete mode 100644 source/CPDLCServer/Web/Pages/Settings/_SettingsLayout.cshtml delete mode 100644 source/CPDLCServer/Web/Pages/Settings/_ViewStart.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Shared/_Branding.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Shared/_CenteredLayout.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Shared/_Pagination.cshtml create mode 100644 source/CPDLCServer/Web/Pages/ViewModels/PaginationViewModel.cs diff --git a/.do/deploy.template.yaml b/.do/deploy.template.yaml index 2e8e5d7..8e43766 100644 --- a/.do/deploy.template.yaml +++ b/.do/deploy.template.yaml @@ -23,6 +23,7 @@ spec: - key: DatabaseConnectionString scope: RUN_TIME value: ${db.DATABASE_URL} + # You must set the master key before you deploy. Without it, the server does not start. # Make a key with: openssl rand -base64 32 # Keep a copy of the key in a safe place. If the key changes, you must enter the ACARS authentication codes again. @@ -30,3 +31,13 @@ spec: scope: RUN_TIME type: SECRET value: "" + + # You must set the VATSIM Connect client before you deploy. Without it, the server does not start. + # Set the redirect URL of the client to https:///signin-vatsim + - key: VatsimConnect__ClientId + scope: RUN_TIME + value: "" + - key: VatsimConnect__ClientSecret + scope: RUN_TIME + type: SECRET + value: "" diff --git a/CPDLC.json b/CPDLC.json index 7449022..253f9b5 100644 --- a/CPDLC.json +++ b/CPDLC.json @@ -1,5 +1,6 @@ { "ServerEndpoint": "https://vatpac-cpdlc.eoinmotherway.dev/hubs/controller", + "AutoConnect": false, "Stations": ["YBBB", "YMMM", "NFFF", "AYPM"], "LogLevel": "Verbose", "MaxCurrentMessages": 50, diff --git a/docs/docs/server/index.md b/docs/docs/server/index.md index 48af96c..cf43da0 100644 --- a/docs/docs/server/index.md +++ b/docs/docs/server/index.md @@ -22,12 +22,12 @@ Deploy your own CPDLC Server instance to DigitalOcean: Since App Platform doesn't offer persistent disks, the template makes a PostgreSQL development database for the server data. :::warning -You must set the `MasterKey` environment variable before you deploy. If `MasterKey` is not set, the server does not start. +You must set the `MasterKey`, `VatsimConnect__ClientId` and `VatsimConnect__ClientSecret` environment variables before you deploy. If one of them is not set, the server does not start. -Make a key with `openssl rand -base64 32`, and keep a copy in a safe place. +Make a key with `openssl rand -base64 32`, and keep a copy in a safe place. See [VATSIM Connect](#vatsim-connect) for the client. ::: -After deployment, open the setup URL from the server log (see [Setup](#setup)). Then add your ACARS connection in Settings → ACARS on the server dashboard (`/settings/acars`). +After deployment, open `/setup` on the server, and enter the CID of the first administrator (see [Setup](#setup)). Then log in with VATSIM, and add your ACARS connection in Configuration → ACARS connections (`/configuration/acars`). ## Prerequisites @@ -39,11 +39,29 @@ Before running the CPDLC Server, ensure you have: ## Setup -When the server starts for the first time, it is not set up. All the pages of the dashboard will redirect to the setup page. The server will write the setup URL to the log: +When the server starts for the first time, it is not set up. All the pages of the dashboard redirect to the setup page (`/setup`). -``` -[12:00:00 WRN] The server is not set up. Open http://localhost:8080/setup?token=... to set it up -``` +On the setup page, enter the VATSIM CID of the first administrator. After the setup, the setup page does not exist. The administrator logs in with VATSIM, and can add more administrators in Configuration → Administrators. + +:::warning +The setup page needs no login. The first person who opens it chooses the administrator. Do the setup immediately after the first start. +::: + +### VATSIM Connect + +All users log in with [VATSIM Connect](https://vatsim.dev/services/connect). Make an OAuth client for the server at [auth.vatsim.net](https://auth.vatsim.net) (or [auth-dev.vatsim.net](https://auth-dev.vatsim.net) for development), with the redirect URL `https:///signin-vatsim`. Then set these environment variables: + +- `VatsimConnect__ClientId`: the ID of the client. +- `VatsimConnect__ClientSecret`: the secret of the client. +- `VatsimConnect__Authority` (optional): the VATSIM Connect server. The default is `https://auth.vatsim.net`. + +Any VATSIM user can log in, open the CPDLC and ADS-C areas, and connect with the plugin. Only an administrator can open the Configuration area. + +Behind a proxy that ends TLS, the server uses the `X-Forwarded-Proto` header, so that the redirect URL uses `https`. + +### Plugin Authentication + +The plugin must authenticate before it can connect to the server. In the SETUP window of the plugin, select **Authenticate**. The browser opens the server, the user logs in with VATSIM, and selects **Allow**. Then the plugin gets a token. The token is valid for 30 days. The plugin keeps it encrypted for the Windows account of the user. ### Master Key @@ -55,7 +73,7 @@ If the key is lost, the server cannot decrypt the secrets. ## Configuration -The logging level, the master key, the data directory and the database are configured with environment variables. Only `MasterKey` is required. +The logging level, the master key, VATSIM Connect, the data directory and the database are configured with environment variables. `MasterKey`, `VatsimConnect__ClientId` and `VatsimConnect__ClientSecret` are required. For local development, copy `example.env` to `.env` and update with your settings: ```bash @@ -66,6 +84,10 @@ Logging__Level=Information # Encrypts the secrets in the database. Make a key with: openssl rand -base64 32 MasterKey=your-master-key +# VATSIM Connect (required) +VatsimConnect__ClientId=your-client-id +VatsimConnect__ClientSecret=your-client-secret + # Data Directory # The directory of the SQLite database (cpdlc.db) (default: /data) DataPath=/data @@ -100,7 +122,7 @@ The server processes the requests from controllers, the ACARS connections and th ### ACARS Connections -The ACARS connections connect the server to the upstream ACARS networks. Add, change and delete them in Settings → ACARS on the dashboard (`/settings/acars`). +The ACARS connections connect the server to the upstream ACARS networks. Add, change and delete them in Configuration → ACARS connections on the dashboard (`/configuration/acars`). - When you add a connection, the server connects to the ACARS network. - When you change a connection, the server will reconnect to the upstream ACARS network with the new settings. @@ -109,15 +131,23 @@ You can add more than one connection, for example when the server serves more th The server keeps the authentication code of each connection encrypted with the master key (`MasterKey`). The dashboard does not show the code. If the master key changes, the server cannot decrypt the codes, and you must enter them again. +Each connection can have a message of the day. The server sends it to each aircraft as a CPDLC free text message, after the aircraft logs on and after the delay of the connection. The aircraft does not reply. The message shows in the dialogues, the same as the other uplinks. + +The Traffic button of a connection shows the most recent requests to the ACARS network and their responses, as raw text. The server keeps the last 500 requests of each connection in memory. The authentication code is not shown. The Logs button shows the log of the connection. + :::note `Hoppie` is currently the only supported ACARS network type. ::: +### Branding + +In the Branding section of Configuration → Settings, you can change the name of the server, add a banner image (PNG, JPEG or WebP, 1 MB or less), and add a message of the day. They show at the top of the sidebar and on the login page. The banner changes when you upload or remove it. The Save button saves the name and the message of the day. + ### Logs -The Logs page of the dashboard (`/logs`) shows the live log of the server, with the same text and level colours as the console output. +The Logs page of the dashboard (`/configuration/logs`) shows the live log of the server, with the same text and level colours as the console output. -You can show only the entries at or above a level, pause the log, and clear the page. The logging level of the server (`Logging__Level`) sets which entries the server writes. +You can show only the entries at or above a level, of one area (CPDLC, ADS-C, ACARS or System), of one ACARS connection, or with a text. You can also pause the log and clear the page. The filters are in the URL, so you can share a link to a filtered log. The logging level of the server (`Logging__Level`) sets which entries the server writes. ### ADS-C @@ -137,7 +167,7 @@ The server keeps one report for each contract. A new report replaces the previou A report expires when the next two periodic reports do not arrive. The expiry time is two reporting intervals plus three minutes, from the time in the report. A contract with only a demand request uses the default reporting interval. When a report expires, or when its contract is removed, the server deletes the report and the plugin shows the flight plan track again. -The ADS-C page of the dashboard (`/adsc`) shows all the contracts and their states, and a log of all the ADS-C messages that the server sent and received. +The ADS-C area of the dashboard shows all the contracts and their states (`/adsc`), and a log of all the ADS-C messages that the server sent and received (`/adsc/messages`). ### ADS-C from VATSIM Status Data diff --git a/docs/docs/vatsys-plugin/configuration.md b/docs/docs/vatsys-plugin/configuration.md index 116dc9a..e0c9a1a 100644 --- a/docs/docs/vatsys-plugin/configuration.md +++ b/docs/docs/vatsys-plugin/configuration.md @@ -17,6 +17,15 @@ URL of the CPDLC server WebSocket endpoint. "ServerEndpoint": "http://localhost:5261/hubs/controller" ``` +### AutoConnect + +When `true`, the plugin connects to the CPDLC server when vatSys connects to VATSIM. It uses the first station in `Stations`. The plugin must be authenticated (see [Connecting to the CPDLC Server](plugin.md#connecting-to-the-cpdlc-server)). Default: `false`. + +**Example:** +```json +"AutoConnect": true +``` + ### Stations List of station identifiers this controller position will use. The plugin will connect to the server using these callsigns. @@ -224,6 +233,7 @@ Array of message groups for organizing messages in the editor. Each group has: ```json { "ServerEndpoint": "http://localhost:5261/hubs/controller", + "AutoConnect": false, "Stations": ["YZZZ", "YXXX"], "LogLevel": "Verbose", "MaxCurrentMessages": 50, diff --git a/docs/docs/vatsys-plugin/plugin.md b/docs/docs/vatsys-plugin/plugin.md index 4825edc..eb7dc42 100644 --- a/docs/docs/vatsys-plugin/plugin.md +++ b/docs/docs/vatsys-plugin/plugin.md @@ -11,6 +11,10 @@ It explains how to connect to the server, interpret track labels, manage CPDLC m To connect, open the CPDLC menu and select Setup. Verify the server URL and station ID, then click Connect. +The first time, you must authenticate with the server. Below the server URL, the Setup window shows if you are authenticated. Click Authenticate. The browser opens the server. Log in with VATSIM, then click Allow. The plugin keeps the authentication for 30 days. To remove it, click Log out. + +The plugin does not connect to the server on the sweatbox. To connect automatically when you connect to VATSIM, set `AutoConnect` in the [configuration](configuration.md#autoconnect). + The station you select is your primary ATSU. Once connected, you can send and receive messages for any ATSU managed by that server. This allows controllers to extend their jurisdiction across FIR boundaries (e.g., Brisbane Centre extending to Melbourne Centre) when both ATSUs share a server. ## Track Label Item diff --git a/example.env b/example.env index c677f8f..79021eb 100644 --- a/example.env +++ b/example.env @@ -8,7 +8,16 @@ Logging__Level=Debug # Encrypts the secrets in the database, for example the authentication codes of the ACARS connections. # Make a key with: openssl rand -base64 32 # Keep the key safe. If the key changes, the server cannot decrypt the secrets, and you must enter them again. -MasterKey=your-master-key-here +MasterKey= + +# VATSIM Connect (required) +# The OAuth client of this server. Make it at https://auth.vatsim.net (or https://auth-dev.vatsim.net for development). +# Set the redirect URL of the client to https:///signin-vatsim +VatsimConnect__ClientId= +VatsimConnect__ClientSecret= + +# The VATSIM Connect server (default: https://auth.vatsim.net) +VatsimConnect__Authority=https://auth-dev.vatsim.net # Data Directory # The directory of the SQLite database (cpdlc.db). The server makes it if it does not exist. diff --git a/source/CPDLCPlugin/CPDLCPlugin.csproj b/source/CPDLCPlugin/CPDLCPlugin.csproj index 6290c1b..9febc1c 100644 --- a/source/CPDLCPlugin/CPDLCPlugin.csproj +++ b/source/CPDLCPlugin/CPDLCPlugin.csproj @@ -37,6 +37,7 @@ + $(VatSysPath)\bin\vatSys.exe False diff --git a/source/CPDLCPlugin/Configuration/PluginConfiguration.cs b/source/CPDLCPlugin/Configuration/PluginConfiguration.cs index e970dfc..617abdc 100644 --- a/source/CPDLCPlugin/Configuration/PluginConfiguration.cs +++ b/source/CPDLCPlugin/Configuration/PluginConfiguration.cs @@ -5,6 +5,10 @@ namespace CPDLCPlugin.Configuration; public class PluginConfiguration { public required string ServerEndpoint { get; init; } + + // When true, the plugin connects to the CPDLC server when vatSys connects to VATSIM. + // It uses the first station in Stations. + public bool AutoConnect { get; init; } public required string[] Stations { get; init; } public int MaxCurrentMessages { get; init; } = 50; public int MaxArchivedMessages { get; init; } = 50; diff --git a/source/CPDLCPlugin/Messages/AuthenticateRequest.cs b/source/CPDLCPlugin/Messages/AuthenticateRequest.cs new file mode 100644 index 0000000..548b08c --- /dev/null +++ b/source/CPDLCPlugin/Messages/AuthenticateRequest.cs @@ -0,0 +1,30 @@ +using CommunityToolkit.Mvvm.Messaging; +using CPDLCPlugin.Server; +using CPDLCServer.Contracts; +using MediatR; +using Serilog; + +namespace CPDLCPlugin.Messages; + +// Opens the browser, so that the user can log in to the CPDLC server with VATSIM +public record AuthenticateRequest(string ServerEndpoint) : IRequest; + +public class AuthenticateRequestHandler( + PluginAuthenticator authenticator, + TokenStore tokenStore, + AuthenticationState authenticationState, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(AuthenticateRequest request, CancellationToken cancellationToken) + { + var server = ServerAddress.GetBaseUri(request.ServerEndpoint); + + var response = await authenticator.Authenticate(server, cancellationToken); + tokenStore.Save(server, response.AccessToken); + authenticationState.Set(server, new PluginUserDto(response.Cid, response.Name, response.Expires)); + + logger.Information("Authenticated with {Server} as {Name} ({Cid})", server, response.Name, response.Cid); + WeakReferenceMessenger.Default.Send(new AuthenticationChangedNotification()); + } +} diff --git a/source/CPDLCPlugin/Messages/AuthenticationChangedNotification.cs b/source/CPDLCPlugin/Messages/AuthenticationChangedNotification.cs new file mode 100644 index 0000000..d1c1187 --- /dev/null +++ b/source/CPDLCPlugin/Messages/AuthenticationChangedNotification.cs @@ -0,0 +1,4 @@ +namespace CPDLCPlugin.Messages; + +// Sent with the WeakReferenceMessenger when the plugin authenticates or logs out +public record AuthenticationChangedNotification; diff --git a/source/CPDLCPlugin/Messages/CheckAuthenticationRequest.cs b/source/CPDLCPlugin/Messages/CheckAuthenticationRequest.cs new file mode 100644 index 0000000..cb98fc7 --- /dev/null +++ b/source/CPDLCPlugin/Messages/CheckAuthenticationRequest.cs @@ -0,0 +1,38 @@ +using CommunityToolkit.Mvvm.Messaging; +using CPDLCPlugin.Server; +using MediatR; +using Serilog; + +namespace CPDLCPlugin.Messages; + +// Asks the CPDLC server if the saved token is valid. Returns the token, or null when the plugin is not authenticated. +// A token that the server does not accept is deleted. +public record CheckAuthenticationRequest(string ServerEndpoint) : IRequest; + +public class CheckAuthenticationRequestHandler( + PluginAuthenticator authenticator, + TokenStore tokenStore, + AuthenticationState authenticationState, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(CheckAuthenticationRequest request, CancellationToken cancellationToken) + { + var server = ServerAddress.GetBaseUri(request.ServerEndpoint); + + var token = tokenStore.Get(server); + var user = token is null ? null : await authenticator.GetUser(server, token, cancellationToken); + + if (token is not null && user is null) + { + logger.Information("The server {Server} did not accept the saved token. Deleting it", server); + tokenStore.Delete(server); + token = null; + } + + authenticationState.Set(server, user); + WeakReferenceMessenger.Default.Send(new AuthenticationChangedNotification()); + + return token; + } +} diff --git a/source/CPDLCPlugin/Messages/ConnectRequest.cs b/source/CPDLCPlugin/Messages/ConnectRequest.cs index 4ee8cf3..9faa110 100644 --- a/source/CPDLCPlugin/Messages/ConnectRequest.cs +++ b/source/CPDLCPlugin/Messages/ConnectRequest.cs @@ -1,54 +1,70 @@ -using CPDLCPlugin.Server; -using MediatR; -using Serilog; -using vatsys; - -namespace CPDLCPlugin.Messages; - -public record ConnectRequest(string ServerEndpoint, string StationId) : IRequest; - -public class ConnectRequestHandler(Plugin plugin, IMediator mediator, ILogger logger) : IRequestHandler -{ - public async Task Handle(ConnectRequest request, CancellationToken cancellationToken) - { - logger.Information("Connecting to {ServerEndpoint}", request.ServerEndpoint); - - // If already connected, disconnect first - if (plugin.ConnectionManager is not null) - { - logger.Information("Existing connection found, disconnecting"); - if (plugin.ConnectionManager.IsConnected) - { - await plugin.ConnectionManager.StopAsync(); - logger.Information("Existing connection stopped"); - } - - plugin.ConnectionManager.Dispose(); - plugin.ConnectionManager = null; - } - - if (!Network.IsConnected) - { - logger.Warning("Cannot connect to server: not connected to VATSIM"); - throw new Exception("Not connected to VATSIM"); - } - - logger.Verbose("Creating SignalR connection"); - var downlinkHandler = new MediatorMessageHandler(mediator); - plugin.ConnectionManager = new SignalRConnectionManager( - request.ServerEndpoint, - downlinkHandler, - logger.ForContext()); - - // Initialize the connection with the station ID and current callsign - logger.Information("Initializing SignalR connection"); - await plugin.ConnectionManager.InitializeAsync(request.StationId, Network.Callsign); - - // Start the connection - logger.Information("Starting SignalR connection"); - await plugin.ConnectionManager.StartAsync(); - - logger.Information("Connected to server"); - await mediator.Publish(new ConnectedNotification(), cancellationToken); - } -} +using CPDLCPlugin.Server; +using MediatR; +using Serilog; +using vatsys; + +namespace CPDLCPlugin.Messages; + +public record ConnectRequest(string ServerEndpoint, string StationId) : IRequest; + +public class ConnectRequestHandler(Plugin plugin, IMediator mediator, ILogger logger) : IRequestHandler +{ + public async Task Handle(ConnectRequest request, CancellationToken cancellationToken) + { + logger.Information("Connecting to {ServerEndpoint}", request.ServerEndpoint); + + // If already connected, disconnect first + if (plugin.ConnectionManager is not null) + { + logger.Information("Existing connection found, disconnecting"); + if (plugin.ConnectionManager.IsConnected) + { + await plugin.ConnectionManager.StopAsync(); + logger.Information("Existing connection stopped"); + } + + plugin.ConnectionManager.Dispose(); + plugin.ConnectionManager = null; + } + + if (!Network.IsConnected) + { + logger.Warning("Cannot connect to server: not connected to VATSIM"); + throw new Exception("Not connected to VATSIM"); + } + + // The CPDLC server is for the live network only + if (!Network.IsOfficialServer) + { + logger.Warning("Cannot connect to server: connected to the sweatbox"); + throw new Exception("Cannot connect to the CPDLC server on the sweatbox"); + } + + // Check the token first, so that an expired token gives a clear error + var token = await mediator.Send(new CheckAuthenticationRequest(request.ServerEndpoint), cancellationToken); + if (token is null) + { + logger.Warning("Cannot connect to server: not authenticated"); + throw new Exception("Not authenticated with the CPDLC server. Open SETUP and select Authenticate."); + } + + logger.Verbose("Creating SignalR connection"); + var downlinkHandler = new MediatorMessageHandler(mediator); + plugin.ConnectionManager = new SignalRConnectionManager( + request.ServerEndpoint, + token, + downlinkHandler, + logger.ForContext()); + + // Initialize the connection with the station ID and current callsign + logger.Information("Initializing SignalR connection"); + await plugin.ConnectionManager.InitializeAsync(request.StationId, Network.Callsign); + + // Start the connection + logger.Information("Starting SignalR connection"); + await plugin.ConnectionManager.StartAsync(); + + logger.Information("Connected to server"); + await mediator.Publish(new ConnectedNotification(), cancellationToken); + } +} diff --git a/source/CPDLCPlugin/Messages/LogOutRequest.cs b/source/CPDLCPlugin/Messages/LogOutRequest.cs new file mode 100644 index 0000000..e211759 --- /dev/null +++ b/source/CPDLCPlugin/Messages/LogOutRequest.cs @@ -0,0 +1,42 @@ +using CommunityToolkit.Mvvm.Messaging; +using CPDLCPlugin.Server; +using MediatR; +using Serilog; + +namespace CPDLCPlugin.Messages; + +// Revokes the token on the CPDLC server, and deletes it from this computer +public record LogOutRequest(string ServerEndpoint) : IRequest; + +public class LogOutRequestHandler( + PluginAuthenticator authenticator, + TokenStore tokenStore, + AuthenticationState authenticationState, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(LogOutRequest request, CancellationToken cancellationToken) + { + var server = ServerAddress.GetBaseUri(request.ServerEndpoint); + + var token = tokenStore.Get(server); + tokenStore.Delete(server); + authenticationState.Set(server, null); + WeakReferenceMessenger.Default.Send(new AuthenticationChangedNotification()); + + if (token is null) + return; + + try + { + await authenticator.Logout(server, token, cancellationToken); + } + catch (Exception ex) + { + // The token is deleted from this computer. It expires on the server later. + logger.Warning(ex, "Failed to revoke the token on {Server}", server); + } + + logger.Information("Logged out from {Server}", server); + } +} diff --git a/source/CPDLCPlugin/Messages/OpenSetupWindowRequest.cs b/source/CPDLCPlugin/Messages/OpenSetupWindowRequest.cs index 298955a..b483b8c 100644 --- a/source/CPDLCPlugin/Messages/OpenSetupWindowRequest.cs +++ b/source/CPDLCPlugin/Messages/OpenSetupWindowRequest.cs @@ -1,4 +1,5 @@ using CPDLCPlugin.Configuration; +using CPDLCPlugin.Server; using CPDLCPlugin.ViewModels; using CPDLCPlugin.Windows; using MediatR; @@ -12,7 +13,9 @@ public class OpenSetupWindowRequestHandler( PluginConfiguration pluginConfiguration, IMediator mediator, Plugin plugin, - IErrorReporter errorReporter) + IErrorReporter errorReporter, + AuthenticationState authenticationState, + IGuiInvoker guiInvoker) : IRequestHandler { public Task Handle(OpenSetupWindowRequest request, CancellationToken cancellationToken) @@ -28,6 +31,8 @@ public Task Handle(OpenSetupWindowRequest request, CancellationToken cancellatio mediator, errorReporter, windowHandle, + authenticationState, + guiInvoker, plugin.ConnectionManager?.ServerEndpoint ?? pluginConfiguration.ServerEndpoint, pluginConfiguration.Stations, isConnected ? plugin.ConnectionManager!.StationIdentifier : pluginConfiguration.Stations.First(), diff --git a/source/CPDLCPlugin/Plugin.cs b/source/CPDLCPlugin/Plugin.cs index d8130c3..ade2a09 100644 --- a/source/CPDLCPlugin/Plugin.cs +++ b/source/CPDLCPlugin/Plugin.cs @@ -1,761 +1,788 @@ -using System.ComponentModel.Composition; -using System.IO; -using System.Threading.Channels; -using System.Windows; -using System.Windows.Forms; -using System.Windows.Media; -using CommunityToolkit.Mvvm.Messaging; -using CPDLCPlugin.Configuration; -using CPDLCPlugin.Extensions; -using CPDLCPlugin.LabelItems; -using CPDLCPlugin.Messages; -using CPDLCPlugin.Server; -using CPDLCPlugin.Windows; -using MediatR; -using Microsoft.Extensions.DependencyInjection; -using Serilog; -using vatsys; -using vatsys.Plugin; - -namespace CPDLCPlugin; - -// TODO: Complex variable entry (popups and validation) -// TODO: Text message fallback -// TODO: window frame styling -// TODO: ADS-C - -[Export(typeof(IPlugin))] -public class Plugin : ILabelPlugin, IStripPlugin, IRecipient, IRecipient -{ -#if DEBUG - public const string Name = "CPDLC Plugin - Debug"; -#else - public const string Name = "CPDLC Plugin"; -#endif - - static readonly Dictionary ErrorMessages = new(); - - readonly CpdlcStatusLabelItemProvider _cpdlcStatusProvider; - readonly TextStatusLabelItemProvider _textStatusProvider; - readonly ColourCache _colourCache; - - readonly WorkQueue _workQueue; - - // 1 if a rebuild of the CPDLC status label items is in the work queue, and 0 if not - int _isLabelRebuildQueued; - - PluginConfiguration? _configuration; - - BackgroundWorker? _ndaRecalculationWorker; - - ToolStripMenuItem? _installationMenuItem; - bool _labelsInstalled; - - const string InstallMenuLabel = "Install label items"; - const string UninstallMenuLabel = "Uninstall label items"; - - string IPlugin.Name => Name; - - IServiceProvider ServiceProvider { get; set; } - - public SignalRConnectionManager? ConnectionManager { get; set; } - - public Plugin() - { - DpiAwareness.EnsureDpiAwareness(); - - ConfigureTheme(); - _colourCache = CacheLabelColours(); - _cpdlcStatusProvider = new CpdlcStatusLabelItemProvider(); - _textStatusProvider = new TextStatusLabelItemProvider(_colourCache); - - var configuration = ConfigurationLoader.Load(); - _configuration = configuration; - ConfigureServices(configuration); - - ApplyAdscTrackPatches(); - ApplyFakeAdscReportPatch(); - - AddToolbarItems(); - - CheckXmlInstallation(); - - Network.Connected += NetworkConnected; - Network.Disconnected += NetworkDisconnected; - - WeakReferenceMessenger.Default.Register(this); - WeakReferenceMessenger.Default.Register(this); - - _workQueue = new WorkQueue(AddError, Log.Logger, new SystemClock()); - } - - void ConfigureServices(PluginConfiguration pluginConfiguration) - { - var logger = ConfigureLogger(pluginConfiguration); - - ServiceProvider = new ServiceCollection() - .AddSingleton(logger) - .AddSingleton(this) // TODO: Ick... Whatever we're relying on this for, move it into a separate service please. - .AddSingleton(pluginConfiguration) - .AddSingleton(new SystemClock()) - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(_cpdlcStatusProvider) - .AddSingleton(_colourCache) - .AddMediatR(c => c.RegisterServicesFromAssemblies(typeof(Plugin).Assembly)) - .BuildServiceProvider(); - } - - ILogger ConfigureLogger(PluginConfiguration configuration) - { - var logFileName = Path.Combine(Helpers.GetFilesFolder(), "cpdlc_log.txt"); - - var logger = new LoggerConfiguration() - .WriteTo.File( - path: logFileName, - rollingInterval: RollingInterval.Day, - retainedFileCountLimit: configuration.MaxLogFileAgeDays, - outputTemplate: "{Timestamp:u} [{Level:u3}] {Message:lj}{NewLine}{Exception}") - .MinimumLevel.Is(configuration.LogLevel) - .CreateLogger(); - - Log.Logger = logger; - - return logger; - } - - void ApplyAdscTrackPatches() - { - try - { - AdscTrackPatches.Apply(ServiceProvider.GetRequiredService()); - } - catch (Exception ex) - { - AddError(ex, "Cannot show ADS-C tracks on the ASD"); - } - } - - void ApplyFakeAdscReportPatch() - { - try - { - FakeAdscReportPatch.Apply(SendFakeAdscReport); - } - catch (Exception ex) - { - AddError(ex, "Cannot use fake ADS-C reports"); - } - } - - // Runs on the UI thread when the ASD is clicked - void SendFakeAdscReport(Coordinate position) - { - var fdr = MMI.SelectedTrack?.GetFDR(); - if (fdr is null) - throw new InvalidOperationException("Select a track with a flight plan before you send a fake ADS-C report"); - - if (fdr.PRL == -1) - throw new InvalidOperationException($"{fdr.Callsign} has no reported level"); - - var now = DateTimeOffset.UtcNow; - var report = new CPDLCServer.Contracts.AdscReportDto( - fdr.Callsign, - ConnectionManager?.StationIdentifier ?? string.Empty, - now, - position.Latitude, - position.Longitude, - fdr.PRL, - now, - CPDLCServer.Contracts.AdscReportSource.Hoppie); - - Log.Information("Sending fake ADS-C report for {Callsign} at {Latitude} {Longitude} {Altitude}", - report.Callsign, - report.Latitude, - report.Longitude, - report.Altitude); - - _workQueue.Enqueue(async () => - { - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Publish(new AdscReportReceivedNotification(report)); - }); - } - - void NetworkConnected(object sender, EventArgs e) - { - Log.Information("Connected to VATSIM as {Callsign}", Network.Callsign); - _workQueue.Enqueue(() => - { - StartNdaRecalculationWorker(); - return Task.CompletedTask; - }); - - // TODO: Connect if auto-connect enabled - } - - void NetworkDisconnected(object sender, EventArgs e) - { - Log.Information("Disconnected from VATSIM"); - - try - { - _workQueue.Enqueue(StopNdaRecalculationWorker); - - _workQueue.Enqueue(async () => - { - var mediator = ServiceProvider.GetService(); - if (mediator is null) - return; - - await mediator.Send(new DisconnectRequest()).ConfigureAwait(false); - }); - } - catch (Exception ex) - { - AddError(ex); - } - } - - void StartNdaRecalculationWorker() - { - var interval = TimeSpan.FromMinutes(_configuration?.NdaRecalculationIntervalMinutes ?? 1); - Log.Information("Starting NDA recalculation worker (interval: {Interval})", interval); - _ndaRecalculationWorker = new BackgroundWorker(async cancellationToken => - { - while (!cancellationToken.IsCancellationRequested) - { - try - { - await Task.Delay(interval, cancellationToken); - await RecalculateNextDataAuthorityForAllAircraft(); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - Log.Verbose("NDA recalculation worker cancellation requested"); - } - catch (Exception ex) - { - AddError(ex); - } - } - }); - } - - async Task StopNdaRecalculationWorker() - { - if (_ndaRecalculationWorker is null) - return; - - Log.Information("Stopping NDA recalculation worker"); - await _ndaRecalculationWorker.DisposeAsync(); - _ndaRecalculationWorker = null; - } - - async Task RecalculateNextDataAuthorityForAllAircraft() - { - var store = ServiceProvider.GetRequiredService(); - var connections = await store.All(CancellationToken.None); - - var ourAircraft = connections - .Where(c => c.StationId == ConnectionManager?.StationIdentifier && - c.DataAuthorityState == CPDLCServer.Contracts.DataAuthorityState.CurrentDataAuthority); - - foreach (var aircraft in ourAircraft) - { - var fdr = FDP2.GetFDRs.FirstOrDefault(f => f.Callsign == aircraft.Callsign); - if (fdr is null || !fdr.IsTrackedByMe) - continue; - - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new UpdateNextDataAuthorityRequest(fdr.Callsign, fdr.GetSectorEntries())); - } - } - - public static void AddError(Exception exception) - { - Log.Error(exception, "An error has occurred"); - TryAddErrorInternal(exception); - } - - public static void AddError(Exception exception, string message) - { - Log.Error(exception, message); - TryAddErrorInternal(exception); - } - - static void TryAddErrorInternal(Exception exception) - { - lock (ErrorMessages) - { - // Don't flood the error window with the same message over and over again - if (ErrorMessages.TryGetValue(exception.Message, out var lastShown) && - DateTimeOffset.Now - lastShown <= TimeSpan.FromMinutes(1)) - return; - - Errors.Add(exception, Name); - ErrorMessages[exception.Message] = DateTimeOffset.Now; - } - } - - void ConfigureTheme() - { - Theme.BackgroundColor = GetColour(Colours.Identities.WindowBackground); - Theme.GenericTextColor = GetColour(Colours.Identities.GenericText); - Theme.InteractiveTextColor = GetColour(Colours.Identities.InteractiveText); - Theme.NonInteractiveTextColor = GetColour(Colours.Identities.NonInteractiveText); - Theme.SelectedButtonColor = GetColour(Colours.Identities.WindowButtonSelected); - - Theme.CPDLCBackgroundColor = GetColour(Colours.Identities.CPDLCMessageBackground); - Theme.CPDLCUplinkColor = GetColour(Colours.Identities.CPDLCUplink); - Theme.CPDLCDownlinkColor = GetColour(Colours.Identities.CPDLCDownlink); - Theme.CPDLCSendBackgroundColor = GetColour(Colours.Identities.CPDLCSendButton); - Theme.CPDLCHotButtonBackgroundColor = GetColour(Colours.Identities.CPDLCSendButton); - - Theme.FontFamily = new FontFamily(MMI.eurofont_xsml.FontFamily.Name); - Theme.FontSize = MMI.eurofont_xsml.Size; - Theme.FontWeight = MMI.eurofont_xsml.Bold ? FontWeights.Bold : FontWeights.Regular; - - SolidColorBrush GetColour(Colours.Identities identity) - { - return new SolidColorBrush(Colours.GetColour(identity).ToWindowsColor()); - } - } - - ColourCache CacheLabelColours() - { - // Need to cache these for thread-safe access - - var downlinkColor = Theme.CPDLCDownlinkColor.Color; - var customDownlinkColor = new CustomColour(downlinkColor.R, downlinkColor.G, downlinkColor.B); - - var unableColor = Theme.CPDLCUnableDownlinkColor.Color; - var customUnableDownlinkColor = new CustomColour(unableColor.R, unableColor.G, unableColor.B); - - var suspendedColor = Theme.CPDLCSuspendedColor.Color; - var customSuspendedColor = new CustomColour(suspendedColor.R, suspendedColor.G, suspendedColor.B); - - return new ColourCache - { - DownlinkBackgroundColour = customDownlinkColor, - UnableBackgroundColour = customUnableDownlinkColor, - SuspendedForegroundColour = customSuspendedColor - }; - } - - void AddToolbarItems() - { - const string menuItemCategory = "CPDLC"; - - var setupMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("Setup")); - setupMenuItem.Item.Click += (_, _) => - { - _workQueue.Enqueue(async () => - { - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenSetupWindowRequest()); - }); - }; - - MMI.AddCustomMenuItem(setupMenuItem); - - var currentMessagesMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("Current Messages")); - currentMessagesMenuItem.Item.Click += (_, _) => - { - _workQueue.Enqueue(async () => - { - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: false)); - }); - }; - - MMI.AddCustomMenuItem(currentMessagesMenuItem); - - var historyMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("History")); - historyMenuItem.Item.Click += (_, _) => - { - _workQueue.Enqueue(async () => - { - var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; - - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenHistoryWindowRequest(selectedCallsign)); - }); - }; - - MMI.AddCustomMenuItem(historyMenuItem); - - var adsContractMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("ADS Contract")); - adsContractMenuItem.Item.Click += (_, _) => - { - _workQueue.Enqueue(async () => - { - var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; - - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenADSContractWindowRequest(selectedCallsign)); - }); - }; - - MMI.AddCustomMenuItem(adsContractMenuItem); - -#if DEBUG - var editorMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("CPDLC Editor")); - editorMenuItem.Item.Click += (_, _) => - { - _workQueue.Enqueue(async () => - { - var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; - if (selectedCallsign is null) - throw new InvalidOperationException("Select a track with a flight plan before you open the CPDLC Editor"); - - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenEditorWindowRequest(selectedCallsign)); - }); - }; - - MMI.AddCustomMenuItem(editorMenuItem); - - var fakeAdscReportMenuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - new ToolStripMenuItem("Fake ADS-C Report")); - fakeAdscReportMenuItem.Item.Click += (_, _) => FakeAdscReportPatch.Arm(); - - MMI.AddCustomMenuItem(fakeAdscReportMenuItem); -#endif - - if (_configuration?.ShowInstallationMenuItems ?? true) - { - var status = XmlInstaller.GetStatus(); - if (!string.IsNullOrEmpty(status.ErrorMessage)) - return; - - _labelsInstalled = status.IsInstalled; - - var toolStripItem = new ToolStripMenuItem(_labelsInstalled ? UninstallMenuLabel : InstallMenuLabel); - toolStripItem.Click += (_, _) => - { - if (_labelsInstalled) - RunUninstall(); - else - RunInstall(); - }; - - _installationMenuItem = toolStripItem; - - var menuItem = new CustomToolStripMenuItem( - CustomToolStripMenuItemWindowType.Main, - menuItemCategory, - toolStripItem); - MMI.AddCustomMenuItem(menuItem); - } - } - - void CheckXmlInstallation() - { - try - { - var status = XmlInstaller.GetStatus(); - if (!string.IsNullOrEmpty(status.ErrorMessage)) - { - Log.Warning("Could not verify Labels.xml/Strips.xml installation: {Error}", status.ErrorMessage); - return; - } - - if (!status.IsInstalled) - { - AddError(new InvalidOperationException("CPDLC Label and Strip items must be installed. Please install them from the CPDLC menu.")); - } - } - catch (Exception ex) - { - AddError(ex, "Failed to verify Labels.xml/Strips.xml installation"); - } - } - - void RunInstall() - { - try - { - var result = XmlInstaller.Install(); - if (result.Succeeded) - { - SetInstallationMenuState(installed: true); - System.Windows.Forms.MessageBox.Show( - "CPDLC label & strip items installed successfully.\n\nPlease restart vatSys to apply the changes.", - Name, - MessageBoxButtons.OK, - MessageBoxIcon.Information); - } - else - { - System.Windows.Forms.MessageBox.Show( - $"Failed to install CPDLC label & strip items.\n\n{result.ErrorMessage}", - Name, - MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - catch (Exception ex) - { - AddError(ex, "Failed to install label & strip items"); - } - } - - void SetInstallationMenuState(bool installed) - { - _labelsInstalled = installed; - if (_installationMenuItem is not null) - _installationMenuItem.Text = installed ? UninstallMenuLabel : InstallMenuLabel; - } - - void RunUninstall() - { - try - { - var result = XmlInstaller.Uninstall(); - if (result.Succeeded) - { - SetInstallationMenuState(installed: false); - System.Windows.Forms.MessageBox.Show( - "CPDLC label & strip items uninstalled successfully.\n\nPlease restart vatSys to apply the changes.", - Name, - MessageBoxButtons.OK, - MessageBoxIcon.Information); - } - else - { - System.Windows.Forms.MessageBox.Show( - $"Failed to uninstall CPDLC label & strip items.\n\n{result.ErrorMessage}", - Name, - MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - catch (Exception ex) - { - AddError(ex, "Failed to uninstall label & strip items"); - } - } - - public void OnFDRUpdate(FDP2.FDR updated) - { - try - { - // Record the last known owner of each FDR - _workQueue.Enqueue(async () => - { - Log.Verbose( - "{Callsign}: IsTracked {IsTracked}; IsTrackedByMe: {IsTrackedByMe}; Controller Tracking: {CurrentController}; Handoff Controller: {HandoffController}", - updated.Callsign, - updated.IsTracked, - updated.IsTrackedByMe, - updated.ControllerTracking?.Callsign, - updated.HandoffController?.Callsign); - - var jurisdictionChecker = ServiceProvider.GetRequiredService(); - - var previousRecord = jurisdictionChecker.GetOwnershipRecord(updated.Callsign); - jurisdictionChecker.RecordFdrOwner(updated.Callsign, updated.ControllerTracking?.Callsign); - - var record = jurisdictionChecker.GetOwnershipRecord(updated.Callsign); - - // Tell the Current Messages Window that the dialogues it must show can be different - if (previousRecord?.CurrentOwner != record?.CurrentOwner) - WeakReferenceMessenger.Default.Send(new FdrOwnerChanged(updated.Callsign)); - - if (record?.PreviousOwner != Network.Callsign) - return; - - // We were the previous owner, process the handoff - Log.Information("{Callsign} handoff to {NextController}", updated.Callsign, record.CurrentOwner); - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Publish(new HandoffCompletedNotification(updated.Callsign, record.CurrentOwner)); - }); - - // Ensure the next data authority is up-to-date - _workQueue.Enqueue(async () => - { - var handoffMediator = ServiceProvider.GetRequiredService(); - await handoffMediator.Send(new UpdateNextDataAuthorityRequest(updated.Callsign, updated.GetSectorEntries())); - }); - - // Re-build the CPDLC status label items - QueueLabelRebuild(); - - // If this flight has any dialogues that we have jurisdiction over, open the current messages window - // Ensures flights handed off to us open the window so we can see their requests - // A closed dialogue stays in the window until it is archived (e.g. a downlink that needs no response) - _workQueue.Enqueue(async () => - { - var store = ServiceProvider.GetRequiredService(); - var jurisdictionChecker = ServiceProvider.GetRequiredService(); - - var hasDialoguesToDisplay = (await store.All(CancellationToken.None)) - .Where(d => d.AircraftCallsign == updated.Callsign) - .Any(d => !d.IsArchived && jurisdictionChecker.ShouldDisplayDialogue(d)); - - // vatSys updates the FDRs often. If the window is open, do not post to the UI thread to open it again. - var windowManager = ServiceProvider.GetRequiredService(); - if (hasDialoguesToDisplay && !windowManager.IsWindowOpen(WindowKeys.CurrentMessages)) - { - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: true)); - } - }); - } - catch (Exception ex) - { - AddError(ex); - } - } - - public void OnRadarTrackUpdate(RDP.RadarTrack updated) {} - - public CustomLabelItem? GetCustomLabelItem( - string itemType, - Track track, - FDP2.FDR flightDataRecord, - RDP.RadarTrack radarTrack) - { - try - { - if (itemType.StartsWith("CPDLCPLUGIN_TEXTSTATUS")) - return _textStatusProvider.GetLabelItem(itemType, flightDataRecord); - - if (itemType.StartsWith("CPDLCPLUGIN_CPDLCSTATUS")) - return _cpdlcStatusProvider.GetLabelItem(itemType, flightDataRecord); - } - catch (Exception ex) - { - AddError(ex, "Failed to generate custom label item"); - } - - return null; - } - - public CustomStripItem? GetCustomStripItem( - string itemType, - Track track, - FDP2.FDR flightDataRecord, - RDP.RadarTrack radarTrack) - { - try - { - if (itemType.StartsWith("CPDLCPLUGIN_TEXTSTATUS")) - return _textStatusProvider.GetStripItem(itemType, flightDataRecord); - - if (itemType.StartsWith("CPDLCPLUGIN_CPDLCSTATUS")) - return _cpdlcStatusProvider.GetStripItem(itemType, flightDataRecord); - } - catch (Exception ex) - { - AddError(ex, "Failed to generate custom strip item"); - } - - return null; - } - - public CustomColour? SelectASDTrackColour(Track track) => null; - - public CustomColour? SelectGroundTrackColour(Track track) => null; - - // vatSys updates the FDRs often, and each rebuild reads all the FDRs. A rebuild reads the state when it runs. Thus, - // if a rebuild is already in the work queue, do not queue another one. - void QueueLabelRebuild() - { - if (Interlocked.Exchange(ref _isLabelRebuildQueued, 1) == 1) - return; - - _workQueue.Enqueue(() => - { - // Clear the flag before the rebuild reads the state. Then a change during the rebuild queues a new rebuild. - Interlocked.Exchange(ref _isLabelRebuildQueued, 0); - return RebuildCpdlcStatusLabelItems(); - }); - } - - async Task RebuildCpdlcStatusLabelItems(CancellationToken cancellationToken = default) - { - try - { - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new RebuildCpdlcStatusLabelItemsRequest(), cancellationToken); - } - catch (Exception ex) - { - AddError(ex); - } - } - - public void Receive(ConnectedAircraftChanged _) - { - try - { - QueueLabelRebuild(); - } - catch (Exception ex) - { - AddError(ex); - } - } - - public void Receive(DialogueChangedNotification dialogueChangedNotification) - { - try - { - // The rebuild is in the work queue before the next work item. Thus, the labels are rebuilt before the window - // opens. - QueueLabelRebuild(); - - _workQueue.Enqueue(async () => - { - // Try to open the Current Messages Window if this dialogue is relevant to the controller - var jurisdictionChecker = ServiceProvider.GetRequiredService(); - if (dialogueChangedNotification.Dialogue.IsArchived || - !jurisdictionChecker.ShouldDisplayDialogue(dialogueChangedNotification.Dialogue)) - { - return; - } - - // If the window is open, do not post to the UI thread to open and activate it again - var windowManager = ServiceProvider.GetRequiredService(); - if (windowManager.IsWindowOpen(WindowKeys.CurrentMessages)) - return; - - var mediator = ServiceProvider.GetRequiredService(); - await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: true)); - }); - } - catch (Exception ex) - { - AddError(ex); - } - } -} +using System.ComponentModel.Composition; +using System.IO; +using System.Threading.Channels; +using System.Windows; +using System.Windows.Forms; +using System.Windows.Media; +using CommunityToolkit.Mvvm.Messaging; +using CPDLCPlugin.Configuration; +using CPDLCPlugin.Extensions; +using CPDLCPlugin.LabelItems; +using CPDLCPlugin.Messages; +using CPDLCPlugin.Server; +using CPDLCPlugin.Windows; +using MediatR; +using Microsoft.Extensions.DependencyInjection; +using Serilog; +using vatsys; +using vatsys.Plugin; + +namespace CPDLCPlugin; + +// TODO: Complex variable entry (popups and validation) +// TODO: Text message fallback +// TODO: window frame styling +// TODO: ADS-C + +[Export(typeof(IPlugin))] +public class Plugin : ILabelPlugin, IStripPlugin, IRecipient, IRecipient +{ +#if DEBUG + public const string Name = "CPDLC Plugin - Debug"; +#else + public const string Name = "CPDLC Plugin"; +#endif + + static readonly Dictionary ErrorMessages = new(); + + readonly CpdlcStatusLabelItemProvider _cpdlcStatusProvider; + readonly TextStatusLabelItemProvider _textStatusProvider; + readonly ColourCache _colourCache; + + readonly WorkQueue _workQueue; + + // 1 if a rebuild of the CPDLC status label items is in the work queue, and 0 if not + int _isLabelRebuildQueued; + + PluginConfiguration? _configuration; + + BackgroundWorker? _ndaRecalculationWorker; + + ToolStripMenuItem? _installationMenuItem; + bool _labelsInstalled; + + const string InstallMenuLabel = "Install label items"; + const string UninstallMenuLabel = "Uninstall label items"; + + string IPlugin.Name => Name; + + IServiceProvider ServiceProvider { get; set; } + + public SignalRConnectionManager? ConnectionManager { get; set; } + + public Plugin() + { + DpiAwareness.EnsureDpiAwareness(); + + ConfigureTheme(); + _colourCache = CacheLabelColours(); + _cpdlcStatusProvider = new CpdlcStatusLabelItemProvider(); + _textStatusProvider = new TextStatusLabelItemProvider(_colourCache); + + var configuration = ConfigurationLoader.Load(); + _configuration = configuration; + ConfigureServices(configuration); + + ApplyAdscTrackPatches(); + ApplyFakeAdscReportPatch(); + + AddToolbarItems(); + + CheckXmlInstallation(); + + Network.Connected += NetworkConnected; + Network.Disconnected += NetworkDisconnected; + + WeakReferenceMessenger.Default.Register(this); + WeakReferenceMessenger.Default.Register(this); + + _workQueue = new WorkQueue(AddError, Log.Logger, new SystemClock()); + + // Check the saved token, so that the SETUP window shows the user. + // The server can be unavailable when vatSys starts, so a failure is not an error. + _workQueue.Enqueue(async () => + { + try + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new CheckAuthenticationRequest(configuration.ServerEndpoint)); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to check the authentication with the CPDLC server"); + } + }); + } + + void ConfigureServices(PluginConfiguration pluginConfiguration) + { + var logger = ConfigureLogger(pluginConfiguration); + + ServiceProvider = new ServiceCollection() + .AddSingleton(logger) + .AddSingleton(this) // TODO: Ick... Whatever we're relying on this for, move it into a separate service please. + .AddSingleton(pluginConfiguration) + .AddSingleton(new SystemClock()) + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton(_cpdlcStatusProvider) + .AddSingleton(_colourCache) + .AddMediatR(c => c.RegisterServicesFromAssemblies(typeof(Plugin).Assembly)) + .BuildServiceProvider(); + } + + ILogger ConfigureLogger(PluginConfiguration configuration) + { + var logFileName = Path.Combine(Helpers.GetFilesFolder(), "cpdlc_log.txt"); + + var logger = new LoggerConfiguration() + .WriteTo.File( + path: logFileName, + rollingInterval: RollingInterval.Day, + retainedFileCountLimit: configuration.MaxLogFileAgeDays, + outputTemplate: "{Timestamp:u} [{Level:u3}] {Message:lj}{NewLine}{Exception}") + .MinimumLevel.Is(configuration.LogLevel) + .CreateLogger(); + + Log.Logger = logger; + + return logger; + } + + void ApplyAdscTrackPatches() + { + try + { + AdscTrackPatches.Apply(ServiceProvider.GetRequiredService()); + } + catch (Exception ex) + { + AddError(ex, "Cannot show ADS-C tracks on the ASD"); + } + } + + void ApplyFakeAdscReportPatch() + { + try + { + FakeAdscReportPatch.Apply(SendFakeAdscReport); + } + catch (Exception ex) + { + AddError(ex, "Cannot use fake ADS-C reports"); + } + } + + // Runs on the UI thread when the ASD is clicked + void SendFakeAdscReport(Coordinate position) + { + var fdr = MMI.SelectedTrack?.GetFDR(); + if (fdr is null) + throw new InvalidOperationException("Select a track with a flight plan before you send a fake ADS-C report"); + + if (fdr.PRL == -1) + throw new InvalidOperationException($"{fdr.Callsign} has no reported level"); + + var now = DateTimeOffset.UtcNow; + var report = new CPDLCServer.Contracts.AdscReportDto( + fdr.Callsign, + ConnectionManager?.StationIdentifier ?? string.Empty, + now, + position.Latitude, + position.Longitude, + fdr.PRL, + now, + CPDLCServer.Contracts.AdscReportSource.Hoppie); + + Log.Information("Sending fake ADS-C report for {Callsign} at {Latitude} {Longitude} {Altitude}", + report.Callsign, + report.Latitude, + report.Longitude, + report.Altitude); + + _workQueue.Enqueue(async () => + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Publish(new AdscReportReceivedNotification(report)); + }); + } + + void NetworkConnected(object sender, EventArgs e) + { + Log.Information("Connected to VATSIM as {Callsign}", Network.Callsign); + _workQueue.Enqueue(() => + { + StartNdaRecalculationWorker(); + return Task.CompletedTask; + }); + + if (_configuration is { AutoConnect: true }) + { + var configuration = _configuration; + _workQueue.Enqueue(async () => + { + Log.Information("Connecting to the CPDLC server automatically"); + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new ConnectRequest(configuration.ServerEndpoint, configuration.Stations.First())); + }); + } + } + + void NetworkDisconnected(object sender, EventArgs e) + { + Log.Information("Disconnected from VATSIM"); + + try + { + _workQueue.Enqueue(StopNdaRecalculationWorker); + + _workQueue.Enqueue(async () => + { + var mediator = ServiceProvider.GetService(); + if (mediator is null) + return; + + await mediator.Send(new DisconnectRequest()).ConfigureAwait(false); + }); + } + catch (Exception ex) + { + AddError(ex); + } + } + + void StartNdaRecalculationWorker() + { + var interval = TimeSpan.FromMinutes(_configuration?.NdaRecalculationIntervalMinutes ?? 1); + Log.Information("Starting NDA recalculation worker (interval: {Interval})", interval); + _ndaRecalculationWorker = new BackgroundWorker(async cancellationToken => + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + await Task.Delay(interval, cancellationToken); + await RecalculateNextDataAuthorityForAllAircraft(); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + Log.Verbose("NDA recalculation worker cancellation requested"); + } + catch (Exception ex) + { + AddError(ex); + } + } + }); + } + + async Task StopNdaRecalculationWorker() + { + if (_ndaRecalculationWorker is null) + return; + + Log.Information("Stopping NDA recalculation worker"); + await _ndaRecalculationWorker.DisposeAsync(); + _ndaRecalculationWorker = null; + } + + async Task RecalculateNextDataAuthorityForAllAircraft() + { + var store = ServiceProvider.GetRequiredService(); + var connections = await store.All(CancellationToken.None); + + var ourAircraft = connections + .Where(c => c.StationId == ConnectionManager?.StationIdentifier && + c.DataAuthorityState == CPDLCServer.Contracts.DataAuthorityState.CurrentDataAuthority); + + foreach (var aircraft in ourAircraft) + { + var fdr = FDP2.GetFDRs.FirstOrDefault(f => f.Callsign == aircraft.Callsign); + if (fdr is null || !fdr.IsTrackedByMe) + continue; + + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new UpdateNextDataAuthorityRequest(fdr.Callsign, fdr.GetSectorEntries())); + } + } + + public static void AddError(Exception exception) + { + Log.Error(exception, "An error has occurred"); + TryAddErrorInternal(exception); + } + + public static void AddError(Exception exception, string message) + { + Log.Error(exception, message); + TryAddErrorInternal(exception); + } + + static void TryAddErrorInternal(Exception exception) + { + lock (ErrorMessages) + { + // Don't flood the error window with the same message over and over again + if (ErrorMessages.TryGetValue(exception.Message, out var lastShown) && + DateTimeOffset.Now - lastShown <= TimeSpan.FromMinutes(1)) + return; + + Errors.Add(exception, Name); + ErrorMessages[exception.Message] = DateTimeOffset.Now; + } + } + + void ConfigureTheme() + { + Theme.BackgroundColor = GetColour(Colours.Identities.WindowBackground); + Theme.GenericTextColor = GetColour(Colours.Identities.GenericText); + Theme.InteractiveTextColor = GetColour(Colours.Identities.InteractiveText); + Theme.NonInteractiveTextColor = GetColour(Colours.Identities.NonInteractiveText); + Theme.SelectedButtonColor = GetColour(Colours.Identities.WindowButtonSelected); + + Theme.CPDLCBackgroundColor = GetColour(Colours.Identities.CPDLCMessageBackground); + Theme.CPDLCUplinkColor = GetColour(Colours.Identities.CPDLCUplink); + Theme.CPDLCDownlinkColor = GetColour(Colours.Identities.CPDLCDownlink); + Theme.CPDLCSendBackgroundColor = GetColour(Colours.Identities.CPDLCSendButton); + Theme.CPDLCHotButtonBackgroundColor = GetColour(Colours.Identities.CPDLCSendButton); + + Theme.FontFamily = new FontFamily(MMI.eurofont_xsml.FontFamily.Name); + Theme.FontSize = MMI.eurofont_xsml.Size; + Theme.FontWeight = MMI.eurofont_xsml.Bold ? FontWeights.Bold : FontWeights.Regular; + + SolidColorBrush GetColour(Colours.Identities identity) + { + return new SolidColorBrush(Colours.GetColour(identity).ToWindowsColor()); + } + } + + ColourCache CacheLabelColours() + { + // Need to cache these for thread-safe access + + var downlinkColor = Theme.CPDLCDownlinkColor.Color; + var customDownlinkColor = new CustomColour(downlinkColor.R, downlinkColor.G, downlinkColor.B); + + var unableColor = Theme.CPDLCUnableDownlinkColor.Color; + var customUnableDownlinkColor = new CustomColour(unableColor.R, unableColor.G, unableColor.B); + + var suspendedColor = Theme.CPDLCSuspendedColor.Color; + var customSuspendedColor = new CustomColour(suspendedColor.R, suspendedColor.G, suspendedColor.B); + + return new ColourCache + { + DownlinkBackgroundColour = customDownlinkColor, + UnableBackgroundColour = customUnableDownlinkColor, + SuspendedForegroundColour = customSuspendedColor + }; + } + + void AddToolbarItems() + { + const string menuItemCategory = "CPDLC"; + + var setupMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("Setup")); + setupMenuItem.Item.Click += (_, _) => + { + _workQueue.Enqueue(async () => + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenSetupWindowRequest()); + }); + }; + + MMI.AddCustomMenuItem(setupMenuItem); + + var currentMessagesMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("Current Messages")); + currentMessagesMenuItem.Item.Click += (_, _) => + { + _workQueue.Enqueue(async () => + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: false)); + }); + }; + + MMI.AddCustomMenuItem(currentMessagesMenuItem); + + var historyMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("History")); + historyMenuItem.Item.Click += (_, _) => + { + _workQueue.Enqueue(async () => + { + var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; + + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenHistoryWindowRequest(selectedCallsign)); + }); + }; + + MMI.AddCustomMenuItem(historyMenuItem); + + var adsContractMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("ADS Contract")); + adsContractMenuItem.Item.Click += (_, _) => + { + _workQueue.Enqueue(async () => + { + var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; + + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenADSContractWindowRequest(selectedCallsign)); + }); + }; + + MMI.AddCustomMenuItem(adsContractMenuItem); + +#if DEBUG + var editorMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("CPDLC Editor")); + editorMenuItem.Item.Click += (_, _) => + { + _workQueue.Enqueue(async () => + { + var selectedCallsign = MMI.SelectedTrack?.GetFDR()?.Callsign; + if (selectedCallsign is null) + throw new InvalidOperationException("Select a track with a flight plan before you open the CPDLC Editor"); + + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenEditorWindowRequest(selectedCallsign)); + }); + }; + + MMI.AddCustomMenuItem(editorMenuItem); + + var fakeAdscReportMenuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + new ToolStripMenuItem("Fake ADS-C Report")); + fakeAdscReportMenuItem.Item.Click += (_, _) => FakeAdscReportPatch.Arm(); + + MMI.AddCustomMenuItem(fakeAdscReportMenuItem); +#endif + + if (_configuration?.ShowInstallationMenuItems ?? true) + { + var status = XmlInstaller.GetStatus(); + if (!string.IsNullOrEmpty(status.ErrorMessage)) + return; + + _labelsInstalled = status.IsInstalled; + + var toolStripItem = new ToolStripMenuItem(_labelsInstalled ? UninstallMenuLabel : InstallMenuLabel); + toolStripItem.Click += (_, _) => + { + if (_labelsInstalled) + RunUninstall(); + else + RunInstall(); + }; + + _installationMenuItem = toolStripItem; + + var menuItem = new CustomToolStripMenuItem( + CustomToolStripMenuItemWindowType.Main, + menuItemCategory, + toolStripItem); + MMI.AddCustomMenuItem(menuItem); + } + } + + void CheckXmlInstallation() + { + try + { + var status = XmlInstaller.GetStatus(); + if (!string.IsNullOrEmpty(status.ErrorMessage)) + { + Log.Warning("Could not verify Labels.xml/Strips.xml installation: {Error}", status.ErrorMessage); + return; + } + + if (!status.IsInstalled) + { + AddError(new InvalidOperationException("CPDLC Label and Strip items must be installed. Please install them from the CPDLC menu.")); + } + } + catch (Exception ex) + { + AddError(ex, "Failed to verify Labels.xml/Strips.xml installation"); + } + } + + void RunInstall() + { + try + { + var result = XmlInstaller.Install(); + if (result.Succeeded) + { + SetInstallationMenuState(installed: true); + System.Windows.Forms.MessageBox.Show( + "CPDLC label & strip items installed successfully.\n\nPlease restart vatSys to apply the changes.", + Name, + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + else + { + System.Windows.Forms.MessageBox.Show( + $"Failed to install CPDLC label & strip items.\n\n{result.ErrorMessage}", + Name, + MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + catch (Exception ex) + { + AddError(ex, "Failed to install label & strip items"); + } + } + + void SetInstallationMenuState(bool installed) + { + _labelsInstalled = installed; + if (_installationMenuItem is not null) + _installationMenuItem.Text = installed ? UninstallMenuLabel : InstallMenuLabel; + } + + void RunUninstall() + { + try + { + var result = XmlInstaller.Uninstall(); + if (result.Succeeded) + { + SetInstallationMenuState(installed: false); + System.Windows.Forms.MessageBox.Show( + "CPDLC label & strip items uninstalled successfully.\n\nPlease restart vatSys to apply the changes.", + Name, + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + else + { + System.Windows.Forms.MessageBox.Show( + $"Failed to uninstall CPDLC label & strip items.\n\n{result.ErrorMessage}", + Name, + MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + catch (Exception ex) + { + AddError(ex, "Failed to uninstall label & strip items"); + } + } + + public void OnFDRUpdate(FDP2.FDR updated) + { + try + { + // Record the last known owner of each FDR + _workQueue.Enqueue(async () => + { + Log.Verbose( + "{Callsign}: IsTracked {IsTracked}; IsTrackedByMe: {IsTrackedByMe}; Controller Tracking: {CurrentController}; Handoff Controller: {HandoffController}", + updated.Callsign, + updated.IsTracked, + updated.IsTrackedByMe, + updated.ControllerTracking?.Callsign, + updated.HandoffController?.Callsign); + + var jurisdictionChecker = ServiceProvider.GetRequiredService(); + + var previousRecord = jurisdictionChecker.GetOwnershipRecord(updated.Callsign); + jurisdictionChecker.RecordFdrOwner(updated.Callsign, updated.ControllerTracking?.Callsign); + + var record = jurisdictionChecker.GetOwnershipRecord(updated.Callsign); + + // Tell the Current Messages Window that the dialogues it must show can be different + if (previousRecord?.CurrentOwner != record?.CurrentOwner) + WeakReferenceMessenger.Default.Send(new FdrOwnerChanged(updated.Callsign)); + + if (record?.PreviousOwner != Network.Callsign) + return; + + // We were the previous owner, process the handoff + Log.Information("{Callsign} handoff to {NextController}", updated.Callsign, record.CurrentOwner); + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Publish(new HandoffCompletedNotification(updated.Callsign, record.CurrentOwner)); + }); + + // Ensure the next data authority is up-to-date + _workQueue.Enqueue(async () => + { + var handoffMediator = ServiceProvider.GetRequiredService(); + await handoffMediator.Send(new UpdateNextDataAuthorityRequest(updated.Callsign, updated.GetSectorEntries())); + }); + + // Re-build the CPDLC status label items + QueueLabelRebuild(); + + // If this flight has any dialogues that we have jurisdiction over, open the current messages window + // Ensures flights handed off to us open the window so we can see their requests + // A closed dialogue stays in the window until it is archived (e.g. a downlink that needs no response) + _workQueue.Enqueue(async () => + { + var store = ServiceProvider.GetRequiredService(); + var jurisdictionChecker = ServiceProvider.GetRequiredService(); + + var hasDialoguesToDisplay = (await store.All(CancellationToken.None)) + .Where(d => d.AircraftCallsign == updated.Callsign) + .Any(d => !d.IsArchived && jurisdictionChecker.ShouldDisplayDialogue(d)); + + // vatSys updates the FDRs often. If the window is open, do not post to the UI thread to open it again. + var windowManager = ServiceProvider.GetRequiredService(); + if (hasDialoguesToDisplay && !windowManager.IsWindowOpen(WindowKeys.CurrentMessages)) + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: true)); + } + }); + } + catch (Exception ex) + { + AddError(ex); + } + } + + public void OnRadarTrackUpdate(RDP.RadarTrack updated) {} + + public CustomLabelItem? GetCustomLabelItem( + string itemType, + Track track, + FDP2.FDR flightDataRecord, + RDP.RadarTrack radarTrack) + { + try + { + if (itemType.StartsWith("CPDLCPLUGIN_TEXTSTATUS")) + return _textStatusProvider.GetLabelItem(itemType, flightDataRecord); + + if (itemType.StartsWith("CPDLCPLUGIN_CPDLCSTATUS")) + return _cpdlcStatusProvider.GetLabelItem(itemType, flightDataRecord); + } + catch (Exception ex) + { + AddError(ex, "Failed to generate custom label item"); + } + + return null; + } + + public CustomStripItem? GetCustomStripItem( + string itemType, + Track track, + FDP2.FDR flightDataRecord, + RDP.RadarTrack radarTrack) + { + try + { + if (itemType.StartsWith("CPDLCPLUGIN_TEXTSTATUS")) + return _textStatusProvider.GetStripItem(itemType, flightDataRecord); + + if (itemType.StartsWith("CPDLCPLUGIN_CPDLCSTATUS")) + return _cpdlcStatusProvider.GetStripItem(itemType, flightDataRecord); + } + catch (Exception ex) + { + AddError(ex, "Failed to generate custom strip item"); + } + + return null; + } + + public CustomColour? SelectASDTrackColour(Track track) => null; + + public CustomColour? SelectGroundTrackColour(Track track) => null; + + // vatSys updates the FDRs often, and each rebuild reads all the FDRs. A rebuild reads the state when it runs. Thus, + // if a rebuild is already in the work queue, do not queue another one. + void QueueLabelRebuild() + { + if (Interlocked.Exchange(ref _isLabelRebuildQueued, 1) == 1) + return; + + _workQueue.Enqueue(() => + { + // Clear the flag before the rebuild reads the state. Then a change during the rebuild queues a new rebuild. + Interlocked.Exchange(ref _isLabelRebuildQueued, 0); + return RebuildCpdlcStatusLabelItems(); + }); + } + + async Task RebuildCpdlcStatusLabelItems(CancellationToken cancellationToken = default) + { + try + { + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new RebuildCpdlcStatusLabelItemsRequest(), cancellationToken); + } + catch (Exception ex) + { + AddError(ex); + } + } + + public void Receive(ConnectedAircraftChanged _) + { + try + { + QueueLabelRebuild(); + } + catch (Exception ex) + { + AddError(ex); + } + } + + public void Receive(DialogueChangedNotification dialogueChangedNotification) + { + try + { + // The rebuild is in the work queue before the next work item. Thus, the labels are rebuilt before the window + // opens. + QueueLabelRebuild(); + + _workQueue.Enqueue(async () => + { + // Try to open the Current Messages Window if this dialogue is relevant to the controller + var jurisdictionChecker = ServiceProvider.GetRequiredService(); + if (dialogueChangedNotification.Dialogue.IsArchived || + !jurisdictionChecker.ShouldDisplayDialogue(dialogueChangedNotification.Dialogue)) + { + return; + } + + // If the window is open, do not post to the UI thread to open and activate it again + var windowManager = ServiceProvider.GetRequiredService(); + if (windowManager.IsWindowOpen(WindowKeys.CurrentMessages)) + return; + + var mediator = ServiceProvider.GetRequiredService(); + await mediator.Send(new OpenCurrentMessagesWindowRequest(OpenedAutomatically: true)); + }); + } + catch (Exception ex) + { + AddError(ex); + } + } +} diff --git a/source/CPDLCPlugin/Server/AuthenticationState.cs b/source/CPDLCPlugin/Server/AuthenticationState.cs new file mode 100644 index 0000000..890e316 --- /dev/null +++ b/source/CPDLCPlugin/Server/AuthenticationState.cs @@ -0,0 +1,28 @@ +using CPDLCServer.Contracts; + +namespace CPDLCPlugin.Server; + +// The user that the plugin is authenticated as on a CPDLC server. The SETUP window shows it. +public class AuthenticationState +{ + readonly object _lock = new(); + Uri? _server; + PluginUserDto? _user; + + public PluginUserDto? GetUser(Uri server) + { + lock (_lock) + { + return _server == server ? _user : null; + } + } + + public void Set(Uri server, PluginUserDto? user) + { + lock (_lock) + { + _server = server; + _user = user; + } + } +} diff --git a/source/CPDLCPlugin/Server/PluginAuthenticator.cs b/source/CPDLCPlugin/Server/PluginAuthenticator.cs new file mode 100644 index 0000000..d15dcea --- /dev/null +++ b/source/CPDLCPlugin/Server/PluginAuthenticator.cs @@ -0,0 +1,245 @@ +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using CPDLCServer.Contracts; +using Serilog; + +namespace CPDLCPlugin.Server; + +/// +/// Gets a token from the CPDLC server with the browser (OAuth authorization code with PKCE and a loopback redirect). +/// The plugin opens the login page in the browser. After the login, the browser goes to a port on this computer with a +/// one-use code. Then the plugin changes the code for a token. +/// +public class PluginAuthenticator(ILogger logger) +{ + static readonly TimeSpan LoginTimeout = TimeSpan.FromMinutes(5); + static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + + readonly HttpClient _httpClient = CreateHttpClient(); + + public async Task Authenticate(Uri server, CancellationToken cancellationToken) + { + // A TcpListener does not need the URL reservation that an HttpListener needs + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + + try + { + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var redirectUri = $"http://127.0.0.1:{port}/callback"; + var codeVerifier = Base64Url(RandomBytes(32)); + var codeChallenge = Base64Url(Sha256(codeVerifier)); + var state = Base64Url(RandomBytes(16)); + + var authorizeUri = new Uri( + server, + "plugin/authorize" + + $"?redirect_uri={Uri.EscapeDataString(redirectUri)}" + + $"&state={state}" + + $"&code_challenge={codeChallenge}" + + "&code_challenge_method=S256"); + + logger.Information("Opening the browser to authenticate with {Server}", server); + Process.Start(new ProcessStartInfo(authorizeUri.ToString()) { UseShellExecute = true }); + + var code = await WaitForCode(listener, state, cancellationToken); + + logger.Information("Getting a token from {Server}", server); + var response = await _httpClient.PostAsync( + new Uri(server, "plugin/token"), + new FormUrlEncodedContent(new Dictionary + { + ["code"] = code, + ["code_verifier"] = codeVerifier, + ["redirect_uri"] = redirectUri + }), + cancellationToken); + + if (!response.IsSuccessStatusCode) + throw new Exception($"The CPDLC server did not give a token ({(int)response.StatusCode})"); + + var json = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(json, JsonOptions) + ?? throw new Exception("The CPDLC server sent an empty token"); + } + finally + { + listener.Stop(); + } + } + + // Returns null when the server does not accept the token + public async Task GetUser(Uri server, string token, CancellationToken cancellationToken) + { + using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(server, "plugin/me")); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + + using var response = await _httpClient.SendAsync(request, cancellationToken); + if (response.StatusCode == HttpStatusCode.Unauthorized) + return null; + + response.EnsureSuccessStatusCode(); + + var json = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(json, JsonOptions); + } + + public async Task Logout(Uri server, string token, CancellationToken cancellationToken) + { + using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(server, "plugin/logout")); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + + using var response = await _httpClient.SendAsync(request, cancellationToken); + + // The token is not valid any more, so it is already logged out + if (response.StatusCode == HttpStatusCode.Unauthorized) + return; + + response.EnsureSuccessStatusCode(); + } + + async Task WaitForCode(TcpListener listener, string expectedState, CancellationToken cancellationToken) + { + using var timeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeoutCancellationTokenSource.CancelAfter(LoginTimeout); + + // AcceptTcpClientAsync has no cancellation token in .NET Framework. Stopping the listener ends the wait. + using var _ = timeoutCancellationTokenSource.Token.Register(listener.Stop); + + while (true) + { + TcpClient client; + try + { + client = await listener.AcceptTcpClientAsync(); + } + catch (Exception ex) when ((ex is ObjectDisposedException or SocketException) && timeoutCancellationTokenSource.IsCancellationRequested) + { + cancellationToken.ThrowIfCancellationRequested(); + throw new TimeoutException("The authentication was not completed in 5 minutes"); + } + + using (client) + { + var stream = client.GetStream(); + var query = await ReadCallbackQuery(stream); + + // For example, the browser asks for /favicon.ico + if (query is null) + { + await WriteResponse(stream, "404 Not Found", "Not found."); + continue; + } + + query.TryGetValue("state", out var state); + query.TryGetValue("code", out var code); + + if (state != expectedState || string.IsNullOrEmpty(code)) + { + await WriteResponse(stream, "400 Bad Request", "The authentication failed. Try again from the SETUP window in vatSys."); + throw new Exception("The CPDLC server sent a response that is not valid"); + } + + await WriteResponse(stream, "200 OK", "The CPDLC plugin is authenticated. You can close this window and go back to vatSys."); + return code!; + } + } + } + + // Reads the request line, for example "GET /callback?code=...&state=... HTTP/1.1". + // Returns null when the request is not for the callback. + static async Task?> ReadCallbackQuery(Stream stream) + { + var reader = new StreamReader(stream, Encoding.ASCII, false, 1024, leaveOpen: true); + var requestLine = await reader.ReadLineAsync(); + + // Read the headers, so that the browser has sent all of the request before the response + string? header; + do + { + header = await reader.ReadLineAsync(); + } + while (!string.IsNullOrEmpty(header)); + + var parts = requestLine?.Split(' '); + if (parts is not { Length: 3 } || parts[0] != "GET") + return null; + + var target = parts[1]; + var queryStart = target.IndexOf('?'); + var path = queryStart < 0 ? target : target.Substring(0, queryStart); + if (path != "/callback" || queryStart < 0) + return null; + + var query = new Dictionary(); + foreach (var pair in target.Substring(queryStart + 1).Split('&')) + { + var separator = pair.IndexOf('='); + if (separator <= 0) + continue; + + var name = Uri.UnescapeDataString(pair.Substring(0, separator)); + var value = Uri.UnescapeDataString(pair.Substring(separator + 1).Replace('+', ' ')); + query[name] = value; + } + + return query; + } + + static async Task WriteResponse(Stream stream, string status, string message) + { + var body = "CPDLC plugin" + + "

" + WebUtility.HtmlEncode(message) + "

"; + var bodyBytes = Encoding.UTF8.GetBytes(body); + + var headers = $"HTTP/1.1 {status}\r\n" + + "Content-Type: text/html; charset=utf-8\r\n" + + $"Content-Length: {bodyBytes.Length}\r\n" + + "Connection: close\r\n\r\n"; + var headerBytes = Encoding.ASCII.GetBytes(headers); + + await stream.WriteAsync(headerBytes, 0, headerBytes.Length); + await stream.WriteAsync(bodyBytes, 0, bodyBytes.Length); + await stream.FlushAsync(); + } + + static byte[] RandomBytes(int count) + { + var bytes = new byte[count]; + using var random = RandomNumberGenerator.Create(); + random.GetBytes(bytes); + return bytes; + } + + static byte[] Sha256(string text) + { + using var sha256 = SHA256.Create(); + return sha256.ComputeHash(Encoding.ASCII.GetBytes(text)); + } + + static string Base64Url(byte[] bytes) + { + return Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } + + static HttpClient CreateHttpClient() + { +#if DEBUG + // In DEBUG mode, bypass SSL certificate validation for local development + var handler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (_, _, _, _) => true + }; + return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) }; +#else + return new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; +#endif + } +} diff --git a/source/CPDLCPlugin/Server/ServerAddress.cs b/source/CPDLCPlugin/Server/ServerAddress.cs new file mode 100644 index 0000000..65151a1 --- /dev/null +++ b/source/CPDLCPlugin/Server/ServerAddress.cs @@ -0,0 +1,14 @@ +namespace CPDLCPlugin.Server; + +public static class ServerAddress +{ + // The configuration has the URL of the hub, for example https://cpdlc.example.com/hubs/controller. + // The authentication endpoints are at the root of the same server. + public static Uri GetBaseUri(string serverEndpoint) + { + if (!Uri.TryCreate(serverEndpoint, UriKind.Absolute, out var endpoint)) + throw new ArgumentException($"The server URL {serverEndpoint} is not valid", nameof(serverEndpoint)); + + return new Uri(endpoint.GetLeftPart(UriPartial.Authority) + "/"); + } +} diff --git a/source/CPDLCPlugin/Server/SignalRConnectionManager.cs b/source/CPDLCPlugin/Server/SignalRConnectionManager.cs index 2080c49..5e592a9 100644 --- a/source/CPDLCPlugin/Server/SignalRConnectionManager.cs +++ b/source/CPDLCPlugin/Server/SignalRConnectionManager.cs @@ -1,415 +1,419 @@ -using CPDLCServer.Contracts; -using Microsoft.AspNetCore.SignalR.Client; -using Microsoft.Extensions.DependencyInjection; -using Serilog; - -namespace CPDLCPlugin.Server; - -// TODO: Register this in the IoC container - -/// -/// Manages the SignalR connection to the CPDLC server. -/// -public class SignalRConnectionManager( - string serverEndpoint, - IDownlinkHandlerDelegate downlinkHandlerDelegate, - ILogger logger) - : IDisposable -{ - HubConnection? _connection; - int _isDisposed; - bool _isStopping; - - /// - /// Gets the current connection state. - /// - public HubConnectionState ConnectionState => _connection?.State ?? HubConnectionState.Disconnected; - - /// - /// Gets whether the connection is currently active. - /// - public bool IsConnected => ConnectionState == HubConnectionState.Connected; - - public string ServerEndpoint { get; } = serverEndpoint; - public string StationIdentifier { get; set; } = string.Empty; - - /// - /// Initializes the SignalR connection. - /// - public async Task InitializeAsync(string stationId, string callsign) - { - if (_connection != null) - { - logger.Verbose("Disposing existing connection before re-initialization"); - await DisposeConnectionAsync(); - } - - var url = $"{ServerEndpoint}?callsign={callsign}&stationId={stationId}"; - logger.Verbose("Building SignalR connection to {Url}", url); - - var hubConnectionBuilder = new HubConnectionBuilder() - .WithUrl(url, options => - { -#if DEBUG - // In DEBUG mode, bypass SSL certificate validation for local development - options.HttpMessageHandlerFactory = _ => - { - var handler = new System.Net.Http.HttpClientHandler - { - ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true - }; - return handler; - }; -#endif - }) - .AddJsonProtocol() - .WithAutomaticReconnect(); - - _connection = hubConnectionBuilder.Build(); - - RegisterHandlers(); - RegisterConnectionEvents(); - - StationIdentifier = stationId; - } - - /// - /// Starts the connection to the server. - /// - public async Task StartAsync() - { - if (_connection == null) - { - throw new InvalidOperationException("Connection not initialized. Call InitializeAsync first."); - } - - if (_connection.State == HubConnectionState.Connected) - { - logger.Warning("Connection already active, skipping start"); - return; - } - - await _connection.StartAsync(); - OnConnectionStateChanged(HubConnectionState.Connected); - } - - /// - /// Stops the connection to the server. - /// - public async Task StopAsync() - { - var connection = _connection; - if (connection == null || connection.State == HubConnectionState.Disconnected) - { - logger.Warning("Connection already stopped or not initialized, skipping stop"); - return; - } - - await connection.StopAsync(); - OnConnectionStateChanged(HubConnectionState.Disconnected); - } - - void RegisterHandlers() - { - if (_connection == null) return; - - logger.Verbose("Registering SignalR message handlers"); - _connection.On("DialogueChanged", downlink => - WithCancellationToken(downlinkHandlerDelegate.DialogueChanged)(downlink)); - _connection.On("AircraftConnectionUpdated", connectedAircraftInfo => - WithCancellationToken(downlinkHandlerDelegate.AircraftConnectionUpdated)(connectedAircraftInfo)); - _connection.On("AircraftConnectionRemoved", (callsign, stationId) => - WithCancellationToken(downlinkHandlerDelegate.AircraftConnectionRemoved)(callsign, stationId)); - _connection.On("AcarsStationsUpdated", callsigns => - WithCancellationToken(downlinkHandlerDelegate.AcarsStationsUpdated)(callsigns)); - _connection.On("AdscContractUpdated", adscContract => - WithCancellationToken(downlinkHandlerDelegate.AdscContractUpdated)(adscContract)); - _connection.On("AdscContractRemoved", (callsign, stationId) => - WithCancellationToken(downlinkHandlerDelegate.AdscContractRemoved)(callsign, stationId)); - _connection.On("AdscReportReceived", adscReport => - WithCancellationToken(downlinkHandlerDelegate.AdscReportReceived)(adscReport)); - _connection.On("AdscReportExpired", (callsign, stationId) => - WithCancellationToken(downlinkHandlerDelegate.AdscReportExpired)(callsign, stationId)); - } - - Func WithCancellationToken(Func action) - { - // TODO: Make configurable - return async x => - { - using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - await action(x, cancellationTokenSource.Token); - }; - } - - Func WithCancellationToken(Func action) - { - // TODO: Make configurable - return async (x, y) => - { - using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - await action(x, y, cancellationTokenSource.Token); - }; - } - - public async Task BeginDialogue(string recipient, - CpdlcUplinkResponseType responseType, - string content, - CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "BeginDialogue", - recipient, - responseType, - content, - cancellationToken: cancellationToken); - } - - public async Task ReplyToDownlink(Guid dialogueId, - int downlinkMessageId, - CpdlcUplinkResponseType responseType, - string content, - CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "ReplyToDownlink", - dialogueId, - downlinkMessageId, - responseType, - content, - cancellationToken: cancellationToken); - } - - public async Task RequestConnection(string callsign, string stationId, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "RequestConnection", - callsign, - stationId, - cancellationToken); - } - - public async Task GetConnectedAircraft(CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - return await connection.InvokeAsync( - "GetConnectedAircraft", - cancellationToken); - } - - public async Task GetAcarsStations(CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - return await connection.InvokeAsync( - "GetAcarsStations", - cancellationToken); - } - - public async Task AcknowledgeDownlink(Guid dialogueId, int downlinkMessageId, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "AcknowledgeDownlink", - dialogueId, - downlinkMessageId, - cancellationToken); - } - - public async Task AcknowledgeUplink(Guid dialogueId, int uplinkMessageId, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "AcknowledgeUplink", - dialogueId, - uplinkMessageId, - cancellationToken); - } - - public async Task ArchiveDialogue(Guid dialogueId, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync("ArchiveDialogue", dialogueId, cancellationToken); - } - - public async Task UpdateNextDataAuthority( - string callsign, - string? nextDataAuthority, - DateTimeOffset? expectedTransferTime, - CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "UpdateNextDataAuthority", - callsign, - nextDataAuthority, - expectedTransferTime, - cancellationToken: cancellationToken); - } - - // The default reporting interval of the ATSU requests the default contract. Any other interval requests a selected contract. - public async Task RequestPeriodicAdscContract( - string callsign, - TimeSpan reportingInterval, - CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync( - "RequestPeriodicAdscContract", - callsign, - reportingInterval, - cancellationToken: cancellationToken); - } - - public async Task RequestAdscDemandReport(string callsign, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync("RequestAdscDemandReport", callsign, cancellationToken); - } - - public async Task CancelAdscContract(string callsign, CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - await connection.InvokeAsync("CancelAdscContract", callsign, cancellationToken); - } - - public async Task GetAdscContracts(CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - return await connection.InvokeAsync( - "GetAdscContracts", - cancellationToken); - } - - public async Task GetAdscReports(CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - return await connection.InvokeAsync( - "GetAdscReports", - cancellationToken); - } - - public async Task GetAllDialogues(CancellationToken cancellationToken) - { - var connection = GetConnectedOrThrow(); - return await connection.InvokeAsync( - "GetAllDialogues", - cancellationToken); - } - - /// - /// Registers connection lifecycle event handlers. - /// - void RegisterConnectionEvents() - { - if (_connection == null) return; - - logger.Verbose("Registering SignalR connection lifecycle event handlers"); - - _connection.Closed += error => - { - if (error != null) - { - if (_isStopping) - { - logger.Verbose(error, "SignalR connection closed with error during intentional stop"); - } - else - { - logger.Warning(error, "SignalR connection closed with error"); - OnConnectionError(error); - } - } - else - { - logger.Verbose("SignalR connection closed"); - } - - OnConnectionStateChanged(HubConnectionState.Disconnected); - return Task.CompletedTask; - }; - - _connection.Reconnecting += error => - { - if (error != null) - { - logger.Warning(error, "SignalR connection lost, attempting to reconnect"); - } - else - { - logger.Information("SignalR connection reconnecting"); - } - - OnConnectionStateChanged(HubConnectionState.Reconnecting); - return Task.CompletedTask; - }; - - _connection.Reconnected += connectionId => - { - logger.Information("SignalR connection reconnected successfully (ConnectionId: {ConnectionId})", connectionId); - OnConnectionStateChanged(HubConnectionState.Connected); - return Task.CompletedTask; - }; - } - - void OnConnectionStateChanged(HubConnectionState newState) - { - logger.Verbose("Connection state changed to {State}", newState); - } - - void OnConnectionError(Exception error) - { - logger.Error(error, "SignalR connection error occurred"); - downlinkHandlerDelegate.Error(error); - } - - HubConnection GetConnectedOrThrow() - { - var connection = _connection ?? throw new InvalidOperationException("Connection not initialized. Call InitializeAsync first."); - if (connection.State != HubConnectionState.Connected) - { - throw new InvalidOperationException($"Connection is not active. Current state: {connection.State}"); - } - - return connection; - } - - public void Dispose() - { - if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) != 0) return; - - logger.Verbose("Disposing SignalR connection manager"); - DisposeConnectionAsync().GetAwaiter().GetResult(); - logger.Verbose("SignalR connection manager disposed"); - GC.SuppressFinalize(this); - } - - async Task DisposeConnectionAsync() - { - if (_connection != null) - { - try - { - if (_connection.State != HubConnectionState.Disconnected) - { - logger.Verbose("Stopping connection during disposal"); - _isStopping = true; - await _connection.StopAsync(); - } - } - catch (Exception ex) - { - logger.Verbose(ex, "Error stopping connection during disposal (ignoring)"); - // Ignore errors during disposal - } - finally - { - _isStopping = false; - await _connection.DisposeAsync(); - _connection = null; - } - } - } -} +using CPDLCServer.Contracts; +using Microsoft.AspNetCore.SignalR.Client; +using Microsoft.Extensions.DependencyInjection; +using Serilog; + +namespace CPDLCPlugin.Server; + +// TODO: Register this in the IoC container + +/// +/// Manages the SignalR connection to the CPDLC server. +/// +public class SignalRConnectionManager( + string serverEndpoint, + string accessToken, + IDownlinkHandlerDelegate downlinkHandlerDelegate, + ILogger logger) + : IDisposable +{ + HubConnection? _connection; + int _isDisposed; + bool _isStopping; + + /// + /// Gets the current connection state. + /// + public HubConnectionState ConnectionState => _connection?.State ?? HubConnectionState.Disconnected; + + /// + /// Gets whether the connection is currently active. + /// + public bool IsConnected => ConnectionState == HubConnectionState.Connected; + + public string ServerEndpoint { get; } = serverEndpoint; + public string StationIdentifier { get; set; } = string.Empty; + + /// + /// Initializes the SignalR connection. + /// + public async Task InitializeAsync(string stationId, string callsign) + { + if (_connection != null) + { + logger.Verbose("Disposing existing connection before re-initialization"); + await DisposeConnectionAsync(); + } + + var url = $"{ServerEndpoint}?callsign={callsign}&stationId={stationId}"; + logger.Verbose("Building SignalR connection to {Url}", url); + + var hubConnectionBuilder = new HubConnectionBuilder() + .WithUrl(url, options => + { + // The server accepts only an authenticated plugin + options.AccessTokenProvider = () => Task.FromResult(accessToken); + +#if DEBUG + // In DEBUG mode, bypass SSL certificate validation for local development + options.HttpMessageHandlerFactory = _ => + { + var handler = new System.Net.Http.HttpClientHandler + { + ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true + }; + return handler; + }; +#endif + }) + .AddJsonProtocol() + .WithAutomaticReconnect(); + + _connection = hubConnectionBuilder.Build(); + + RegisterHandlers(); + RegisterConnectionEvents(); + + StationIdentifier = stationId; + } + + /// + /// Starts the connection to the server. + /// + public async Task StartAsync() + { + if (_connection == null) + { + throw new InvalidOperationException("Connection not initialized. Call InitializeAsync first."); + } + + if (_connection.State == HubConnectionState.Connected) + { + logger.Warning("Connection already active, skipping start"); + return; + } + + await _connection.StartAsync(); + OnConnectionStateChanged(HubConnectionState.Connected); + } + + /// + /// Stops the connection to the server. + /// + public async Task StopAsync() + { + var connection = _connection; + if (connection == null || connection.State == HubConnectionState.Disconnected) + { + logger.Warning("Connection already stopped or not initialized, skipping stop"); + return; + } + + await connection.StopAsync(); + OnConnectionStateChanged(HubConnectionState.Disconnected); + } + + void RegisterHandlers() + { + if (_connection == null) return; + + logger.Verbose("Registering SignalR message handlers"); + _connection.On("DialogueChanged", downlink => + WithCancellationToken(downlinkHandlerDelegate.DialogueChanged)(downlink)); + _connection.On("AircraftConnectionUpdated", connectedAircraftInfo => + WithCancellationToken(downlinkHandlerDelegate.AircraftConnectionUpdated)(connectedAircraftInfo)); + _connection.On("AircraftConnectionRemoved", (callsign, stationId) => + WithCancellationToken(downlinkHandlerDelegate.AircraftConnectionRemoved)(callsign, stationId)); + _connection.On("AcarsStationsUpdated", callsigns => + WithCancellationToken(downlinkHandlerDelegate.AcarsStationsUpdated)(callsigns)); + _connection.On("AdscContractUpdated", adscContract => + WithCancellationToken(downlinkHandlerDelegate.AdscContractUpdated)(adscContract)); + _connection.On("AdscContractRemoved", (callsign, stationId) => + WithCancellationToken(downlinkHandlerDelegate.AdscContractRemoved)(callsign, stationId)); + _connection.On("AdscReportReceived", adscReport => + WithCancellationToken(downlinkHandlerDelegate.AdscReportReceived)(adscReport)); + _connection.On("AdscReportExpired", (callsign, stationId) => + WithCancellationToken(downlinkHandlerDelegate.AdscReportExpired)(callsign, stationId)); + } + + Func WithCancellationToken(Func action) + { + // TODO: Make configurable + return async x => + { + using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await action(x, cancellationTokenSource.Token); + }; + } + + Func WithCancellationToken(Func action) + { + // TODO: Make configurable + return async (x, y) => + { + using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await action(x, y, cancellationTokenSource.Token); + }; + } + + public async Task BeginDialogue(string recipient, + CpdlcUplinkResponseType responseType, + string content, + CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "BeginDialogue", + recipient, + responseType, + content, + cancellationToken: cancellationToken); + } + + public async Task ReplyToDownlink(Guid dialogueId, + int downlinkMessageId, + CpdlcUplinkResponseType responseType, + string content, + CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "ReplyToDownlink", + dialogueId, + downlinkMessageId, + responseType, + content, + cancellationToken: cancellationToken); + } + + public async Task RequestConnection(string callsign, string stationId, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "RequestConnection", + callsign, + stationId, + cancellationToken); + } + + public async Task GetConnectedAircraft(CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + return await connection.InvokeAsync( + "GetConnectedAircraft", + cancellationToken); + } + + public async Task GetAcarsStations(CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + return await connection.InvokeAsync( + "GetAcarsStations", + cancellationToken); + } + + public async Task AcknowledgeDownlink(Guid dialogueId, int downlinkMessageId, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "AcknowledgeDownlink", + dialogueId, + downlinkMessageId, + cancellationToken); + } + + public async Task AcknowledgeUplink(Guid dialogueId, int uplinkMessageId, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "AcknowledgeUplink", + dialogueId, + uplinkMessageId, + cancellationToken); + } + + public async Task ArchiveDialogue(Guid dialogueId, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync("ArchiveDialogue", dialogueId, cancellationToken); + } + + public async Task UpdateNextDataAuthority( + string callsign, + string? nextDataAuthority, + DateTimeOffset? expectedTransferTime, + CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "UpdateNextDataAuthority", + callsign, + nextDataAuthority, + expectedTransferTime, + cancellationToken: cancellationToken); + } + + // The default reporting interval of the ATSU requests the default contract. Any other interval requests a selected contract. + public async Task RequestPeriodicAdscContract( + string callsign, + TimeSpan reportingInterval, + CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync( + "RequestPeriodicAdscContract", + callsign, + reportingInterval, + cancellationToken: cancellationToken); + } + + public async Task RequestAdscDemandReport(string callsign, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync("RequestAdscDemandReport", callsign, cancellationToken); + } + + public async Task CancelAdscContract(string callsign, CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + await connection.InvokeAsync("CancelAdscContract", callsign, cancellationToken); + } + + public async Task GetAdscContracts(CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + return await connection.InvokeAsync( + "GetAdscContracts", + cancellationToken); + } + + public async Task GetAdscReports(CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + return await connection.InvokeAsync( + "GetAdscReports", + cancellationToken); + } + + public async Task GetAllDialogues(CancellationToken cancellationToken) + { + var connection = GetConnectedOrThrow(); + return await connection.InvokeAsync( + "GetAllDialogues", + cancellationToken); + } + + /// + /// Registers connection lifecycle event handlers. + /// + void RegisterConnectionEvents() + { + if (_connection == null) return; + + logger.Verbose("Registering SignalR connection lifecycle event handlers"); + + _connection.Closed += error => + { + if (error != null) + { + if (_isStopping) + { + logger.Verbose(error, "SignalR connection closed with error during intentional stop"); + } + else + { + logger.Warning(error, "SignalR connection closed with error"); + OnConnectionError(error); + } + } + else + { + logger.Verbose("SignalR connection closed"); + } + + OnConnectionStateChanged(HubConnectionState.Disconnected); + return Task.CompletedTask; + }; + + _connection.Reconnecting += error => + { + if (error != null) + { + logger.Warning(error, "SignalR connection lost, attempting to reconnect"); + } + else + { + logger.Information("SignalR connection reconnecting"); + } + + OnConnectionStateChanged(HubConnectionState.Reconnecting); + return Task.CompletedTask; + }; + + _connection.Reconnected += connectionId => + { + logger.Information("SignalR connection reconnected successfully (ConnectionId: {ConnectionId})", connectionId); + OnConnectionStateChanged(HubConnectionState.Connected); + return Task.CompletedTask; + }; + } + + void OnConnectionStateChanged(HubConnectionState newState) + { + logger.Verbose("Connection state changed to {State}", newState); + } + + void OnConnectionError(Exception error) + { + logger.Error(error, "SignalR connection error occurred"); + downlinkHandlerDelegate.Error(error); + } + + HubConnection GetConnectedOrThrow() + { + var connection = _connection ?? throw new InvalidOperationException("Connection not initialized. Call InitializeAsync first."); + if (connection.State != HubConnectionState.Connected) + { + throw new InvalidOperationException($"Connection is not active. Current state: {connection.State}"); + } + + return connection; + } + + public void Dispose() + { + if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) != 0) return; + + logger.Verbose("Disposing SignalR connection manager"); + DisposeConnectionAsync().GetAwaiter().GetResult(); + logger.Verbose("SignalR connection manager disposed"); + GC.SuppressFinalize(this); + } + + async Task DisposeConnectionAsync() + { + if (_connection != null) + { + try + { + if (_connection.State != HubConnectionState.Disconnected) + { + logger.Verbose("Stopping connection during disposal"); + _isStopping = true; + await _connection.StopAsync(); + } + } + catch (Exception ex) + { + logger.Verbose(ex, "Error stopping connection during disposal (ignoring)"); + // Ignore errors during disposal + } + finally + { + _isStopping = false; + await _connection.DisposeAsync(); + _connection = null; + } + } + } +} diff --git a/source/CPDLCPlugin/Server/TokenStore.cs b/source/CPDLCPlugin/Server/TokenStore.cs new file mode 100644 index 0000000..92ccd09 --- /dev/null +++ b/source/CPDLCPlugin/Server/TokenStore.cs @@ -0,0 +1,70 @@ +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using vatsys; + +namespace CPDLCPlugin.Server; + +/// +/// Keeps the token for each CPDLC server, so that the user does not have to authenticate each time that vatSys starts. +/// The tokens are encrypted with the Windows account of the user (DPAPI), so a different account cannot read them. +/// +public class TokenStore +{ + readonly string _filePath = Path.Combine(Helpers.GetFilesFolder(), "cpdlc_tokens.json"); + readonly object _lock = new(); + + public string? Get(Uri server) + { + lock (_lock) + { + var tokens = Load(); + if (!tokens.TryGetValue(Key(server), out var encryptedToken)) + return null; + + try + { + var bytes = ProtectedData.Unprotect(Convert.FromBase64String(encryptedToken), null, DataProtectionScope.CurrentUser); + return Encoding.UTF8.GetString(bytes); + } + catch (CryptographicException) + { + // A different Windows account encrypted the token + return null; + } + } + } + + public void Save(Uri server, string token) + { + lock (_lock) + { + var tokens = Load(); + var bytes = ProtectedData.Protect(Encoding.UTF8.GetBytes(token), null, DataProtectionScope.CurrentUser); + tokens[Key(server)] = Convert.ToBase64String(bytes); + File.WriteAllText(_filePath, JsonSerializer.Serialize(tokens)); + } + } + + public void Delete(Uri server) + { + lock (_lock) + { + var tokens = Load(); + if (tokens.Remove(Key(server))) + File.WriteAllText(_filePath, JsonSerializer.Serialize(tokens)); + } + } + + Dictionary Load() + { + if (!File.Exists(_filePath)) + return new Dictionary(); + + return JsonSerializer.Deserialize>(File.ReadAllText(_filePath)) + ?? new Dictionary(); + } + + static string Key(Uri server) => server.GetLeftPart(UriPartial.Authority).ToLowerInvariant(); +} diff --git a/source/CPDLCPlugin/ViewModels/SetupViewModel.cs b/source/CPDLCPlugin/ViewModels/SetupViewModel.cs index acf507e..c5d8885 100644 --- a/source/CPDLCPlugin/ViewModels/SetupViewModel.cs +++ b/source/CPDLCPlugin/ViewModels/SetupViewModel.cs @@ -2,27 +2,36 @@ using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Messaging; using CPDLCPlugin.Messages; +using CPDLCPlugin.Server; using MediatR; namespace CPDLCPlugin.ViewModels; public partial class SetupViewModel : ObservableObject, IRecipient, - IRecipient + IRecipient, + IRecipient { readonly IMediator _mediator; readonly IErrorReporter _errorReporter; readonly IWindowHandle _windowHandle; + readonly AuthenticationState _authenticationState; + readonly IGuiInvoker _guiInvoker; [ObservableProperty] string serverEndpoint; [ObservableProperty] string[] availableStationIdentifiers; [ObservableProperty] string selectedStationIdentifier; [ObservableProperty] bool connected; + [ObservableProperty] bool authenticated; + [ObservableProperty] string authenticationStatus = string.Empty; + [ObservableProperty] bool authenticating; public SetupViewModel( IMediator mediator, IErrorReporter errorReporter, IWindowHandle windowHandle, + AuthenticationState authenticationState, + IGuiInvoker guiInvoker, string serverEndpoint, string[] availableStationIdentifiers, string selectedStationIdentifier, @@ -31,14 +40,18 @@ public SetupViewModel( _mediator = mediator; _errorReporter = errorReporter; _windowHandle = windowHandle; + _authenticationState = authenticationState; + _guiInvoker = guiInvoker; ServerEndpoint = serverEndpoint; AvailableStationIdentifiers = availableStationIdentifiers; SelectedStationIdentifier = selectedStationIdentifier; Connected = connected; + UpdateAuthenticationStatus(); // Register for connection notifications WeakReferenceMessenger.Default.Register(this); WeakReferenceMessenger.Default.Register(this); + WeakReferenceMessenger.Default.Register(this); } [RelayCommand] @@ -61,12 +74,65 @@ async Task ConnectOrDisconnect() } } + [RelayCommand] + async Task AuthenticateOrLogOut() + { + try + { + Authenticating = true; + + if (Authenticated) + { + await _mediator.Send(new LogOutRequest(ServerEndpoint)); + } + else + { + await _mediator.Send(new AuthenticateRequest(ServerEndpoint)); + } + } + catch (Exception e) + { + _errorReporter.ReportError(e); + } + finally + { + Authenticating = false; + } + } + [RelayCommand] void Close() { _windowHandle.Close(); } + // The status is for the server in the text box, so it changes when the URL changes + partial void OnServerEndpointChanged(string value) + { + UpdateAuthenticationStatus(); + } + + void UpdateAuthenticationStatus() + { + Uri server; + try + { + server = ServerAddress.GetBaseUri(ServerEndpoint); + } + catch (ArgumentException) + { + Authenticated = false; + AuthenticationStatus = "The server URL is not valid"; + return; + } + + var user = _authenticationState.GetUser(server); + Authenticated = user is not null; + AuthenticationStatus = user is null + ? "Not authenticated" + : $"Authenticated as {user.Name} ({user.Cid})"; + } + public void Receive(ConnectedNotification message) { Connected = true; @@ -76,4 +142,10 @@ public void Receive(DisconnectedNotification message) { Connected = false; } + + // The notification can come from a background thread + public void Receive(AuthenticationChangedNotification message) + { + _guiInvoker.InvokeOnGUI(_ => UpdateAuthenticationStatus()); + } } diff --git a/source/CPDLCPlugin/Windows/SetupView.xaml b/source/CPDLCPlugin/Windows/SetupView.xaml index b7b8eac..2fb3d24 100644 --- a/source/CPDLCPlugin/Windows/SetupView.xaml +++ b/source/CPDLCPlugin/Windows/SetupView.xaml @@ -51,6 +51,39 @@ IsEnabled="{Binding Connected, Converter={StaticResource BoolInversionConverter}}"/> + + + + + + + + + + + + @@ -65,21 +98,6 @@ SelectedItem="{Binding SelectedStationIdentifier}"/> - - - - - - - - - - - - - - - diff --git a/source/CPDLCServer.Contracts/AcarsMessages.cs b/source/CPDLCServer.Contracts/AcarsMessages.cs index d59c399..0215a96 100644 --- a/source/CPDLCServer.Contracts/AcarsMessages.cs +++ b/source/CPDLCServer.Contracts/AcarsMessages.cs @@ -146,3 +146,8 @@ public class DownlinkMessageDto : CpdlcMessageDto } + +// Plugin authentication DTOs +public record PluginTokenResponse(string AccessToken, DateTimeOffset Expires, int Cid, string Name); + +public record PluginUserDto(int Cid, string Name, DateTimeOffset Expires); diff --git a/source/CPDLCServer.Tests/AcarsConnections/Hoppie/HoppieAcarsConnectionTests.cs b/source/CPDLCServer.Tests/AcarsConnections/Hoppie/HoppieAcarsConnectionTests.cs index 6484d73..f49056a 100644 --- a/source/CPDLCServer.Tests/AcarsConnections/Hoppie/HoppieAcarsConnectionTests.cs +++ b/source/CPDLCServer.Tests/AcarsConnections/Hoppie/HoppieAcarsConnectionTests.cs @@ -1,6 +1,7 @@ using System.Net; using CPDLCServer.AcarsConnections; using CPDLCServer.AcarsConnections.Hoppie; +using CPDLCServer.AcarsConnections.Traffic; using CPDLCServer.AdscContracts; using CPDLCServer.AdscContracts.MessageLog; using CPDLCServer.Cpdlc.Dialogues; @@ -23,6 +24,7 @@ public class HoppieAcarsConnectionTests : IDisposable private readonly List _connections = new(); private readonly TestAdscMessageLogRepository _adscMessageLogRepository = new(); + private readonly AcarsTrafficLog _trafficLog = new(); public void Dispose() { @@ -51,6 +53,7 @@ private HoppieAcarsConnection CreateConnection(TestHttpMessageHandler httpHandle httpClient, clock ?? new TestClock(), _adscMessageLogRepository, + _trafficLog, Logger.None); _connections.Add(connection); return connection; diff --git a/source/CPDLCServer.Tests/AcarsConnections/Traffic/AcarsTrafficLogTests.cs b/source/CPDLCServer.Tests/AcarsConnections/Traffic/AcarsTrafficLogTests.cs new file mode 100644 index 0000000..b52db51 --- /dev/null +++ b/source/CPDLCServer.Tests/AcarsConnections/Traffic/AcarsTrafficLogTests.cs @@ -0,0 +1,85 @@ +using CPDLCServer.AcarsConnections.Traffic; + +namespace CPDLCServer.Tests.AcarsConnections.Traffic; + +public class AcarsTrafficLogTests +{ + [Fact] + public void Get_ReturnsTheNewestEntriesFirst() + { + // Arrange + var trafficLog = new AcarsTrafficLog(); + + // Act + trafficLog.Add("Hoppies/YBBB", CreateEntry("first")); + trafficLog.Add("Hoppies/YBBB", CreateEntry("second")); + + // Assert + Assert.Equal(["second", "first"], trafficLog.Get("Hoppies/YBBB").Select(e => e.Response)); + } + + [Fact] + public void Add_KeepsOnlyTheMostRecentEntriesOfEachConnection() + { + // Arrange + var trafficLog = new AcarsTrafficLog(capacity: 2); + + // Act + trafficLog.Add("Hoppies/YBBB", CreateEntry("first")); + trafficLog.Add("Hoppies/YBBB", CreateEntry("second")); + trafficLog.Add("Hoppies/YBBB", CreateEntry("third")); + trafficLog.Add("Hoppies/YMMM", CreateEntry("other")); + + // Assert + Assert.Equal(["third", "second"], trafficLog.Get("Hoppies/YBBB").Select(e => e.Response)); + Assert.Equal(["other"], trafficLog.Get("Hoppies/YMMM").Select(e => e.Response)); + } + + [Fact] + public void Get_WhenNoTraffic_ReturnsNoEntries() + { + // Arrange + var trafficLog = new AcarsTrafficLog(); + + // Act & Assert + Assert.Empty(trafficLog.Get("Hoppies/YBBB")); + } + + [Fact] + public void FormatRequest_ReplacesTheAuthenticationCode() + { + // Arrange + var fields = new Dictionary + { + ["logon"] = "SECRET123", + ["from"] = "YBBB", + ["type"] = "poll" + }; + + // Act + var request = AcarsTrafficLog.FormatRequest(fields); + + // Assert + Assert.DoesNotContain("SECRET123", request); + Assert.Equal($"logon={AcarsTrafficLog.RedactedValue}\nfrom=YBBB\ntype=poll", request); + } + + [Theory] + [InlineData("poll", "ok", null, true)] + [InlineData("poll", "ok {UAL123 cpdlc {/data2/1//Y/REQUEST DESCENT}}", null, false)] + [InlineData("poll", null, "Timeout", false)] + [InlineData("cpdlc", "ok", null, false)] + public void IsEmptyPoll_IsTrueOnlyForAPollWithNoMessages(string type, string? response, string? error, bool expected) + { + // Arrange + var entry = new AcarsTrafficEntry(DateTimeOffset.UtcNow, type, "type=poll", 200, response, TimeSpan.Zero, error); + + // Act & Assert + Assert.Equal(expected, entry.IsEmptyPoll); + } + + static AcarsTrafficEntry CreateEntry(string response) + { + return new AcarsTrafficEntry(DateTimeOffset.UtcNow, "poll", "type=poll", 200, response, TimeSpan.Zero, null); + } +} diff --git a/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs index 8b3e036..466a5d2 100644 --- a/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/AdscContracts/Reports/AdscReportReceivedNotificationHandlerTests.cs @@ -17,10 +17,10 @@ public async Task Handle_NotifiesAllConnectedControllers() // Arrange var controllerRepository = new TestControllerRepository(); await controllerRepository.Add( - new ControllerInfo(Guid.NewGuid(), "ConnectionId-1", "YBBB", "BN-TSN_FSS"), + new ControllerInfo(Guid.NewGuid(), "ConnectionId-1", "YBBB", "BN-TSN_FSS", 1234567, "Test Controller"), CancellationToken.None); await controllerRepository.Add( - new ControllerInfo(Guid.NewGuid(), "ConnectionId-2", "YMMM", "ML-ASP_CTR"), + new ControllerInfo(Guid.NewGuid(), "ConnectionId-2", "YMMM", "ML-ASP_CTR", 1234567, "Test Controller"), CancellationToken.None); var hubContext = Substitute.For>(); diff --git a/source/CPDLCServer.Tests/Auth/Administrators/AdministratorCommandHandlerTests.cs b/source/CPDLCServer.Tests/Auth/Administrators/AdministratorCommandHandlerTests.cs new file mode 100644 index 0000000..d6e6535 --- /dev/null +++ b/source/CPDLCServer.Tests/Auth/Administrators/AdministratorCommandHandlerTests.cs @@ -0,0 +1,132 @@ +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Setup; +using CPDLCServer.Tests.Mocks; +using Microsoft.Extensions.DependencyInjection; +using Serilog.Core; + +namespace CPDLCServer.Tests.Auth.Administrators; + +public class AdministratorCommandHandlerTests +{ + readonly TestAdministratorRepository _administratorRepository = new(); + readonly TestClock _clock = new(); + + [Fact] + public async Task Add_AddsTheAdministrator() + { + // Arrange + var handler = new AddAdministratorCommandHandler(_administratorRepository, _clock, new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new AddAdministratorCommand(1234567), CancellationToken.None); + + // Assert + var administrator = await _administratorRepository.FindByCid(1234567, CancellationToken.None); + Assert.NotNull(administrator); + Assert.Null(administrator.Name); + Assert.Equal(_clock.UtcNow(), administrator.Added); + } + + [Fact] + public async Task Add_WhenAlreadyAdministrator_Throws() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = 1234567 }, CancellationToken.None); + var handler = new AddAdministratorCommandHandler(_administratorRepository, _clock, new TestUnitOfWork(), Logger.None); + + // Act & Assert + await Assert.ThrowsAsync(() => + handler.Handle(new AddAdministratorCommand(1234567), CancellationToken.None)); + } + + [Fact] + public async Task Remove_RemovesTheAdministrator() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = 1111111 }, CancellationToken.None); + await _administratorRepository.Add(new Administrator { Cid = 2222222 }, CancellationToken.None); + var handler = new RemoveAdministratorCommandHandler(_administratorRepository, new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new RemoveAdministratorCommand(2222222, CurrentUserCid: 1111111), CancellationToken.None); + + // Assert + Assert.Null(await _administratorRepository.FindByCid(2222222, CancellationToken.None)); + } + + [Fact] + public async Task Remove_Yourself_Throws() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = 1111111 }, CancellationToken.None); + await _administratorRepository.Add(new Administrator { Cid = 2222222 }, CancellationToken.None); + var handler = new RemoveAdministratorCommandHandler(_administratorRepository, new TestUnitOfWork(), Logger.None); + + // Act & Assert + await Assert.ThrowsAsync(() => + handler.Handle(new RemoveAdministratorCommand(1111111, CurrentUserCid: 1111111), CancellationToken.None)); + Assert.NotNull(await _administratorRepository.FindByCid(1111111, CancellationToken.None)); + } + + [Fact] + public async Task Remove_LastAdministrator_Throws() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = 1111111 }, CancellationToken.None); + var handler = new RemoveAdministratorCommandHandler(_administratorRepository, new TestUnitOfWork(), Logger.None); + + // Act & Assert + await Assert.ThrowsAsync(() => + handler.Handle(new RemoveAdministratorCommand(1111111, CurrentUserCid: 9999999), CancellationToken.None)); + } + + [Fact] + public async Task CreateFirst_AddsTheAdministratorAndCompletesTheSetup() + { + // Arrange + var setupState = CreateSetupState(); + var handler = new CreateFirstAdministratorCommandHandler(_administratorRepository, setupState, _clock, new TestUnitOfWork(), Logger.None); + + // Act + await handler.Handle(new CreateFirstAdministratorCommand(1234567), CancellationToken.None); + + // Assert + Assert.NotNull(await _administratorRepository.FindByCid(1234567, CancellationToken.None)); + Assert.True(setupState.IsConfigured); + } + + [Fact] + public async Task CreateFirst_WhenAnAdministratorExists_Throws() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = 1111111 }, CancellationToken.None); + var handler = new CreateFirstAdministratorCommandHandler(_administratorRepository, CreateSetupState(), _clock, new TestUnitOfWork(), Logger.None); + + // Act & Assert + await Assert.ThrowsAsync(() => + handler.Handle(new CreateFirstAdministratorCommand(1234567), CancellationToken.None)); + Assert.Null(await _administratorRepository.FindByCid(1234567, CancellationToken.None)); + } + + [Fact] + public async Task UpdateName_ChangesTheNameOfAnAdministrator() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = 1234567 }, CancellationToken.None); + var handler = new UpdateAdministratorNameCommandHandler(_administratorRepository); + + // Act + await handler.Handle(new UpdateAdministratorNameCommand(1234567, "Test Controller"), CancellationToken.None); + + // Assert + var administrator = await _administratorRepository.FindByCid(1234567, CancellationToken.None); + Assert.Equal("Test Controller", administrator!.Name); + } + + SetupState CreateSetupState() + { + var services = new ServiceCollection(); + services.AddSingleton(_administratorRepository); + return new SetupState(services.BuildServiceProvider().GetRequiredService()); + } +} diff --git a/source/CPDLCServer.Tests/Auth/Login/ClientIpAddressTests.cs b/source/CPDLCServer.Tests/Auth/Login/ClientIpAddressTests.cs deleted file mode 100644 index 9eeb073..0000000 --- a/source/CPDLCServer.Tests/Auth/Login/ClientIpAddressTests.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System.Net; -using CPDLCServer.Auth.Login; -using Microsoft.AspNetCore.Http; - -namespace CPDLCServer.Tests.Auth.Login; - -public class ClientIpAddressTests -{ - [Fact] - public void Get_WithoutHeaders_ReturnsTheConnectionAddress() - { - var httpContext = CreateHttpContext(); - - Assert.Equal("10.0.0.1", ClientIpAddress.Get(httpContext)); - } - - [Fact] - public void Get_WithDigitalOceanHeader_ReturnsTheHeaderAddress() - { - var httpContext = CreateHttpContext(); - httpContext.Request.Headers["do-connecting-ip"] = "203.0.113.10"; - httpContext.Request.Headers["x-forwarded-for"] = "10.0.0.2"; - - Assert.Equal("203.0.113.10", ClientIpAddress.Get(httpContext)); - } - - [Fact] - public void Get_WithForwardedForList_ReturnsTheFirstAddress() - { - var httpContext = CreateHttpContext(); - httpContext.Request.Headers["x-forwarded-for"] = "203.0.113.10, 10.0.0.2"; - - Assert.Equal("203.0.113.10", ClientIpAddress.Get(httpContext)); - } - - [Fact] - public void Get_WithInvalidHeaderValue_UsesTheNextHeader() - { - var httpContext = CreateHttpContext(); - httpContext.Request.Headers["do-connecting-ip"] = "not an address"; - httpContext.Request.Headers["x-real-ip"] = "2001:db8::1"; - - Assert.Equal("2001:db8::1", ClientIpAddress.Get(httpContext)); - } - - static DefaultHttpContext CreateHttpContext() - { - var httpContext = new DefaultHttpContext(); - httpContext.Connection.RemoteIpAddress = IPAddress.Parse("10.0.0.1"); - return httpContext; - } -} diff --git a/source/CPDLCServer.Tests/Auth/Login/LoginCommandHandlerTests.cs b/source/CPDLCServer.Tests/Auth/Login/LoginCommandHandlerTests.cs deleted file mode 100644 index c3dca9f..0000000 --- a/source/CPDLCServer.Tests/Auth/Login/LoginCommandHandlerTests.cs +++ /dev/null @@ -1,163 +0,0 @@ -using CPDLCServer.Auth.Login; -using CPDLCServer.Auth.Users; -using CPDLCServer.Tests.Mocks; -using Microsoft.AspNetCore.Identity; -using Serilog.Core; - -namespace CPDLCServer.Tests.Auth.Login; - -public class LoginCommandHandlerTests -{ - const string Password = "correct horse battery"; - const string IpAddress = "203.0.113.10"; - - readonly TestUserRepository _repository = new(); - readonly PasswordHasher _passwordHasher = new(); - readonly TestClock _clock = new(); - readonly LoginLockout _loginLockout; - readonly User _user; - - public LoginCommandHandlerTests() - { - _loginLockout = new LoginLockout(_clock); - _user = new User { Id = Guid.NewGuid(), Username = "admin" }; - _user.PasswordHash = _passwordHasher.HashPassword(_user, Password); - _repository.Add(_user, CancellationToken.None); - } - - [Fact] - public async Task Handle_WithCorrectPassword_ReturnsTheUser() - { - // Arrange - var handler = CreateHandler(); - - // Act - var result = await handler.Handle(new LoginCommand(" admin ", Password, IpAddress), CancellationToken.None); - - // Assert - Assert.NotNull(result); - Assert.Equal(_user.Id, result.UserId); - Assert.Equal("admin", result.Username); - } - - [Fact] - public async Task Handle_WithWrongPassword_ReturnsNull() - { - // Arrange - var handler = CreateHandler(); - - // Act - var result = await handler.Handle(new LoginCommand("admin", "wrong password", IpAddress), CancellationToken.None); - - // Assert - Assert.Null(result); - } - - [Fact] - public async Task Handle_WithUnknownUser_ReturnsNull() - { - // Arrange - var handler = CreateHandler(); - - // Act - var result = await handler.Handle(new LoginCommand("intruder", Password, IpAddress), CancellationToken.None); - - // Assert - Assert.Null(result); - } - - [Fact] - public async Task Handle_AfterTooManyFailures_LocksOutTheIpAddress() - { - // Arrange - var handler = CreateHandler(); - - // Act - await FailLogins(handler, "admin", LoginLockout.MaxFailedLogins); - - // Assert - Assert.True(_loginLockout.IsLockedOut(IpAddress)); - } - - [Fact] - public async Task Handle_FailuresWithUnknownUsers_LockOutTheIpAddress() - { - // Arrange - var handler = CreateHandler(); - - // Act - await FailLogins(handler, "intruder", LoginLockout.MaxFailedLogins); - - // Assert - Assert.True(_loginLockout.IsLockedOut(IpAddress)); - } - - [Fact] - public async Task Handle_DuringLockout_RejectsTheCorrectPassword() - { - // Arrange - var handler = CreateHandler(); - await FailLogins(handler, "admin", LoginLockout.MaxFailedLogins); - - // Act - var result = await handler.Handle(new LoginCommand("admin", Password, IpAddress), CancellationToken.None); - - // Assert - Assert.Null(result); - } - - [Fact] - public async Task Handle_DuringLockout_AcceptsTheCorrectPasswordFromAnotherIpAddress() - { - // Arrange - var handler = CreateHandler(); - await FailLogins(handler, "admin", LoginLockout.MaxFailedLogins); - - // Act - var result = await handler.Handle(new LoginCommand("admin", Password, "198.51.100.20"), CancellationToken.None); - - // Assert - Assert.NotNull(result); - } - - [Fact] - public async Task Handle_AfterLockout_AcceptsTheCorrectPassword() - { - // Arrange - var handler = CreateHandler(); - await FailLogins(handler, "admin", LoginLockout.MaxFailedLogins); - _clock.SetUtcNow(_clock.UtcNow() + LoginLockout.LockoutDuration); - - // Act - var result = await handler.Handle(new LoginCommand("admin", Password, IpAddress), CancellationToken.None); - - // Assert - Assert.NotNull(result); - } - - [Fact] - public async Task Handle_WithCorrectPassword_ResetsTheFailedLogins() - { - // Arrange - var handler = CreateHandler(); - await FailLogins(handler, "admin", LoginLockout.MaxFailedLogins - 1); - - // Act - await handler.Handle(new LoginCommand("admin", Password, IpAddress), CancellationToken.None); - await FailLogins(handler, "admin", 1); - - // Assert - Assert.False(_loginLockout.IsLockedOut(IpAddress)); - } - - static async Task FailLogins(LoginCommandHandler handler, string username, int count) - { - for (var i = 0; i < count; i++) - await handler.Handle(new LoginCommand(username, "wrong password", IpAddress), CancellationToken.None); - } - - LoginCommandHandler CreateHandler() - { - return new LoginCommandHandler(_repository, _passwordHasher, _loginLockout, Logger.None); - } -} diff --git a/source/CPDLCServer.Tests/Auth/Login/LoginLockoutTests.cs b/source/CPDLCServer.Tests/Auth/Login/LoginLockoutTests.cs deleted file mode 100644 index cb38a5e..0000000 --- a/source/CPDLCServer.Tests/Auth/Login/LoginLockoutTests.cs +++ /dev/null @@ -1,99 +0,0 @@ -using CPDLCServer.Auth.Login; -using CPDLCServer.Tests.Mocks; - -namespace CPDLCServer.Tests.Auth.Login; - -public class LoginLockoutTests -{ - const string IpAddress = "203.0.113.10"; - - readonly TestClock _clock = new(); - readonly LoginLockout _loginLockout; - - public LoginLockoutTests() - { - _loginLockout = new LoginLockout(_clock); - } - - [Fact] - public void RecordFailure_BelowTheLimit_DoesNotLockOut() - { - // Act - for (var i = 0; i < LoginLockout.MaxFailedLogins - 1; i++) - Assert.Null(_loginLockout.RecordFailure(IpAddress)); - - // Assert - Assert.False(_loginLockout.IsLockedOut(IpAddress)); - } - - [Fact] - public void RecordFailure_AtTheLimit_LocksOutForTheLockoutDuration() - { - // Act - DateTimeOffset? lockoutEnd = null; - for (var i = 0; i < LoginLockout.MaxFailedLogins; i++) - lockoutEnd = _loginLockout.RecordFailure(IpAddress); - - // Assert - Assert.Equal(_clock.UtcNow() + LoginLockout.LockoutDuration, lockoutEnd); - Assert.True(_loginLockout.IsLockedOut(IpAddress)); - } - - [Fact] - public void IsLockedOut_AfterTheLockoutDuration_IsFalse() - { - // Arrange - LockOut(); - - // Act - _clock.SetUtcNow(_clock.UtcNow() + LoginLockout.LockoutDuration); - - // Assert - Assert.False(_loginLockout.IsLockedOut(IpAddress)); - } - - [Fact] - public void RecordFailure_AfterTheFailuresExpire_StartsTheCountAgain() - { - // Arrange - for (var i = 0; i < LoginLockout.MaxFailedLogins - 1; i++) - _loginLockout.RecordFailure(IpAddress); - _clock.SetUtcNow(_clock.UtcNow() + LoginLockout.LockoutDuration); - - // Act - var lockoutEnd = _loginLockout.RecordFailure(IpAddress); - - // Assert - Assert.Null(lockoutEnd); - Assert.False(_loginLockout.IsLockedOut(IpAddress)); - } - - [Fact] - public void Reset_EndsTheLockout() - { - // Arrange - LockOut(); - - // Act - _loginLockout.Reset(IpAddress); - - // Assert - Assert.False(_loginLockout.IsLockedOut(IpAddress)); - } - - [Fact] - public void LockOut_DoesNotAffectOtherIpAddresses() - { - // Act - LockOut(); - - // Assert - Assert.False(_loginLockout.IsLockedOut("198.51.100.20")); - } - - void LockOut() - { - for (var i = 0; i < LoginLockout.MaxFailedLogins; i++) - _loginLockout.RecordFailure(IpAddress); - } -} diff --git a/source/CPDLCServer.Tests/Auth/PluginTokens/PluginAuthorizationCodesTests.cs b/source/CPDLCServer.Tests/Auth/PluginTokens/PluginAuthorizationCodesTests.cs new file mode 100644 index 0000000..7c2de9c --- /dev/null +++ b/source/CPDLCServer.Tests/Auth/PluginTokens/PluginAuthorizationCodesTests.cs @@ -0,0 +1,109 @@ +using CPDLCServer.Auth.PluginTokens; +using CPDLCServer.Tests.Mocks; + +namespace CPDLCServer.Tests.Auth.PluginTokens; + +public class PluginAuthorizationCodesTests +{ + const string RedirectUri = "http://127.0.0.1:50000/callback"; + const string CodeVerifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; + + readonly TestClock _clock = new(); + + [Fact] + public void ComputeChallenge_MatchesTheExampleOfRfc7636() + { + // Act + var challenge = PluginAuthorizationCodes.ComputeChallenge(CodeVerifier); + + // Assert + Assert.Equal("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", challenge); + } + + [Fact] + public void Redeem_WithTheVerifier_ReturnsTheUser() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create(1234567, "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + + // Act + var user = codes.Redeem(code, RedirectUri, CodeVerifier); + + // Assert + Assert.Equal(new PluginUser(1234567, "Test Controller"), user); + } + + [Fact] + public void Redeem_WithAWrongVerifier_ReturnsNull() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create(1234567, "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + + // Act + var user = codes.Redeem(code, RedirectUri, "wrong-verifier"); + + // Assert + Assert.Null(user); + } + + [Fact] + public void Redeem_WithADifferentRedirectUri_ReturnsNull() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create(1234567, "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + + // Act + var user = codes.Redeem(code, "http://127.0.0.1:50001/callback", CodeVerifier); + + // Assert + Assert.Null(user); + } + + [Fact] + public void Redeem_AfterTheCodeExpires_ReturnsNull() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create(1234567, "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + _clock.SetUtcNow(_clock.UtcNow() + PluginAuthorizationCodes.CodeLifetime); + + // Act + var user = codes.Redeem(code, RedirectUri, CodeVerifier); + + // Assert + Assert.Null(user); + } + + [Fact] + public void Redeem_TwoTimes_ReturnsNullTheSecondTime() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create(1234567, "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + codes.Redeem(code, RedirectUri, CodeVerifier); + + // Act + var user = codes.Redeem(code, RedirectUri, CodeVerifier); + + // Assert + Assert.Null(user); + } + + [Fact] + public void Redeem_AfterAFailedCheck_ReturnsNull() + { + // Arrange + var codes = new PluginAuthorizationCodes(_clock); + var code = codes.Create(1234567, "Test Controller", RedirectUri, PluginAuthorizationCodes.ComputeChallenge(CodeVerifier)); + codes.Redeem(code, RedirectUri, "wrong-verifier"); + + // Act + var user = codes.Redeem(code, RedirectUri, CodeVerifier); + + // Assert + Assert.Null(user); + } +} diff --git a/source/CPDLCServer.Tests/Auth/PluginTokens/PluginRedirectUriTests.cs b/source/CPDLCServer.Tests/Auth/PluginTokens/PluginRedirectUriTests.cs new file mode 100644 index 0000000..34378e8 --- /dev/null +++ b/source/CPDLCServer.Tests/Auth/PluginTokens/PluginRedirectUriTests.cs @@ -0,0 +1,23 @@ +using CPDLCServer.Auth.PluginTokens; + +namespace CPDLCServer.Tests.Auth.PluginTokens; + +public class PluginRedirectUriTests +{ + [Theory] + [InlineData("http://127.0.0.1:50000/callback", true)] + [InlineData("http://localhost:50000/callback", true)] + [InlineData("https://127.0.0.1:50000/callback", false)] + [InlineData("http://127.0.0.1/callback", false)] + [InlineData("http://example.com:50000/callback", false)] + [InlineData("http://127.0.0.1.example.com:50000/callback", false)] + [InlineData("http://127.0.0.1:50000/callback?next=http://example.com", false)] + [InlineData("http://user@127.0.0.1:50000/callback", false)] + [InlineData("not a URL", false)] + [InlineData(null, false)] + public void IsValid_AcceptsOnlyAPortOnThisComputer(string? redirectUri, bool expected) + { + // Act & Assert + Assert.Equal(expected, PluginRedirectUri.IsValid(redirectUri)); + } +} diff --git a/source/CPDLCServer.Tests/Auth/Users/ChangePasswordCommandHandlerTests.cs b/source/CPDLCServer.Tests/Auth/Users/ChangePasswordCommandHandlerTests.cs deleted file mode 100644 index 30f1053..0000000 --- a/source/CPDLCServer.Tests/Auth/Users/ChangePasswordCommandHandlerTests.cs +++ /dev/null @@ -1,59 +0,0 @@ -using CPDLCServer.Auth.Users; -using CPDLCServer.Tests.Mocks; -using Microsoft.AspNetCore.Identity; -using Serilog.Core; - -namespace CPDLCServer.Tests.Auth.Users; - -public class ChangePasswordCommandHandlerTests -{ - const string CurrentPassword = "correct horse battery"; - const string NewPassword = "another long password"; - - readonly TestUserRepository _repository = new(); - readonly PasswordHasher _passwordHasher = new(); - readonly User _user; - - public ChangePasswordCommandHandlerTests() - { - _user = new User { Id = Guid.NewGuid(), Username = "admin" }; - _user.PasswordHash = _passwordHasher.HashPassword(_user, CurrentPassword); - _repository.Add(_user, CancellationToken.None); - } - - [Fact] - public async Task Handle_ChangesThePassword() - { - // Arrange - var handler = CreateHandler(); - - // Act - await handler.Handle(new ChangePasswordCommand(_user.Id, NewPassword), CancellationToken.None); - - // Assert - Assert.Equal(PasswordVerificationResult.Success, Verify(NewPassword)); - Assert.Equal(PasswordVerificationResult.Failed, Verify(CurrentPassword)); - } - - [Fact] - public async Task Handle_WithUnknownUser_Throws() - { - // Arrange - var handler = CreateHandler(); - - // Act & Assert - await Assert.ThrowsAsync(() => handler.Handle( - new ChangePasswordCommand(Guid.NewGuid(), NewPassword), - CancellationToken.None)); - } - - PasswordVerificationResult Verify(string password) - { - return _passwordHasher.VerifyHashedPassword(_user, _user.PasswordHash, password); - } - - ChangePasswordCommandHandler CreateHandler() - { - return new ChangePasswordCommandHandler(_repository, _passwordHasher, Logger.None); - } -} diff --git a/source/CPDLCServer.Tests/Auth/Users/CreateUserCommandHandlerTests.cs b/source/CPDLCServer.Tests/Auth/Users/CreateUserCommandHandlerTests.cs deleted file mode 100644 index 8225c9b..0000000 --- a/source/CPDLCServer.Tests/Auth/Users/CreateUserCommandHandlerTests.cs +++ /dev/null @@ -1,80 +0,0 @@ -using CPDLCServer.Auth.Users; -using CPDLCServer.Setup; -using CPDLCServer.Tests.Mocks; -using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.DependencyInjection; -using Serilog.Core; - -namespace CPDLCServer.Tests.Auth.Users; - -public class CreateUserCommandHandlerTests -{ - readonly TestUserRepository _repository = new(); - readonly PasswordHasher _passwordHasher = new(); - - [Fact] - public async Task Handle_CreatesAdminWithHashedPassword() - { - // Arrange - var handler = CreateHandler(CreateSetupState()); - - // Act - var id = await handler.Handle(new CreateUserCommand(" admin ", "correct horse battery"), CancellationToken.None); - - // Assert - var user = await _repository.FindByUsername("admin", CancellationToken.None); - Assert.NotNull(user); - Assert.Equal(id, user.Id); - Assert.NotEqual("correct horse battery", user.PasswordHash); - Assert.Equal( - PasswordVerificationResult.Success, - _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, "correct horse battery")); - } - - [Fact] - public async Task Handle_MarksAdminCreated() - { - // Arrange - var setupState = CreateSetupState(); - var handler = CreateHandler(setupState); - - // Act - await handler.Handle(new CreateUserCommand("admin", "correct horse battery"), CancellationToken.None); - - // Assert - Assert.True(setupState.IsConfigured); - } - - [Fact] - public async Task Handle_WhenAdminExists_Throws() - { - // Arrange - var handler = CreateHandler(CreateSetupState()); - await handler.Handle(new CreateUserCommand("admin", "correct horse battery"), CancellationToken.None); - - // Act & Assert - await Assert.ThrowsAsync(() => - handler.Handle(new CreateUserCommand("intruder", "another password"), CancellationToken.None)); - Assert.Null(await _repository.FindByUsername("intruder", CancellationToken.None)); - } - - CreateUserCommandHandler CreateHandler(SetupState setupState) - { - return new CreateUserCommandHandler( - _repository, - _passwordHasher, - setupState, - new TestClock(), - new TestUnitOfWork(), - Logger.None); - } - - SetupState CreateSetupState() - { - var services = new ServiceCollection(); - services.AddSingleton(_repository); - var serviceProvider = services.BuildServiceProvider(); - - return new SetupState(serviceProvider.GetRequiredService()); - } -} diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs index 0d78668..4807ea0 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionEstablishedNotificationHandlerTests.cs @@ -20,12 +20,16 @@ public async Task Handle_NotifiesAllConnectedControllers() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", - "BN-OCN_CTR"); + "BN-OCN_CTR", + 1234567, + "Test Controller"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs index ce41b8d..c83b61f 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionLostNotificationHandlerTests.cs @@ -69,12 +69,16 @@ public async Task Handle_CreatesDialogueWithErrorMessageAndNotifiesControllers() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", - "BN-OCN_CTR"); + "BN-OCN_CTR", + 1234567, + "Test Controller"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); @@ -254,7 +258,9 @@ public async Task Handle_AddsErrorMessageToExistingOpenDialogue() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var dialogueRepository = new TestDialogueRepository(); @@ -325,7 +331,9 @@ public async Task Handle_ClosesOpenDialogue_SoItCanBeArchived() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var dialogueRepository = new TestDialogueRepository(); diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs index 72e2f87..7bee226 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/AircraftConnectionTerminatedNotificationHandlerTests.cs @@ -19,12 +19,16 @@ public async Task Handle_NotifiesAllConnectedControllers() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", - "BN-OCN_CTR"); + "BN-OCN_CTR", + 1234567, + "Test Controller"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); diff --git a/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs index 2ed02d5..4b06a40 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Connections/LogonCommandHandlerTests.cs @@ -106,7 +106,9 @@ public async Task Handle_NewConnection_AcceptsLogon() Guid.NewGuid(), "Connection-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); @@ -139,7 +141,9 @@ public async Task Handle_NewConnection_TracksConnection() Guid.NewGuid(), "Connection-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); @@ -173,7 +177,9 @@ public async Task Handle_NewConnection_PersistsDialogueWithDownlinkAndUplink() Guid.NewGuid(), "Connection-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); @@ -215,7 +221,9 @@ static async Task AddController(TestControllerRepository controllerRepository) Guid.NewGuid(), "Connection-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); await controllerRepository.Add(controller, CancellationToken.None); } @@ -342,7 +350,9 @@ public async Task Handle_NotifiesATC() Guid.NewGuid(), "Connection-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); await controllerRepository.Add(controller, CancellationToken.None); var command = BuildLogonCommand(clock); diff --git a/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs index d95f305..fe44d25 100644 --- a/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs +++ b/source/CPDLCServer.Tests/Cpdlc/Downlinks/DownlinkReceivedNotificationHandlerTests.cs @@ -47,12 +47,16 @@ public async Task Handle_PublishesDialogueChangedNotification() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); var controller2 = new ControllerInfo( Guid.NewGuid(), "ConnectionId-2", "YBBB", - "BN-OCN_CTR"); + "BN-OCN_CTR", + 1234567, + "Test Controller"); await controllerManager.Add(controller1, CancellationToken.None); await controllerManager.Add(controller2, CancellationToken.None); @@ -109,7 +113,9 @@ public async Task Handle_StillCreatesDialogueWhenNoControllersMatch() Guid.NewGuid(), "ConnectionId-1", "YMMM", - "ML-IND_FSS"); + "ML-IND_FSS", + 1234567, + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -161,7 +167,9 @@ public async Task Handle_PromotesAircraftToCurrentDataAuthorityOnFirstDownlink() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -232,7 +240,9 @@ public async Task Handle_DoesNotPromoteToCurrentDataAuthority_WhenNotCurrentData Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -294,7 +304,9 @@ public async Task Handle_UpdatesLastSeen() Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); await controllerManager.Add(controller, CancellationToken.None); var mediator = Substitute.For(); @@ -599,7 +611,9 @@ public async Task Handle_LogoffMessage_FromNextDataAuthority_DoesNotPromoteOrNot Guid.NewGuid(), "ConnectionId-1", "YBBB", - "BN-TSN_FSS"); + "BN-TSN_FSS", + 1234567, + "Test Controller"); await controllerRepository.Add(controller, CancellationToken.None); var dialogueRepository = new TestDialogueRepository(); diff --git a/source/CPDLCServer.Tests/Cpdlc/Motd/SendMotdCommandHandlerTests.cs b/source/CPDLCServer.Tests/Cpdlc/Motd/SendMotdCommandHandlerTests.cs new file mode 100644 index 0000000..10bcc75 --- /dev/null +++ b/source/CPDLCServer.Tests/Cpdlc/Motd/SendMotdCommandHandlerTests.cs @@ -0,0 +1,83 @@ +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Motd; +using CPDLCServer.Cpdlc.Uplinks; +using CPDLCServer.Tests.Mocks; +using MediatR; +using NSubstitute; +using Serilog.Core; + +namespace CPDLCServer.Tests.Cpdlc.Motd; + +public class SendMotdCommandHandlerTests +{ + readonly TestAircraftRepository _aircraftRepository = new(); + readonly TestAcarsConnectionManager _acarsConnectionManager = new(); + readonly IMediator _mediator = Substitute.For(); + readonly TestClock _clock = new(); + + SendMotdCommandHandler CreateHandler() => new(_aircraftRepository, _acarsConnectionManager, _mediator, Logger.None); + + async Task AddAircraft(string callsign, DataAuthorityState dataAuthorityState) + { + var aircraft = new AircraftConnection(callsign, "hoppies-ybbb", "YBBB", dataAuthorityState); + aircraft.RequestLogon(_clock.UtcNow()); + aircraft.AcceptLogon(_clock.UtcNow()); + await _aircraftRepository.Add(new AircraftKey(aircraft.Callsign, aircraft.AcarsConnectionId), aircraft, CancellationToken.None); + } + + [Fact] + public async Task Handle_SendsTheMessageAsFreeTextWithNoResponse() + { + // Arrange + _acarsConnectionManager.AddConfiguration(TestAcarsConnectionManager.CreateConfiguration("YBBB", 10, motd: "WELCOME TO BRISBANE")); + await AddAircraft("UAL123", DataAuthorityState.CurrentDataAuthority); + + // Act + await CreateHandler().Handle(new SendMotdCommand("hoppies-ybbb", "UAL123"), CancellationToken.None); + + // Assert + await _mediator.Received(1).Send( + new BeginDialogueCommand("YBBB", "UAL123", CpdlcUplinkResponseType.NoResponse, "WELCOME TO BRISBANE"), + Arg.Any()); + } + + [Fact] + public async Task Handle_WhenAircraftDisconnected_DoesNotSend() + { + // Arrange + _acarsConnectionManager.AddConfiguration(TestAcarsConnectionManager.CreateConfiguration("YBBB", 10, motd: "WELCOME TO BRISBANE")); + + // Act + await CreateHandler().Handle(new SendMotdCommand("hoppies-ybbb", "UAL123"), CancellationToken.None); + + // Assert + await _mediator.DidNotReceiveWithAnyArgs().Send(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_WhenNextDataAuthority_DoesNotSend() + { + // Arrange + _acarsConnectionManager.AddConfiguration(TestAcarsConnectionManager.CreateConfiguration("YBBB", 10, motd: "WELCOME TO BRISBANE")); + await AddAircraft("UAL123", DataAuthorityState.NextDataAuthority); + + // Act + await CreateHandler().Handle(new SendMotdCommand("hoppies-ybbb", "UAL123"), CancellationToken.None); + + // Assert + await _mediator.DidNotReceiveWithAnyArgs().Send(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Handle_WhenTheMessageWasRemoved_DoesNotSend() + { + // Arrange + await AddAircraft("UAL123", DataAuthorityState.CurrentDataAuthority); + + // Act + await CreateHandler().Handle(new SendMotdCommand("hoppies-ybbb", "UAL123"), CancellationToken.None); + + // Assert + await _mediator.DidNotReceiveWithAnyArgs().Send(Arg.Any(), Arg.Any()); + } +} diff --git a/source/CPDLCServer.Tests/Logging/LogAreaTests.cs b/source/CPDLCServer.Tests/Logging/LogAreaTests.cs new file mode 100644 index 0000000..665532d --- /dev/null +++ b/source/CPDLCServer.Tests/Logging/LogAreaTests.cs @@ -0,0 +1,26 @@ +using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.AdscContracts.Reports; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Logging; +using CPDLCServer.Settings; +using CPDLCServer.VatsimStatus; + +namespace CPDLCServer.Tests.Logging; + +public class LogAreaTests +{ + [Theory] + [InlineData(typeof(LogonCommand), LogArea.Cpdlc)] + [InlineData(typeof(ExpireAdscReportsRequest), LogArea.Adsc)] + [InlineData(typeof(ProduceVatsimAdscReportsRequest), LogArea.Adsc)] + [InlineData(typeof(RefreshAcarsCallsignsRequest), LogArea.Acars)] + [InlineData(typeof(SaveServerSettingsCommand), LogArea.System)] + public void ForType_UsesTheNamespaceOfTheType(Type type, string expectedArea) + { + // Act + var area = LogArea.ForType(type); + + // Assert + Assert.Equal(expectedArea, area); + } +} diff --git a/source/CPDLCServer.Tests/Logging/LogBufferTests.cs b/source/CPDLCServer.Tests/Logging/LogBufferTests.cs index bcf3871..29acbd1 100644 --- a/source/CPDLCServer.Tests/Logging/LogBufferTests.cs +++ b/source/CPDLCServer.Tests/Logging/LogBufferTests.cs @@ -98,8 +98,36 @@ public void Sink_WritesTheSameTextAsTheConsole() Assert.Contains("Send failed", error.Exception); } + [Fact] + public void Sink_ReadsTheAreaAndTheAcarsConnection() + { + // Arrange + var logBuffer = new LogBuffer(); + using var logger = new LoggerConfiguration() + .MinimumLevel.Verbose() + .WriteTo.Sink(new InMemoryLogBufferSink(logBuffer)) + .CreateLogger(); + + // Act + logger + .ForContext(LogArea.PropertyName, LogArea.Acars) + .ForContext(LogArea.AcarsConnectionIdPropertyName, "Hoppies/YBBB") + .Information("Polling for messages"); + logger.Information("No area"); + + // Assert + using var subscription = logBuffer.Subscribe(); + var acarsEntry = subscription.RecentEntries[0]; + Assert.Equal(LogArea.Acars, acarsEntry.Area); + Assert.Equal("Hoppies/YBBB", acarsEntry.AcarsConnectionId); + + var systemEntry = subscription.RecentEntries[1]; + Assert.Equal(LogArea.System, systemEntry.Area); + Assert.Null(systemEntry.AcarsConnectionId); + } + static LogEntry CreateEntry(string message) { - return new LogEntry(0, "12:00:00", "Information", "INF", message, null); + return new LogEntry(0, "12:00:00", "Information", "INF", LogArea.System, null, message, null); } } diff --git a/source/CPDLCServer.Tests/Mocks/TestAcarsConnectionManager.cs b/source/CPDLCServer.Tests/Mocks/TestAcarsConnectionManager.cs index 66227b0..a48b9c7 100644 --- a/source/CPDLCServer.Tests/Mocks/TestAcarsConnectionManager.cs +++ b/source/CPDLCServer.Tests/Mocks/TestAcarsConnectionManager.cs @@ -29,7 +29,8 @@ public void AddConfiguration(HoppiesConfiguration configuration) public static HoppiesConfiguration CreateConfiguration( string stationId, int defaultAdscReportingInterval, - int selectedAdscContractDuration = 60) + int selectedAdscContractDuration = 60, + string? motd = null) { return new HoppiesConfiguration { @@ -38,7 +39,8 @@ public static HoppiesConfiguration CreateConfiguration( FlightSimulationNetwork = "VATSIM", StationIdentifier = stationId, DefaultAdscReportingInterval = defaultAdscReportingInterval, - SelectedAdscContractDuration = selectedAdscContractDuration + SelectedAdscContractDuration = selectedAdscContractDuration, + Motd = motd }; } diff --git a/source/CPDLCServer.Tests/Mocks/TestAdministratorRepository.cs b/source/CPDLCServer.Tests/Mocks/TestAdministratorRepository.cs new file mode 100644 index 0000000..b724bf9 --- /dev/null +++ b/source/CPDLCServer.Tests/Mocks/TestAdministratorRepository.cs @@ -0,0 +1,35 @@ +using CPDLCServer.Auth.Administrators; + +namespace CPDLCServer.Tests.Mocks; + +public class TestAdministratorRepository : IAdministratorRepository +{ + private readonly List _administrators = []; + + public Task Add(Administrator administrator, CancellationToken cancellationToken) + { + _administrators.Add(administrator); + return Task.CompletedTask; + } + + public Task Remove(Administrator administrator, CancellationToken cancellationToken) + { + _administrators.Remove(administrator); + return Task.CompletedTask; + } + + public Task FindByCid(int cid, CancellationToken cancellationToken) + { + return Task.FromResult(_administrators.FirstOrDefault(a => a.Cid == cid)); + } + + public Task All(CancellationToken cancellationToken) + { + return Task.FromResult(_administrators.OrderBy(a => a.Cid).ToArray()); + } + + public Task Any(CancellationToken cancellationToken) + { + return Task.FromResult(_administrators.Count > 0); + } +} diff --git a/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs b/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs index ee6d27a..62bda7f 100644 --- a/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs +++ b/source/CPDLCServer.Tests/Mocks/TestServerSettingsProvider.cs @@ -19,7 +19,25 @@ public Task Load(CancellationToken cancellationToken) public Task Save(ServerSettings settings, CancellationToken cancellationToken) { - _settings = settings; + _settings = settings with + { + BannerImage = _settings.BannerImage, + BannerContentType = _settings.BannerContentType, + BannerVersion = _settings.BannerVersion + }; return Task.CompletedTask; } + + public Task LoadBranding(CancellationToken cancellationToken) + { + return Task.FromResult(new BrandingInfo(_settings.ServerName, _settings.Motd, _settings.BannerImage is not null, _settings.BannerVersion)); + } + + public Task<(byte[] Image, string ContentType)?> LoadBanner(CancellationToken cancellationToken) + { + (byte[] Image, string ContentType)? banner = _settings is { BannerImage: not null, BannerContentType: not null } + ? (_settings.BannerImage, _settings.BannerContentType) + : null; + return Task.FromResult(banner); + } } diff --git a/source/CPDLCServer.Tests/Mocks/TestUserRepository.cs b/source/CPDLCServer.Tests/Mocks/TestUserRepository.cs deleted file mode 100644 index cc46d21..0000000 --- a/source/CPDLCServer.Tests/Mocks/TestUserRepository.cs +++ /dev/null @@ -1,34 +0,0 @@ -using CPDLCServer.Auth.Users; - -namespace CPDLCServer.Tests.Mocks; - -public class TestUserRepository : IUserRepository -{ - private readonly List _users = []; - - public Task Add(User user, CancellationToken cancellationToken) - { - _users.Add(user); - return Task.CompletedTask; - } - - public Task FindByUsername(string username, CancellationToken cancellationToken) - { - return Task.FromResult(_users.FirstOrDefault(u => u.Username == username)); - } - - public Task FindById(Guid id, CancellationToken cancellationToken) - { - return Task.FromResult(_users.FirstOrDefault(u => u.Id == id)); - } - - public Task All(CancellationToken cancellationToken) - { - return Task.FromResult(_users.OrderBy(u => u.Username).ToArray()); - } - - public Task Any(CancellationToken cancellationToken) - { - return Task.FromResult(_users.Count > 0); - } -} diff --git a/source/CPDLCServer.Tests/Settings/BannerImageFormatTests.cs b/source/CPDLCServer.Tests/Settings/BannerImageFormatTests.cs new file mode 100644 index 0000000..826b923 --- /dev/null +++ b/source/CPDLCServer.Tests/Settings/BannerImageFormatTests.cs @@ -0,0 +1,30 @@ +using CPDLCServer.Settings; + +namespace CPDLCServer.Tests.Settings; + +public class BannerImageFormatTests +{ + [Fact] + public void FindContentType_FindsPngJpegAndWebp() + { + // Arrange + byte[] png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00]; + byte[] jpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0x00]; + byte[] webp = [.."RIFF"u8, 0x00, 0x00, 0x00, 0x00, .."WEBP"u8, 0x00]; + + // Act & Assert + Assert.Equal("image/png", BannerImageFormat.FindContentType(png)); + Assert.Equal("image/jpeg", BannerImageFormat.FindContentType(jpeg)); + Assert.Equal("image/webp", BannerImageFormat.FindContentType(webp)); + } + + [Fact] + public void FindContentType_DoesNotAcceptSvg() + { + // Arrange + var svg = ""u8.ToArray(); + + // Act & Assert + Assert.Null(BannerImageFormat.FindContentType(svg)); + } +} diff --git a/source/CPDLCServer.Tests/Setup/SetupStateTests.cs b/source/CPDLCServer.Tests/Setup/SetupStateTests.cs index 9a5ccc4..ba2fda3 100644 --- a/source/CPDLCServer.Tests/Setup/SetupStateTests.cs +++ b/source/CPDLCServer.Tests/Setup/SetupStateTests.cs @@ -1,4 +1,4 @@ -using CPDLCServer.Auth.Users; +using CPDLCServer.Auth.Administrators; using CPDLCServer.Setup; using CPDLCServer.Tests.Mocks; using Microsoft.Extensions.DependencyInjection; @@ -7,10 +7,10 @@ namespace CPDLCServer.Tests.Setup; public class SetupStateTests { - readonly TestUserRepository _userRepository = new(); + readonly TestAdministratorRepository _administratorRepository = new(); [Fact] - public async Task Load_WhenNoUser_IsNotConfigured() + public async Task Load_WhenNoAdministrator_IsNotConfigured() { // Arrange var setupState = CreateSetupState(); @@ -23,10 +23,10 @@ public async Task Load_WhenNoUser_IsNotConfigured() } [Fact] - public async Task Load_WhenUserExists_IsConfigured() + public async Task Load_WhenAdministratorExists_IsConfigured() { // Arrange - await _userRepository.Add(new User { Id = Guid.NewGuid(), Username = "admin" }, CancellationToken.None); + await _administratorRepository.Add(new Administrator { Cid = 1234567 }, CancellationToken.None); var setupState = CreateSetupState(); // Act @@ -37,36 +37,23 @@ public async Task Load_WhenUserExists_IsConfigured() } [Fact] - public async Task MarkAdminCreated_CompletesTheSetup() + public async Task MarkConfigured_CompletesTheSetup() { // Arrange var setupState = CreateSetupState(); await setupState.Load(CancellationToken.None); // Act - setupState.MarkAdminCreated(); + setupState.MarkConfigured(); // Assert Assert.True(setupState.IsConfigured); } - [Fact] - public void IsValidSetupToken_AcceptsOnlyTheSetupToken() - { - // Arrange - var setupState = CreateSetupState(); - - // Act & Assert - Assert.True(setupState.IsValidSetupToken(setupState.SetupToken)); - Assert.False(setupState.IsValidSetupToken("wrong-token")); - Assert.False(setupState.IsValidSetupToken(null)); - Assert.False(setupState.IsValidSetupToken(string.Empty)); - } - SetupState CreateSetupState() { var services = new ServiceCollection(); - services.AddSingleton(_userRepository); + services.AddSingleton(_administratorRepository); var serviceProvider = services.BuildServiceProvider(); return new SetupState(serviceProvider.GetRequiredService()); diff --git a/source/CPDLCServer/AcarsConnections/AcarsConnectionManager.cs b/source/CPDLCServer/AcarsConnections/AcarsConnectionManager.cs index 9dab5f0..aebe951 100644 --- a/source/CPDLCServer/AcarsConnections/AcarsConnectionManager.cs +++ b/source/CPDLCServer/AcarsConnections/AcarsConnectionManager.cs @@ -1,13 +1,16 @@ using System.Collections.Concurrent; using CPDLCServer.AcarsConnections.ConnectionSettings; using CPDLCServer.AcarsConnections.Hoppie; +using CPDLCServer.AcarsConnections.Traffic; using CPDLCServer.AdscContracts; using CPDLCServer.AdscContracts.MessageLog; using CPDLCServer.Cpdlc.Downlinks; using CPDLCServer.Infrastructure; +using CPDLCServer.Logging; using CPDLCServer.Persistence; using CPDLCServer.Security; using Microsoft.EntityFrameworkCore; +using Serilog.Context; namespace CPDLCServer.AcarsConnections; @@ -35,12 +38,15 @@ public class AcarsConnectionManager( IUnitOfWorkMediator mediator, IClock clock, IAdscMessageLogRepository adscMessageLogRepository, + AcarsTrafficLog trafficLog, ILogger logger) : BackgroundService, IAcarsConnectionManager { readonly SemaphoreSlim _semaphoreSlim = new(1, 1); readonly ConcurrentDictionary _connections = []; - readonly ILogger _logger = logger.ForContext(); + readonly ILogger _logger = logger + .ForContext() + .ForContext(LogArea.PropertyName, LogArea.Acars); protected override async Task ExecuteAsync(CancellationToken stoppingToken) { @@ -205,7 +211,9 @@ AcarsConfiguration CreateConfiguration(AcarsConnectionSettings settings) FlightSimulationNetwork = settings.FlightSimulationNetwork, StationIdentifier = settings.StationIdentifier, DefaultAdscReportingInterval = settings.DefaultAdscReportingInterval, - SelectedAdscContractDuration = settings.SelectedAdscContractDuration + SelectedAdscContractDuration = settings.SelectedAdscContractDuration, + Motd = settings.Motd, + MotdDelay = TimeSpan.FromSeconds(settings.MotdDelaySeconds) }, _ => throw new NotSupportedException($"ACARS network type {settings.Type} is not supported") }; @@ -265,12 +273,13 @@ HoppieAcarsConnection CreateHoppieConnection(HoppiesConfiguration configuration) httpClient, clock, adscMessageLogRepository, + trafficLog, _logger.ForContext()); } async Task Subscribe(string acarsConnectionId, string stationId, IAcarsConnection acarsConnection, IUnitOfWorkMediator mediator, CancellationToken cancellationToken) { - var subscriptionLogger = _logger.ForContext("AcarsConnectionId", acarsConnectionId); + var subscriptionLogger = _logger.ForContext(LogArea.AcarsConnectionIdPropertyName, acarsConnectionId); try { @@ -281,6 +290,9 @@ async Task Subscribe(string acarsConnectionId, string stationId, IAcarsConnectio using var publishTimeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); publishTimeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10)); + // The handlers of the message write the ACARS connection ID in their log entries + using var _ = LogContext.PushProperty(LogArea.AcarsConnectionIdPropertyName, acarsConnectionId); + try { await mediator.Publish( @@ -313,7 +325,7 @@ await mediator.Publish( async Task SubscribeAdsc(string acarsConnectionId, string stationId, IAcarsConnection acarsConnection, IUnitOfWorkMediator mediator, CancellationToken cancellationToken) { - var subscriptionLogger = _logger.ForContext("AcarsConnectionId", acarsConnectionId); + var subscriptionLogger = _logger.ForContext(LogArea.AcarsConnectionIdPropertyName, acarsConnectionId); try { @@ -324,6 +336,9 @@ async Task SubscribeAdsc(string acarsConnectionId, string stationId, IAcarsConne using var publishTimeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); publishTimeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10)); + // The handlers of the message write the ACARS connection ID in their log entries + using var _ = LogContext.PushProperty(LogArea.AcarsConnectionIdPropertyName, acarsConnectionId); + try { await mediator.Publish( diff --git a/source/CPDLCServer/AcarsConnections/AcarsConnectionsServiceCollectionExtensions.cs b/source/CPDLCServer/AcarsConnections/AcarsConnectionsServiceCollectionExtensions.cs index 0418fea..0b0ff43 100644 --- a/source/CPDLCServer/AcarsConnections/AcarsConnectionsServiceCollectionExtensions.cs +++ b/source/CPDLCServer/AcarsConnections/AcarsConnectionsServiceCollectionExtensions.cs @@ -1,4 +1,5 @@ using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.AcarsConnections.Traffic; namespace CPDLCServer.AcarsConnections; @@ -6,6 +7,7 @@ public static class AcarsConnectionsServiceCollectionExtensions { public static IServiceCollection AddAcarsConnections(this IServiceCollection services) { + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); services.AddHostedService(sp => sp.GetRequiredService()); diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettings.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettings.cs index e5ba86f..c0a1836 100644 --- a/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettings.cs +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettings.cs @@ -13,6 +13,8 @@ public enum AcarsNetworkType // The settings page binds its form to this type, so the form cannot set the ID or the encrypted authentication code. public class AcarsConnectionSettings { + public const int MaxMotdLength = 200; + [BindNever] public Guid Id { get; init; } = Guid.NewGuid(); @@ -42,7 +44,33 @@ public class AcarsConnectionSettings [Range(1, int.MaxValue)] public int SelectedAdscContractDuration { get; set; } = 60; + // A CPDLC free text message that is sent to each aircraft after it logs on. "/" is not accepted, because the + // Hoppie packet uses it as a separator. + [StringLength(MaxMotdLength)] + [RegularExpression(@"^[A-Za-z0-9 .,:?'()+\-\r\n]*$", ErrorMessage = "Use only letters, digits, spaces and . , : ? ' ( ) + -")] + public string? Motd { get; set; } + + [Range(0, 3600)] + public int MotdDelaySeconds { get; set; } = 30; + // Free text for the users. The server does not use it. [StringLength(2000)] public string? Notes { get; set; } + + // The ID of the running connection. The log entries and the traffic log use it. + public string AcarsConnectionId => Type switch + { + AcarsNetworkType.Hoppie => $"Hoppies/{StationIdentifier.ToUpperInvariant()}", + _ => throw new NotSupportedException($"ACARS network type {Type} is not supported") + }; + + // CPDLC free text is upper case on one line. An empty message is no message. + public static string? NormalizeMotd(string? motd) + { + if (string.IsNullOrWhiteSpace(motd)) + return null; + + var words = motd.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + return string.Join(' ', words).ToUpperInvariant(); + } } diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettingsConfiguration.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettingsConfiguration.cs index 796fffa..835c716 100644 --- a/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettingsConfiguration.cs +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/AcarsConnectionSettingsConfiguration.cs @@ -15,6 +15,9 @@ public void Configure(EntityTypeBuilder builder) builder.Property(c => c.Type).HasConversion(); builder.Property(c => c.Url).HasConversion(); + // Calculated from the type and the station identifier + builder.Ignore(c => c.AcarsConnectionId); + // The ACARS connection ID comes from the station identifier, so only one connection can use a station identifier builder.HasIndex(c => c.StationIdentifier).IsUnique(); } diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommandHandler.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommandHandler.cs index 26a2887..ee3695f 100644 --- a/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommandHandler.cs +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/CreateAcarsConnectionCommandHandler.cs @@ -19,6 +19,7 @@ public Task Handle(CreateAcarsConnectionCommand request, CancellationToken var settings = request.Settings; settings.StationIdentifier = settings.StationIdentifier.ToUpperInvariant(); + settings.Motd = AcarsConnectionSettings.NormalizeMotd(settings.Motd); settings.EncryptedAuthenticationCode = masterKeyEncryption.Encrypt(request.AuthenticationCode); dbContext.AcarsConnections.Add(settings); diff --git a/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommandHandler.cs b/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommandHandler.cs index 21782b6..40e4d51 100644 --- a/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommandHandler.cs +++ b/source/CPDLCServer/AcarsConnections/ConnectionSettings/UpdateAcarsConnectionCommandHandler.cs @@ -26,6 +26,8 @@ public async Task Handle(UpdateAcarsConnectionCommand request, CancellationToken settings.Url = changes.Url; settings.DefaultAdscReportingInterval = changes.DefaultAdscReportingInterval; settings.SelectedAdscContractDuration = changes.SelectedAdscContractDuration; + settings.Motd = AcarsConnectionSettings.NormalizeMotd(changes.Motd); + settings.MotdDelaySeconds = changes.MotdDelaySeconds; settings.Notes = changes.Notes; if (!string.IsNullOrWhiteSpace(request.AuthenticationCode)) diff --git a/source/CPDLCServer/AcarsConnections/Hoppie/HoppieAcarsConnection.cs b/source/CPDLCServer/AcarsConnections/Hoppie/HoppieAcarsConnection.cs index 1f260c7..a526fb7 100644 --- a/source/CPDLCServer/AcarsConnections/Hoppie/HoppieAcarsConnection.cs +++ b/source/CPDLCServer/AcarsConnections/Hoppie/HoppieAcarsConnection.cs @@ -1,5 +1,7 @@ +using System.Diagnostics; using System.Globalization; using System.Threading.Channels; +using CPDLCServer.AcarsConnections.Traffic; using CPDLCServer.AdscContracts; using CPDLCServer.AdscContracts.MessageLog; using CPDLCServer.AdscContracts.Reports; @@ -7,6 +9,7 @@ using CPDLCServer.Cpdlc.Downlinks; using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Infrastructure; +using CPDLCServer.Logging; namespace CPDLCServer.AcarsConnections.Hoppie; @@ -23,6 +26,7 @@ public class HoppieAcarsConnection : IAcarsConnection readonly HttpClient _httpClient; readonly IClock _clock; readonly IAdscMessageLogRepository _adscMessageLogRepository; + readonly AcarsTrafficLog _trafficLog; readonly ILogger _logger; readonly Channel _messageChannel = Channel.CreateUnbounded(); @@ -39,14 +43,23 @@ public class HoppieAcarsConnection : IAcarsConnection public ChannelReader AdscMessageReader => _adscMessageChannel.Reader; public string StationId => _configuration.StationIdentifier; - public HoppieAcarsConnection(HoppiesConfiguration configuration, HttpClient httpClient, IClock clock, IAdscMessageLogRepository adscMessageLogRepository, ILogger logger) + public HoppieAcarsConnection( + HoppiesConfiguration configuration, + HttpClient httpClient, + IClock clock, + IAdscMessageLogRepository adscMessageLogRepository, + AcarsTrafficLog trafficLog, + ILogger logger) { _configuration = configuration; _httpClient = httpClient; _httpClient.Timeout = TimeSpan.FromSeconds(15); _clock = clock; _adscMessageLogRepository = adscMessageLogRepository; - _logger = logger.ForContext("AcarsConnectionId", _configuration.AcarsConnectionId); + _trafficLog = trafficLog; + _logger = logger + .ForContext(LogArea.PropertyName, LogArea.Acars) + .ForContext(LogArea.AcarsConnectionIdPropertyName, _configuration.AcarsConnectionId); } public Task Connect(CancellationToken cancellationToken) @@ -132,15 +145,10 @@ async Task SendPacket(string to, string messageType, string packet, Cancellation if (!string.IsNullOrEmpty(packet)) parameters["packet"] = packet; - var content = new FormUrlEncodedContent(parameters); - try { _logger.Verbose("Sending {MessageType} to {Recipient} with packet {Packet}", messageType, to, packet); - var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); - response.EnsureSuccessStatusCode(); - - var responseText = await response.Content.ReadAsStringAsync(cancellationToken); + var responseText = await Post(parameters, cancellationToken); _logger.Verbose("Send response: {Response}", responseText); _lastSendTime = _clock.UtcNow(); @@ -156,6 +164,45 @@ async Task SendPacket(string to, string messageType, string packet, Cancellation } } + // Sends a request to the ACARS network, and keeps the request and the response in the traffic log + async Task Post(Dictionary parameters, CancellationToken cancellationToken) + { + var time = _clock.UtcNow(); + var stopwatch = Stopwatch.StartNew(); + int? statusCode = null; + string? responseText = null; + string? error = null; + + try + { + var content = new FormUrlEncodedContent(parameters); + var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); + statusCode = (int)response.StatusCode; + responseText = await response.Content.ReadAsStringAsync(cancellationToken); + + response.EnsureSuccessStatusCode(); + return responseText; + } + catch (Exception ex) + { + error = ex.Message; + throw; + } + finally + { + _trafficLog.Add( + _configuration.AcarsConnectionId, + new AcarsTrafficEntry( + time, + parameters["type"], + AcarsTrafficLog.FormatRequest(parameters), + statusCode, + responseText, + stopwatch.Elapsed, + error)); + } + } + public async Task ListConnections(CancellationToken cancellationToken) { if (_disposed) @@ -170,15 +217,10 @@ public async Task ListConnections(CancellationToken cancellationToken) ["packet"] = "ALL-CALLSIGNS" }; - var content = new FormUrlEncodedContent(parameters); - try { _logger.Verbose("Listing connections"); - var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); - response.EnsureSuccessStatusCode(); - - var responseText = await response.Content.ReadAsStringAsync(cancellationToken); + var responseText = await Post(parameters, cancellationToken); _logger.Verbose("ListConnections response: {Response}", responseText); // Parse the response to extract callsigns @@ -256,11 +298,7 @@ async Task Poll(CancellationToken cancellationToken) ["type"] = "poll" }; - var content = new FormUrlEncodedContent(parameters); - var response = await _httpClient.PostAsync(_configuration.Url, content, cancellationToken); - response.EnsureSuccessStatusCode(); - - var responseText = await response.Content.ReadAsStringAsync(cancellationToken); + var responseText = await Post(parameters, cancellationToken); _logger.Verbose("Poll response: {Response}", responseText); diff --git a/source/CPDLCServer/AcarsConnections/HoppiesConfiguration.cs b/source/CPDLCServer/AcarsConnections/HoppiesConfiguration.cs index de2e611..5c2bbef 100644 --- a/source/CPDLCServer/AcarsConnections/HoppiesConfiguration.cs +++ b/source/CPDLCServer/AcarsConnections/HoppiesConfiguration.cs @@ -13,6 +13,12 @@ public abstract class AcarsConfiguration // The time in minutes from the request of a selected ADS-C contract to its end. After this time, the default contract is requested again. public int SelectedAdscContractDuration { get; init; } = 60; + + // A CPDLC free text message that is sent to each aircraft after it logs on. Null when there is no message. + public string? Motd { get; init; } + + // The time from the logon to the message of the day + public TimeSpan MotdDelay { get; init; } = TimeSpan.FromSeconds(30); } public class HoppiesConfiguration : AcarsConfiguration diff --git a/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficEntry.cs b/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficEntry.cs new file mode 100644 index 0000000..982f64c --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficEntry.cs @@ -0,0 +1,16 @@ +namespace CPDLCServer.AcarsConnections.Traffic; + +// One HTTP request to the ACARS network and its response, as they were sent and received. +// The authentication code is not in the request. +public record AcarsTrafficEntry( + DateTimeOffset Time, + string Type, + string Request, + int? StatusCode, + string? Response, + TimeSpan Duration, + string? Error) +{ + // Most polls get no messages. The traffic page can hide them. + public bool IsEmptyPoll => Type == "poll" && Error is null && Response?.Trim() == "ok"; +} diff --git a/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficLog.cs b/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficLog.cs new file mode 100644 index 0000000..4132887 --- /dev/null +++ b/source/CPDLCServer/AcarsConnections/Traffic/AcarsTrafficLog.cs @@ -0,0 +1,53 @@ +namespace CPDLCServer.AcarsConnections.Traffic; + +/// +/// Keeps the most recent requests to the ACARS network and their responses for each ACARS connection, so that an +/// administrator can see the raw data. The entries are kept only in memory, so a restart clears them. +/// +public class AcarsTrafficLog(int capacity = 500) +{ + public const string RedactedValue = "***"; + + // The names of the request fields that contain a secret + static readonly string[] SecretFields = ["logon"]; + + public int Capacity { get; } = capacity; + + readonly Lock _lock = new(); + readonly Dictionary> _entries = new(); + + public void Add(string acarsConnectionId, AcarsTrafficEntry entry) + { + lock (_lock) + { + if (!_entries.TryGetValue(acarsConnectionId, out var entries)) + { + entries = new Queue(); + _entries[acarsConnectionId] = entries; + } + + entries.Enqueue(entry); + if (entries.Count > Capacity) + entries.Dequeue(); + } + } + + // Newest entries first + public AcarsTrafficEntry[] Get(string acarsConnectionId) + { + lock (_lock) + { + return _entries.TryGetValue(acarsConnectionId, out var entries) + ? entries.Reverse().ToArray() + : []; + } + } + + // The request fields as text, one field on each line. The secrets are replaced. + public static string FormatRequest(IReadOnlyDictionary fields) + { + return string.Join( + '\n', + fields.Select(field => $"{field.Key}={(SecretFields.Contains(field.Key) ? RedactedValue : field.Value)}")); + } +} diff --git a/source/CPDLCServer/Auth/AdministratorRequirement.cs b/source/CPDLCServer/Auth/AdministratorRequirement.cs new file mode 100644 index 0000000..6f59652 --- /dev/null +++ b/source/CPDLCServer/Auth/AdministratorRequirement.cs @@ -0,0 +1,25 @@ +using CPDLCServer.Auth.Administrators; +using Microsoft.AspNetCore.Authorization; + +namespace CPDLCServer.Auth; + +// Only an administrator can open the Configuration area. +// The handler reads the database for each request, so a removed administrator loses access immediately. +public class AdministratorRequirement : IAuthorizationRequirement +{ + public const string PolicyName = "Administrator"; +} + +public class AdministratorRequirementHandler(IAdministratorRepository administratorRepository) + : AuthorizationHandler +{ + protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, AdministratorRequirement requirement) + { + var cid = context.User.GetCid(); + if (cid is null) + return; + + if (await administratorRepository.FindByCid(cid.Value, CancellationToken.None) is not null) + context.Succeed(requirement); + } +} diff --git a/source/CPDLCServer/Auth/Administrators/AddAdministratorCommand.cs b/source/CPDLCServer/Auth/Administrators/AddAdministratorCommand.cs new file mode 100644 index 0000000..cbc032e --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/AddAdministratorCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +public record AddAdministratorCommand(int Cid) : IRequest; diff --git a/source/CPDLCServer/Auth/Administrators/AddAdministratorCommandHandler.cs b/source/CPDLCServer/Auth/Administrators/AddAdministratorCommandHandler.cs new file mode 100644 index 0000000..fe495e2 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/AddAdministratorCommandHandler.cs @@ -0,0 +1,29 @@ +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +public class AddAdministratorCommandHandler( + IAdministratorRepository administratorRepository, + IClock clock, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(AddAdministratorCommand request, CancellationToken cancellationToken) + { + if (await administratorRepository.FindByCid(request.Cid, cancellationToken) is not null) + throw new InvalidOperationException($"{request.Cid} is already an administrator"); + + await administratorRepository.Add( + new Administrator { Cid = request.Cid, Added = clock.UtcNow() }, + cancellationToken); + + unitOfWork.AfterCommit(_ => + { + logger.Information("Administrator {Cid} added", request.Cid); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Auth/Administrators/Administrator.cs b/source/CPDLCServer/Auth/Administrators/Administrator.cs new file mode 100644 index 0000000..2ff9dfe --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/Administrator.cs @@ -0,0 +1,12 @@ +namespace CPDLCServer.Auth.Administrators; + +// A VATSIM user that can open the Configuration area of the dashboard +public class Administrator +{ + public int Cid { get; init; } + + // The VATSIM API does not give the name for a CID, so the name is not known until the administrator logs in + public string? Name { get; set; } + + public DateTimeOffset Added { get; init; } +} diff --git a/source/CPDLCServer/Auth/Administrators/AdministratorConfiguration.cs b/source/CPDLCServer/Auth/Administrators/AdministratorConfiguration.cs new file mode 100644 index 0000000..5f64477 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/AdministratorConfiguration.cs @@ -0,0 +1,15 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Auth.Administrators; + +public class AdministratorConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Administrators"); + + builder.HasKey(a => a.Cid); + builder.Property(a => a.Cid).ValueGeneratedNever(); + } +} diff --git a/source/CPDLCServer/Auth/Administrators/AdministratorRepository.cs b/source/CPDLCServer/Auth/Administrators/AdministratorRepository.cs new file mode 100644 index 0000000..eaa6313 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/AdministratorRepository.cs @@ -0,0 +1,39 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Auth.Administrators; + +// The changes are saved when the unit of work is committed. +// Queries load the rows into the context, then read the local entities, so that the results include entities that are +// added in the unit of work and exclude entities that are removed in it. +public class AdministratorRepository(CpdlcDbContext dbContext) : IAdministratorRepository +{ + public Task Add(Administrator administrator, CancellationToken cancellationToken) + { + dbContext.Administrators.Add(administrator); + return Task.CompletedTask; + } + + public Task Remove(Administrator administrator, CancellationToken cancellationToken) + { + dbContext.Administrators.Remove(administrator); + return Task.CompletedTask; + } + + public async Task FindByCid(int cid, CancellationToken cancellationToken) + { + return await dbContext.Administrators.FindAsync([cid], cancellationToken); + } + + public async Task All(CancellationToken cancellationToken) + { + await dbContext.Administrators.LoadAsync(cancellationToken); + return dbContext.Administrators.Local.OrderBy(a => a.Cid).ToArray(); + } + + public async Task Any(CancellationToken cancellationToken) + { + await dbContext.Administrators.LoadAsync(cancellationToken); + return dbContext.Administrators.Local.Count > 0; + } +} diff --git a/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommand.cs b/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommand.cs new file mode 100644 index 0000000..418d42b --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +// The setup adds the first administrator +public record CreateFirstAdministratorCommand(int Cid) : IRequest; diff --git a/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommandHandler.cs b/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommandHandler.cs new file mode 100644 index 0000000..8d08c15 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommandHandler.cs @@ -0,0 +1,32 @@ +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using CPDLCServer.Setup; +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +public class CreateFirstAdministratorCommandHandler( + IAdministratorRepository administratorRepository, + SetupState setupState, + IClock clock, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(CreateFirstAdministratorCommand request, CancellationToken cancellationToken) + { + if (await administratorRepository.Any(cancellationToken)) + throw new InvalidOperationException("An administrator already exists"); + + await administratorRepository.Add( + new Administrator { Cid = request.Cid, Added = clock.UtcNow() }, + cancellationToken); + + unitOfWork.AfterCommit(_ => + { + setupState.MarkConfigured(); + logger.Information("First administrator {Cid} added. The setup is complete", request.Cid); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Auth/Administrators/IAdministratorRepository.cs b/source/CPDLCServer/Auth/Administrators/IAdministratorRepository.cs new file mode 100644 index 0000000..f0e6a68 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/IAdministratorRepository.cs @@ -0,0 +1,10 @@ +namespace CPDLCServer.Auth.Administrators; + +public interface IAdministratorRepository +{ + Task Add(Administrator administrator, CancellationToken cancellationToken); + Task Remove(Administrator administrator, CancellationToken cancellationToken); + Task FindByCid(int cid, CancellationToken cancellationToken); + Task All(CancellationToken cancellationToken); + Task Any(CancellationToken cancellationToken); +} diff --git a/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommand.cs b/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommand.cs new file mode 100644 index 0000000..ad4459e --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +// The current user cannot remove their own access, so that the server always has an administrator +public record RemoveAdministratorCommand(int Cid, int CurrentUserCid) : IRequest; diff --git a/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommandHandler.cs b/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommandHandler.cs new file mode 100644 index 0000000..86f1154 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/RemoveAdministratorCommandHandler.cs @@ -0,0 +1,33 @@ +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +public class RemoveAdministratorCommandHandler( + IAdministratorRepository administratorRepository, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(RemoveAdministratorCommand request, CancellationToken cancellationToken) + { + if (request.Cid == request.CurrentUserCid) + throw new InvalidOperationException("You cannot remove yourself"); + + var administrator = await administratorRepository.FindByCid(request.Cid, cancellationToken); + if (administrator is null) + throw new InvalidOperationException($"{request.Cid} is not an administrator"); + + var administrators = await administratorRepository.All(cancellationToken); + if (administrators.Length <= 1) + throw new InvalidOperationException("You cannot remove the last administrator"); + + await administratorRepository.Remove(administrator, cancellationToken); + + unitOfWork.AfterCommit(_ => + { + logger.Information("Administrator {Cid} removed by {CurrentUserCid}", request.Cid, request.CurrentUserCid); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommand.cs b/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommand.cs new file mode 100644 index 0000000..0911b43 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +// Keeps the name of an administrator the same as the name in VATSIM. Does nothing if the user is not an administrator. +public record UpdateAdministratorNameCommand(int Cid, string Name) : IRequest; diff --git a/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommandHandler.cs b/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommandHandler.cs new file mode 100644 index 0000000..8d0dc98 --- /dev/null +++ b/source/CPDLCServer/Auth/Administrators/UpdateAdministratorNameCommandHandler.cs @@ -0,0 +1,16 @@ +using MediatR; + +namespace CPDLCServer.Auth.Administrators; + +public class UpdateAdministratorNameCommandHandler(IAdministratorRepository administratorRepository) + : IRequestHandler +{ + public async Task Handle(UpdateAdministratorNameCommand request, CancellationToken cancellationToken) + { + var administrator = await administratorRepository.FindByCid(request.Cid, cancellationToken); + if (administrator is null || administrator.Name == request.Name) + return; + + administrator.Name = request.Name; + } +} diff --git a/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs b/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs index 7bea987..e3426b0 100644 --- a/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs +++ b/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs @@ -1,17 +1,32 @@ -using CPDLCServer.Auth.Login; -using CPDLCServer.Auth.Users; +using System.Net.Http.Headers; +using System.Text.Json; +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Auth.PluginTokens; +using CPDLCServer.Auth.VatsimConnect; +using CPDLCServer.Infrastructure; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; -using Microsoft.AspNetCore.Identity; namespace CPDLCServer.Auth; public static class AuthServiceCollectionExtensions { - public static IServiceCollection AddAuth(this IServiceCollection services) + public static IServiceCollection AddAuth(this IServiceCollection services, IConfiguration configuration) { - services.AddScoped(); - services.AddSingleton, PasswordHasher>(); + var vatsimConnectOptions = new VatsimConnectOptions + { + ClientId = configuration.GetRequiredValue("VatsimConnect:ClientId"), + ClientSecret = configuration.GetRequiredValue("VatsimConnect:ClientSecret"), + Authority = configuration["VatsimConnect:Authority"] is { Length: > 0 } authority + ? new Uri(authority) + : new Uri("https://auth.vatsim.net") + }; + + services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); // Keep the keys of the login cookies only in memory, so that no key is on the disk. // After a restart, the user must log in again. @@ -22,17 +37,70 @@ public static IServiceCollection AddAuth(this IServiceCollection services) { options.LoginPath = "/login"; options.LogoutPath = "/logout"; - options.AccessDeniedPath = "/login"; - options.Cookie.Name = "cpdlc-admin"; + options.AccessDeniedPath = "/access-denied"; + options.Cookie.Name = "cpdlc-session"; options.Cookie.HttpOnly = true; - options.Cookie.SameSite = SameSiteMode.Strict; + + // Lax, not Strict: after the login, VATSIM Connect redirects the browser back to this server. + // With Strict, the browser does not send the cookie in that redirect, and the user is not logged in. + options.Cookie.SameSite = SameSiteMode.Lax; options.ExpireTimeSpan = TimeSpan.FromHours(8); options.SlidingExpiration = true; - }); - services.AddAuthorization(); + }) + .AddOAuth(VatsimConnectOptions.AuthenticationScheme, "VATSIM", options => + { + options.ClientId = vatsimConnectOptions.ClientId; + options.ClientSecret = vatsimConnectOptions.ClientSecret; + options.CallbackPath = VatsimConnectOptions.CallbackPath; + options.AuthorizationEndpoint = new Uri(vatsimConnectOptions.Authority, "/oauth/authorize").ToString(); + options.TokenEndpoint = new Uri(vatsimConnectOptions.Authority, "/oauth/token").ToString(); + options.UserInformationEndpoint = new Uri(vatsimConnectOptions.Authority, "/api/user").ToString(); + options.UsePkce = true; + options.Scope.Add("full_name"); + options.Scope.Add("vatsim_details"); + + // The server uses the VATSIM token only to read the user. It does not keep the token. + options.SaveTokens = false; + + options.Events.OnCreatingTicket = async context => + { + using var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + using var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted); + response.EnsureSuccessStatusCode(); + + using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(context.HttpContext.RequestAborted)); + var user = VatsimUser.Parse(document.RootElement); + + context.Principal = new(CurrentUser.CreateIdentity(user.Cid, user.Name, VatsimConnectOptions.AuthenticationScheme)); + + var mediator = context.HttpContext.RequestServices.GetRequiredService(); + await mediator.Send(new UpdateAdministratorNameCommand(user.Cid, user.Name), context.HttpContext.RequestAborted); + + var logger = context.HttpContext.RequestServices.GetRequiredService(); + logger.Information("{Name} ({Cid}) logged in", user.Name, user.Cid); + }; + }) + .AddScheme( + PluginTokenAuthenticationHandler.AuthenticationScheme, + _ => { }); + + services.AddScoped(); + services.AddAuthorization(options => + { + options.AddPolicy( + AdministratorRequirement.PolicyName, + policy => policy.RequireAuthenticatedUser().AddRequirements(new AdministratorRequirement())); - services.AddSingleton(); - services.AddRateLimiter(PasswordRateLimit.Configure); + // The plugin uses its token, not the login cookie + options.AddPolicy( + PluginTokenAuthenticationHandler.PolicyName, + policy => policy + .AddAuthenticationSchemes(PluginTokenAuthenticationHandler.AuthenticationScheme) + .RequireAuthenticatedUser()); + }); return services; } diff --git a/source/CPDLCServer/Auth/CurrentUser.cs b/source/CPDLCServer/Auth/CurrentUser.cs new file mode 100644 index 0000000..8d637c7 --- /dev/null +++ b/source/CPDLCServer/Auth/CurrentUser.cs @@ -0,0 +1,28 @@ +using System.Security.Claims; + +namespace CPDLCServer.Auth; + +// Reads the VATSIM user from the claims of a logged in user +public static class CurrentUser +{ + public static int? GetCid(this ClaimsPrincipal principal) + { + var value = principal.FindFirstValue(ClaimTypes.NameIdentifier); + return int.TryParse(value, out var cid) ? cid : null; + } + + public static string GetName(this ClaimsPrincipal principal) + { + return principal.FindFirstValue(ClaimTypes.Name) ?? string.Empty; + } + + public static ClaimsIdentity CreateIdentity(int cid, string name, string authenticationType) + { + return new ClaimsIdentity( + [ + new Claim(ClaimTypes.NameIdentifier, cid.ToString()), + new Claim(ClaimTypes.Name, name) + ], + authenticationType); + } +} diff --git a/source/CPDLCServer/Auth/Login/AdminAuthentication.cs b/source/CPDLCServer/Auth/Login/AdminAuthentication.cs deleted file mode 100644 index 6738d37..0000000 --- a/source/CPDLCServer/Auth/Login/AdminAuthentication.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Security.Claims; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; - -namespace CPDLCServer.Auth.Login; - -public static class AdminAuthentication -{ - public static Task SignIn(HttpContext httpContext, Guid userId, string username) - { - var identity = new ClaimsIdentity( - [ - new Claim(ClaimTypes.NameIdentifier, userId.ToString()), - new Claim(ClaimTypes.Name, username) - ], - CookieAuthenticationDefaults.AuthenticationScheme); - - return httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); - } - - public static Task SignOut(HttpContext httpContext) - { - return httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); - } -} diff --git a/source/CPDLCServer/Auth/Login/ClientIpAddress.cs b/source/CPDLCServer/Auth/Login/ClientIpAddress.cs deleted file mode 100644 index d6c5cc0..0000000 --- a/source/CPDLCServer/Auth/Login/ClientIpAddress.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Net; - -namespace CPDLCServer.Auth.Login; - -/// -/// Gives the IP address of the client. -/// Behind a proxy, the connection comes from the proxy, so the IP address of the client comes from a header that the proxy adds. -/// A client can also send these headers. Thus a client that connects without the proxy can choose its IP address. -/// -public static class ClientIpAddress -{ - // The first header that contains a valid IP address is used - static readonly string[] Headers = - [ - "do-connecting-ip", // DigitalOcean App Platform - "cf-connecting-ip", // Cloudflare - "true-client-ip", // Akamai, Cloudflare Enterprise - "x-real-ip", // nginx - "x-forwarded-for" // Most proxies. The first address is the client. - ]; - - public static string Get(HttpContext httpContext) - { - foreach (var header in Headers) - { - if (!httpContext.Request.Headers.TryGetValue(header, out var stringValues)) - continue; - - var firstAddress = stringValues.ToString().Split(',')[0].Trim(); - if (IPAddress.TryParse(firstAddress, out var address)) - return address.ToString(); - } - - return httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown"; - } -} diff --git a/source/CPDLCServer/Auth/Login/LoginCommand.cs b/source/CPDLCServer/Auth/Login/LoginCommand.cs deleted file mode 100644 index ea0d6b7..0000000 --- a/source/CPDLCServer/Auth/Login/LoginCommand.cs +++ /dev/null @@ -1,8 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Auth.Login; - -// Returns null when the login fails -public record LoginCommand(string Username, string Password, string IpAddress) : IRequest; - -public record LoginResult(Guid UserId, string Username); diff --git a/source/CPDLCServer/Auth/Login/LoginCommandHandler.cs b/source/CPDLCServer/Auth/Login/LoginCommandHandler.cs deleted file mode 100644 index c2a9553..0000000 --- a/source/CPDLCServer/Auth/Login/LoginCommandHandler.cs +++ /dev/null @@ -1,56 +0,0 @@ -using CPDLCServer.Auth.Users; -using MediatR; -using Microsoft.AspNetCore.Identity; - -namespace CPDLCServer.Auth.Login; - -// Checks the password of a user. -// After too many failed logins from an IP address, the login is locked for that IP address. -public class LoginCommandHandler( - IUserRepository userRepository, - IPasswordHasher passwordHasher, - LoginLockout loginLockout, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(LoginCommand request, CancellationToken cancellationToken) - { - // Do not check the password during the lockout, so that a person cannot continue to try passwords - if (loginLockout.IsLockedOut(request.IpAddress)) - { - logger.Warning("Failed login for {Username} from {IpAddress}: the IP address is locked out", request.Username, request.IpAddress); - return null; - } - - var user = await userRepository.FindByUsername(request.Username.Trim(), cancellationToken); - var result = user is null - ? PasswordVerificationResult.Failed - : passwordHasher.VerifyHashedPassword(user, user.PasswordHash, request.Password); - - if (user is null || result == PasswordVerificationResult.Failed) - { - var lockoutEnd = loginLockout.RecordFailure(request.IpAddress); - if (lockoutEnd is not null) - { - logger.Warning( - "Failed login for {Username} from {IpAddress}: the IP address is locked out until {LockoutEnd}", - request.Username, request.IpAddress, lockoutEnd); - } - else - { - logger.Warning("Failed login for {Username} from {IpAddress}", request.Username, request.IpAddress); - } - - return null; - } - - loginLockout.Reset(request.IpAddress); - - // The hash was made with older settings. Make it again with the current settings. - if (result == PasswordVerificationResult.SuccessRehashNeeded) - user.PasswordHash = passwordHasher.HashPassword(user, request.Password); - - logger.Information("User {Username} logged in from {IpAddress}", user.Username, request.IpAddress); - return new LoginResult(user.Id, user.Username); - } -} diff --git a/source/CPDLCServer/Auth/Login/LoginLockout.cs b/source/CPDLCServer/Auth/Login/LoginLockout.cs deleted file mode 100644 index f3aaef2..0000000 --- a/source/CPDLCServer/Auth/Login/LoginLockout.cs +++ /dev/null @@ -1,79 +0,0 @@ -using CPDLCServer.Infrastructure; - -namespace CPDLCServer.Auth.Login; - -// Locks the login for an IP address after too many failed logins. -// The failed logins are kept only in memory, so a restart clears them. -public class LoginLockout(IClock clock) -{ - public const int MaxFailedLogins = 5; - public static readonly TimeSpan LockoutDuration = TimeSpan.FromMinutes(15); - - readonly Lock _lock = new(); - readonly Dictionary _failedLogins = new(); - - public bool IsLockedOut(string ipAddress) - { - lock (_lock) - { - var now = clock.UtcNow(); - RemoveExpired(now); - - return _failedLogins.TryGetValue(ipAddress, out var failedLogins) && failedLogins.LockoutEnd > now; - } - } - - // Returns the end of the lockout when this failure locks the IP address - public DateTimeOffset? RecordFailure(string ipAddress) - { - lock (_lock) - { - var now = clock.UtcNow(); - RemoveExpired(now); - - if (!_failedLogins.TryGetValue(ipAddress, out var failedLogins)) - { - failedLogins = new FailedLogins(); - _failedLogins[ipAddress] = failedLogins; - } - - failedLogins.Count++; - failedLogins.LastFailure = now; - - if (failedLogins.Count < MaxFailedLogins) - return null; - - failedLogins.Count = 0; - failedLogins.LockoutEnd = now + LockoutDuration; - return failedLogins.LockoutEnd; - } - } - - public void Reset(string ipAddress) - { - lock (_lock) - { - _failedLogins.Remove(ipAddress); - } - } - - // The failed logins of an IP address expire after the lockout duration without a new failure. - // This also ends a lockout, because a lockout starts at a failure. - void RemoveExpired(DateTimeOffset now) - { - var expired = _failedLogins - .Where(pair => pair.Value.LastFailure + LockoutDuration <= now) - .Select(pair => pair.Key) - .ToList(); - - foreach (var ipAddress in expired) - _failedLogins.Remove(ipAddress); - } - - class FailedLogins - { - public int Count { get; set; } - public DateTimeOffset LastFailure { get; set; } - public DateTimeOffset? LockoutEnd { get; set; } - } -} diff --git a/source/CPDLCServer/Auth/Login/PasswordRateLimit.cs b/source/CPDLCServer/Auth/Login/PasswordRateLimit.cs deleted file mode 100644 index 9cf74e3..0000000 --- a/source/CPDLCServer/Auth/Login/PasswordRateLimit.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Threading.RateLimiting; -using Microsoft.AspNetCore.RateLimiting; - -namespace CPDLCServer.Auth.Login; - -/// -/// Limits the number of password attempts from one IP address, so that a person cannot quickly try many passwords. -/// -public static class PasswordRateLimit -{ - public const string PolicyName = "password"; - - const int PermitLimit = 10; - static readonly TimeSpan Window = TimeSpan.FromMinutes(1); - - public static void Configure(RateLimiterOptions options) - { - options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; - options.OnRejected = (context, cancellationToken) => - new ValueTask(context.HttpContext.Response.WriteAsync( - "Too many attempts. Wait one minute, then try again.", - cancellationToken)); - - options.AddPolicy(PolicyName, httpContext => - { - // Only a form post sends a password. Do not limit the page itself. - if (!HttpMethods.IsPost(httpContext.Request.Method)) - return RateLimitPartition.GetNoLimiter(string.Empty); - - var address = ClientIpAddress.Get(httpContext); - return RateLimitPartition.GetFixedWindowLimiter(address, _ => new FixedWindowRateLimiterOptions - { - PermitLimit = PermitLimit, - Window = Window, - QueueLimit = 0 - }); - }); - } -} diff --git a/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommand.cs b/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommand.cs new file mode 100644 index 0000000..c59f456 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommand.cs @@ -0,0 +1,6 @@ +using CPDLCServer.Contracts; +using MediatR; + +namespace CPDLCServer.Auth.PluginTokens; + +public record CreatePluginTokenCommand(int Cid, string Name) : IRequest; diff --git a/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommandHandler.cs b/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommandHandler.cs new file mode 100644 index 0000000..44adb3a --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/CreatePluginTokenCommandHandler.cs @@ -0,0 +1,40 @@ +using CPDLCServer.Contracts; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Auth.PluginTokens; + +public class CreatePluginTokenCommandHandler( + IPluginTokenRepository pluginTokenRepository, + IClock clock, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(CreatePluginTokenCommand request, CancellationToken cancellationToken) + { + var token = PluginTokenHash.NewToken(); + var now = clock.UtcNow(); + + var pluginToken = new PluginToken + { + Id = Guid.NewGuid(), + Cid = request.Cid, + Name = request.Name, + TokenHash = PluginTokenHash.Compute(token), + Created = now, + Expires = now + PluginToken.Lifetime + }; + + await pluginTokenRepository.Add(pluginToken, cancellationToken); + + unitOfWork.AfterCommit(_ => + { + logger.Information("Plugin token created for {Name} ({Cid})", request.Name, request.Cid); + return Task.CompletedTask; + }); + + return new PluginTokenResponse(token, pluginToken.Expires, request.Cid, request.Name); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/IPluginTokenRepository.cs b/source/CPDLCServer/Auth/PluginTokens/IPluginTokenRepository.cs new file mode 100644 index 0000000..351beca --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/IPluginTokenRepository.cs @@ -0,0 +1,8 @@ +namespace CPDLCServer.Auth.PluginTokens; + +public interface IPluginTokenRepository +{ + Task Add(PluginToken token, CancellationToken cancellationToken); + Task Remove(PluginToken token, CancellationToken cancellationToken); + Task FindByHash(string tokenHash, CancellationToken cancellationToken); +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginAuthorizationCodes.cs b/source/CPDLCServer/Auth/PluginTokens/PluginAuthorizationCodes.cs new file mode 100644 index 0000000..f9b7491 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginAuthorizationCodes.cs @@ -0,0 +1,73 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; +using CPDLCServer.Infrastructure; + +namespace CPDLCServer.Auth.PluginTokens; + +/// +/// The one-use codes of the plugin login (OAuth authorization code with PKCE). +/// The browser gives the code to the plugin. The plugin changes the code for a token, with the verifier that only it has. +/// The codes are kept only in memory. They expire after one minute. +/// +public class PluginAuthorizationCodes(IClock clock) +{ + public static readonly TimeSpan CodeLifetime = TimeSpan.FromMinutes(1); + + readonly ConcurrentDictionary _codes = new(); + + public string Create(int cid, string name, string redirectUri, string codeChallenge) + { + RemoveExpired(); + + var code = PluginTokenHash.Base64Url(RandomNumberGenerator.GetBytes(32)); + _codes[code] = new PendingCode(cid, name, redirectUri, codeChallenge, clock.UtcNow() + CodeLifetime); + return code; + } + + // Returns null when the code does not exist, has expired, or does not match the redirect URI and the verifier. + // A code can be used one time only, also when the check fails. + public PluginUser? Redeem(string code, string redirectUri, string codeVerifier) + { + if (!_codes.TryRemove(code, out var pendingCode)) + return null; + + if (pendingCode.Expires <= clock.UtcNow()) + return null; + + if (pendingCode.RedirectUri != redirectUri) + return null; + + if (!IsValidVerifier(codeVerifier, pendingCode.CodeChallenge)) + return null; + + return new PluginUser(pendingCode.Cid, pendingCode.Name); + } + + // S256: the challenge is the Base64 URL of the SHA-256 of the verifier + public static string ComputeChallenge(string codeVerifier) + { + return PluginTokenHash.Base64Url(SHA256.HashData(Encoding.ASCII.GetBytes(codeVerifier))); + } + + static bool IsValidVerifier(string codeVerifier, string codeChallenge) + { + return CryptographicOperations.FixedTimeEquals( + Encoding.ASCII.GetBytes(ComputeChallenge(codeVerifier)), + Encoding.ASCII.GetBytes(codeChallenge)); + } + + void RemoveExpired() + { + var now = clock.UtcNow(); + foreach (var (code, pendingCode) in _codes) + { + if (pendingCode.Expires <= now) + _codes.TryRemove(code, out _); + } + } + + record PendingCode(int Cid, string Name, string RedirectUri, string CodeChallenge, DateTimeOffset Expires); +} + +public record PluginUser(int Cid, string Name); diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginEndpoints.cs b/source/CPDLCServer/Auth/PluginTokens/PluginEndpoints.cs new file mode 100644 index 0000000..9db314d --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginEndpoints.cs @@ -0,0 +1,62 @@ +using System.Security.Claims; +using CPDLCServer.Contracts; +using CPDLCServer.Infrastructure; + +namespace CPDLCServer.Auth.PluginTokens; + +// The plugin changes its code for a token here, and checks or revokes its token. +// The browser part of the login is the /plugin/authorize page. +public static class PluginEndpoints +{ + public static void MapPluginEndpoints(this IEndpointRouteBuilder endpoints) + { + endpoints.MapPost("/plugin/token", CreateToken); + endpoints.MapGet("/plugin/me", GetUser).RequireAuthorization(PluginTokenAuthenticationHandler.PolicyName); + endpoints.MapPost("/plugin/logout", Logout).RequireAuthorization(PluginTokenAuthenticationHandler.PolicyName); + } + + // The form is read directly, so that no antiforgery token is necessary. The plugin is not a browser. + // The PKCE verifier protects the code. + static async Task CreateToken( + HttpRequest request, + PluginAuthorizationCodes authorizationCodes, + IUnitOfWorkMediator mediator, + ILogger logger, + CancellationToken cancellationToken) + { + if (!request.HasFormContentType) + return Results.BadRequest(new { error = "invalid_request" }); + + var form = await request.ReadFormAsync(cancellationToken); + var code = form["code"].ToString(); + var codeVerifier = form["code_verifier"].ToString(); + var redirectUri = form["redirect_uri"].ToString(); + + if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(codeVerifier) || string.IsNullOrEmpty(redirectUri)) + return Results.BadRequest(new { error = "invalid_request" }); + + var user = authorizationCodes.Redeem(code, redirectUri, codeVerifier); + if (user is null) + { + logger.Warning("Plugin token request with a code that is not valid"); + return Results.BadRequest(new { error = "invalid_grant" }); + } + + var response = await mediator.Send(new CreatePluginTokenCommand(user.Cid, user.Name), cancellationToken); + return Results.Ok(response); + } + + static IResult GetUser(ClaimsPrincipal user) + { + var expires = DateTimeOffset.Parse(user.FindFirstValue(PluginTokenAuthenticationHandler.ExpiresClaimType)!); + return Results.Ok(new PluginUserDto(user.GetCid()!.Value, user.GetName(), expires)); + } + + static async Task Logout(HttpRequest request, IUnitOfWorkMediator mediator, CancellationToken cancellationToken) + { + // The policy accepted the token, so the header has it + var token = request.Headers.Authorization.ToString()["Bearer ".Length..].Trim(); + await mediator.Send(new RevokePluginTokenCommand(token), cancellationToken); + return Results.NoContent(); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginRedirectUri.cs b/source/CPDLCServer/Auth/PluginTokens/PluginRedirectUri.cs new file mode 100644 index 0000000..40dfd71 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginRedirectUri.cs @@ -0,0 +1,19 @@ +namespace CPDLCServer.Auth.PluginTokens; + +// The plugin gets the code on a port of the computer that it runs on. Only these addresses are accepted, so that a +// link cannot send the code to a different computer. +public static class PluginRedirectUri +{ + public static bool IsValid(string? redirectUri) + { + if (!Uri.TryCreate(redirectUri, UriKind.Absolute, out var uri)) + return false; + + return uri.Scheme == Uri.UriSchemeHttp && + uri.Host is "127.0.0.1" or "localhost" && + !uri.IsDefaultPort && + string.IsNullOrEmpty(uri.Query) && + string.IsNullOrEmpty(uri.Fragment) && + string.IsNullOrEmpty(uri.UserInfo); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginToken.cs b/source/CPDLCServer/Auth/PluginTokens/PluginToken.cs new file mode 100644 index 0000000..0dc67c9 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginToken.cs @@ -0,0 +1,14 @@ +namespace CPDLCServer.Auth.PluginTokens; + +// Lets the plugin of one VATSIM user connect to the hub. The plain token is never stored, only its hash. +public class PluginToken +{ + public static readonly TimeSpan Lifetime = TimeSpan.FromDays(30); + + public Guid Id { get; init; } + public int Cid { get; init; } + public string Name { get; init; } = string.Empty; + public string TokenHash { get; init; } = string.Empty; + public DateTimeOffset Created { get; init; } + public DateTimeOffset Expires { get; init; } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginTokenAuthenticationHandler.cs b/source/CPDLCServer/Auth/PluginTokens/PluginTokenAuthenticationHandler.cs new file mode 100644 index 0000000..081c9a8 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginTokenAuthenticationHandler.cs @@ -0,0 +1,57 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using CPDLCServer.Infrastructure; +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Options; + +namespace CPDLCServer.Auth.PluginTokens; + +/// +/// Authenticates the plugin with its token. The token is in the Authorization header ("Bearer ..."). +/// For the hub, the token can also be in the access_token query parameter, because a browser WebSocket cannot send headers. +/// +public class PluginTokenAuthenticationHandler( + IOptionsMonitor options, + ILoggerFactory loggerFactory, + UrlEncoder encoder, + IPluginTokenRepository pluginTokenRepository, + IClock clock) + : AuthenticationHandler(options, loggerFactory, encoder) +{ + public const string AuthenticationScheme = "PluginToken"; + + // The authorization policy of the hub and of the plugin endpoints + public const string PolicyName = "Plugin"; + public const string ExpiresClaimType = "plugin_token_expires"; + + protected override async Task HandleAuthenticateAsync() + { + var token = ReadToken(); + if (string.IsNullOrEmpty(token)) + return AuthenticateResult.NoResult(); + + var pluginToken = await pluginTokenRepository.FindByHash(PluginTokenHash.Compute(token), Context.RequestAborted); + if (pluginToken is null) + return AuthenticateResult.Fail("The token is not valid"); + + if (pluginToken.Expires <= clock.UtcNow()) + return AuthenticateResult.Fail("The token has expired"); + + var identity = CurrentUser.CreateIdentity(pluginToken.Cid, pluginToken.Name, AuthenticationScheme); + identity.AddClaim(new Claim(ExpiresClaimType, pluginToken.Expires.ToString("O"))); + + return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), AuthenticationScheme)); + } + + string? ReadToken() + { + var authorization = Request.Headers.Authorization.ToString(); + if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + return authorization["Bearer ".Length..].Trim(); + + if (Request.Path.StartsWithSegments("/hubs")) + return Request.Query["access_token"].ToString(); + + return null; + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginTokenConfiguration.cs b/source/CPDLCServer/Auth/PluginTokens/PluginTokenConfiguration.cs new file mode 100644 index 0000000..771c2fa --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginTokenConfiguration.cs @@ -0,0 +1,18 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace CPDLCServer.Auth.PluginTokens; + +public class PluginTokenConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("PluginTokens"); + + builder.HasKey(t => t.Id); + builder.Property(t => t.Id).ValueGeneratedNever(); + + builder.HasIndex(t => t.TokenHash).IsUnique(); + builder.HasIndex(t => t.Cid); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginTokenHash.cs b/source/CPDLCServer/Auth/PluginTokens/PluginTokenHash.cs new file mode 100644 index 0000000..fc8987f --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginTokenHash.cs @@ -0,0 +1,23 @@ +using System.Security.Cryptography; +using System.Text; + +namespace CPDLCServer.Auth.PluginTokens; + +public static class PluginTokenHash +{ + // The token is random and long, so a fast hash is safe. A slow hash, as for a password, is not necessary. + public static string Compute(string token) + { + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))); + } + + public static string NewToken() + { + return Base64Url(RandomNumberGenerator.GetBytes(32)); + } + + public static string Base64Url(byte[] bytes) + { + return Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/PluginTokenRepository.cs b/source/CPDLCServer/Auth/PluginTokens/PluginTokenRepository.cs new file mode 100644 index 0000000..f86b1f6 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/PluginTokenRepository.cs @@ -0,0 +1,25 @@ +using CPDLCServer.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Auth.PluginTokens; + +// The changes are saved when the unit of work is committed +public class PluginTokenRepository(CpdlcDbContext dbContext) : IPluginTokenRepository +{ + public Task Add(PluginToken token, CancellationToken cancellationToken) + { + dbContext.PluginTokens.Add(token); + return Task.CompletedTask; + } + + public Task Remove(PluginToken token, CancellationToken cancellationToken) + { + dbContext.PluginTokens.Remove(token); + return Task.CompletedTask; + } + + public async Task FindByHash(string tokenHash, CancellationToken cancellationToken) + { + return await dbContext.PluginTokens.SingleOrDefaultAsync(t => t.TokenHash == tokenHash, cancellationToken); + } +} diff --git a/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommand.cs b/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommand.cs new file mode 100644 index 0000000..8961f6d --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.Auth.PluginTokens; + +// Does nothing if the token does not exist +public record RevokePluginTokenCommand(string Token) : IRequest; diff --git a/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommandHandler.cs b/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommandHandler.cs new file mode 100644 index 0000000..6890747 --- /dev/null +++ b/source/CPDLCServer/Auth/PluginTokens/RevokePluginTokenCommandHandler.cs @@ -0,0 +1,26 @@ +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Auth.PluginTokens; + +public class RevokePluginTokenCommandHandler( + IPluginTokenRepository pluginTokenRepository, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(RevokePluginTokenCommand request, CancellationToken cancellationToken) + { + var pluginToken = await pluginTokenRepository.FindByHash(PluginTokenHash.Compute(request.Token), cancellationToken); + if (pluginToken is null) + return; + + await pluginTokenRepository.Remove(pluginToken, cancellationToken); + + unitOfWork.AfterCommit(_ => + { + logger.Information("Plugin token revoked for {Name} ({Cid})", pluginToken.Name, pluginToken.Cid); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Auth/Users/ChangePasswordCommand.cs b/source/CPDLCServer/Auth/Users/ChangePasswordCommand.cs deleted file mode 100644 index 02559df..0000000 --- a/source/CPDLCServer/Auth/Users/ChangePasswordCommand.cs +++ /dev/null @@ -1,5 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Auth.Users; - -public record ChangePasswordCommand(Guid UserId, string NewPassword) : IRequest; diff --git a/source/CPDLCServer/Auth/Users/ChangePasswordCommandHandler.cs b/source/CPDLCServer/Auth/Users/ChangePasswordCommandHandler.cs deleted file mode 100644 index 12d756a..0000000 --- a/source/CPDLCServer/Auth/Users/ChangePasswordCommandHandler.cs +++ /dev/null @@ -1,21 +0,0 @@ -using MediatR; -using Microsoft.AspNetCore.Identity; - -namespace CPDLCServer.Auth.Users; - -public class ChangePasswordCommandHandler( - IUserRepository userRepository, - IPasswordHasher passwordHasher, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(ChangePasswordCommand request, CancellationToken cancellationToken) - { - var user = await userRepository.FindById(request.UserId, cancellationToken); - if (user is null) - throw new InvalidOperationException($"User {request.UserId} does not exist"); - - user.PasswordHash = passwordHasher.HashPassword(user, request.NewPassword); - logger.Information("The password of user {Username} was changed", user.Username); - } -} diff --git a/source/CPDLCServer/Auth/Users/CreateUserCommand.cs b/source/CPDLCServer/Auth/Users/CreateUserCommand.cs deleted file mode 100644 index bf76ec6..0000000 --- a/source/CPDLCServer/Auth/Users/CreateUserCommand.cs +++ /dev/null @@ -1,5 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Auth.Users; - -public record CreateUserCommand(string Username, string Password) : IRequest; diff --git a/source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs b/source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs deleted file mode 100644 index a1ca693..0000000 --- a/source/CPDLCServer/Auth/Users/CreateUserCommandHandler.cs +++ /dev/null @@ -1,44 +0,0 @@ -using CPDLCServer.Infrastructure; -using CPDLCServer.Persistence; -using CPDLCServer.Setup; -using MediatR; -using Microsoft.AspNetCore.Identity; - -namespace CPDLCServer.Auth.Users; - -// The setup creates the first user -public class CreateUserCommandHandler( - IUserRepository userRepository, - IPasswordHasher passwordHasher, - SetupState setupState, - IClock clock, - IUnitOfWork unitOfWork, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(CreateUserCommand request, CancellationToken cancellationToken) - { - if (await userRepository.Any(cancellationToken)) - throw new InvalidOperationException("A user already exists"); - - var user = new User - { - Id = Guid.NewGuid(), - Username = request.Username.Trim(), - Created = clock.UtcNow() - }; - - user.PasswordHash = passwordHasher.HashPassword(user, request.Password); - - await userRepository.Add(user, cancellationToken); - - unitOfWork.AfterCommit(_ => - { - setupState.MarkAdminCreated(); - logger.Information("User {Username} created", user.Username); - return Task.CompletedTask; - }); - - return user.Id; - } -} diff --git a/source/CPDLCServer/Auth/Users/IUserRepository.cs b/source/CPDLCServer/Auth/Users/IUserRepository.cs deleted file mode 100644 index 635cee1..0000000 --- a/source/CPDLCServer/Auth/Users/IUserRepository.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace CPDLCServer.Auth.Users; - -public interface IUserRepository -{ - Task Add(User user, CancellationToken cancellationToken); - Task FindByUsername(string username, CancellationToken cancellationToken); - Task FindById(Guid id, CancellationToken cancellationToken); - Task All(CancellationToken cancellationToken); - Task Any(CancellationToken cancellationToken); -} diff --git a/source/CPDLCServer/Auth/Users/User.cs b/source/CPDLCServer/Auth/Users/User.cs deleted file mode 100644 index ee630a1..0000000 --- a/source/CPDLCServer/Auth/Users/User.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace CPDLCServer.Auth.Users; - -// A user that can open the restricted pages of the dashboard -public class User -{ - public Guid Id { get; init; } - public string Username { get; init; } = string.Empty; - public string PasswordHash { get; set; } = string.Empty; - public DateTimeOffset Created { get; init; } -} diff --git a/source/CPDLCServer/Auth/Users/UserConfiguration.cs b/source/CPDLCServer/Auth/Users/UserConfiguration.cs deleted file mode 100644 index ffb8a10..0000000 --- a/source/CPDLCServer/Auth/Users/UserConfiguration.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace CPDLCServer.Auth.Users; - -public class UserConfiguration : IEntityTypeConfiguration -{ - public void Configure(EntityTypeBuilder builder) - { - builder.ToTable("Users"); - - builder.HasKey(u => u.Id); - builder.Property(u => u.Id).ValueGeneratedNever(); - - builder.HasIndex(u => u.Username).IsUnique(); - } -} diff --git a/source/CPDLCServer/Auth/Users/UserRepository.cs b/source/CPDLCServer/Auth/Users/UserRepository.cs deleted file mode 100644 index 8b25a7c..0000000 --- a/source/CPDLCServer/Auth/Users/UserRepository.cs +++ /dev/null @@ -1,42 +0,0 @@ -using CPDLCServer.Persistence; -using Microsoft.EntityFrameworkCore; - -namespace CPDLCServer.Auth.Users; - -// The changes are saved when the unit of work is committed. -// Queries load the rows into the context, then read the local entities, so that the results include entities that are -// added in the unit of work and exclude entities that are removed in it. -public class UserRepository(CpdlcDbContext dbContext) : IUserRepository -{ - public Task Add(User user, CancellationToken cancellationToken) - { - dbContext.Users.Add(user); - return Task.CompletedTask; - } - - public async Task FindByUsername(string username, CancellationToken cancellationToken) - { - await dbContext.Users - .Where(u => u.Username == username) - .LoadAsync(cancellationToken); - - return dbContext.Users.Local.FirstOrDefault(u => u.Username == username); - } - - public async Task FindById(Guid id, CancellationToken cancellationToken) - { - return await dbContext.Users.FindAsync([id], cancellationToken); - } - - public async Task All(CancellationToken cancellationToken) - { - await dbContext.Users.LoadAsync(cancellationToken); - return dbContext.Users.Local.OrderBy(u => u.Username).ToArray(); - } - - public async Task Any(CancellationToken cancellationToken) - { - await dbContext.Users.LoadAsync(cancellationToken); - return dbContext.Users.Local.Count > 0; - } -} diff --git a/source/CPDLCServer/Auth/VatsimConnect/VatsimConnectOptions.cs b/source/CPDLCServer/Auth/VatsimConnect/VatsimConnectOptions.cs new file mode 100644 index 0000000..75ac2fa --- /dev/null +++ b/source/CPDLCServer/Auth/VatsimConnect/VatsimConnectOptions.cs @@ -0,0 +1,13 @@ +namespace CPDLCServer.Auth.VatsimConnect; + +// The OAuth client of this server on VATSIM Connect. Make the client at https://auth.vatsim.net (or https://auth-dev.vatsim.net). +// The redirect URL of the client is https:///signin-vatsim +public class VatsimConnectOptions +{ + public const string AuthenticationScheme = "VatsimConnect"; + public const string CallbackPath = "/signin-vatsim"; + + public required string ClientId { get; init; } + public required string ClientSecret { get; init; } + public Uri Authority { get; init; } = new("https://auth.vatsim.net"); +} diff --git a/source/CPDLCServer/Auth/VatsimConnect/VatsimUser.cs b/source/CPDLCServer/Auth/VatsimConnect/VatsimUser.cs new file mode 100644 index 0000000..d464b4d --- /dev/null +++ b/source/CPDLCServer/Auth/VatsimConnect/VatsimUser.cs @@ -0,0 +1,27 @@ +using System.Text.Json; + +namespace CPDLCServer.Auth.VatsimConnect; + +// The user from the /api/user endpoint of VATSIM Connect +public record VatsimUser(int Cid, string Name) +{ + // The response is { "data": { "cid": "1234567", "personal": { "name_full": "..." } } }. + // The CID can be a string or a number. + public static VatsimUser Parse(JsonElement root) + { + var data = root.GetProperty("data"); + + var cidElement = data.GetProperty("cid"); + var cid = cidElement.ValueKind == JsonValueKind.Number + ? cidElement.GetInt32() + : int.Parse(cidElement.GetString()!); + + // The name is empty if the user did not give the full_name scope + var name = data.TryGetProperty("personal", out var personal) && + personal.TryGetProperty("name_full", out var nameFull) + ? nameFull.GetString() ?? string.Empty + : string.Empty; + + return new VatsimUser(cid, string.IsNullOrWhiteSpace(name) ? cid.ToString() : name); + } +} diff --git a/source/CPDLCServer/Controllers/ControllerInfo.cs b/source/CPDLCServer/Controllers/ControllerInfo.cs index ba8e104..a6160d5 100644 --- a/source/CPDLCServer/Controllers/ControllerInfo.cs +++ b/source/CPDLCServer/Controllers/ControllerInfo.cs @@ -1,13 +1,19 @@ namespace CPDLCServer.Controllers; +// A controller that is connected to the hub with the plugin. +// The user ID identifies the hub connection. The CID and the name come from the plugin token. public class ControllerInfo( Guid userId, string connectionId, string stationId, - string callsign) + string callsign, + int cid, + string name) { public Guid UserId { get; } = userId; public string ConnectionId { get; } = connectionId; public string StationId { get; } = stationId; public string Callsign { get; } = callsign; + public int Cid { get; } = cid; + public string Name { get; } = name; } diff --git a/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs b/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs index a9684b3..cc30575 100644 --- a/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs +++ b/source/CPDLCServer/Cpdlc/CpdlcServiceCollectionExtensions.cs @@ -1,5 +1,6 @@ using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Cpdlc.Dialogues; +using CPDLCServer.Cpdlc.Motd; using CPDLCServer.Cpdlc.Uplinks; namespace CPDLCServer.Cpdlc; @@ -18,6 +19,8 @@ public static IServiceCollection AddCpdlc(this IServiceCollection services) services.AddScoped(); services.AddScoped(); + services.AddSingleton(); + return services; } } diff --git a/source/CPDLCServer/Cpdlc/Motd/MotdScheduler.cs b/source/CPDLCServer/Cpdlc/Motd/MotdScheduler.cs new file mode 100644 index 0000000..cd9fabf --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Motd/MotdScheduler.cs @@ -0,0 +1,35 @@ +using CPDLCServer.Infrastructure; + +namespace CPDLCServer.Cpdlc.Motd; + +/// +/// Sends the message of the day of an ACARS connection to an aircraft after a delay. +/// The delay runs in the background, so that the logon does not wait for it. +/// +public class MotdScheduler( + IUnitOfWorkMediator mediator, + IHostApplicationLifetime lifetime, + ILogger logger) +{ + public void Schedule(string acarsConnectionId, string callsign, TimeSpan delay) + { + _ = Task.Run(async () => + { + var cancellationToken = lifetime.ApplicationStopping; + + try + { + await Task.Delay(delay, cancellationToken); + await mediator.Send(new SendMotdCommand(acarsConnectionId, callsign), cancellationToken); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // The server is stopping + } + catch (Exception ex) + { + logger.Error(ex, "Failed to send the message of the day to {Callsign} on {AcarsConnectionId}", callsign, acarsConnectionId); + } + }); + } +} diff --git a/source/CPDLCServer/Cpdlc/Motd/SendMotdCommand.cs b/source/CPDLCServer/Cpdlc/Motd/SendMotdCommand.cs new file mode 100644 index 0000000..43d5349 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Motd/SendMotdCommand.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace CPDLCServer.Cpdlc.Motd; + +public record SendMotdCommand(string AcarsConnectionId, string Callsign) : IRequest; diff --git a/source/CPDLCServer/Cpdlc/Motd/SendMotdCommandHandler.cs b/source/CPDLCServer/Cpdlc/Motd/SendMotdCommandHandler.cs new file mode 100644 index 0000000..8a24f78 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Motd/SendMotdCommandHandler.cs @@ -0,0 +1,42 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Cpdlc.Uplinks; +using MediatR; + +namespace CPDLCServer.Cpdlc.Motd; + +// Sends the message of the day as a CPDLC free text message with no response. +// The message is not sent if the aircraft disconnected during the delay, or if the message was removed. +public class SendMotdCommandHandler( + IAircraftRepository aircraftRepository, + IAcarsConnectionManager acarsConnectionManager, + IMediator mediator, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(SendMotdCommand request, CancellationToken cancellationToken) + { + var aircraftConnection = await aircraftRepository.Find( + new AircraftKey(request.Callsign, request.AcarsConnectionId), + cancellationToken); + if (aircraftConnection is not { DataAuthorityState: DataAuthorityState.CurrentDataAuthority }) + { + logger.Information("Message of the day not sent to {Callsign}: the aircraft is not connected", request.Callsign); + return; + } + + var configuration = await acarsConnectionManager.GetConfigurationForStation(aircraftConnection.StationId, cancellationToken); + if (string.IsNullOrWhiteSpace(configuration.Motd)) + return; + + logger.Information("Sending the message of the day to {Callsign}", request.Callsign); + + await mediator.Send( + new BeginDialogueCommand( + aircraftConnection.StationId, + request.Callsign, + CpdlcUplinkResponseType.NoResponse, + configuration.Motd), + cancellationToken); + } +} diff --git a/source/CPDLCServer/Cpdlc/Motd/SendMotdOnConnectionEstablishedHandler.cs b/source/CPDLCServer/Cpdlc/Motd/SendMotdOnConnectionEstablishedHandler.cs new file mode 100644 index 0000000..1f255c8 --- /dev/null +++ b/source/CPDLCServer/Cpdlc/Motd/SendMotdOnConnectionEstablishedHandler.cs @@ -0,0 +1,31 @@ +using CPDLCServer.AcarsConnections; +using CPDLCServer.Cpdlc.Connections; +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Cpdlc.Motd; + +// When an aircraft logs on, the message of the day of the ACARS connection is sent after its delay. +// It is sent only to the current data authority, so that the next data authority does not send it a second time. +public class SendMotdOnConnectionEstablishedHandler( + IAcarsConnectionManager acarsConnectionManager, + MotdScheduler motdScheduler, + IUnitOfWork unitOfWork) + : INotificationHandler +{ + public async Task Handle(AircraftConnectionEstablished notification, CancellationToken cancellationToken) + { + if (notification.DataAuthorityState != DataAuthorityState.CurrentDataAuthority) + return; + + var configuration = await acarsConnectionManager.GetConfigurationForStation(notification.StationId, cancellationToken); + if (string.IsNullOrWhiteSpace(configuration.Motd)) + return; + + unitOfWork.AfterCommit(_ => + { + motdScheduler.Schedule(notification.AcarsConnectionId, notification.Callsign, configuration.MotdDelay); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs b/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs index e41aa06..3367e49 100644 --- a/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs +++ b/source/CPDLCServer/Infrastructure/UnitOfWorkMediator.cs @@ -1,6 +1,8 @@ +using CPDLCServer.Logging; using CPDLCServer.Persistence; using MediatR; using Microsoft.EntityFrameworkCore; +using Serilog.Context; namespace CPDLCServer.Infrastructure; @@ -27,6 +29,7 @@ public class UnitOfWorkMediator(IServiceScopeFactory serviceScopeFactory, ILogge public async Task Send(IRequest request, CancellationToken cancellationToken = default) { await Run( + request.GetType(), async mediator => { await mediator.Send(request, cancellationToken); @@ -37,12 +40,13 @@ await Run( public async Task Send(IRequest request, CancellationToken cancellationToken = default) { - return await Run(mediator => mediator.Send(request, cancellationToken), cancellationToken); + return await Run(request.GetType(), mediator => mediator.Send(request, cancellationToken), cancellationToken); } public async Task Publish(INotification notification, CancellationToken cancellationToken = default) { await Run( + notification.GetType(), async mediator => { await mediator.Publish(notification, cancellationToken); @@ -51,8 +55,11 @@ await Run( cancellationToken); } - async Task Run(Func> action, CancellationToken cancellationToken) + // The log entries of the unit of work get the area of the message. The nested messages are in the same area. + async Task Run(Type messageType, Func> action, CancellationToken cancellationToken) { + using var _ = LogContext.PushProperty(LogArea.PropertyName, LogArea.ForType(messageType)); + for (var attempt = 1; ; attempt++) { await using var scope = serviceScopeFactory.CreateAsyncScope(); diff --git a/source/CPDLCServer/Logging/InMemoryLogBufferSink.cs b/source/CPDLCServer/Logging/InMemoryLogBufferSink.cs index 42332da..42fc05e 100644 --- a/source/CPDLCServer/Logging/InMemoryLogBufferSink.cs +++ b/source/CPDLCServer/Logging/InMemoryLogBufferSink.cs @@ -22,10 +22,19 @@ public void Emit(LogEvent logEvent) Time: logEvent.Timestamp.ToString("HH:mm:ss"), Level: logEvent.Level.ToString(), LevelCode: LevelCode(logEvent.Level), + Area: StringProperty(logEvent, LogArea.PropertyName) ?? LogArea.System, + AcarsConnectionId: StringProperty(logEvent, LogArea.AcarsConnectionIdPropertyName), Message: writer.ToString(), Exception: logEvent.Exception?.ToString())); } + static string? StringProperty(LogEvent logEvent, string name) + { + return logEvent.Properties.TryGetValue(name, out var value) && value is ScalarValue { Value: string text } + ? text + : null; + } + // The same codes as {Level:u3} in the console output static string LevelCode(LogEventLevel level) { diff --git a/source/CPDLCServer/Logging/LogArea.cs b/source/CPDLCServer/Logging/LogArea.cs new file mode 100644 index 0000000..9775697 --- /dev/null +++ b/source/CPDLCServer/Logging/LogArea.cs @@ -0,0 +1,40 @@ +namespace CPDLCServer.Logging; + +/// +/// The part of the server that wrote a log entry. The Logs page can show only the entries of one area. +/// +public static class LogArea +{ + // The names of the log event properties + public const string PropertyName = "Area"; + public const string AcarsConnectionIdPropertyName = "AcarsConnectionId"; + + public const string Cpdlc = "CPDLC"; + public const string Adsc = "ADS-C"; + public const string Acars = "ACARS"; + public const string System = "System"; + + public static readonly string[] All = [Cpdlc, Adsc, Acars, System]; + + // The area of a request or a notification comes from its namespace + public static string ForType(Type type) + { + var typeNamespace = type.Namespace ?? string.Empty; + + if (IsIn(typeNamespace, "CPDLCServer.Cpdlc")) + return Cpdlc; + + if (IsIn(typeNamespace, "CPDLCServer.AdscContracts") || IsIn(typeNamespace, "CPDLCServer.VatsimStatus")) + return Adsc; + + if (IsIn(typeNamespace, "CPDLCServer.AcarsConnections")) + return Acars; + + return System; + } + + static bool IsIn(string typeNamespace, string areaNamespace) + { + return typeNamespace == areaNamespace || typeNamespace.StartsWith(areaNamespace + ".", StringComparison.Ordinal); + } +} diff --git a/source/CPDLCServer/Logging/LogEntry.cs b/source/CPDLCServer/Logging/LogEntry.cs index 1a97e6c..01a52c6 100644 --- a/source/CPDLCServer/Logging/LogEntry.cs +++ b/source/CPDLCServer/Logging/LogEntry.cs @@ -7,5 +7,7 @@ public record LogEntry( string Time, string Level, string LevelCode, + string Area, + string? AcarsConnectionId, string Message, string? Exception); diff --git a/source/CPDLCServer/Persistence/CpdlcDbContext.cs b/source/CPDLCServer/Persistence/CpdlcDbContext.cs index edaa75a..8e9fdd8 100644 --- a/source/CPDLCServer/Persistence/CpdlcDbContext.cs +++ b/source/CPDLCServer/Persistence/CpdlcDbContext.cs @@ -1,7 +1,8 @@ using CPDLCServer.AcarsConnections.ConnectionSettings; using CPDLCServer.AdscContracts; using CPDLCServer.AdscContracts.Reports; -using CPDLCServer.Auth.Users; +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Auth.PluginTokens; using CPDLCServer.Cpdlc.Connections; using CPDLCServer.Cpdlc.Dialogues; using CPDLCServer.Cpdlc.Downlinks; @@ -27,7 +28,8 @@ public class CpdlcDbContext(DbContextOptions options) : DbContext(options) public DbSet MessageIdSequences => Set(); public DbSet ServerSettings => Set(); public DbSet AcarsConnections => Set(); - public DbSet Users => Set(); + public DbSet Administrators => Set(); + public DbSet PluginTokens => Set(); protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { @@ -57,7 +59,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new MessageIdSequenceConfiguration()); modelBuilder.ApplyConfiguration(new ServerSettingsConfiguration()); modelBuilder.ApplyConfiguration(new AcarsConnectionSettingsConfiguration()); - modelBuilder.ApplyConfiguration(new UserConfiguration()); + modelBuilder.ApplyConfiguration(new AdministratorConfiguration()); + modelBuilder.ApplyConfiguration(new PluginTokenConfiguration()); // The messages have no version. A change to a message is a change to its dialogue (see SaveChangesAsync). Type[] versionedEntityTypes = @@ -69,7 +72,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) typeof(MessageIdSequence), typeof(ServerSettings), typeof(AcarsConnectionSettings), - typeof(User) + typeof(Administrator) ]; foreach (var entityType in versionedEntityTypes) diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.Designer.cs similarity index 90% rename from source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.Designer.cs rename to source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.Designer.cs index c82eadd..b1656ed 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.Designer.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.Designer.cs @@ -13,7 +13,7 @@ namespace CPDLCServer.Persistence.Migrations.PostgreSql { [DbContext(typeof(PostgreSqlCpdlcDbContext))] - [Migration("20261115043637_InitialCreate")] + [Migration("20261121042342_InitialCreate")] partial class InitialCreate { /// @@ -45,6 +45,13 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Motd") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("MotdDelaySeconds") + .HasColumnType("integer"); + b.Property("Notes") .HasMaxLength(2000) .HasColumnType("character varying(2000)"); @@ -194,32 +201,56 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.ToTable("AdscReports", (string)null); }); - modelBuilder.Entity("CPDLCServer.Auth.Users.User", b => + modelBuilder.Entity("CPDLCServer.Auth.Administrators.Administrator", b => + { + b.Property("Cid") + .HasColumnType("integer"); + + b.Property("Added") + .HasColumnType("bigint"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Cid"); + + b.ToTable("Administrators", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.PluginTokens.PluginToken", b => { b.Property("Id") .HasColumnType("uuid"); + b.Property("Cid") + .HasColumnType("integer"); + b.Property("Created") .HasColumnType("bigint"); - b.Property("PasswordHash") + b.Property("Expires") + .HasColumnType("bigint"); + + b.Property("Name") .IsRequired() .HasColumnType("text"); - b.Property("Username") + b.Property("TokenHash") .IsRequired() .HasColumnType("text"); - b.Property("Version") - .IsConcurrencyToken() - .HasColumnType("integer"); - b.HasKey("Id"); - b.HasIndex("Username") + b.HasIndex("Cid"); + + b.HasIndex("TokenHash") .IsUnique(); - b.ToTable("Users", (string)null); + b.ToTable("PluginTokens", (string)null); }); modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => @@ -395,6 +426,15 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("AircraftConnectionTimeoutMinutes") .HasColumnType("integer"); + b.Property("BannerContentType") + .HasColumnType("text"); + + b.Property("BannerImage") + .HasColumnType("bytea"); + + b.Property("BannerVersion") + .HasColumnType("integer"); + b.Property("ConnectivityCheckIntervalMinutes") .HasColumnType("integer"); @@ -404,6 +444,15 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("HandoffNotificationLeadTimeMinutes") .HasColumnType("integer"); + b.Property("Motd") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ServerName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + b.Property("VatsimStatusAllowNonEquippedAircraft") .HasColumnType("boolean"); diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.cs similarity index 87% rename from source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.cs rename to source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.cs index 6fc25f8..a8079e5 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261115043637_InitialCreate.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.cs @@ -25,6 +25,8 @@ protected override void Up(MigrationBuilder migrationBuilder) EncryptedAuthenticationCode = table.Column(type: "text", nullable: false), DefaultAdscReportingInterval = table.Column(type: "integer", nullable: false), SelectedAdscContractDuration = table.Column(type: "integer", nullable: false), + Motd = table.Column(type: "character varying(200)", maxLength: 200, nullable: true), + MotdDelaySeconds = table.Column(type: "integer", nullable: false), Notes = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: true), Version = table.Column(type: "integer", nullable: false) }, @@ -33,6 +35,20 @@ protected override void Up(MigrationBuilder migrationBuilder) table.PrimaryKey("PK_AcarsConnections", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Administrators", + columns: table => new + { + Cid = table.Column(type: "integer", nullable: false), + Name = table.Column(type: "text", nullable: true), + Added = table.Column(type: "bigint", nullable: false), + Version = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Administrators", x => x.Cid); + }); + migrationBuilder.CreateTable( name: "AdscContracts", columns: table => new @@ -135,12 +151,33 @@ protected override void Up(MigrationBuilder migrationBuilder) table.PrimaryKey("PK_MessageIdSequences", x => new { x.AcarsConnectionId, x.Callsign }); }); + migrationBuilder.CreateTable( + name: "PluginTokens", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Cid = table.Column(type: "integer", nullable: false), + Name = table.Column(type: "text", nullable: false), + TokenHash = table.Column(type: "text", nullable: false), + Created = table.Column(type: "bigint", nullable: false), + Expires = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PluginTokens", x => x.Id); + }); + migrationBuilder.CreateTable( name: "ServerSettings", columns: table => new { Id = table.Column(type: "integer", nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ServerName = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Motd = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true), + BannerImage = table.Column(type: "bytea", nullable: true), + BannerContentType = table.Column(type: "text", nullable: true), + BannerVersion = table.Column(type: "integer", nullable: false), ConnectivityCheckIntervalMinutes = table.Column(type: "integer", nullable: false), AircraftConnectionTimeoutMinutes = table.Column(type: "integer", nullable: false), AdscContractTimeoutMinutes = table.Column(type: "integer", nullable: false), @@ -158,21 +195,6 @@ protected override void Up(MigrationBuilder migrationBuilder) table.PrimaryKey("PK_ServerSettings", x => x.Id); }); - migrationBuilder.CreateTable( - name: "Users", - columns: table => new - { - Id = table.Column(type: "uuid", nullable: false), - Username = table.Column(type: "text", nullable: false), - PasswordHash = table.Column(type: "text", nullable: false), - Created = table.Column(type: "bigint", nullable: false), - Version = table.Column(type: "integer", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Users", x => x.Id); - }); - migrationBuilder.CreateTable( name: "CpdlcMessages", columns: table => new @@ -251,9 +273,14 @@ protected override void Up(MigrationBuilder migrationBuilder) column: "Opened"); migrationBuilder.CreateIndex( - name: "IX_Users_Username", - table: "Users", - column: "Username", + name: "IX_PluginTokens_Cid", + table: "PluginTokens", + column: "Cid"); + + migrationBuilder.CreateIndex( + name: "IX_PluginTokens_TokenHash", + table: "PluginTokens", + column: "TokenHash", unique: true); } @@ -263,6 +290,9 @@ protected override void Down(MigrationBuilder migrationBuilder) migrationBuilder.DropTable( name: "AcarsConnections"); + migrationBuilder.DropTable( + name: "Administrators"); + migrationBuilder.DropTable( name: "AdscContracts"); @@ -279,10 +309,10 @@ protected override void Down(MigrationBuilder migrationBuilder) name: "MessageIdSequences"); migrationBuilder.DropTable( - name: "ServerSettings"); + name: "PluginTokens"); migrationBuilder.DropTable( - name: "Users"); + name: "ServerSettings"); migrationBuilder.DropTable( name: "Dialogues"); diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs index 8662c94..ac5282a 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs @@ -42,6 +42,13 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("text"); + b.Property("Motd") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("MotdDelaySeconds") + .HasColumnType("integer"); + b.Property("Notes") .HasMaxLength(2000) .HasColumnType("character varying(2000)"); @@ -191,32 +198,56 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("AdscReports", (string)null); }); - modelBuilder.Entity("CPDLCServer.Auth.Users.User", b => + modelBuilder.Entity("CPDLCServer.Auth.Administrators.Administrator", b => + { + b.Property("Cid") + .HasColumnType("integer"); + + b.Property("Added") + .HasColumnType("bigint"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Cid"); + + b.ToTable("Administrators", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.PluginTokens.PluginToken", b => { b.Property("Id") .HasColumnType("uuid"); + b.Property("Cid") + .HasColumnType("integer"); + b.Property("Created") .HasColumnType("bigint"); - b.Property("PasswordHash") + b.Property("Expires") + .HasColumnType("bigint"); + + b.Property("Name") .IsRequired() .HasColumnType("text"); - b.Property("Username") + b.Property("TokenHash") .IsRequired() .HasColumnType("text"); - b.Property("Version") - .IsConcurrencyToken() - .HasColumnType("integer"); - b.HasKey("Id"); - b.HasIndex("Username") + b.HasIndex("Cid"); + + b.HasIndex("TokenHash") .IsUnique(); - b.ToTable("Users", (string)null); + b.ToTable("PluginTokens", (string)null); }); modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => @@ -392,6 +423,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("AircraftConnectionTimeoutMinutes") .HasColumnType("integer"); + b.Property("BannerContentType") + .HasColumnType("text"); + + b.Property("BannerImage") + .HasColumnType("bytea"); + + b.Property("BannerVersion") + .HasColumnType("integer"); + b.Property("ConnectivityCheckIntervalMinutes") .HasColumnType("integer"); @@ -401,6 +441,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("HandoffNotificationLeadTimeMinutes") .HasColumnType("integer"); + b.Property("Motd") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("ServerName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + b.Property("VatsimStatusAllowNonEquippedAircraft") .HasColumnType("boolean"); diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.Designer.cs similarity index 89% rename from source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.Designer.cs rename to source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.Designer.cs index 8f91f06..a03d2ad 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.Designer.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ namespace CPDLCServer.Persistence.Migrations.Sqlite { [DbContext(typeof(SqliteCpdlcDbContext))] - [Migration("20261115043633_InitialCreate")] + [Migration("20261121042339_InitialCreate")] partial class InitialCreate { /// @@ -40,6 +40,13 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Motd") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("MotdDelaySeconds") + .HasColumnType("INTEGER"); + b.Property("Notes") .HasMaxLength(2000) .HasColumnType("TEXT"); @@ -185,32 +192,56 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.ToTable("AdscReports", (string)null); }); - modelBuilder.Entity("CPDLCServer.Auth.Users.User", b => + modelBuilder.Entity("CPDLCServer.Auth.Administrators.Administrator", b => + { + b.Property("Cid") + .HasColumnType("INTEGER"); + + b.Property("Added") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Cid"); + + b.ToTable("Administrators", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.PluginTokens.PluginToken", b => { b.Property("Id") .HasColumnType("TEXT"); + b.Property("Cid") + .HasColumnType("INTEGER"); + b.Property("Created") .HasColumnType("INTEGER"); - b.Property("PasswordHash") + b.Property("Expires") + .HasColumnType("INTEGER"); + + b.Property("Name") .IsRequired() .HasColumnType("TEXT"); - b.Property("Username") + b.Property("TokenHash") .IsRequired() .HasColumnType("TEXT"); - b.Property("Version") - .IsConcurrencyToken() - .HasColumnType("INTEGER"); - b.HasKey("Id"); - b.HasIndex("Username") + b.HasIndex("Cid"); + + b.HasIndex("TokenHash") .IsUnique(); - b.ToTable("Users", (string)null); + b.ToTable("PluginTokens", (string)null); }); modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => @@ -380,6 +411,15 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("AircraftConnectionTimeoutMinutes") .HasColumnType("INTEGER"); + b.Property("BannerContentType") + .HasColumnType("TEXT"); + + b.Property("BannerImage") + .HasColumnType("BLOB"); + + b.Property("BannerVersion") + .HasColumnType("INTEGER"); + b.Property("ConnectivityCheckIntervalMinutes") .HasColumnType("INTEGER"); @@ -389,6 +429,15 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) b.Property("HandoffNotificationLeadTimeMinutes") .HasColumnType("INTEGER"); + b.Property("Motd") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("ServerName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + b.Property("VatsimStatusAllowNonEquippedAircraft") .HasColumnType("INTEGER"); diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.cs similarity index 87% rename from source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.cs rename to source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.cs index 452d70c..92183dc 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261115043633_InitialCreate.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.cs @@ -24,6 +24,8 @@ protected override void Up(MigrationBuilder migrationBuilder) EncryptedAuthenticationCode = table.Column(type: "TEXT", nullable: false), DefaultAdscReportingInterval = table.Column(type: "INTEGER", nullable: false), SelectedAdscContractDuration = table.Column(type: "INTEGER", nullable: false), + Motd = table.Column(type: "TEXT", maxLength: 200, nullable: true), + MotdDelaySeconds = table.Column(type: "INTEGER", nullable: false), Notes = table.Column(type: "TEXT", maxLength: 2000, nullable: true), Version = table.Column(type: "INTEGER", nullable: false) }, @@ -32,6 +34,20 @@ protected override void Up(MigrationBuilder migrationBuilder) table.PrimaryKey("PK_AcarsConnections", x => x.Id); }); + migrationBuilder.CreateTable( + name: "Administrators", + columns: table => new + { + Cid = table.Column(type: "INTEGER", nullable: false), + Name = table.Column(type: "TEXT", nullable: true), + Added = table.Column(type: "INTEGER", nullable: false), + Version = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Administrators", x => x.Cid); + }); + migrationBuilder.CreateTable( name: "AdscContracts", columns: table => new @@ -134,12 +150,33 @@ protected override void Up(MigrationBuilder migrationBuilder) table.PrimaryKey("PK_MessageIdSequences", x => new { x.AcarsConnectionId, x.Callsign }); }); + migrationBuilder.CreateTable( + name: "PluginTokens", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Cid = table.Column(type: "INTEGER", nullable: false), + Name = table.Column(type: "TEXT", nullable: false), + TokenHash = table.Column(type: "TEXT", nullable: false), + Created = table.Column(type: "INTEGER", nullable: false), + Expires = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_PluginTokens", x => x.Id); + }); + migrationBuilder.CreateTable( name: "ServerSettings", columns: table => new { Id = table.Column(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), + ServerName = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Motd = table.Column(type: "TEXT", maxLength: 1000, nullable: true), + BannerImage = table.Column(type: "BLOB", nullable: true), + BannerContentType = table.Column(type: "TEXT", nullable: true), + BannerVersion = table.Column(type: "INTEGER", nullable: false), ConnectivityCheckIntervalMinutes = table.Column(type: "INTEGER", nullable: false), AircraftConnectionTimeoutMinutes = table.Column(type: "INTEGER", nullable: false), AdscContractTimeoutMinutes = table.Column(type: "INTEGER", nullable: false), @@ -157,21 +194,6 @@ protected override void Up(MigrationBuilder migrationBuilder) table.PrimaryKey("PK_ServerSettings", x => x.Id); }); - migrationBuilder.CreateTable( - name: "Users", - columns: table => new - { - Id = table.Column(type: "TEXT", nullable: false), - Username = table.Column(type: "TEXT", nullable: false), - PasswordHash = table.Column(type: "TEXT", nullable: false), - Created = table.Column(type: "INTEGER", nullable: false), - Version = table.Column(type: "INTEGER", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Users", x => x.Id); - }); - migrationBuilder.CreateTable( name: "CpdlcMessages", columns: table => new @@ -250,9 +272,14 @@ protected override void Up(MigrationBuilder migrationBuilder) column: "Opened"); migrationBuilder.CreateIndex( - name: "IX_Users_Username", - table: "Users", - column: "Username", + name: "IX_PluginTokens_Cid", + table: "PluginTokens", + column: "Cid"); + + migrationBuilder.CreateIndex( + name: "IX_PluginTokens_TokenHash", + table: "PluginTokens", + column: "TokenHash", unique: true); } @@ -262,6 +289,9 @@ protected override void Down(MigrationBuilder migrationBuilder) migrationBuilder.DropTable( name: "AcarsConnections"); + migrationBuilder.DropTable( + name: "Administrators"); + migrationBuilder.DropTable( name: "AdscContracts"); @@ -278,10 +308,10 @@ protected override void Down(MigrationBuilder migrationBuilder) name: "MessageIdSequences"); migrationBuilder.DropTable( - name: "ServerSettings"); + name: "PluginTokens"); migrationBuilder.DropTable( - name: "Users"); + name: "ServerSettings"); migrationBuilder.DropTable( name: "Dialogues"); diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs index 018ccc0..1447785 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs @@ -37,6 +37,13 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired() .HasColumnType("TEXT"); + b.Property("Motd") + .HasMaxLength(200) + .HasColumnType("TEXT"); + + b.Property("MotdDelaySeconds") + .HasColumnType("INTEGER"); + b.Property("Notes") .HasMaxLength(2000) .HasColumnType("TEXT"); @@ -182,32 +189,56 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("AdscReports", (string)null); }); - modelBuilder.Entity("CPDLCServer.Auth.Users.User", b => + modelBuilder.Entity("CPDLCServer.Auth.Administrators.Administrator", b => + { + b.Property("Cid") + .HasColumnType("INTEGER"); + + b.Property("Added") + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.HasKey("Cid"); + + b.ToTable("Administrators", (string)null); + }); + + modelBuilder.Entity("CPDLCServer.Auth.PluginTokens.PluginToken", b => { b.Property("Id") .HasColumnType("TEXT"); + b.Property("Cid") + .HasColumnType("INTEGER"); + b.Property("Created") .HasColumnType("INTEGER"); - b.Property("PasswordHash") + b.Property("Expires") + .HasColumnType("INTEGER"); + + b.Property("Name") .IsRequired() .HasColumnType("TEXT"); - b.Property("Username") + b.Property("TokenHash") .IsRequired() .HasColumnType("TEXT"); - b.Property("Version") - .IsConcurrencyToken() - .HasColumnType("INTEGER"); - b.HasKey("Id"); - b.HasIndex("Username") + b.HasIndex("Cid"); + + b.HasIndex("TokenHash") .IsUnique(); - b.ToTable("Users", (string)null); + b.ToTable("PluginTokens", (string)null); }); modelBuilder.Entity("CPDLCServer.Cpdlc.Connections.AircraftConnection", b => @@ -377,6 +408,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("AircraftConnectionTimeoutMinutes") .HasColumnType("INTEGER"); + b.Property("BannerContentType") + .HasColumnType("TEXT"); + + b.Property("BannerImage") + .HasColumnType("BLOB"); + + b.Property("BannerVersion") + .HasColumnType("INTEGER"); + b.Property("ConnectivityCheckIntervalMinutes") .HasColumnType("INTEGER"); @@ -386,6 +426,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("HandoffNotificationLeadTimeMinutes") .HasColumnType("INTEGER"); + b.Property("Motd") + .HasMaxLength(1000) + .HasColumnType("TEXT"); + + b.Property("ServerName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + b.Property("VatsimStatusAllowNonEquippedAircraft") .HasColumnType("INTEGER"); diff --git a/source/CPDLCServer/Program.cs b/source/CPDLCServer/Program.cs index 9323476..611c4a9 100644 --- a/source/CPDLCServer/Program.cs +++ b/source/CPDLCServer/Program.cs @@ -1,231 +1,211 @@ -using CPDLCServer.AcarsConnections; -using CPDLCServer.AdscContracts; -using CPDLCServer.Auth; -using CPDLCServer.Controllers; -using CPDLCServer.Cpdlc; -using CPDLCServer.Infrastructure; -using CPDLCServer.Logging; -using CPDLCServer.Persistence; -using CPDLCServer.Security; -using CPDLCServer.Settings; -using CPDLCServer.Setup; -using CPDLCServer.VatsimStatus; -using CPDLCServer.Web; -using DotNetEnv; -using Microsoft.AspNetCore.Hosting.Server; -using Microsoft.AspNetCore.Hosting.Server.Features; -using Microsoft.EntityFrameworkCore; -using Serilog; -using Serilog.Events; - -// TODO: -// - Remove FlightSimulationNetwork variable -// - Aggregate controller connections for multiple FIRs -// - Introduce a Contracts project -// - Value types for IDs -// - Re-do dashboard - -TryLoadEnvFile(); - -var builder = WebApplication.CreateBuilder(args); - -builder.Configuration.AddEnvironmentVariables(); - -ConfigureSerilog(builder); - -// The data directory holds the SQLite database -var dataPath = GetDataPath(builder); - -var databaseProvider = GetDatabaseProvider(builder); -var databasePath = Path.Combine(dataPath, "cpdlc.db"); - -builder.Services - .AddInfrastructure() - .AddPersistence(builder.Configuration, databaseProvider, databasePath) - .AddSecurity(builder.Configuration) - .AddSetup() - .AddAuth() - .AddSettings() - .AddAcarsConnections() - .AddAirTrafficControllers() - .AddCpdlc() - .AddAdsContracts() - .AddVatsimStatus() - .AddWeb(); - -var app = builder.Build(); - -await MigrateDatabase(app, databaseProvider, databasePath); -await SeedServerSettings(app); - -var setupState = app.Services.GetRequiredService(); -await setupState.Load(CancellationToken.None); -app.Lifetime.ApplicationStarted.Register(() => TryLogSetupUrl(app, setupState)); - -app.UseHttpsRedirection(); -app.UseRouting(); - -app.UseMiddleware(); -app.UseAuthentication(); -app.UseAuthorization(); -app.UseRateLimiter(); - -app.MapRazorPages(); -app.MapHub("/hubs/controller"); - -app.MapGet("/logs/stream", LogStreamEndpoint.Handle).RequireAuthorization(); -app.MapGet("/health", () => Results.Ok()); - -app.Run(); -return; - -void TryLoadEnvFile() -{ - // Only load .env file in development - if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != "Development") - return; - - // Search for .env file in current directory and parent directories up to git root or filesystem root - var currentDir = new DirectoryInfo(Directory.GetCurrentDirectory()); - while (currentDir != null) - { - var envPath = Path.Combine(currentDir.FullName, ".env"); - if (File.Exists(envPath)) - { - Env.Load(envPath); - break; - } - - // Stop at git root - if (Directory.Exists(Path.Combine(currentDir.FullName, ".git"))) - { - break; - } - - currentDir = currentDir.Parent; - } -} - -DatabaseProvider GetDatabaseProvider(WebApplicationBuilder builder) -{ - var configuredProvider = builder.Configuration["DatabaseProvider"]; - if (string.IsNullOrWhiteSpace(configuredProvider)) - return DatabaseProvider.Sqlite; - - if (!Enum.TryParse(configuredProvider, ignoreCase: true, out var provider)) - throw new Exception($"The database provider {configuredProvider} is not supported. Use {nameof(DatabaseProvider.Sqlite)} or {nameof(DatabaseProvider.PostgreSql)}."); - - return provider; -} - -string GetDataPath(WebApplicationBuilder builder) -{ - var configuredPath = builder.Configuration["DataPath"]; - if (!string.IsNullOrWhiteSpace(configuredPath)) - return Path.GetFullPath(configuredPath); - - // For local development, keep the data in the .data directory at the root of the repository - if (builder.Environment.IsDevelopment()) - return Path.Combine(FindRepositoryRoot() ?? Directory.GetCurrentDirectory(), ".data"); - - return "/data"; -} - -string? FindRepositoryRoot() -{ - var currentDir = new DirectoryInfo(Directory.GetCurrentDirectory()); - while (currentDir != null) - { - if (Directory.Exists(Path.Combine(currentDir.FullName, ".git"))) - return currentDir.FullName; - - currentDir = currentDir.Parent; - } - - return null; -} - -void TryLogSetupUrl(WebApplication app, SetupState setupState) -{ - if (setupState.IsConfigured) - return; - - var setupPath = $"/setup?token={setupState.SetupToken}"; - - var addresses = app.Services.GetRequiredService().Features.Get()?.Addresses ?? []; - if (addresses.Count == 0) - { - Log.Warning("The server is not set up. Open {SetupPath} on this server to set it up", setupPath); - return; - } - - foreach (var address in addresses) - { - // The server can listen on all addresses, for example in Docker. Show an address that a browser can open. - var browserAddress = address - .Replace("://[::]", "://localhost") - .Replace("://0.0.0.0", "://localhost") - .Replace("://+", "://localhost") - .Replace("://*", "://localhost") - .TrimEnd('/'); - - Log.Warning("The server is not set up. Open {SetupUrl} to set it up", browserAddress + setupPath); - } -} - -async Task MigrateDatabase(WebApplication app, DatabaseProvider provider, string databasePath) -{ - await using var scope = app.Services.CreateAsyncScope(); - var dbContext = scope.ServiceProvider.GetRequiredService(); - - if (provider == DatabaseProvider.Sqlite) - { - // SQLite makes the database file, but not the directory - var databaseDirectory = Path.GetDirectoryName(databasePath); - if (databaseDirectory is not null) - Directory.CreateDirectory(databaseDirectory); - - Log.Information("Using SQLite database {DatabasePath}", databasePath); - } - else - { - // Do not write the connection string to the log, because it contains the password - var connection = dbContext.Database.GetDbConnection(); - Log.Information("Using PostgreSQL database {Database} on {Host}", connection.Database, connection.DataSource); - } - - await dbContext.Database.MigrateAsync(); -} - -// Adds the default settings to the database if they do not exist already -async Task SeedServerSettings(WebApplication app) -{ - await using var scope = app.Services.CreateAsyncScope(); - await scope.ServiceProvider.GetRequiredService().SeedDefaults(CancellationToken.None); - await scope.ServiceProvider.GetRequiredService().Commit(CancellationToken.None); -} - -void ConfigureSerilog(WebApplicationBuilder builder) -{ - if (!Enum.TryParse(builder.Configuration["Logging:Level"], out var logLevel)) - { - logLevel = LogEventLevel.Information; - } - - // Keeps the recent log entries for the Logs page - var logBuffer = new LogBuffer(); - - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Is(logLevel) - .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) - .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) - .Enrich.FromLogContext() - .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.Sink(new InMemoryLogBufferSink(logBuffer)) - .CreateLogger(); - - builder.Host.UseSerilog(); - - builder.Services.AddSingleton(Log.Logger); - builder.Services.AddSingleton(logBuffer); -} +using CPDLCServer.AcarsConnections; +using CPDLCServer.AdscContracts; +using CPDLCServer.Auth; +using CPDLCServer.Auth.PluginTokens; +using CPDLCServer.Controllers; +using CPDLCServer.Cpdlc; +using CPDLCServer.Infrastructure; +using CPDLCServer.Logging; +using CPDLCServer.Persistence; +using CPDLCServer.Security; +using CPDLCServer.Settings; +using CPDLCServer.Setup; +using CPDLCServer.VatsimStatus; +using CPDLCServer.Web; +using DotNetEnv; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.EntityFrameworkCore; +using Serilog; +using Serilog.Events; + +// TODO: +// - Remove FlightSimulationNetwork variable +// - Aggregate controller connections for multiple FIRs +// - Introduce a Contracts project +// - Value types for IDs + +TryLoadEnvFile(); + +var builder = WebApplication.CreateBuilder(args); + +builder.Configuration.AddEnvironmentVariables(); + +ConfigureSerilog(builder); + +// The data directory holds the SQLite database +var dataPath = GetDataPath(builder); + +var databaseProvider = GetDatabaseProvider(builder); +var databasePath = Path.Combine(dataPath, "cpdlc.db"); + +builder.Services + .AddInfrastructure() + .AddPersistence(builder.Configuration, databaseProvider, databasePath) + .AddSecurity(builder.Configuration) + .AddSetup() + .AddAuth(builder.Configuration) + .AddSettings() + .AddAcarsConnections() + .AddAirTrafficControllers() + .AddCpdlc() + .AddAdsContracts() + .AddVatsimStatus() + .AddWeb(); + +var app = builder.Build(); + +await MigrateDatabase(app, databaseProvider, databasePath); +await SeedServerSettings(app); + +var setupState = app.Services.GetRequiredService(); +await setupState.Load(CancellationToken.None); +if (!setupState.IsConfigured) + Log.Warning("The server is not set up. Open /setup on this server to set it up"); + +// Behind a proxy that ends TLS, the request comes with http. VATSIM Connect needs the https redirect URL, so use the +// scheme that the proxy received. +var forwardedHeadersOptions = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedProto }; +forwardedHeadersOptions.KnownIPNetworks.Clear(); +forwardedHeadersOptions.KnownProxies.Clear(); +app.UseForwardedHeaders(forwardedHeadersOptions); + +app.UseHttpsRedirection(); +app.UseRouting(); + +app.UseMiddleware(); +app.UseAuthentication(); +app.UseAuthorization(); + +app.MapRazorPages(); +app.MapHub("/hubs/controller"); +app.MapPluginEndpoints(); + +app.MapGet("/logs/stream", LogStreamEndpoint.Handle).RequireAuthorization(AdministratorRequirement.PolicyName); +app.MapGet("/health", () => Results.Ok()); +app.MapGet("/branding/banner", BannerEndpoint.Handle); + +app.Run(); +return; + +void TryLoadEnvFile() +{ + // Only load .env file in development + if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != "Development") + return; + + // Search for .env file in current directory and parent directories up to git root or filesystem root + var currentDir = new DirectoryInfo(Directory.GetCurrentDirectory()); + while (currentDir != null) + { + var envPath = Path.Combine(currentDir.FullName, ".env"); + if (File.Exists(envPath)) + { + Env.Load(envPath); + break; + } + + // Stop at git root + if (Directory.Exists(Path.Combine(currentDir.FullName, ".git"))) + { + break; + } + + currentDir = currentDir.Parent; + } +} + +DatabaseProvider GetDatabaseProvider(WebApplicationBuilder builder) +{ + var configuredProvider = builder.Configuration["DatabaseProvider"]; + if (string.IsNullOrWhiteSpace(configuredProvider)) + return DatabaseProvider.Sqlite; + + if (!Enum.TryParse(configuredProvider, ignoreCase: true, out var provider)) + throw new Exception($"The database provider {configuredProvider} is not supported. Use {nameof(DatabaseProvider.Sqlite)} or {nameof(DatabaseProvider.PostgreSql)}."); + + return provider; +} + +string GetDataPath(WebApplicationBuilder builder) +{ + var configuredPath = builder.Configuration["DataPath"]; + if (!string.IsNullOrWhiteSpace(configuredPath)) + return Path.GetFullPath(configuredPath); + + // For local development, keep the data in the .data directory at the root of the repository + if (builder.Environment.IsDevelopment()) + return Path.Combine(FindRepositoryRoot() ?? Directory.GetCurrentDirectory(), ".data"); + + return "/data"; +} + +string? FindRepositoryRoot() +{ + var currentDir = new DirectoryInfo(Directory.GetCurrentDirectory()); + while (currentDir != null) + { + if (Directory.Exists(Path.Combine(currentDir.FullName, ".git"))) + return currentDir.FullName; + + currentDir = currentDir.Parent; + } + + return null; +} + +async Task MigrateDatabase(WebApplication app, DatabaseProvider provider, string databasePath) +{ + await using var scope = app.Services.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + if (provider == DatabaseProvider.Sqlite) + { + // SQLite makes the database file, but not the directory + var databaseDirectory = Path.GetDirectoryName(databasePath); + if (databaseDirectory is not null) + Directory.CreateDirectory(databaseDirectory); + + Log.Information("Using SQLite database {DatabasePath}", databasePath); + } + else + { + // Do not write the connection string to the log, because it contains the password + var connection = dbContext.Database.GetDbConnection(); + Log.Information("Using PostgreSQL database {Database} on {Host}", connection.Database, connection.DataSource); + } + + await dbContext.Database.MigrateAsync(); +} + +// Adds the default settings to the database if they do not exist already +async Task SeedServerSettings(WebApplication app) +{ + await using var scope = app.Services.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().SeedDefaults(CancellationToken.None); + await scope.ServiceProvider.GetRequiredService().Commit(CancellationToken.None); +} + +void ConfigureSerilog(WebApplicationBuilder builder) +{ + if (!Enum.TryParse(builder.Configuration["Logging:Level"], out var logLevel)) + { + logLevel = LogEventLevel.Information; + } + + // Keeps the recent log entries for the Logs page + var logBuffer = new LogBuffer(capacity: 5000); + + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Is(logLevel) + .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) + .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) + .Enrich.FromLogContext() + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Sink(new InMemoryLogBufferSink(logBuffer)) + .CreateLogger(); + + builder.Host.UseSerilog(); + + builder.Services.AddSingleton(Log.Logger); + builder.Services.AddSingleton(logBuffer); +} diff --git a/source/CPDLCServer/Settings/BannerEndpoint.cs b/source/CPDLCServer/Settings/BannerEndpoint.cs new file mode 100644 index 0000000..6fcb698 --- /dev/null +++ b/source/CPDLCServer/Settings/BannerEndpoint.cs @@ -0,0 +1,19 @@ +using Microsoft.Net.Http.Headers; + +namespace CPDLCServer.Settings; + +// Sends the banner image. The URL contains the banner version, so the browser can keep the image in its cache. +public static class BannerEndpoint +{ + public static async Task Handle(HttpContext context, IServerSettingsProvider settingsProvider, CancellationToken cancellationToken) + { + var banner = await settingsProvider.LoadBanner(cancellationToken); + if (banner is null) + return Results.NotFound(); + + context.Response.Headers[HeaderNames.CacheControl] = "public, max-age=31536000, immutable"; + context.Response.Headers[HeaderNames.XContentTypeOptions] = "nosniff"; + + return Results.File(banner.Value.Image, banner.Value.ContentType); + } +} diff --git a/source/CPDLCServer/Settings/BannerImageFormat.cs b/source/CPDLCServer/Settings/BannerImageFormat.cs new file mode 100644 index 0000000..3ec0429 --- /dev/null +++ b/source/CPDLCServer/Settings/BannerImageFormat.cs @@ -0,0 +1,28 @@ +namespace CPDLCServer.Settings; + +// Finds the type of an image from its first bytes. The type from the browser is not used, because the browser can send any type. +// SVG is not accepted, because an SVG file can contain scripts. +public static class BannerImageFormat +{ + public const int MaxSize = 1024 * 1024; + + static readonly byte[] Png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + static readonly byte[] Jpeg = [0xFF, 0xD8, 0xFF]; + static readonly byte[] Riff = "RIFF"u8.ToArray(); + static readonly byte[] Webp = "WEBP"u8.ToArray(); + + // Returns null when the image is not PNG, JPEG or WebP + public static string? FindContentType(ReadOnlySpan image) + { + if (image.StartsWith(Png)) + return "image/png"; + + if (image.StartsWith(Jpeg)) + return "image/jpeg"; + + if (image.Length >= 12 && image[..4].SequenceEqual(Riff) && image[8..12].SequenceEqual(Webp)) + return "image/webp"; + + return null; + } +} diff --git a/source/CPDLCServer/Settings/BrandingInfo.cs b/source/CPDLCServer/Settings/BrandingInfo.cs new file mode 100644 index 0000000..848641f --- /dev/null +++ b/source/CPDLCServer/Settings/BrandingInfo.cs @@ -0,0 +1,4 @@ +namespace CPDLCServer.Settings; + +// The branding of the server settings without the image, for each page of the dashboard +public record BrandingInfo(string ServerName, string? Motd, bool HasBanner, int BannerVersion); diff --git a/source/CPDLCServer/Settings/SaveServerSettingsCommandHandler.cs b/source/CPDLCServer/Settings/SaveServerSettingsCommandHandler.cs index d90ec51..adf84d6 100644 --- a/source/CPDLCServer/Settings/SaveServerSettingsCommandHandler.cs +++ b/source/CPDLCServer/Settings/SaveServerSettingsCommandHandler.cs @@ -15,7 +15,8 @@ public async Task Handle(SaveServerSettingsCommand request, CancellationToken ca unitOfWork.AfterCommit(_ => { - logger.Information("Server settings changed: {@Settings}", request.Settings); + // Without the banner, so that the image bytes are not in the log + logger.Information("Server settings changed: {@Settings}", request.Settings with { BannerImage = null }); return Task.CompletedTask; }); } diff --git a/source/CPDLCServer/Settings/ServerSettings.cs b/source/CPDLCServer/Settings/ServerSettings.cs index 3f15d25..e783adb 100644 --- a/source/CPDLCServer/Settings/ServerSettings.cs +++ b/source/CPDLCServer/Settings/ServerSettings.cs @@ -1,4 +1,6 @@ using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; namespace CPDLCServer.Settings; @@ -7,6 +9,34 @@ namespace CPDLCServer.Settings; /// public record ServerSettings { + public const string DefaultServerName = "CPDLC Server"; + public const int MaxServerNameLength = 64; + public const int MaxMotdLength = 1000; + + // Branding: the dashboard shows the name, the banner and the message of the day at the top of the sidebar and on + // the login page. + [Required] + [StringLength(MaxServerNameLength)] + public string ServerName { get; init; } = DefaultServerName; + + // Plain text. The dashboard keeps the line breaks. + [StringLength(MaxMotdLength)] + public string? Motd { get; init; } + + // The banner is changed with SetBannerImageCommand, not with the settings form + [BindNever] + [ValidateNever] + public byte[]? BannerImage { get; set; } + + [BindNever] + [ValidateNever] + public string? BannerContentType { get; set; } + + // Increases each time that the banner changes, so that the browser does not show an old banner from its cache + [BindNever] + [ValidateNever] + public int BannerVersion { get; set; } + [Range(1, int.MaxValue)] public int ConnectivityCheckIntervalMinutes { get; init; } = 15; diff --git a/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs b/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs index 8a66d2b..7a5197c 100644 --- a/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs +++ b/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs @@ -17,5 +17,8 @@ public void Configure(EntityTypeBuilder builder) builder.HasKey(IdProperty); builder.Property(s => s.VatsimStatusUrl).HasConversion(); + + builder.Property(s => s.ServerName).HasMaxLength(ServerSettings.MaxServerNameLength); + builder.Property(s => s.Motd).HasMaxLength(ServerSettings.MaxMotdLength); } } diff --git a/source/CPDLCServer/Settings/ServerSettingsProvider.cs b/source/CPDLCServer/Settings/ServerSettingsProvider.cs index d38cbee..9e9ade9 100644 --- a/source/CPDLCServer/Settings/ServerSettingsProvider.cs +++ b/source/CPDLCServer/Settings/ServerSettingsProvider.cs @@ -10,7 +10,14 @@ public interface IServerSettingsProvider /// Task SeedDefaults(CancellationToken cancellationToken); Task Load(CancellationToken cancellationToken); + + // Does not change the banner Task Save(ServerSettings settings, CancellationToken cancellationToken); + + // Does not load the image + Task LoadBranding(CancellationToken cancellationToken); + + Task<(byte[] Image, string ContentType)?> LoadBanner(CancellationToken cancellationToken); } public class ServerSettingsProvider(CpdlcDbContext dbContext) : IServerSettingsProvider @@ -32,6 +39,36 @@ public async Task Load(CancellationToken cancellationToken) public async Task Save(ServerSettings settings, CancellationToken cancellationToken) { var current = await Load(cancellationToken); - dbContext.Entry(current).CurrentValues.SetValues(settings); + + // The settings form does not have the banner, so keep the current banner + var changes = settings with + { + BannerImage = current.BannerImage, + BannerContentType = current.BannerContentType, + BannerVersion = current.BannerVersion + }; + + dbContext.Entry(current).CurrentValues.SetValues(changes); + } + + public async Task LoadBranding(CancellationToken cancellationToken) + { + return await dbContext.ServerSettings + .AsNoTracking() + .Select(s => new BrandingInfo(s.ServerName, s.Motd, s.BannerImage != null, s.BannerVersion)) + .SingleAsync(cancellationToken); + } + + public async Task<(byte[] Image, string ContentType)?> LoadBanner(CancellationToken cancellationToken) + { + var banner = await dbContext.ServerSettings + .AsNoTracking() + .Select(s => new { s.BannerImage, s.BannerContentType }) + .SingleAsync(cancellationToken); + + if (banner.BannerImage is null || banner.BannerContentType is null) + return null; + + return (banner.BannerImage, banner.BannerContentType); } } diff --git a/source/CPDLCServer/Settings/SetBannerImageCommand.cs b/source/CPDLCServer/Settings/SetBannerImageCommand.cs new file mode 100644 index 0000000..e127352 --- /dev/null +++ b/source/CPDLCServer/Settings/SetBannerImageCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.Settings; + +// A null image removes the banner +public record SetBannerImageCommand(byte[]? Image) : IRequest; diff --git a/source/CPDLCServer/Settings/SetBannerImageCommandHandler.cs b/source/CPDLCServer/Settings/SetBannerImageCommandHandler.cs new file mode 100644 index 0000000..ea4d470 --- /dev/null +++ b/source/CPDLCServer/Settings/SetBannerImageCommandHandler.cs @@ -0,0 +1,35 @@ +using CPDLCServer.Persistence; +using MediatR; + +namespace CPDLCServer.Settings; + +public class SetBannerImageCommandHandler( + IServerSettingsProvider settingsProvider, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(SetBannerImageCommand request, CancellationToken cancellationToken) + { + string? contentType = null; + if (request.Image is not null) + { + if (request.Image.Length > BannerImageFormat.MaxSize) + throw new InvalidOperationException("The image is larger than 1 MB"); + + contentType = BannerImageFormat.FindContentType(request.Image) + ?? throw new InvalidOperationException("The image must be PNG, JPEG or WebP"); + } + + var settings = await settingsProvider.Load(cancellationToken); + settings.BannerImage = request.Image; + settings.BannerContentType = contentType; + settings.BannerVersion++; + + unitOfWork.AfterCommit(_ => + { + logger.Information(request.Image is null ? "Banner removed" : "Banner changed"); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Setup/RedirectToSetupMiddleware.cs b/source/CPDLCServer/Setup/RedirectToSetupMiddleware.cs index c8a53d0..e271ae9 100644 --- a/source/CPDLCServer/Setup/RedirectToSetupMiddleware.cs +++ b/source/CPDLCServer/Setup/RedirectToSetupMiddleware.cs @@ -5,7 +5,7 @@ namespace CPDLCServer.Setup; /// public class RedirectToSetupMiddleware(RequestDelegate next, SetupState setupState) { - static readonly string[] AllowedPaths = ["/setup", "/login", "/logout", "/health", "/hubs"]; + static readonly string[] AllowedPaths = ["/setup", "/health", "/hubs", "/branding"]; public async Task InvokeAsync(HttpContext context) { diff --git a/source/CPDLCServer/Setup/SetupState.cs b/source/CPDLCServer/Setup/SetupState.cs index a3ce074..fed85fa 100644 --- a/source/CPDLCServer/Setup/SetupState.cs +++ b/source/CPDLCServer/Setup/SetupState.cs @@ -1,40 +1,23 @@ -using System.Security.Cryptography; -using System.Text; -using CPDLCServer.Auth.Users; +using CPDLCServer.Auth.Administrators; namespace CPDLCServer.Setup; -// The setup creates the first user. The server is configured when a user exists. +// The setup adds the first administrator. The server is configured when an administrator exists. public class SetupState(IServiceScopeFactory serviceScopeFactory) { volatile bool _isConfigured; - // Only a person who can read the server log has this token, so only that person can create the first user. - // The server makes a new token each time that it starts. - public string SetupToken { get; } = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); - public bool IsConfigured => _isConfigured; public async Task Load(CancellationToken cancellationToken) { await using var scope = serviceScopeFactory.CreateAsyncScope(); - var userRepository = scope.ServiceProvider.GetRequiredService(); - - _isConfigured = await userRepository.Any(cancellationToken); - } - - public bool IsValidSetupToken(string? token) - { - if (string.IsNullOrEmpty(token)) - return false; + var administratorRepository = scope.ServiceProvider.GetRequiredService(); - // Compare in constant time, so that the time of the comparison does not show the token - return CryptographicOperations.FixedTimeEquals( - Encoding.UTF8.GetBytes(token), - Encoding.UTF8.GetBytes(SetupToken)); + _isConfigured = await administratorRepository.Any(cancellationToken); } - public void MarkAdminCreated() + public void MarkConfigured() { _isConfigured = true; } diff --git a/source/CPDLCServer/Web/ControllerHub.cs b/source/CPDLCServer/Web/ControllerHub.cs index 32eb377..7df3eaa 100644 --- a/source/CPDLCServer/Web/ControllerHub.cs +++ b/source/CPDLCServer/Web/ControllerHub.cs @@ -1,5 +1,7 @@ using CPDLCServer.Contracts; using CPDLCServer.AcarsConnections.Stations; +using CPDLCServer.Auth; +using CPDLCServer.Auth.PluginTokens; using CPDLCServer.AdscContracts; using CPDLCServer.AdscContracts.Reports; using CPDLCServer.Controllers; @@ -8,11 +10,14 @@ using CPDLCServer.Cpdlc.Downlinks; using CPDLCServer.Cpdlc.Uplinks; using CPDLCServer.Infrastructure; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; using CpdlcUplinkResponseType = CPDLCServer.Contracts.CpdlcUplinkResponseType; namespace CPDLCServer.Web; +// Only a plugin with a valid token can connect +[Authorize(Policy = PluginTokenAuthenticationHandler.PolicyName)] public class ControllerHub( IControllerRepository controllerRepository, IDialogueRepository dialogueRepository, @@ -45,25 +50,21 @@ public override async Task OnConnectedAsync() throw new HubException("callsign must be provided"); } - // TODO: Validate API key - // var validationResult = await _apiKeyValidator.ValidateAsync(apiKey); - // if (validationResult is null) - // { - // _logger.Warning("Invalid API key attempt from {ConnectionId}", Context.ConnectionId); - // throw new HubException("Invalid API key"); - // } - + // The policy accepted the plugin token, so the user has a CID + var user = Context.User!; var controller = new ControllerInfo( Guid.NewGuid(), Context.ConnectionId, stationId, - callsign); + callsign, + user.GetCid()!.Value, + user.GetName()); await controllerRepository.Add(controller, Context.GetHttpContext()?.RequestAborted ?? CancellationToken.None); _logger.Information( - "Controller connected: {Callsign}. ConnectionId: {ConnectionId}", - callsign, Context.ConnectionId); + "Controller connected: {Callsign} ({Name}, {Cid}). ConnectionId: {ConnectionId}", + callsign, controller.Name, controller.Cid, Context.ConnectionId); await mediator.Publish( new ControllerConnectedNotification( diff --git a/source/CPDLCServer/Web/Pages/Account/AccessDenied.cshtml b/source/CPDLCServer/Web/Pages/Account/AccessDenied.cshtml new file mode 100644 index 0000000..119ec19 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Account/AccessDenied.cshtml @@ -0,0 +1,8 @@ +@page "/access-denied" +@{ + ViewData["Title"] = "Access denied"; +} + +

Access denied

+

Only an administrator can open this page. To get access, speak to an administrator of this server.

+Go to the overview diff --git a/source/CPDLCServer/Web/Pages/Account/Login.cshtml b/source/CPDLCServer/Web/Pages/Account/Login.cshtml index e732754..b3dc3a2 100644 --- a/source/CPDLCServer/Web/Pages/Account/Login.cshtml +++ b/source/CPDLCServer/Web/Pages/Account/Login.cshtml @@ -2,37 +2,13 @@ @model LoginModel @{ ViewData["Title"] = "Log in"; + Layout = "_CenteredLayout"; } -
-
-

Log in

-

Log in as the administrator to open the Settings and Logs pages.

+

Log in

+

Log in with your VATSIM account.

- - - - - -
-
-
- - - -
- -
- - - -
-
-
- -
- -
- -
-
+
+ + +
diff --git a/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs b/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs index 9dac8bc..6e08d6e 100644 --- a/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs @@ -1,64 +1,32 @@ -using System.ComponentModel.DataAnnotations; -using CPDLCServer.Auth.Login; -using CPDLCServer.Infrastructure; +using CPDLCServer.Auth.VatsimConnect; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -using Microsoft.AspNetCore.RateLimiting; namespace CPDLCServer.Web.Pages.Account; -[EnableRateLimiting(PasswordRateLimit.PolicyName)] public class LoginModel : PageModel { - private readonly IUnitOfWorkMediator _mediator; - - public LoginModel(IUnitOfWorkMediator mediator) - { - _mediator = mediator; - } - - [BindProperty] - public LoginInput Input { get; set; } = new(); - // The page to open after the login [BindProperty(SupportsGet = true)] public string? ReturnUrl { get; set; } - public void OnGet() - { - } - - public async Task OnPostAsync(CancellationToken cancellationToken) + public IActionResult OnGet() { - if (!ModelState.IsValid) - return Page(); - - var result = await _mediator.Send(new LoginCommand(Input.Username, Input.Password, ClientIpAddress.Get(HttpContext)), cancellationToken); - if (result is null) - { - // The same message for an unknown user, a wrong password and a lockout - ModelState.AddModelError( - string.Empty, - "The username or password is not correct, or the login is locked because of too many failed logins. " + - "If the login is locked, try again after 15 minutes."); - return Page(); - } + if (User.Identity?.IsAuthenticated == true) + return LocalRedirect(SafeReturnUrl()); - await AdminAuthentication.SignIn(HttpContext, result.UserId, result.Username); - - // Open only pages on this server, so that a link cannot send the user to a different site - return Url.IsLocalUrl(ReturnUrl) ? LocalRedirect(ReturnUrl) : Redirect("/"); + return Page(); } - public class LoginInput + // A form post starts the login, so that a link on a different site cannot start it + public IActionResult OnPost() { - [Required] - [Display(Name = "Username")] - public string Username { get; set; } = string.Empty; - - [Required] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; set; } = string.Empty; + return Challenge( + new AuthenticationProperties { RedirectUri = SafeReturnUrl() }, + VatsimConnectOptions.AuthenticationScheme); } + + // Open only pages on this server, so that a link cannot send the user to a different site + string SafeReturnUrl() => Url.IsLocalUrl(ReturnUrl) ? ReturnUrl : "/"; } diff --git a/source/CPDLCServer/Web/Pages/Account/Logout.cshtml.cs b/source/CPDLCServer/Web/Pages/Account/Logout.cshtml.cs index 465b7c3..719b406 100644 --- a/source/CPDLCServer/Web/Pages/Account/Logout.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Account/Logout.cshtml.cs @@ -1,4 +1,5 @@ -using CPDLCServer.Auth.Login; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; @@ -14,7 +15,7 @@ public IActionResult OnGet() public async Task OnPostAsync() { - await AdminAuthentication.SignOut(HttpContext); - return Redirect("/"); + await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + return Redirect("/login"); } } diff --git a/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml index 9a16633..aef5a70 100644 --- a/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml @@ -1,67 +1,56 @@ @page "/adsc" @using CPDLCServer.AdscContracts -@using CPDLCServer.AdscContracts.MessageLog @model IndexModel @{ - ViewData["Title"] = "ADS-C"; + ViewData["Title"] = "ADS-C contracts"; string FormatInterval(TimeSpan? interval) => interval is null ? "-" : $"{interval.Value.TotalMinutes:0.#} min"; string GetStateBadgeClass(AdscContractState? state) => state switch { - AdscContractState.Sent => "bg-info", - AdscContractState.Accepted => "bg-success", - AdscContractState.Rejected => "bg-danger", - _ => "bg-light text-dark" + AdscContractState.Sent => "text-bg-info", + AdscContractState.Accepted => "text-bg-success", + AdscContractState.Rejected => "text-bg-danger", + _ => "text-bg-light" }; } - +

ADS-C contracts

-

ADS-C

- -
-
-
Contracts
-
+
@if (Model.Contracts.Length == 0) { -

No ADS-C contracts.

+

No ADS-C contracts.

} else {
- - +
+ - - + + - + - + - + @foreach (var contract in Model.Contracts) { - - + + - + @@ -72,98 +61,3 @@ } - -
-
-
Message Log
-
-
- @if (Model.LogEntries.Length == 0) - { -

No ADS-C messages.

- } - else - { -
-
CallsignATSU CodeCurrent IntervalStationCurrent interval DefaultSelected IntervalSelected interval SelectedSelected EndsSelected ends DemandReport SourceReport source
@contract.Callsign@contract.StationId@contract.Callsign@contract.StationId @FormatInterval(contract.ReportingInterval) @(contract.DefaultContractState?.ToString() ?? "-") @FormatInterval(contract.SelectedReportingInterval) @(contract.SelectedContractState?.ToString() ?? "-")@(contract.SelectedContractEnds?.ToString("yyyy-MM-dd HH:mm:ss") ?? "-")@(contract.SelectedContractEnds?.ToString("HH:mm:ss") ?? "-") @(contract.DemandContractState?.ToString() ?? "-") @(Model.ReportSources.TryGetValue(contract.Callsign, out var source) ? source.ToString() : "-")
- - - - - - - - - - - - @foreach (var entry in Model.LogEntries) - { - - - - - - - - - } - -
TimestampNetworkDirATSU CodeCallsignPacket
@entry.Time.ToString("yyyy-MM-dd HH:mm:ss")@entry.AcarsConnectionId@(entry.Direction == AdscMessageDirection.Uplink ? "↑" : "↓")@entry.StationId@entry.Callsign@entry.Packet
-
- } -
-
- -@if (Model.TotalPages > 1) -{ - -} diff --git a/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml.cs index 4519e0c..50764d7 100644 --- a/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Adsc/Index.cshtml.cs @@ -1,7 +1,5 @@ using CPDLCServer.AdscContracts; -using CPDLCServer.AdscContracts.MessageLog; using CPDLCServer.AdscContracts.Reports; -using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace CPDLCServer.Web.Pages.Adsc; @@ -9,29 +7,20 @@ namespace CPDLCServer.Web.Pages.Adsc; public class IndexModel : PageModel { private readonly IAdscContractRepository _adscContractRepository; - private readonly IAdscMessageLogRepository _adscMessageLogRepository; private readonly IAdscReportRepository _adscReportRepository; - private const int PageSize = 50; public IndexModel( IAdscContractRepository adscContractRepository, - IAdscMessageLogRepository adscMessageLogRepository, IAdscReportRepository adscReportRepository) { _adscContractRepository = adscContractRepository; - _adscMessageLogRepository = adscMessageLogRepository; _adscReportRepository = adscReportRepository; } - [BindProperty(SupportsGet = true)] - public int PageNumber { get; set; } = 1; - public AdscContract[] Contracts { get; private set; } = []; + // The source of the latest report for each aircraft public Dictionary ReportSources { get; private set; } = new(); - public AdscMessageLogEntry[] LogEntries { get; private set; } = []; - public int TotalPages { get; private set; } - public int CurrentPage => PageNumber; public async Task OnGetAsync(CancellationToken cancellationToken) { @@ -43,15 +32,5 @@ public async Task OnGetAsync(CancellationToken cancellationToken) var reports = await _adscReportRepository.AllLatest(cancellationToken); ReportSources = reports.ToDictionary(r => r.Callsign, r => r.Report.Source); - - var logEntries = await _adscMessageLogRepository.All(cancellationToken); - - TotalPages = (int)Math.Ceiling(logEntries.Length / (double)PageSize); - PageNumber = Math.Clamp(PageNumber, 1, Math.Max(1, TotalPages)); - - LogEntries = logEntries - .Skip((PageNumber - 1) * PageSize) - .Take(PageSize) - .ToArray(); } } diff --git a/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml b/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml new file mode 100644 index 0000000..b6b5ff0 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml @@ -0,0 +1,49 @@ +@page "/adsc/messages" +@using CPDLCServer.AdscContracts.MessageLog +@model MessagesModel +@{ + ViewData["Title"] = "ADS-C message log"; +} + +

ADS-C message log

+ +
+
+ @if (Model.LogEntries.Length == 0) + { +

No ADS-C messages.

+ } + else + { +
+ + + + + + + + + + + + + @foreach (var entry in Model.LogEntries) + { + + + + + + + + + } + +
TimeCallsignStationPacketACARS connection
@entry.Time.ToString("yyyy-MM-dd HH:mm:ss")@(entry.Direction == AdscMessageDirection.Uplink ? "↑" : "↓")@entry.Callsign@entry.StationId@entry.Packet@entry.AcarsConnectionId
+
+ } + + +
+
diff --git a/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml.cs b/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml.cs new file mode 100644 index 0000000..184d47d --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Adsc/Messages.cshtml.cs @@ -0,0 +1,38 @@ +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.Web.Pages.ViewModels; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Adsc; + +public class MessagesModel : PageModel +{ + private const int PageSize = 50; + + private readonly IAdscMessageLogRepository _adscMessageLogRepository; + + public MessagesModel(IAdscMessageLogRepository adscMessageLogRepository) + { + _adscMessageLogRepository = adscMessageLogRepository; + } + + [BindProperty(SupportsGet = true)] + public int PageNumber { get; set; } = 1; + + public AdscMessageLogEntry[] LogEntries { get; private set; } = []; + public PaginationViewModel Pagination { get; private set; } = new("/adsc/messages", 1, 1); + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + var logEntries = await _adscMessageLogRepository.All(cancellationToken); + + var totalPages = (int)Math.Ceiling(logEntries.Length / (double)PageSize); + PageNumber = Math.Clamp(PageNumber, 1, Math.Max(1, totalPages)); + Pagination = new PaginationViewModel("/adsc/messages", PageNumber, totalPages); + + LogEntries = logEntries + .Skip((PageNumber - 1) * PageSize) + .Take(PageSize) + .ToArray(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Atsu/Index.cshtml b/source/CPDLCServer/Web/Pages/Atsu/Index.cshtml deleted file mode 100644 index 7af055a..0000000 --- a/source/CPDLCServer/Web/Pages/Atsu/Index.cshtml +++ /dev/null @@ -1,54 +0,0 @@ -@page "/atsu/{stationId}" -@model IndexModel -@{ - ViewData["Title"] = $"ATSU {Model.StationId}"; -} - - - -

ATSU: @Model.StationId

- -@if (Model.Controllers.Length > 0) -{ -
-
-
Active Controllers
-
-
-
- - - - - - - - - @foreach (var controller in Model.Controllers) - { - - - - - } - -
CallsignConnection ID
@controller.Callsign@controller.ConnectionId
-
-
-
-} -else -{ -
No active controllers at this ATSU.
-} - -

Messages

- -
- -
diff --git a/source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml similarity index 80% rename from source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml rename to source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml index 4c5a9ef..e0d7e30 100644 --- a/source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml @@ -1,20 +1,12 @@ -@page "/settings/acars/edit/{id:guid?}" +@page "/configuration/acars/edit/{id:guid?}" @using CPDLCServer.AcarsConnections.ConnectionSettings @model EditModel @{ - ViewData["Title"] = Model.IsNew ? "Add ACARS Connection" : "Edit ACARS Connection"; + ViewData["Title"] = Model.IsNew ? "Add ACARS connection" : "Edit ACARS connection"; } - - -

@ViewData["Title"]

-

+

@ViewData["Title"]

+

@if (Model.IsNew) { When you save an enabled connection, the server connects to the ACARS network immediately. @@ -28,7 +20,7 @@

-
+
@@ -136,6 +128,32 @@
Default: @Model.Defaults.SelectedAdscContractDuration minutes
+
+
+ +
Optional. A CPDLC free text message that the server sends to each aircraft after it logs on. The aircraft does not reply. Use letters, digits, spaces and . , : ? ' ( ) + -
+
+
+ + +
+
+ +
+
+ +
The time from the logon to the message of the day.
+
+
+
+ + seconds +
+ +
+
Default: @Model.Defaults.MotdDelaySeconds seconds
+
+
diff --git a/source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml.cs b/source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml.cs similarity index 98% rename from source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml.cs rename to source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml.cs index 6f95def..f731867 100644 --- a/source/CPDLCServer/Web/Pages/Settings/Acars/Edit.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Edit.cshtml.cs @@ -5,7 +5,7 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; -namespace CPDLCServer.Web.Pages.Settings.Acars; +namespace CPDLCServer.Web.Pages.Configuration.Acars; public class EditModel : PageModel { diff --git a/source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml similarity index 82% rename from source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml rename to source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml index 1d833a1..007ac32 100644 --- a/source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml @@ -1,21 +1,14 @@ -@page "/settings/acars" +@page "/configuration/acars" @model IndexModel @{ - ViewData["Title"] = "ACARS Connections"; + ViewData["Title"] = "ACARS connections"; } - -
-

ACARS Connections

+

ACARS connections

Add ACARS connection
-

The server connects to the upstream ACARS network with each enabled connection. A change takes effect immediately. A restart is not necessary.

+

The server connects to the upstream ACARS network with each enabled connection. A change takes effect immediately. A restart is not necessary.

@if (Model.StatusMessage is not null) { @@ -27,7 +20,7 @@ } -
+
@if (Model.Connections.Length == 0) { @@ -36,8 +29,8 @@ else {
- - +
+ @@ -76,6 +69,8 @@ } +} + +@foreach (var entry in Model) +{ + + + + + + + +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml new file mode 100644 index 0000000..59d60fa --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml @@ -0,0 +1,83 @@ +@page "/configuration/administrators" +@model IndexModel +@{ + ViewData["Title"] = "Administrators"; +} + +

Administrators

+

Administrators can open the Configuration area. Each person logs in with VATSIM. The name shows after the first login.

+ +@if (Model.StatusMessage is not null) +{ + +} + +@if (Model.ErrorMessage is not null) +{ + +} + +
+
Add an administrator
+
+ +
+ + + +
+
+ +
+ +
+
+ +
+
+
+
Station Type + Logs + Traffic Edit diff --git a/source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml.cs similarity index 97% rename from source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml.cs rename to source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml.cs index 25a54a1..9b25ad2 100644 --- a/source/CPDLCServer/Web/Pages/Settings/Acars/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml.cs @@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; -namespace CPDLCServer.Web.Pages.Settings.Acars; +namespace CPDLCServer.Web.Pages.Configuration.Acars; public class IndexModel : PageModel { @@ -36,7 +36,6 @@ public IndexModel( public string? ErrorMessage { get; set; } public bool IsRunning(AcarsConnectionSettings settings) => _acarsConnectionManager.IsRunning(settings.Id); - public async Task OnGetAsync(CancellationToken cancellationToken) { Connections = await _dbContext.AcarsConnections diff --git a/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml new file mode 100644 index 0000000..2180a08 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml @@ -0,0 +1,78 @@ +@page "/configuration/acars/{id:guid}/traffic" +@model TrafficModel +@{ + ViewData["Title"] = $"Traffic of {Model.AcarsConnectionId}"; +} + +
+

Traffic of @Model.AcarsConnectionId

+ +
+

+ The most recent requests to the ACARS network and their responses, newest first. The server keeps the last + @Model.Capacity requests in memory. The authentication code is not shown. +

+ +
+
+ + +
+
+ + +
+
+ +
+
+
+ + + + + + + + + + + + + +
TimeTypeStatusRequestResponse
+
+
+
+ +@section Scripts { + +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml.cs b/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml.cs new file mode 100644 index 0000000..1cb60d3 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Traffic.cshtml.cs @@ -0,0 +1,59 @@ +using CPDLCServer.AcarsConnections.Traffic; +using CPDLCServer.Persistence; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; + +namespace CPDLCServer.Web.Pages.Configuration.Acars; + +public class TrafficModel : PageModel +{ + private readonly CpdlcDbContext _dbContext; + private readonly AcarsTrafficLog _trafficLog; + + public TrafficModel(CpdlcDbContext dbContext, AcarsTrafficLog trafficLog) + { + _dbContext = dbContext; + _trafficLog = trafficLog; + } + + [BindProperty(SupportsGet = true)] + public bool ShowEmptyPolls { get; set; } + + public string AcarsConnectionId { get; private set; } = string.Empty; + public AcarsTrafficEntry[] Entries { get; private set; } = []; + + public int Capacity => _trafficLog.Capacity; + + public async Task OnGetAsync(Guid id, CancellationToken cancellationToken) + { + if (!await Load(id, cancellationToken)) + return NotFound(); + + return Page(); + } + + // The rows only, for the automatic refresh + public async Task OnGetRowsAsync(Guid id, CancellationToken cancellationToken) + { + if (!await Load(id, cancellationToken)) + return NotFound(); + + return Partial("_TrafficRows", Entries); + } + + async Task Load(Guid id, CancellationToken cancellationToken) + { + var connection = await _dbContext.AcarsConnections + .AsNoTracking() + .SingleOrDefaultAsync(c => c.Id == id, cancellationToken); + if (connection is null) + return false; + + AcarsConnectionId = connection.AcarsConnectionId; + Entries = _trafficLog.Get(AcarsConnectionId) + .Where(e => ShowEmptyPolls || !e.IsEmptyPoll) + .ToArray(); + return true; + } +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Acars/_TrafficRows.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Acars/_TrafficRows.cshtml new file mode 100644 index 0000000..e303e88 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/_TrafficRows.cshtml @@ -0,0 +1,29 @@ +@model CPDLCServer.AcarsConnections.Traffic.AcarsTrafficEntry[] + +@if (Model.Length == 0) +{ +
No traffic.
+ @entry.Time.ToString("HH:mm:ss") +
@entry.Duration.TotalMilliseconds.ToString("0") ms
+
@entry.Type@(entry.StatusCode?.ToString() ?? "-")
@entry.Request
+ @if (entry.Response is not null) + { +
@entry.Response
+ } + @if (entry.Error is not null) + { +
@entry.Error
+ } +
+ + + + + + + + + + @foreach (var administrator in Model.Administrators) + { + + + + + + + } + +
CIDNameAdded
@administrator.Cid + @if (administrator.Name is null) + { + Not logged in yet + } + else + { + @administrator.Name + } + @if (Model.IsCurrentUser(administrator)) + { + You + } + @administrator.Added.ToString("yyyy-MM-dd HH:mm") UTC + @if (!Model.IsCurrentUser(administrator)) + { +
+ +
+ } +
+
+
+
diff --git a/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml.cs new file mode 100644 index 0000000..7795851 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Administrators/Index.cshtml.cs @@ -0,0 +1,81 @@ +using System.ComponentModel.DataAnnotations; +using CPDLCServer.Auth; +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Infrastructure; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Configuration.Administrators; + +public class IndexModel : PageModel +{ + private readonly IAdministratorRepository _administratorRepository; + private readonly IUnitOfWorkMediator _mediator; + + public IndexModel(IAdministratorRepository administratorRepository, IUnitOfWorkMediator mediator) + { + _administratorRepository = administratorRepository; + _mediator = mediator; + } + + public Administrator[] Administrators { get; private set; } = []; + + [BindProperty] + [Required(ErrorMessage = "Enter a CID.")] + [Range(1, int.MaxValue, ErrorMessage = "Enter a valid CID.")] + [Display(Name = "CID")] + public int? Cid { get; set; } + + [TempData] + public string? StatusMessage { get; set; } + + [TempData] + public string? ErrorMessage { get; set; } + + public bool IsCurrentUser(Administrator administrator) => User.GetCid() == administrator.Cid; + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + Administrators = await _administratorRepository.All(cancellationToken); + } + + public async Task OnPostAddAsync(CancellationToken cancellationToken) + { + if (!ModelState.IsValid) + { + Administrators = await _administratorRepository.All(cancellationToken); + return Page(); + } + + try + { + await _mediator.Send(new AddAdministratorCommand(Cid!.Value), cancellationToken); + StatusMessage = $"{Cid} is now an administrator."; + } + catch (InvalidOperationException ex) + { + ErrorMessage = ex.Message; + } + + return RedirectToPage(); + } + + public async Task OnPostRemoveAsync(int cid, CancellationToken cancellationToken) + { + var currentUserCid = User.GetCid(); + if (currentUserCid is null) + return Forbid(); + + try + { + await _mediator.Send(new RemoveAdministratorCommand(cid, currentUserCid.Value), cancellationToken); + StatusMessage = $"{cid} is no longer an administrator."; + } + catch (InvalidOperationException ex) + { + ErrorMessage = ex.Message; + } + + return RedirectToPage(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml new file mode 100644 index 0000000..9826be1 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml @@ -0,0 +1,243 @@ +@page "/configuration/logs" +@using CPDLCServer.Logging +@model IndexModel +@{ + ViewData["Title"] = "Logs"; +} + + + +
+

Logs

+ Connecting +
+

The live log of the server. The page shows the recent entries, then each new entry. The logging level of the server (Logging__Level) sets which entries the server writes.

+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+ + +
+
+ +
+ +@section Scripts { + +} diff --git a/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml.cs new file mode 100644 index 0000000..53ee28e --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml.cs @@ -0,0 +1,23 @@ +using CPDLCServer.AcarsConnections; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Configuration.Logs; + +// The page gets the log entries from /logs/stream with JavaScript. The filters are in the query string, so that a +// link can open the page with a filter, for example the logs of one ACARS connection. +public class IndexModel : PageModel +{ + private readonly IAcarsConnectionManager _acarsConnectionManager; + + public IndexModel(IAcarsConnectionManager acarsConnectionManager) + { + _acarsConnectionManager = acarsConnectionManager; + } + + public string[] AcarsConnectionIds { get; private set; } = []; + + public void OnGet() + { + AcarsConnectionIds = _acarsConnectionManager.GetAcarsConnectionIds().Order().ToArray(); + } +} diff --git a/source/CPDLCServer/Web/Pages/Settings/Index.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml similarity index 73% rename from source/CPDLCServer/Web/Pages/Settings/Index.cshtml rename to source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml index bb7c443..9960c48 100644 --- a/source/CPDLCServer/Web/Pages/Settings/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml @@ -1,31 +1,81 @@ -@page "/settings" +@page "/configuration/settings" @model IndexModel @{ - ViewData["Title"] = "Global Settings"; + ViewData["Title"] = "Settings"; } - +

Settings

+

The server applies the changes immediately. A restart is not necessary.

-

Global Settings

-

The server applies the changes immediately. A restart is not necessary.

- -@if (Model.Saved) +@if (Model.StatusMessage is not null) { - + }
-
-
Connections
+
Branding
+
+

The name, banner and message of the day show at the top of the sidebar and on the login page.

+ +
+
+ +
Shows in the browser tab, and in the sidebar when there is no banner.
+
+
+
+ + +
+ +
+
Default: @Model.Defaults.ServerName
+
+ +
+
+ +
Optional. Plain text. The line breaks are kept.
+
+
+ + +
+
+ +
+
+ +
Optional. PNG, JPEG or WebP, 1 MB or less. The sidebar is 16rem wide, so a wide image is best. The banner changes when you upload it. The Save button does not change it.
+
+
+ @if (Model.Branding.HasBanner) + { +
+ Current banner +
+ } + + @* These controls are in the banner forms below the settings form, because a form cannot contain a form *@ + + @Html.ValidationMessage("Banner", null, new { @class = "text-danger small" }) +
+ + @if (Model.Branding.HasBanner) + { + + } +
+
+
+
+ +
+
Connections
@if (Model.OneFailedCheckCausesTimeout) { @@ -69,9 +119,7 @@
-
-
Dialogues
-
+
Dialogues
@@ -92,9 +140,7 @@
-
-
ADS-C
-
+
ADS-C
@@ -115,9 +161,7 @@
-
-
Handoff
-
+
Handoff
@@ -138,9 +182,7 @@
-
-
ADS-C from VATSIM status data
-
+
ADS-C from VATSIM status data
@@ -218,11 +260,14 @@
+ + + @section Scripts { -} diff --git a/source/CPDLCServer/Web/Pages/Logs/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Logs/Index.cshtml.cs deleted file mode 100644 index b83970a..0000000 --- a/source/CPDLCServer/Web/Pages/Logs/Index.cshtml.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace CPDLCServer.Web.Pages.Logs; - -// The page gets the log entries from /logs/stream with JavaScript -public class IndexModel : PageModel -{ - public void OnGet() - { - } -} diff --git a/source/CPDLCServer/Web/Pages/Pilot/Index.cshtml b/source/CPDLCServer/Web/Pages/Pilot/Index.cshtml deleted file mode 100644 index 071931f..0000000 --- a/source/CPDLCServer/Web/Pages/Pilot/Index.cshtml +++ /dev/null @@ -1,47 +0,0 @@ -@page "/pilot/{callsign}" -@model IndexModel -@{ - ViewData["Title"] = $"Pilot {Model.Callsign}"; -} - - - -

Pilot: @Model.Callsign

- -@if (Model.Aircraft != null) -{ -
-
-
-
Callsign
-
@Model.Aircraft.Callsign
- -
ATSU
-
@Model.Aircraft.StationId
- -
ACARS Network
-
@Model.Aircraft.AcarsConnectionId
- -
Data Authority
-
@Model.Aircraft.DataAuthorityState
- -
Connection State
-
@Model.Aircraft.ConnectionState
- -
Last Seen
-
@Model.Aircraft.LastSeen.ToString("yyyy-MM-dd HH:mm:ss")
-
-
-
-} - -

Messages

- -
- -
diff --git a/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml b/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml new file mode 100644 index 0000000..6a056e2 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml @@ -0,0 +1,30 @@ +@page "/plugin/authorize" +@model AuthorizeModel +@{ + ViewData["Title"] = "Connect the plugin"; + Layout = "_CenteredLayout"; +} + +@if (!Model.IsValidRequest) +{ +

The request is not valid

+

Start the authentication again from the SETUP window of the CPDLC plugin in vatSys.

+} +else +{ +

Connect the vatSys plugin

+

+ The CPDLC plugin on this computer will connect to the server as + @User.GetName() (@User.GetCid()). +

+

Continue only if you started the authentication from the SETUP window in vatSys.

+ +
+ @* The same names as the query string of the GET request *@ + + + + + +
+} diff --git a/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml.cs b/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml.cs new file mode 100644 index 0000000..1a2b9d4 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Plugin/Authorize.cshtml.cs @@ -0,0 +1,51 @@ +using CPDLCServer.Auth; +using CPDLCServer.Auth.PluginTokens; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages.Plugin; + +// The browser part of the plugin login. The user logs in with VATSIM, then allows the plugin to connect. +// Then the browser goes to the plugin on this computer with a one-use code. +public class AuthorizeModel : PageModel +{ + private readonly PluginAuthorizationCodes _authorizationCodes; + + public AuthorizeModel(PluginAuthorizationCodes authorizationCodes) + { + _authorizationCodes = authorizationCodes; + } + + [BindProperty(SupportsGet = true, Name = "redirect_uri")] + public string? RedirectUri { get; set; } + + [BindProperty(SupportsGet = true, Name = "state")] + public string? State { get; set; } + + [BindProperty(SupportsGet = true, Name = "code_challenge")] + public string? CodeChallenge { get; set; } + + [BindProperty(SupportsGet = true, Name = "code_challenge_method")] + public string? CodeChallengeMethod { get; set; } + + public bool IsValidRequest => + PluginRedirectUri.IsValid(RedirectUri) && + !string.IsNullOrEmpty(State) && + !string.IsNullOrEmpty(CodeChallenge) && + CodeChallengeMethod == "S256"; + + public void OnGet() + { + } + + public IActionResult OnPost() + { + if (!IsValidRequest) + return Page(); + + var code = _authorizationCodes.Create(User.GetCid()!.Value, User.GetName(), RedirectUri!, CodeChallenge!); + + var redirectUri = $"{RedirectUri}?code={Uri.EscapeDataString(code)}&state={Uri.EscapeDataString(State!)}"; + return Redirect(redirectUri); + } +} diff --git a/source/CPDLCServer/Web/Pages/Settings/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Settings/Index.cshtml.cs deleted file mode 100644 index 1f00f49..0000000 --- a/source/CPDLCServer/Web/Pages/Settings/Index.cshtml.cs +++ /dev/null @@ -1,49 +0,0 @@ -using CPDLCServer.Infrastructure; -using CPDLCServer.Settings; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace CPDLCServer.Web.Pages.Settings; - -public class IndexModel : PageModel -{ - private readonly IServerSettingsProvider _settingsProvider; - private readonly IUnitOfWorkMediator _mediator; - - public IndexModel(IServerSettingsProvider settingsProvider, IUnitOfWorkMediator mediator) - { - _settingsProvider = settingsProvider; - _mediator = mediator; - } - - [BindProperty] - public ServerSettings Settings { get; set; } = new(); - - public ServerSettings Defaults { get; } = new(); - - [TempData] - public bool Saved { get; set; } - - // If one connectivity check fails, the time between two updates of the last seen time is two check intervals - public bool OneFailedCheckCausesTimeout => - Settings.AircraftConnectionTimeoutMinutes <= Settings.ConnectivityCheckIntervalMinutes * 2; - - public async Task OnGetAsync(CancellationToken cancellationToken) - { - Settings = await _settingsProvider.Load(cancellationToken); - } - - public async Task OnPostAsync(CancellationToken cancellationToken) - { - if (Settings.VatsimStatusUrl is { IsAbsoluteUri: false }) - ModelState.AddModelError($"{nameof(Settings)}.{nameof(Settings.VatsimStatusUrl)}", "Enter an absolute URL."); - - if (!ModelState.IsValid) - return Page(); - - await _mediator.Send(new SaveServerSettingsCommand(Settings), cancellationToken); - - Saved = true; - return RedirectToPage(); - } -} diff --git a/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml b/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml deleted file mode 100644 index 194848e..0000000 --- a/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml +++ /dev/null @@ -1,44 +0,0 @@ -@page "/settings/users/{id:guid}/password" -@model ChangePasswordModel -@{ - ViewData["Title"] = "Change password"; -} - - - -

Change password

-

Set a new password for @Model.Username. The current password is not necessary.

- - - -
-
-
- - -
- - -
Use 12 characters or more.
- -
- -
- - - -
-
-
- -
- Cancel - -
-
diff --git a/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml.cs b/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml.cs deleted file mode 100644 index b162e81..0000000 --- a/source/CPDLCServer/Web/Pages/Settings/Users/ChangePassword.cshtml.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.ComponentModel.DataAnnotations; -using CPDLCServer.Auth.Users; -using CPDLCServer.Infrastructure; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace CPDLCServer.Web.Pages.Settings.Users; - -public class ChangePasswordModel : PageModel -{ - private readonly IUserRepository _userRepository; - private readonly IUnitOfWorkMediator _mediator; - - public ChangePasswordModel(IUserRepository userRepository, IUnitOfWorkMediator mediator) - { - _userRepository = userRepository; - _mediator = mediator; - } - - [BindProperty(SupportsGet = true)] - public Guid Id { get; set; } - - [BindProperty] - public ChangePasswordInput Input { get; set; } = new(); - - public string Username { get; private set; } = string.Empty; - - [TempData] - public string? StatusMessage { get; set; } - - public async Task OnGetAsync(CancellationToken cancellationToken) - { - var user = await _userRepository.FindById(Id, cancellationToken); - if (user is null) - return NotFound(); - - Username = user.Username; - return Page(); - } - - public async Task OnPostAsync(CancellationToken cancellationToken) - { - var user = await _userRepository.FindById(Id, cancellationToken); - if (user is null) - return NotFound(); - - Username = user.Username; - if (!ModelState.IsValid) - return Page(); - - await _mediator.Send(new ChangePasswordCommand(Id, Input.NewPassword), cancellationToken); - - StatusMessage = $"The password of {Username} was changed."; - return RedirectToPage("Index"); - } - - public class ChangePasswordInput - { - [Required] - [StringLength(200, MinimumLength = 12, ErrorMessage = "Use a password of 12 characters or more.")] - [DataType(DataType.Password)] - [Display(Name = "New password")] - public string NewPassword { get; set; } = string.Empty; - - [Required] - [Compare(nameof(NewPassword), ErrorMessage = "The passwords are not the same.")] - [DataType(DataType.Password)] - [Display(Name = "Confirm new password")] - public string ConfirmNewPassword { get; set; } = string.Empty; - } -} diff --git a/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml b/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml deleted file mode 100644 index d4eeaeb..0000000 --- a/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml +++ /dev/null @@ -1,54 +0,0 @@ -@page "/settings/users" -@model IndexModel -@{ - ViewData["Title"] = "Users"; -} - - - -

Users

-

The users that can log in to the dashboard.

- -@if (Model.StatusMessage is not null) -{ - -} - -
-
-
- - - - - - - - - - @foreach (var user in Model.Users) - { - - - - - - } - -
UsernameCreated
- @user.Username - @if (Model.IsCurrentUser(user)) - { - (you) - } - @user.Created.ToString("yyyy-MM-dd HH:mm") UTC - Change password -
-
-
-
diff --git a/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml.cs deleted file mode 100644 index a55e5f5..0000000 --- a/source/CPDLCServer/Web/Pages/Settings/Users/Index.cshtml.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Security.Claims; -using CPDLCServer.Auth.Users; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace CPDLCServer.Web.Pages.Settings.Users; - -public class IndexModel : PageModel -{ - private readonly IUserRepository _userRepository; - - public IndexModel(IUserRepository userRepository) - { - _userRepository = userRepository; - } - - public User[] Users { get; private set; } = []; - - [TempData] - public string? StatusMessage { get; set; } - - public bool IsCurrentUser(User user) => User.FindFirstValue(ClaimTypes.NameIdentifier) == user.Id.ToString(); - - public async Task OnGetAsync(CancellationToken cancellationToken) - { - Users = await _userRepository.All(cancellationToken); - } -} diff --git a/source/CPDLCServer/Web/Pages/Settings/_SettingsLayout.cshtml b/source/CPDLCServer/Web/Pages/Settings/_SettingsLayout.cshtml deleted file mode 100644 index ff5f4b4..0000000 --- a/source/CPDLCServer/Web/Pages/Settings/_SettingsLayout.cshtml +++ /dev/null @@ -1,25 +0,0 @@ -@{ - Layout = "_Layout"; - - var path = Context.Request.Path; - var isAcars = path.StartsWithSegments("/settings/acars"); - var isUsers = path.StartsWithSegments("/settings/users"); - var isGlobal = !isAcars && !isUsers; -} - -
- -
- @RenderBody() -
-
- -@section Scripts { - @await RenderSectionAsync("Scripts", required: false) -} diff --git a/source/CPDLCServer/Web/Pages/Settings/_ViewStart.cshtml b/source/CPDLCServer/Web/Pages/Settings/_ViewStart.cshtml deleted file mode 100644 index ff2cb3f..0000000 --- a/source/CPDLCServer/Web/Pages/Settings/_ViewStart.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@{ - Layout = "_SettingsLayout"; -} diff --git a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml index e400c01..0e87f97 100644 --- a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml @@ -2,63 +2,23 @@ @model IndexModel @{ ViewData["Title"] = "Setup"; + Layout = "_CenteredLayout"; } -
-
-

Set up the server

-

Create the first user

+

Set up the server

+

+ Enter the VATSIM CID of the first administrator. After the setup, that person logs in with VATSIM + and can add more administrators. You can do the setup only one time. +

- @if (!Model.IsTokenValid) - { - - } - else - { -

- The administrator can open the Settings and Logs pages. - Keep the password in a safe place. The server cannot show it again. -

+ - - -
- - -
-
-
- - - -
- -
- - -
Use 12 characters or more.
- -
- -
- - - -
-
-
- -
- -
-
- } +
+
+ + +
-
+ + + diff --git a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs index 23a4328..1c974d7 100644 --- a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs @@ -1,6 +1,5 @@ using System.ComponentModel.DataAnnotations; -using CPDLCServer.Auth.Login; -using CPDLCServer.Auth.Users; +using CPDLCServer.Auth.Administrators; using CPDLCServer.Infrastructure; using CPDLCServer.Setup; using Microsoft.AspNetCore.Mvc; @@ -8,7 +7,7 @@ namespace CPDLCServer.Web.Pages.Setup; -// The setup: create the first user +// The setup adds the first administrator. After the setup, the page does not exist. public class IndexModel : PageModel { private readonly SetupState _setupState; @@ -25,70 +24,39 @@ public IndexModel( _logger = logger; } - // The token from the setup URL in the server log - [BindProperty(SupportsGet = true)] - public string? Token { get; set; } - [BindProperty] - public CreateAdminInput Input { get; set; } = new(); - - public bool IsTokenValid { get; private set; } + [Required] + [Range(1, int.MaxValue, ErrorMessage = "Enter a valid CID.")] + [Display(Name = "Administrator CID")] + public int? Cid { get; set; } public IActionResult OnGet() { if (_setupState.IsConfigured) - return Redirect("/"); + return NotFound(); - IsTokenValid = _setupState.IsValidSetupToken(Token); return Page(); } public async Task OnPostAsync(CancellationToken cancellationToken) { if (_setupState.IsConfigured) - return Redirect("/"); - - IsTokenValid = _setupState.IsValidSetupToken(Token); - if (!IsTokenValid) - return Page(); + return NotFound(); if (!ModelState.IsValid) return Page(); - Guid userId; try { - userId = await _mediator.Send(new CreateUserCommand(Input.Username, Input.Password), cancellationToken); + await _mediator.Send(new CreateFirstAdministratorCommand(Cid!.Value), cancellationToken); } catch (InvalidOperationException ex) { - // Another person completed this step first - _logger.Warning(ex, "Failed to create the administrator"); - return RedirectToPage("/Account/Login"); + // Another person completed the setup first + _logger.Warning(ex, "Failed to add the first administrator"); + return NotFound(); } - await AdminAuthentication.SignIn(HttpContext, userId, Input.Username.Trim()); - - return Redirect("/"); - } - - public class CreateAdminInput - { - [Required] - [StringLength(64)] - [Display(Name = "Username")] - public string Username { get; set; } = string.Empty; - - [Required] - [StringLength(200, MinimumLength = 12, ErrorMessage = "Use a password of 12 characters or more.")] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; set; } = string.Empty; - - [Required] - [Compare(nameof(Password), ErrorMessage = "The passwords are not the same.")] - [DataType(DataType.Password)] - [Display(Name = "Confirm password")] - public string ConfirmPassword { get; set; } = string.Empty; + return Redirect("/login"); } } diff --git a/source/CPDLCServer/Web/Pages/Shared/_Branding.cshtml b/source/CPDLCServer/Web/Pages/Shared/_Branding.cshtml new file mode 100644 index 0000000..6ebdbb5 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Shared/_Branding.cshtml @@ -0,0 +1,18 @@ +@model CPDLCServer.Settings.BrandingInfo + +@* The banner or the server name, then the message of the day. The sidebar and the login page show it. *@ + + @if (Model.HasBanner) + { + @Model.ServerName + } + else + { + @Model.ServerName + } + + +@if (!string.IsNullOrWhiteSpace(Model.Motd)) +{ +
@Model.Motd
+} diff --git a/source/CPDLCServer/Web/Pages/Shared/_CenteredLayout.cshtml b/source/CPDLCServer/Web/Pages/Shared/_CenteredLayout.cshtml new file mode 100644 index 0000000..b766cc9 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Shared/_CenteredLayout.cshtml @@ -0,0 +1,31 @@ +@inject IServerSettingsProvider SettingsProvider +@{ + var branding = await SettingsProvider.LoadBranding(Context.RequestAborted); +} +@* For the pages without the sidebar: login, setup and plugin authorization *@ + + + + + + @ViewData["Title"] - @branding.ServerName + + + + +
+
+
+ +
+
+
+ @RenderBody() +
+
+
+
+ + diff --git a/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml b/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml index 7c80b1d..75b9208 100644 --- a/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml +++ b/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml @@ -1,48 +1,113 @@ +@using Microsoft.AspNetCore.Authorization +@inject IServerSettingsProvider SettingsProvider +@inject IAuthorizationService AuthorizationService +@{ + var branding = await SettingsProvider.LoadBranding(Context.RequestAborted); + var isAdministrator = (await AuthorizationService.AuthorizeAsync(User, AdministratorRequirement.PolicyName)).Succeeded; + var path = Context.Request.Path; + + // "exact" is for a page that has sub-pages in a different menu item + string NavLink(string href, bool exact = false) + { + var isActive = exact + ? string.Equals(path.Value?.TrimEnd('/'), href, StringComparison.OrdinalIgnoreCase) + : path.StartsWithSegments(href, StringComparison.OrdinalIgnoreCase); + return isActive ? "nav-link active" : "nav-link"; + } +} - @ViewData["Title"] - CPDLC Server + @ViewData["Title"] - @branding.ServerName + - -
-
-
- CPDLC Server + +
+
-
-
-
- @RenderBody() + +
+
+ +
+
+ @if (!string.IsNullOrWhiteSpace(branding.Motd)) + { +
@branding.Motd
+ } +
+ + + +
+
@User.GetName()
+
CID @User.GetCid()
+
+
+ @Html.AntiForgeryToken() + +
+ Documentation +
+
+
+ + +
+
+ + @branding.ServerName +
+ +
+ @RenderBody() +
-
+
@await RenderSectionAsync("Scripts", required: false) - diff --git a/source/CPDLCServer/Web/Pages/Shared/_MessageTable.cshtml b/source/CPDLCServer/Web/Pages/Shared/_MessageTable.cshtml index e096e90..51ce03d 100644 --- a/source/CPDLCServer/Web/Pages/Shared/_MessageTable.cshtml +++ b/source/CPDLCServer/Web/Pages/Shared/_MessageTable.cshtml @@ -3,50 +3,53 @@ @{ string GetAlertBadgeClass(string alertType) => alertType switch { - "High" => "bg-danger", - "Medium" => "bg-warning text-dark", - "Low" => "bg-info", - _ => "bg-light text-dark" + "High" => "text-bg-danger", + "Medium" => "text-bg-warning", + "Low" => "text-bg-info", + _ => "text-bg-light" }; } -
- - - - - - - - - - - - - - - - - @foreach (var msg in Model) - { - - - - - - - - - - - - - } - -
DialogueTimestampNetworkDirSenderReceiverAlertResponseContentState
@msg.DialogueId.ToString()[..8]...@msg.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")@msg.AcarsNetwork@(msg.IsUplink ? "↑" : "↓")@msg.Sender@msg.Receiver@msg.AlertType@msg.ResponseType@msg.Content@(msg.IsClosed ? "Closed" : "Open")
-
- @if (!Model.Any()) { -

No messages found.

+

No messages.

+} +else +{ +
+ + + + + + + + + + + + + + + + @foreach (var msg in Model) + { + + + + + + + + + + + + } + +
TimeSenderReceiverContentResponseAlertDialogueACARS connection
@msg.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")@(msg.IsUplink ? "↑" : "↓")@msg.Sender@msg.Receiver@msg.Content@msg.ResponseType@msg.AlertType + @msg.DialogueId.ToString()[..8] + @(msg.IsClosed ? "Closed" : "Open") + @msg.AcarsNetwork
+
} diff --git a/source/CPDLCServer/Web/Pages/Shared/_Pagination.cshtml b/source/CPDLCServer/Web/Pages/Shared/_Pagination.cshtml new file mode 100644 index 0000000..95d3d90 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Shared/_Pagination.cshtml @@ -0,0 +1,44 @@ +@model CPDLCServer.Web.Pages.ViewModels.PaginationViewModel + +@if (Model.TotalPages > 1) +{ + var startPage = Math.Max(1, Model.CurrentPage - 2); + var endPage = Math.Min(Model.TotalPages, Model.CurrentPage + 2); + + +} diff --git a/source/CPDLCServer/Web/Pages/ViewModels/MessageRowViewModel.cs b/source/CPDLCServer/Web/Pages/ViewModels/MessageRowViewModel.cs index 02543e7..781df8f 100644 --- a/source/CPDLCServer/Web/Pages/ViewModels/MessageRowViewModel.cs +++ b/source/CPDLCServer/Web/Pages/ViewModels/MessageRowViewModel.cs @@ -18,7 +18,7 @@ public record MessageRowViewModel( bool IsClosed) { public static MessageRowViewModel From( - Cpdlc.Dialogues.Dialogue dialogue, + CPDLCServer.Cpdlc.Dialogues.Dialogue dialogue, CpdlcMessage message, Dictionary aircraftLookup) { diff --git a/source/CPDLCServer/Web/Pages/ViewModels/PaginationViewModel.cs b/source/CPDLCServer/Web/Pages/ViewModels/PaginationViewModel.cs new file mode 100644 index 0000000..096f22e --- /dev/null +++ b/source/CPDLCServer/Web/Pages/ViewModels/PaginationViewModel.cs @@ -0,0 +1,7 @@ +namespace CPDLCServer.Web.Pages.ViewModels; + +// The page links below a table. The path is the page URL without the query string. +public record PaginationViewModel(string Path, int CurrentPage, int TotalPages) +{ + public string Url(int pageNumber) => $"{Path}?pageNumber={pageNumber}"; +} diff --git a/source/CPDLCServer/Web/Pages/_ViewImports.cshtml b/source/CPDLCServer/Web/Pages/_ViewImports.cshtml index d53f26e..e6a451c 100644 --- a/source/CPDLCServer/Web/Pages/_ViewImports.cshtml +++ b/source/CPDLCServer/Web/Pages/_ViewImports.cshtml @@ -1,2 +1,4 @@ @namespace CPDLCServer.Web.Pages +@using CPDLCServer.Auth +@using CPDLCServer.Settings @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/source/CPDLCServer/Web/WebServiceCollectionExtensions.cs b/source/CPDLCServer/Web/WebServiceCollectionExtensions.cs index 4e8745a..5546939 100644 --- a/source/CPDLCServer/Web/WebServiceCollectionExtensions.cs +++ b/source/CPDLCServer/Web/WebServiceCollectionExtensions.cs @@ -1,3 +1,5 @@ +using CPDLCServer.Auth; + namespace CPDLCServer.Web; public static class WebServiceCollectionExtensions @@ -9,9 +11,14 @@ public static IServiceCollection AddWeb(this IServiceCollection services) { options.RootDirectory = "/Web/Pages"; - // Only a user that is logged in can open these pages - options.Conventions.AuthorizeFolder("/Settings"); - options.Conventions.AuthorizeFolder("/Logs"); + // Any VATSIM user that is logged in can open the pages + options.Conventions.AuthorizeFolder("/"); + options.Conventions.AllowAnonymousToPage("/Account/Login"); + options.Conventions.AllowAnonymousToPage("/Account/Logout"); + options.Conventions.AllowAnonymousToPage("/Setup/Index"); + + // Only an administrator can open the Configuration area + options.Conventions.AuthorizeFolder("/Configuration", AdministratorRequirement.PolicyName); }); return services; From 0c7557e89de04ed0dff00c8dbb7ed6baa46fff16 Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:24:39 +1000 Subject: [PATCH 13/18] Add a privacy policy and the VATSIM disclaimer Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + docs/docs/server/index.md | 24 ++- .../AdministratorCommandHandlerTests.cs | 37 ---- .../Settings/PrivacyContactTests.cs | 31 +++ .../Setup/CompleteSetupCommandHandlerTests.cs | 59 ++++++ .../PurgeExpiredAdscDataRequestHandler.cs | 5 +- .../CreateFirstAdministratorCommand.cs | 6 - .../CreateFirstAdministratorCommandHandler.cs | 32 --- .../Auth/AuthServiceCollectionExtensions.cs | 5 +- source/CPDLCServer/Logging/LogBuffer.cs | 6 +- ... 20261121062110_InitialCreate.Designer.cs} | 12 +- ...ate.cs => 20261121062110_InitialCreate.cs} | 2 + .../PostgreSqlCpdlcDbContextModelSnapshot.cs | 10 + ... 20261121062107_InitialCreate.Designer.cs} | 12 +- ...ate.cs => 20261121062107_InitialCreate.cs} | 2 + .../SqliteCpdlcDbContextModelSnapshot.cs | 10 + .../Settings/PrivacyContactFormat.cs | 43 ++++ source/CPDLCServer/Settings/ServerSettings.cs | 13 ++ .../Settings/ServerSettingsConfiguration.cs | 2 + .../CPDLCServer/Setup/CompleteSetupCommand.cs | 6 + .../Setup/CompleteSetupCommandHandler.cs | 43 ++++ .../Web/Pages/Account/Login.cshtml | 5 + .../Pages/Configuration/Settings/Index.cshtml | 29 +++ source/CPDLCServer/Web/Pages/Privacy.cshtml | 193 ++++++++++++++++++ .../CPDLCServer/Web/Pages/Privacy.cshtml.cs | 39 ++++ .../CPDLCServer/Web/Pages/Setup/Index.cshtml | 26 ++- .../Web/Pages/Setup/Index.cshtml.cs | 34 ++- .../Web/Pages/Shared/_CenteredLayout.cshtml | 6 +- .../Web/Pages/Shared/_Disclaimer.cshtml | 5 + .../Web/Pages/Shared/_Layout.cshtml | 3 + .../Web/WebServiceCollectionExtensions.cs | 1 + 31 files changed, 603 insertions(+), 100 deletions(-) create mode 100644 source/CPDLCServer.Tests/Settings/PrivacyContactTests.cs create mode 100644 source/CPDLCServer.Tests/Setup/CompleteSetupCommandHandlerTests.cs delete mode 100644 source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommand.cs delete mode 100644 source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommandHandler.cs rename source/CPDLCServer/Persistence/Migrations/PostgreSql/{20261121042342_InitialCreate.Designer.cs => 20261121062110_InitialCreate.Designer.cs} (97%) rename source/CPDLCServer/Persistence/Migrations/PostgreSql/{20261121042342_InitialCreate.cs => 20261121062110_InitialCreate.cs} (98%) rename source/CPDLCServer/Persistence/Migrations/Sqlite/{20261121042339_InitialCreate.Designer.cs => 20261121062107_InitialCreate.Designer.cs} (97%) rename source/CPDLCServer/Persistence/Migrations/Sqlite/{20261121042339_InitialCreate.cs => 20261121062107_InitialCreate.cs} (98%) create mode 100644 source/CPDLCServer/Settings/PrivacyContactFormat.cs create mode 100644 source/CPDLCServer/Setup/CompleteSetupCommand.cs create mode 100644 source/CPDLCServer/Setup/CompleteSetupCommandHandler.cs create mode 100644 source/CPDLCServer/Web/Pages/Privacy.cshtml create mode 100644 source/CPDLCServer/Web/Pages/Privacy.cshtml.cs create mode 100644 source/CPDLCServer/Web/Pages/Shared/_Disclaimer.cshtml diff --git a/README.md b/README.md index 6f544fa..cb0bc51 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,8 @@ > [!NOTE] > Even though the development of this plugin was inspired by real ATM systems such as those from Thales Group, the plugin is absolutely NOT affiliated with or endorsed by said company. The plugin and all associated files shall be used solely for the purpose of simulation on the VATSIM network. +> +> The plugin and the CPDLC server are third-party software. They are not provided, operated or endorsed by VATSIM. ## Overview diff --git a/docs/docs/server/index.md b/docs/docs/server/index.md index cf43da0..f9b7470 100644 --- a/docs/docs/server/index.md +++ b/docs/docs/server/index.md @@ -27,7 +27,7 @@ You must set the `MasterKey`, `VatsimConnect__ClientId` and `VatsimConnect__Clie Make a key with `openssl rand -base64 32`, and keep a copy in a safe place. See [VATSIM Connect](#vatsim-connect) for the client. ::: -After deployment, open `/setup` on the server, and enter the CID of the first administrator (see [Setup](#setup)). Then log in with VATSIM, and add your ACARS connection in Configuration → ACARS connections (`/configuration/acars`). +After deployment, open `/setup` on the server, and enter the CID of the first administrator and the operator details (see [Setup](#setup)). Then log in with VATSIM, and add your ACARS connection in Configuration → ACARS connections (`/configuration/acars`). ## Prerequisites @@ -41,7 +41,15 @@ Before running the CPDLC Server, ensure you have: When the server starts for the first time, it is not set up. All the pages of the dashboard redirect to the setup page (`/setup`). -On the setup page, enter the VATSIM CID of the first administrator. After the setup, the setup page does not exist. The administrator logs in with VATSIM, and can add more administrators in Configuration → Administrators. +On the setup page, enter: + +- The VATSIM CID of the first administrator. +- The operator name: the person or organisation that operates the server, for example a VATSIM division or FIR. +- The privacy contact: an email address or a URL. Users use it to ask questions about their data, or to ask for their data to be deleted. + +The privacy policy shows the operator name and the privacy contact. You can change them later in Configuration → Settings. + +After the setup, the setup page does not exist. The administrator logs in with VATSIM, and can add more administrators in Configuration → Administrators. :::warning The setup page needs no login. The first person who opens it chooses the administrator. Do the setup immediately after the first start. @@ -139,6 +147,18 @@ The Traffic button of a connection shows the most recent requests to the ACARS n `Hoppie` is currently the only supported ACARS network type. ::: +### Privacy Policy + +VATSIM Connect needs a privacy policy and a statement that the service is not provided or endorsed by VATSIM. The server has both: + +- The privacy policy is at `/privacy`. Everyone can open it, also without a login. It shows the operator, the privacy contact, the data that the server collects, who can see it, the third parties, and how long the server keeps the data. The retention times come from the settings, so the page is correct when you change them. +- Each page shows this statement, with a link to the privacy policy: "This server is a third-party service. It is not provided, operated or endorsed by VATSIM." +- The login page tells users that VATSIM gives the server their CID and name, and that they accept the privacy policy when they log in. + +:::warning +The privacy policy describes the software. The operator is responsible for the data on their server. Read the policy, and make sure that it agrees with the laws that apply to you and with the VATSIM policies, before you open the server to users. +::: + ### Branding In the Branding section of Configuration → Settings, you can change the name of the server, add a banner image (PNG, JPEG or WebP, 1 MB or less), and add a message of the day. They show at the top of the sidebar and on the login page. The banner changes when you upload or remove it. The Save button saves the name and the message of the day. diff --git a/source/CPDLCServer.Tests/Auth/Administrators/AdministratorCommandHandlerTests.cs b/source/CPDLCServer.Tests/Auth/Administrators/AdministratorCommandHandlerTests.cs index d6e6535..86074fa 100644 --- a/source/CPDLCServer.Tests/Auth/Administrators/AdministratorCommandHandlerTests.cs +++ b/source/CPDLCServer.Tests/Auth/Administrators/AdministratorCommandHandlerTests.cs @@ -1,7 +1,5 @@ using CPDLCServer.Auth.Administrators; -using CPDLCServer.Setup; using CPDLCServer.Tests.Mocks; -using Microsoft.Extensions.DependencyInjection; using Serilog.Core; namespace CPDLCServer.Tests.Auth.Administrators; @@ -80,34 +78,6 @@ await Assert.ThrowsAsync(() => handler.Handle(new RemoveAdministratorCommand(1111111, CurrentUserCid: 9999999), CancellationToken.None)); } - [Fact] - public async Task CreateFirst_AddsTheAdministratorAndCompletesTheSetup() - { - // Arrange - var setupState = CreateSetupState(); - var handler = new CreateFirstAdministratorCommandHandler(_administratorRepository, setupState, _clock, new TestUnitOfWork(), Logger.None); - - // Act - await handler.Handle(new CreateFirstAdministratorCommand(1234567), CancellationToken.None); - - // Assert - Assert.NotNull(await _administratorRepository.FindByCid(1234567, CancellationToken.None)); - Assert.True(setupState.IsConfigured); - } - - [Fact] - public async Task CreateFirst_WhenAnAdministratorExists_Throws() - { - // Arrange - await _administratorRepository.Add(new Administrator { Cid = 1111111 }, CancellationToken.None); - var handler = new CreateFirstAdministratorCommandHandler(_administratorRepository, CreateSetupState(), _clock, new TestUnitOfWork(), Logger.None); - - // Act & Assert - await Assert.ThrowsAsync(() => - handler.Handle(new CreateFirstAdministratorCommand(1234567), CancellationToken.None)); - Assert.Null(await _administratorRepository.FindByCid(1234567, CancellationToken.None)); - } - [Fact] public async Task UpdateName_ChangesTheNameOfAnAdministrator() { @@ -122,11 +92,4 @@ public async Task UpdateName_ChangesTheNameOfAnAdministrator() var administrator = await _administratorRepository.FindByCid(1234567, CancellationToken.None); Assert.Equal("Test Controller", administrator!.Name); } - - SetupState CreateSetupState() - { - var services = new ServiceCollection(); - services.AddSingleton(_administratorRepository); - return new SetupState(services.BuildServiceProvider().GetRequiredService()); - } } diff --git a/source/CPDLCServer.Tests/Settings/PrivacyContactTests.cs b/source/CPDLCServer.Tests/Settings/PrivacyContactTests.cs new file mode 100644 index 0000000..c0b0ee9 --- /dev/null +++ b/source/CPDLCServer.Tests/Settings/PrivacyContactTests.cs @@ -0,0 +1,31 @@ +using CPDLCServer.Settings; + +namespace CPDLCServer.Tests.Settings; + +public class PrivacyContactTests +{ + [Theory] + [InlineData("privacy@example.com", true)] + [InlineData("https://example.com/privacy", true)] + [InlineData("http://example.com/privacy", true)] + [InlineData("", true)] + [InlineData(null, true)] + [InlineData("not a contact", false)] + [InlineData("javascript:alert(1)", false)] + [InlineData("ftp://example.com", false)] + [InlineData("Privacy ", false)] + public void IsValid_AcceptsAnEmailAddressOrAWebUrl(string? contact, bool expected) + { + // Act & Assert + Assert.Equal(expected, new PrivacyContactAttribute().IsValid(contact)); + } + + [Theory] + [InlineData("privacy@example.com", "mailto:privacy@example.com")] + [InlineData("https://example.com/privacy", "https://example.com/privacy")] + public void ToHref_MakesALink(string contact, string expected) + { + // Act & Assert + Assert.Equal(expected, PrivacyContactFormat.ToHref(contact)); + } +} diff --git a/source/CPDLCServer.Tests/Setup/CompleteSetupCommandHandlerTests.cs b/source/CPDLCServer.Tests/Setup/CompleteSetupCommandHandlerTests.cs new file mode 100644 index 0000000..cec2f28 --- /dev/null +++ b/source/CPDLCServer.Tests/Setup/CompleteSetupCommandHandlerTests.cs @@ -0,0 +1,59 @@ +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Settings; +using CPDLCServer.Setup; +using CPDLCServer.Tests.Mocks; +using Microsoft.Extensions.DependencyInjection; +using Serilog.Core; + +namespace CPDLCServer.Tests.Setup; + +public class CompleteSetupCommandHandlerTests +{ + readonly TestAdministratorRepository _administratorRepository = new(); + readonly TestServerSettingsProvider _settingsProvider = new(new ServerSettings()); + readonly TestClock _clock = new(); + + [Fact] + public async Task Handle_AddsTheAdministratorAndTheOperatorAndCompletesTheSetup() + { + // Arrange + var setupState = CreateSetupState(); + var handler = CreateHandler(setupState); + + // Act + await handler.Handle(new CompleteSetupCommand(1234567, " VATPAC ", " privacy@example.com "), CancellationToken.None); + + // Assert + Assert.NotNull(await _administratorRepository.FindByCid(1234567, CancellationToken.None)); + + var settings = await _settingsProvider.Load(CancellationToken.None); + Assert.Equal("VATPAC", settings.OperatorName); + Assert.Equal("privacy@example.com", settings.PrivacyContact); + + Assert.True(setupState.IsConfigured); + } + + [Fact] + public async Task Handle_WhenAnAdministratorExists_Throws() + { + // Arrange + await _administratorRepository.Add(new Administrator { Cid = 1111111 }, CancellationToken.None); + var handler = CreateHandler(CreateSetupState()); + + // Act & Assert + await Assert.ThrowsAsync(() => + handler.Handle(new CompleteSetupCommand(1234567, "VATPAC", "privacy@example.com"), CancellationToken.None)); + Assert.Null(await _administratorRepository.FindByCid(1234567, CancellationToken.None)); + Assert.Equal(string.Empty, (await _settingsProvider.Load(CancellationToken.None)).OperatorName); + } + + CompleteSetupCommandHandler CreateHandler(SetupState setupState) => + new(_administratorRepository, _settingsProvider, setupState, _clock, new TestUnitOfWork(), Logger.None); + + SetupState CreateSetupState() + { + var services = new ServiceCollection(); + services.AddSingleton(_administratorRepository); + return new SetupState(services.BuildServiceProvider().GetRequiredService()); + } +} diff --git a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs index 3d00e70..f729f4a 100644 --- a/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs +++ b/source/CPDLCServer/AdscContracts/PurgeExpiredAdscDataRequestHandler.cs @@ -9,7 +9,8 @@ public class PurgeExpiredAdscDataRequestHandler( IClock clock) : IRequestHandler { - readonly TimeSpan _messageLogRetention = TimeSpan.FromHours(24); + // The privacy policy shows this value + public static readonly TimeSpan MessageLogRetention = TimeSpan.FromHours(24); // The ADS-C reports are not purged here. Each contract keeps only its latest report, and the report expires // soon after the next periodic reports do not arrive (ExpireAdscReportsRequestHandler). @@ -17,6 +18,6 @@ public async Task Handle(PurgeExpiredAdscDataRequest request, CancellationToken { var now = clock.UtcNow(); - await adscMessageLogRepository.RemoveOlderThan(now - _messageLogRetention, cancellationToken); + await adscMessageLogRepository.RemoveOlderThan(now - MessageLogRetention, cancellationToken); } } diff --git a/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommand.cs b/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommand.cs deleted file mode 100644 index 418d42b..0000000 --- a/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommand.cs +++ /dev/null @@ -1,6 +0,0 @@ -using MediatR; - -namespace CPDLCServer.Auth.Administrators; - -// The setup adds the first administrator -public record CreateFirstAdministratorCommand(int Cid) : IRequest; diff --git a/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommandHandler.cs b/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommandHandler.cs deleted file mode 100644 index 8d08c15..0000000 --- a/source/CPDLCServer/Auth/Administrators/CreateFirstAdministratorCommandHandler.cs +++ /dev/null @@ -1,32 +0,0 @@ -using CPDLCServer.Infrastructure; -using CPDLCServer.Persistence; -using CPDLCServer.Setup; -using MediatR; - -namespace CPDLCServer.Auth.Administrators; - -public class CreateFirstAdministratorCommandHandler( - IAdministratorRepository administratorRepository, - SetupState setupState, - IClock clock, - IUnitOfWork unitOfWork, - ILogger logger) - : IRequestHandler -{ - public async Task Handle(CreateFirstAdministratorCommand request, CancellationToken cancellationToken) - { - if (await administratorRepository.Any(cancellationToken)) - throw new InvalidOperationException("An administrator already exists"); - - await administratorRepository.Add( - new Administrator { Cid = request.Cid, Added = clock.UtcNow() }, - cancellationToken); - - unitOfWork.AfterCommit(_ => - { - setupState.MarkConfigured(); - logger.Information("First administrator {Cid} added. The setup is complete", request.Cid); - return Task.CompletedTask; - }); - } -} diff --git a/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs b/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs index e3426b0..8a3068b 100644 --- a/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs +++ b/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs @@ -13,6 +13,9 @@ namespace CPDLCServer.Auth; public static class AuthServiceCollectionExtensions { + // The time without a request before the user must log in again. The privacy policy shows this value. + public static readonly TimeSpan SessionLifetime = TimeSpan.FromHours(8); + public static IServiceCollection AddAuth(this IServiceCollection services, IConfiguration configuration) { var vatsimConnectOptions = new VatsimConnectOptions @@ -44,7 +47,7 @@ public static IServiceCollection AddAuth(this IServiceCollection services, IConf // Lax, not Strict: after the login, VATSIM Connect redirects the browser back to this server. // With Strict, the browser does not send the cookie in that redirect, and the user is not logged in. options.Cookie.SameSite = SameSiteMode.Lax; - options.ExpireTimeSpan = TimeSpan.FromHours(8); + options.ExpireTimeSpan = SessionLifetime; options.SlidingExpiration = true; }) .AddOAuth(VatsimConnectOptions.AuthenticationScheme, "VATSIM", options => diff --git a/source/CPDLCServer/Logging/LogBuffer.cs b/source/CPDLCServer/Logging/LogBuffer.cs index caebbe8..e0410f2 100644 --- a/source/CPDLCServer/Logging/LogBuffer.cs +++ b/source/CPDLCServer/Logging/LogBuffer.cs @@ -7,6 +7,8 @@ namespace CPDLCServer.Logging; /// public class LogBuffer(int capacity = 1000) { + public int Capacity { get; } = capacity; + readonly object _lock = new(); readonly Queue _entries = new(); readonly List> _subscribers = []; @@ -19,7 +21,7 @@ public void Add(LogEntry entry) var sequencedEntry = entry with { Sequence = _nextSequence++ }; _entries.Enqueue(sequencedEntry); - if (_entries.Count > capacity) + if (_entries.Count > Capacity) _entries.Dequeue(); foreach (var subscriber in _subscribers) @@ -35,7 +37,7 @@ public LogSubscription Subscribe() { lock (_lock) { - var channel = Channel.CreateBounded(new BoundedChannelOptions(capacity) + var channel = Channel.CreateBounded(new BoundedChannelOptions(Capacity) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121062110_InitialCreate.Designer.cs similarity index 97% rename from source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.Designer.cs rename to source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121062110_InitialCreate.Designer.cs index b1656ed..4625452 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.Designer.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121062110_InitialCreate.Designer.cs @@ -13,7 +13,7 @@ namespace CPDLCServer.Persistence.Migrations.PostgreSql { [DbContext(typeof(PostgreSqlCpdlcDbContext))] - [Migration("20261121042342_InitialCreate")] + [Migration("20261121062110_InitialCreate")] partial class InitialCreate { /// @@ -448,6 +448,16 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasMaxLength(1000) .HasColumnType("character varying(1000)"); + b.Property("OperatorName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PrivacyContact") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + b.Property("ServerName") .IsRequired() .HasMaxLength(64) diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121062110_InitialCreate.cs similarity index 98% rename from source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.cs rename to source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121062110_InitialCreate.cs index a8079e5..cf582d1 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121042342_InitialCreate.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/20261121062110_InitialCreate.cs @@ -173,6 +173,8 @@ protected override void Up(MigrationBuilder migrationBuilder) { Id = table.Column(type: "integer", nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + OperatorName = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + PrivacyContact = table.Column(type: "character varying(256)", maxLength: 256, nullable: false), ServerName = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), Motd = table.Column(type: "character varying(1000)", maxLength: 1000, nullable: true), BannerImage = table.Column(type: "bytea", nullable: true), diff --git a/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs index ac5282a..6cef055 100644 --- a/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs +++ b/source/CPDLCServer/Persistence/Migrations/PostgreSql/PostgreSqlCpdlcDbContextModelSnapshot.cs @@ -445,6 +445,16 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(1000) .HasColumnType("character varying(1000)"); + b.Property("OperatorName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PrivacyContact") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + b.Property("ServerName") .IsRequired() .HasMaxLength(64) diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.Designer.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121062107_InitialCreate.Designer.cs similarity index 97% rename from source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.Designer.cs rename to source/CPDLCServer/Persistence/Migrations/Sqlite/20261121062107_InitialCreate.Designer.cs index a03d2ad..bb91ac7 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.Designer.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121062107_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ namespace CPDLCServer.Persistence.Migrations.Sqlite { [DbContext(typeof(SqliteCpdlcDbContext))] - [Migration("20261121042339_InitialCreate")] + [Migration("20261121062107_InitialCreate")] partial class InitialCreate { /// @@ -433,6 +433,16 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasMaxLength(1000) .HasColumnType("TEXT"); + b.Property("OperatorName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PrivacyContact") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + b.Property("ServerName") .IsRequired() .HasMaxLength(64) diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121062107_InitialCreate.cs similarity index 98% rename from source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.cs rename to source/CPDLCServer/Persistence/Migrations/Sqlite/20261121062107_InitialCreate.cs index 92183dc..24ff566 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121042339_InitialCreate.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/20261121062107_InitialCreate.cs @@ -172,6 +172,8 @@ protected override void Up(MigrationBuilder migrationBuilder) { Id = table.Column(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), + OperatorName = table.Column(type: "TEXT", maxLength: 128, nullable: false), + PrivacyContact = table.Column(type: "TEXT", maxLength: 256, nullable: false), ServerName = table.Column(type: "TEXT", maxLength: 64, nullable: false), Motd = table.Column(type: "TEXT", maxLength: 1000, nullable: true), BannerImage = table.Column(type: "BLOB", nullable: true), diff --git a/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs index 1447785..3396ee7 100644 --- a/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs +++ b/source/CPDLCServer/Persistence/Migrations/Sqlite/SqliteCpdlcDbContextModelSnapshot.cs @@ -430,6 +430,16 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(1000) .HasColumnType("TEXT"); + b.Property("OperatorName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PrivacyContact") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + b.Property("ServerName") .IsRequired() .HasMaxLength(64) diff --git a/source/CPDLCServer/Settings/PrivacyContactFormat.cs b/source/CPDLCServer/Settings/PrivacyContactFormat.cs new file mode 100644 index 0000000..8ac5ddc --- /dev/null +++ b/source/CPDLCServer/Settings/PrivacyContactFormat.cs @@ -0,0 +1,43 @@ +using System.ComponentModel.DataAnnotations; +using System.Net.Mail; + +namespace CPDLCServer.Settings; + +/// +/// The contact of the operator for privacy requests: an email address, or an http or https URL. +/// +public static class PrivacyContactFormat +{ + public static bool IsEmail(string contact) + { + return !contact.Contains("://") && MailAddress.TryCreate(contact, out var address) && address.Address == contact; + } + + public static bool IsUrl(string contact) + { + return Uri.TryCreate(contact, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp); + } + + // The link of the contact on the privacy policy + public static string ToHref(string contact) + { + return IsEmail(contact) ? $"mailto:{contact}" : contact; + } +} + +public class PrivacyContactAttribute : ValidationAttribute +{ + public PrivacyContactAttribute() + : base("Enter an email address, or a URL that starts with https://") + { + } + + // An empty value is valid. Use [Required] when the value is necessary. + public override bool IsValid(object? value) + { + return value is not string contact || + string.IsNullOrWhiteSpace(contact) || + PrivacyContactFormat.IsEmail(contact.Trim()) || + PrivacyContactFormat.IsUrl(contact.Trim()); + } +} diff --git a/source/CPDLCServer/Settings/ServerSettings.cs b/source/CPDLCServer/Settings/ServerSettings.cs index e783adb..9d88414 100644 --- a/source/CPDLCServer/Settings/ServerSettings.cs +++ b/source/CPDLCServer/Settings/ServerSettings.cs @@ -12,6 +12,19 @@ public record ServerSettings public const string DefaultServerName = "CPDLC Server"; public const int MaxServerNameLength = 64; public const int MaxMotdLength = 1000; + public const int MaxOperatorNameLength = 128; + public const int MaxPrivacyContactLength = 256; + + // The person or organisation that operates the server. The privacy policy shows it, and the setup sets it. + [Required] + [StringLength(MaxOperatorNameLength)] + public string OperatorName { get; init; } = string.Empty; + + // An email address or a URL, for questions about the privacy policy and requests to delete data + [Required] + [StringLength(MaxPrivacyContactLength)] + [PrivacyContact] + public string PrivacyContact { get; init; } = string.Empty; // Branding: the dashboard shows the name, the banner and the message of the day at the top of the sidebar and on // the login page. diff --git a/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs b/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs index 7a5197c..a9ef67f 100644 --- a/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs +++ b/source/CPDLCServer/Settings/ServerSettingsConfiguration.cs @@ -20,5 +20,7 @@ public void Configure(EntityTypeBuilder builder) builder.Property(s => s.ServerName).HasMaxLength(ServerSettings.MaxServerNameLength); builder.Property(s => s.Motd).HasMaxLength(ServerSettings.MaxMotdLength); + builder.Property(s => s.OperatorName).HasMaxLength(ServerSettings.MaxOperatorNameLength); + builder.Property(s => s.PrivacyContact).HasMaxLength(ServerSettings.MaxPrivacyContactLength); } } diff --git a/source/CPDLCServer/Setup/CompleteSetupCommand.cs b/source/CPDLCServer/Setup/CompleteSetupCommand.cs new file mode 100644 index 0000000..0ca3f80 --- /dev/null +++ b/source/CPDLCServer/Setup/CompleteSetupCommand.cs @@ -0,0 +1,6 @@ +using MediatR; + +namespace CPDLCServer.Setup; + +// The setup adds the first administrator, and the operator details for the privacy policy +public record CompleteSetupCommand(int AdministratorCid, string OperatorName, string PrivacyContact) : IRequest; diff --git a/source/CPDLCServer/Setup/CompleteSetupCommandHandler.cs b/source/CPDLCServer/Setup/CompleteSetupCommandHandler.cs new file mode 100644 index 0000000..0636a87 --- /dev/null +++ b/source/CPDLCServer/Setup/CompleteSetupCommandHandler.cs @@ -0,0 +1,43 @@ +using CPDLCServer.Auth.Administrators; +using CPDLCServer.Infrastructure; +using CPDLCServer.Persistence; +using CPDLCServer.Settings; +using MediatR; + +namespace CPDLCServer.Setup; + +public class CompleteSetupCommandHandler( + IAdministratorRepository administratorRepository, + IServerSettingsProvider settingsProvider, + SetupState setupState, + IClock clock, + IUnitOfWork unitOfWork, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(CompleteSetupCommand request, CancellationToken cancellationToken) + { + if (await administratorRepository.Any(cancellationToken)) + throw new InvalidOperationException("An administrator already exists"); + + await administratorRepository.Add( + new Administrator { Cid = request.AdministratorCid, Added = clock.UtcNow() }, + cancellationToken); + + var settings = await settingsProvider.Load(cancellationToken); + await settingsProvider.Save( + settings with + { + OperatorName = request.OperatorName.Trim(), + PrivacyContact = request.PrivacyContact.Trim() + }, + cancellationToken); + + unitOfWork.AfterCommit(_ => + { + setupState.MarkConfigured(); + logger.Information("First administrator {Cid} added. The setup is complete", request.AdministratorCid); + return Task.CompletedTask; + }); + } +} diff --git a/source/CPDLCServer/Web/Pages/Account/Login.cshtml b/source/CPDLCServer/Web/Pages/Account/Login.cshtml index b3dc3a2..11dae37 100644 --- a/source/CPDLCServer/Web/Pages/Account/Login.cshtml +++ b/source/CPDLCServer/Web/Pages/Account/Login.cshtml @@ -12,3 +12,8 @@ + +

+ When you log in, VATSIM gives this server your CID and your name. + By logging in, you accept the privacy policy. +

diff --git a/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml index 9960c48..638e8f7 100644 --- a/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Configuration/Settings/Index.cshtml @@ -74,6 +74,35 @@
+
+
Operator
+
+

The privacy policy shows the operator and the contact.

+ +
+
+ +
The person or organisation that operates this server, for example a VATSIM division or FIR.
+
+
+ + +
+
+ +
+
+ +
An email address or a URL. Users use it to ask questions about their data, or to ask you to delete it.
+
+
+ + +
+
+
+
+
Connections
diff --git a/source/CPDLCServer/Web/Pages/Privacy.cshtml b/source/CPDLCServer/Web/Pages/Privacy.cshtml new file mode 100644 index 0000000..0ea0cf1 --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Privacy.cshtml @@ -0,0 +1,193 @@ +@page "/privacy" +@model PrivacyModel +@{ + ViewData["Title"] = "Privacy policy"; + ViewData["Wide"] = true; + Layout = "_CenteredLayout"; + + var operatorName = string.IsNullOrWhiteSpace(Model.Settings.OperatorName) ? "the operator of this server" : Model.Settings.OperatorName; + var contact = Model.Settings.PrivacyContact; + + string Hours(TimeSpan time) => time.TotalHours == 1 ? "1 hour" : $"{time.TotalHours:0.#} hours"; + string Days(TimeSpan time) => $"{time.TotalDays:0} days"; +} + +

Privacy policy

+ +
+ @Model.Settings.ServerName is a third-party service. + It is not provided, operated or endorsed by VATSIM. +
+ +

About this service

+

+ This server relays CPDLC and ADS-C messages between air traffic controllers on VATSIM and aircraft on the + ACARS network. @operatorName operates this server. In this policy, "the operator" is + @operatorName. +

+@if (!string.IsNullOrWhiteSpace(contact)) +{ +

+ For questions about your data, or to ask the operator to delete your data, use this contact: + @contact. +

+} +

+ The server uses the open source CPDLC Plugin software. + The authors of the software do not operate this server, and they cannot see its data. +

+ +

The data that the server collects

+
    +
  • + Your VATSIM account. You log in with VATSIM Connect. VATSIM gives the server your CID and + your full name. The server also asks VATSIM for your VATSIM details (for example, your rating and division), + but it does not use or keep them. The server does not get your email address or your password. +
  • +
  • + Controllers. When you connect with the vatSys plugin, the server records your CID, your name, + your callsign and your station while you are connected. +
  • +
  • + Administrators. The server records the CID and the name of each administrator, and the date + when they became an administrator. +
  • +
  • + Flight data. The server receives aircraft callsigns, CPDLC messages and ADS-C reports + (position, level and time) from the ACARS network. + @if (Model.Settings.VatsimStatusEnabled) + { + It also reads aircraft positions from the public VATSIM status data. + } + CPDLC messages can contain free text from pilots and controllers. +
  • +
  • + Logs. The server log records events, for example logins, plugin connections and messages. + A log entry can contain your CID, your name, your callsign and the text of a message. +
  • +
  • + Cookies. The server uses only the cookies that are necessary for it to operate: one cookie + that keeps you logged in, and short-term cookies that protect the login and the forms. The server does not use + cookies for analytics or advertising. +
  • +
  • + IP addresses. The server does not record your IP address. The hosting provider of the server + can record it (see Third parties). +
  • +
+ +

How the server uses the data

+

The server uses the data only to operate the service:

+
    +
  • to identify you, and to give administrators access to the configuration,
  • +
  • to relay CPDLC and ADS-C messages between controllers and aircraft,
  • +
  • to show the connected controllers and aircraft, and the messages,
  • +
  • to find and correct problems.
  • +
+

The operator does not sell the data, and does not use it for advertising or analytics.

+ +

Who can see the data

+
    +
  • + Each VATSIM user who logs in to this server can see the CPDLC and ADS-C pages. These pages show the name and + the CID of each connected controller, the callsigns of the aircraft, the CPDLC messages and the ADS-C data. +
  • +
  • Controllers who use the plugin see the CPDLC messages and the ADS-C data of the aircraft.
  • +
  • Administrators can also see the server log and the raw messages to and from the ACARS network.
  • +
+ +

Third parties

+
    +
  • VATSIM operates VATSIM Connect, which identifies you when you log in.
  • +
  • + The ACARS network (for example, Hoppie's ACARS) + carries the CPDLC and ADS-C messages to and from the aircraft. It receives the station, the callsigns and + the messages. It does not receive your CID or your name. +
  • +
  • The hosting provider of the server stores the database and can record network data, for example IP addresses.
  • +
  • + jsDelivr (cdn.jsdelivr.net) supplies the styles and scripts of the web pages. Your browser + downloads them from jsDelivr, so jsDelivr receives your IP address. +
  • +
+ +

How long the server keeps the data

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DataKept
Login cookieUntil you log out, or after @Hours(Model.SessionLifetime) without activity. A restart of the server also logs out all users.
Plugin authentication (CID, name and token)The token is valid for @Days(Model.PluginTokenLifetime). When you select Log out in the plugin, the server deletes it. The record of an expired token stays in the database.
AdministratorsUntil an administrator removes them.
Connected controllersOnly in memory, until the controller disconnects.
Aircraft connectionsUntil the connection ends, or after @Model.Settings.AircraftConnectionTimeoutMinutes minutes without contact from the aircraft.
CPDLC messages@Model.Settings.DialogueRetentionHours hours from the start of the dialogue.
ADS-C contracts and reportsUntil the contract ends, or after @Model.Settings.AdscContractTimeoutMinutes minutes without ADS-C activity. The server keeps only the latest report of each contract.
ADS-C message logOnly in memory, for @Hours(Model.AdscMessageLogRetention), and not more than the last @Model.AdscMessageLogCapacity messages.
Server logOnly in memory, the last @Model.LogCapacity entries. A restart deletes them. The hosting provider can keep a copy of the log output for a period that the operator sets.
Raw ACARS messagesOnly in memory, the last @Model.TrafficLogCapacity requests of each ACARS connection. A restart deletes them.
+
+

+ The vatSys plugin keeps your token on your computer, encrypted for your Windows account. The plugin log on your + computer is kept for 5 days by default. +

+ +

Security

+

+ The server keeps only a hash of each plugin token. It encrypts the ACARS network codes with a key that is not in + the database. Use the server only over HTTPS. +

+ +

Your choices

+
    +
  • To remove the plugin authentication, select Log out in the SETUP window of the plugin.
  • + @if (!string.IsNullOrWhiteSpace(contact)) + { +
  • To ask for a copy of your data, or to ask the operator to delete it, use the contact: @contact.
  • + } + else + { +
  • To ask for a copy of your data, or to ask the operator to delete it, speak to an administrator of this server.
  • + } +
  • If you do not accept this policy, do not log in to this server and do not connect the plugin to it.
  • +
+ +

Changes to this policy

+

The operator can change this policy. This page always shows the current policy.

diff --git a/source/CPDLCServer/Web/Pages/Privacy.cshtml.cs b/source/CPDLCServer/Web/Pages/Privacy.cshtml.cs new file mode 100644 index 0000000..a77671a --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Privacy.cshtml.cs @@ -0,0 +1,39 @@ +using CPDLCServer.AcarsConnections.Traffic; +using CPDLCServer.AdscContracts; +using CPDLCServer.AdscContracts.MessageLog; +using CPDLCServer.Auth; +using CPDLCServer.Auth.PluginTokens; +using CPDLCServer.Logging; +using CPDLCServer.Settings; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace CPDLCServer.Web.Pages; + +// The privacy policy. The values come from the settings and the code, so the page is correct when they change. +public class PrivacyModel : PageModel +{ + private readonly IServerSettingsProvider _settingsProvider; + private readonly LogBuffer _logBuffer; + private readonly AcarsTrafficLog _trafficLog; + + public PrivacyModel(IServerSettingsProvider settingsProvider, LogBuffer logBuffer, AcarsTrafficLog trafficLog) + { + _settingsProvider = settingsProvider; + _logBuffer = logBuffer; + _trafficLog = trafficLog; + } + + public ServerSettings Settings { get; private set; } = new(); + + public TimeSpan SessionLifetime => AuthServiceCollectionExtensions.SessionLifetime; + public TimeSpan PluginTokenLifetime => PluginToken.Lifetime; + public TimeSpan AdscMessageLogRetention => PurgeExpiredAdscDataRequestHandler.MessageLogRetention; + public int AdscMessageLogCapacity => InMemoryAdscMessageLogRepository.Capacity; + public int LogCapacity => _logBuffer.Capacity; + public int TrafficLogCapacity => _trafficLog.Capacity; + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + Settings = await _settingsProvider.Load(cancellationToken); + } +} diff --git a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml index 0e87f97..58c9bb9 100644 --- a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml @@ -6,18 +6,30 @@ }

Set up the server

-

- Enter the VATSIM CID of the first administrator. After the setup, that person logs in with VATSIM - and can add more administrators. You can do the setup only one time. -

+

You can do the setup only one time. You can change the operator details later in Configuration → Settings.

- - - + + +
The VATSIM CID of the first administrator. That person logs in with VATSIM and can add more administrators.
+ +
+ +
+ + +
The person or organisation that operates this server, for example a VATSIM division or FIR. The privacy policy shows it.
+ +
+ +
+ + +
An email address or a URL. Users use it to ask questions about their data, or to ask you to delete it.
+
diff --git a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs index 1c974d7..55e4d4a 100644 --- a/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Setup/Index.cshtml.cs @@ -1,13 +1,13 @@ using System.ComponentModel.DataAnnotations; -using CPDLCServer.Auth.Administrators; using CPDLCServer.Infrastructure; +using CPDLCServer.Settings; using CPDLCServer.Setup; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace CPDLCServer.Web.Pages.Setup; -// The setup adds the first administrator. After the setup, the page does not exist. +// The setup adds the first administrator and the operator details. After the setup, the page does not exist. public class IndexModel : PageModel { private readonly SetupState _setupState; @@ -25,10 +25,7 @@ public IndexModel( } [BindProperty] - [Required] - [Range(1, int.MaxValue, ErrorMessage = "Enter a valid CID.")] - [Display(Name = "Administrator CID")] - public int? Cid { get; set; } + public SetupInput Input { get; set; } = new(); public IActionResult OnGet() { @@ -48,15 +45,36 @@ public async Task OnPostAsync(CancellationToken cancellationToken try { - await _mediator.Send(new CreateFirstAdministratorCommand(Cid!.Value), cancellationToken); + await _mediator.Send( + new CompleteSetupCommand(Input.Cid!.Value, Input.OperatorName, Input.PrivacyContact), + cancellationToken); } catch (InvalidOperationException ex) { // Another person completed the setup first - _logger.Warning(ex, "Failed to add the first administrator"); + _logger.Warning(ex, "Failed to complete the setup"); return NotFound(); } return Redirect("/login"); } + + public class SetupInput + { + [Required(ErrorMessage = "Enter a CID.")] + [Range(1, int.MaxValue, ErrorMessage = "Enter a valid CID.")] + [Display(Name = "Administrator CID")] + public int? Cid { get; set; } + + [Required(ErrorMessage = "Enter the operator name.")] + [StringLength(ServerSettings.MaxOperatorNameLength)] + [Display(Name = "Operator name")] + public string OperatorName { get; set; } = string.Empty; + + [Required(ErrorMessage = "Enter a privacy contact.")] + [StringLength(ServerSettings.MaxPrivacyContactLength)] + [PrivacyContact] + [Display(Name = "Privacy contact")] + public string PrivacyContact { get; set; } = string.Empty; + } } diff --git a/source/CPDLCServer/Web/Pages/Shared/_CenteredLayout.cshtml b/source/CPDLCServer/Web/Pages/Shared/_CenteredLayout.cshtml index b766cc9..a3e269e 100644 --- a/source/CPDLCServer/Web/Pages/Shared/_CenteredLayout.cshtml +++ b/source/CPDLCServer/Web/Pages/Shared/_CenteredLayout.cshtml @@ -16,7 +16,8 @@
-
+ @* A page with much text, for example the privacy policy, sets ViewData["Wide"] *@ +
@@ -25,6 +26,9 @@ @RenderBody()
+
+ +
diff --git a/source/CPDLCServer/Web/Pages/Shared/_Disclaimer.cshtml b/source/CPDLCServer/Web/Pages/Shared/_Disclaimer.cshtml new file mode 100644 index 0000000..96df7eb --- /dev/null +++ b/source/CPDLCServer/Web/Pages/Shared/_Disclaimer.cshtml @@ -0,0 +1,5 @@ +@* The VATSIM disclaimer and the link to the privacy policy. It shows on each page. *@ +

+ This server is a third-party service. It is not provided, operated or endorsed by VATSIM. + Privacy policy +

diff --git a/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml b/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml index 75b9208..ddd63c6 100644 --- a/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml +++ b/source/CPDLCServer/Web/Pages/Shared/_Layout.cshtml @@ -91,6 +91,9 @@ Documentation
+
+ +
diff --git a/source/CPDLCServer/Web/WebServiceCollectionExtensions.cs b/source/CPDLCServer/Web/WebServiceCollectionExtensions.cs index 5546939..a75cd6b 100644 --- a/source/CPDLCServer/Web/WebServiceCollectionExtensions.cs +++ b/source/CPDLCServer/Web/WebServiceCollectionExtensions.cs @@ -16,6 +16,7 @@ public static IServiceCollection AddWeb(this IServiceCollection services) options.Conventions.AllowAnonymousToPage("/Account/Login"); options.Conventions.AllowAnonymousToPage("/Account/Logout"); options.Conventions.AllowAnonymousToPage("/Setup/Index"); + options.Conventions.AllowAnonymousToPage("/Privacy"); // Only an administrator can open the Configuration area options.Conventions.AuthorizeFolder("/Configuration", AdministratorRequirement.PolicyName); From 2c6cbb33c543fe2aa91a0f4dc181363742dc5795 Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:01:42 +1000 Subject: [PATCH 14/18] Fix the docs image build without corepack Co-Authored-By: Claude Opus 5.5 --- docs/Dockerfile | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/Dockerfile b/docs/Dockerfile index ef45c26..4674d31 100644 --- a/docs/Dockerfile +++ b/docs/Dockerfile @@ -3,7 +3,6 @@ # Stage 1: Build the static site with Node. FROM node:lts-alpine AS build ENV FORCE_COLOR=0 -RUN corepack enable WORKDIR /opt/docusaurus COPY . /opt/docusaurus/ RUN npm ci From caba87919ea77bfbd0c1108322e4aae1e6a46ec0 Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:01:42 +1000 Subject: [PATCH 15/18] Add a development login that does not use VATSIM Connect Co-Authored-By: Claude Opus 5.5 --- docs/docs/server/index.md | 1 + example.env | 4 + .../Auth/AuthServiceCollectionExtensions.cs | 107 ++++++++++-------- .../Auth/VatsimConnect/DevelopmentLogin.cs | 8 ++ source/CPDLCServer/Program.cs | 2 +- .../Web/Pages/Account/Login.cshtml.cs | 22 +++- 6 files changed, 95 insertions(+), 49 deletions(-) create mode 100644 source/CPDLCServer/Auth/VatsimConnect/DevelopmentLogin.cs diff --git a/docs/docs/server/index.md b/docs/docs/server/index.md index f9b7470..e8f510a 100644 --- a/docs/docs/server/index.md +++ b/docs/docs/server/index.md @@ -62,6 +62,7 @@ All users log in with [VATSIM Connect](https://vatsim.dev/services/connect). Mak - `VatsimConnect__ClientId`: the ID of the client. - `VatsimConnect__ClientSecret`: the secret of the client. - `VatsimConnect__Authority` (optional): the VATSIM Connect server. The default is `https://auth.vatsim.net`. +- `VatsimConnect__DevCid` (optional, development only): the login page logs in all users with this CID, and does not use VATSIM Connect. The client ID and the client secret are then not necessary. The server uses this value only when `ASPNETCORE_ENVIRONMENT` is `Development`. Any VATSIM user can log in, open the CPDLC and ADS-C areas, and connect with the plugin. Only an administrator can open the Configuration area. diff --git a/example.env b/example.env index 79021eb..290ea90 100644 --- a/example.env +++ b/example.env @@ -19,6 +19,10 @@ VatsimConnect__ClientSecret= # The VATSIM Connect server (default: https://auth.vatsim.net) VatsimConnect__Authority=https://auth-dev.vatsim.net +# Development only: log in all users with this CID, and do not use VATSIM Connect. +# When this is set, the client ID and the client secret are not necessary. +# VatsimConnect__DevCid=10000001 + # Data Directory # The directory of the SQLite database (cpdlc.db). The server makes it if it does not exist. # (default: .data at the root of the repository in Development, /data in other environments) diff --git a/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs b/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs index 8a3068b..d6aeb29 100644 --- a/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs +++ b/source/CPDLCServer/Auth/AuthServiceCollectionExtensions.cs @@ -16,16 +16,14 @@ public static class AuthServiceCollectionExtensions // The time without a request before the user must log in again. The privacy policy shows this value. public static readonly TimeSpan SessionLifetime = TimeSpan.FromHours(8); - public static IServiceCollection AddAuth(this IServiceCollection services, IConfiguration configuration) + public static IServiceCollection AddAuth( + this IServiceCollection services, + IConfiguration configuration, + IHostEnvironment environment) { - var vatsimConnectOptions = new VatsimConnectOptions - { - ClientId = configuration.GetRequiredValue("VatsimConnect:ClientId"), - ClientSecret = configuration.GetRequiredValue("VatsimConnect:ClientSecret"), - Authority = configuration["VatsimConnect:Authority"] is { Length: > 0 } authority - ? new Uri(authority) - : new Uri("https://auth.vatsim.net") - }; + var developmentLogin = new DevelopmentLogin( + environment.IsDevelopment() ? configuration.GetValue("VatsimConnect:DevCid") : null); + services.AddSingleton(developmentLogin); services.AddScoped(); services.AddScoped(); @@ -35,7 +33,7 @@ public static IServiceCollection AddAuth(this IServiceCollection services, IConf // After a restart, the user must log in again. services.AddSingleton(); - services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) + var authentication = services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/login"; @@ -50,46 +48,14 @@ public static IServiceCollection AddAuth(this IServiceCollection services, IConf options.ExpireTimeSpan = SessionLifetime; options.SlidingExpiration = true; }) - .AddOAuth(VatsimConnectOptions.AuthenticationScheme, "VATSIM", options => - { - options.ClientId = vatsimConnectOptions.ClientId; - options.ClientSecret = vatsimConnectOptions.ClientSecret; - options.CallbackPath = VatsimConnectOptions.CallbackPath; - options.AuthorizationEndpoint = new Uri(vatsimConnectOptions.Authority, "/oauth/authorize").ToString(); - options.TokenEndpoint = new Uri(vatsimConnectOptions.Authority, "/oauth/token").ToString(); - options.UserInformationEndpoint = new Uri(vatsimConnectOptions.Authority, "/api/user").ToString(); - options.UsePkce = true; - options.Scope.Add("full_name"); - options.Scope.Add("vatsim_details"); - - // The server uses the VATSIM token only to read the user. It does not keep the token. - options.SaveTokens = false; - - options.Events.OnCreatingTicket = async context => - { - using var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); - request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - - using var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted); - response.EnsureSuccessStatusCode(); - - using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(context.HttpContext.RequestAborted)); - var user = VatsimUser.Parse(document.RootElement); - - context.Principal = new(CurrentUser.CreateIdentity(user.Cid, user.Name, VatsimConnectOptions.AuthenticationScheme)); - - var mediator = context.HttpContext.RequestServices.GetRequiredService(); - await mediator.Send(new UpdateAdministratorNameCommand(user.Cid, user.Name), context.HttpContext.RequestAborted); - - var logger = context.HttpContext.RequestServices.GetRequiredService(); - logger.Information("{Name} ({Cid}) logged in", user.Name, user.Cid); - }; - }) .AddScheme( PluginTokenAuthenticationHandler.AuthenticationScheme, _ => { }); + // With the development login, the server does not need a VATSIM Connect client + if (developmentLogin.Cid is null) + AddVatsimConnect(authentication, configuration); + services.AddScoped(); services.AddAuthorization(options => { @@ -107,4 +73,53 @@ public static IServiceCollection AddAuth(this IServiceCollection services, IConf return services; } + + static void AddVatsimConnect(AuthenticationBuilder authentication, IConfiguration configuration) + { + var vatsimConnectOptions = new VatsimConnectOptions + { + ClientId = configuration.GetRequiredValue("VatsimConnect:ClientId"), + ClientSecret = configuration.GetRequiredValue("VatsimConnect:ClientSecret"), + Authority = configuration["VatsimConnect:Authority"] is { Length: > 0 } authority + ? new Uri(authority) + : new Uri("https://auth.vatsim.net") + }; + + authentication.AddOAuth(VatsimConnectOptions.AuthenticationScheme, "VATSIM", options => + { + options.ClientId = vatsimConnectOptions.ClientId; + options.ClientSecret = vatsimConnectOptions.ClientSecret; + options.CallbackPath = VatsimConnectOptions.CallbackPath; + options.AuthorizationEndpoint = new Uri(vatsimConnectOptions.Authority, "/oauth/authorize").ToString(); + options.TokenEndpoint = new Uri(vatsimConnectOptions.Authority, "/oauth/token").ToString(); + options.UserInformationEndpoint = new Uri(vatsimConnectOptions.Authority, "/api/user").ToString(); + options.UsePkce = true; + options.Scope.Add("full_name"); + options.Scope.Add("vatsim_details"); + + // The server uses the VATSIM token only to read the user. It does not keep the token. + options.SaveTokens = false; + + options.Events.OnCreatingTicket = async context => + { + using var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + using var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted); + response.EnsureSuccessStatusCode(); + + using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(context.HttpContext.RequestAborted)); + var user = VatsimUser.Parse(document.RootElement); + + context.Principal = new(CurrentUser.CreateIdentity(user.Cid, user.Name, VatsimConnectOptions.AuthenticationScheme)); + + var mediator = context.HttpContext.RequestServices.GetRequiredService(); + await mediator.Send(new UpdateAdministratorNameCommand(user.Cid, user.Name), context.HttpContext.RequestAborted); + + var logger = context.HttpContext.RequestServices.GetRequiredService(); + logger.Information("{Name} ({Cid}) logged in", user.Name, user.Cid); + }; + }); + } } diff --git a/source/CPDLCServer/Auth/VatsimConnect/DevelopmentLogin.cs b/source/CPDLCServer/Auth/VatsimConnect/DevelopmentLogin.cs new file mode 100644 index 0000000..5a8cc3f --- /dev/null +++ b/source/CPDLCServer/Auth/VatsimConnect/DevelopmentLogin.cs @@ -0,0 +1,8 @@ +namespace CPDLCServer.Auth.VatsimConnect; + +// In development, the login page logs in each user with this CID and does not use VATSIM Connect. +// Set VatsimConnect__DevCid to use it. In other environments, the server ignores the value. +public record DevelopmentLogin(int? Cid) +{ + public const string Name = "Development User"; +} diff --git a/source/CPDLCServer/Program.cs b/source/CPDLCServer/Program.cs index 611c4a9..c7f56d6 100644 --- a/source/CPDLCServer/Program.cs +++ b/source/CPDLCServer/Program.cs @@ -43,7 +43,7 @@ .AddPersistence(builder.Configuration, databaseProvider, databasePath) .AddSecurity(builder.Configuration) .AddSetup() - .AddAuth(builder.Configuration) + .AddAuth(builder.Configuration, builder.Environment) .AddSettings() .AddAcarsConnections() .AddAirTrafficControllers() diff --git a/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs b/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs index 6e08d6e..51a7b7e 100644 --- a/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs +++ b/source/CPDLCServer/Web/Pages/Account/Login.cshtml.cs @@ -1,21 +1,28 @@ +using CPDLCServer.Auth; +using CPDLCServer.Auth.Administrators; using CPDLCServer.Auth.VatsimConnect; +using CPDLCServer.Infrastructure; using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace CPDLCServer.Web.Pages.Account; -public class LoginModel : PageModel +public class LoginModel(DevelopmentLogin developmentLogin, IUnitOfWorkMediator mediator, ILogger logger) : PageModel { // The page to open after the login [BindProperty(SupportsGet = true)] public string? ReturnUrl { get; set; } - public IActionResult OnGet() + public async Task OnGet(CancellationToken cancellationToken) { if (User.Identity?.IsAuthenticated == true) return LocalRedirect(SafeReturnUrl()); + if (developmentLogin.Cid is { } cid) + return await DevelopmentSignIn(cid, cancellationToken); + return Page(); } @@ -27,6 +34,17 @@ public IActionResult OnPost() VatsimConnectOptions.AuthenticationScheme); } + async Task DevelopmentSignIn(int cid, CancellationToken cancellationToken) + { + var identity = CurrentUser.CreateIdentity(cid, DevelopmentLogin.Name, CookieAuthenticationDefaults.AuthenticationScheme); + await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new(identity)); + + await mediator.Send(new UpdateAdministratorNameCommand(cid, DevelopmentLogin.Name), cancellationToken); + logger.Warning("{Cid} logged in with the development login. VATSIM Connect was not used", cid); + + return LocalRedirect(SafeReturnUrl()); + } + // Open only pages on this server, so that a link cannot send the user to a different site string SafeReturnUrl() => Url.IsLocalUrl(ReturnUrl) ? ReturnUrl : "/"; } From ccf2a6a32748c3c5ae2c77d7dbc93c079882860c Mon Sep 17 00:00:00 2001 From: Eoin Motherway <25342760+YuKitsune@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:01:42 +1000 Subject: [PATCH 16/18] Use Bootstrap classes in place of custom CSS Co-Authored-By: Claude Opus 5.5 --- .../Pages/Configuration/Acars/Index.cshtml | 2 +- .../Web/Pages/Configuration/Logs/Index.cshtml | 40 +++++++------------ .../Pages/Configuration/Settings/Index.cshtml | 6 +-- .../Web/Pages/Shared/_Branding.cshtml | 5 +-- .../Web/Pages/Shared/_CenteredLayout.cshtml | 27 ++++++------- .../Web/Pages/Shared/_Layout.cshtml | 37 +++++------------ .../CPDLCServer/Web/Pages/Shared/_Motd.cshtml | 12 ++++++ 7 files changed, 54 insertions(+), 75 deletions(-) create mode 100644 source/CPDLCServer/Web/Pages/Shared/_Motd.cshtml diff --git a/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml index 007ac32..fa27ce3 100644 --- a/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Configuration/Acars/Index.cshtml @@ -48,7 +48,7 @@ @connection.StationIdentifier @if (!string.IsNullOrWhiteSpace(connection.Notes)) { -
@connection.Notes
+
@connection.Notes
} @connection.Type diff --git a/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml b/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml index 9826be1..3e55b67 100644 --- a/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml +++ b/source/CPDLCServer/Web/Pages/Configuration/Logs/Index.cshtml @@ -5,27 +5,6 @@ ViewData["Title"] = "Logs"; } - -

Logs

Connecting @@ -78,7 +57,8 @@
-
+@* The log has a dark background, the same as the console *@ +
@section Scripts {