├── README.md ├── src ├── Altinn.DialogportenAdapter.WebApi │ ├── HttpRequests │ │ ├── http-client.env.json │ │ ├── DeleteInstance.http │ │ ├── SyncByInstanceId.http │ │ └── Requests.http │ ├── Properties │ │ ├── AssemblyInfo.cs │ │ └── launchSettings.json │ ├── Common │ │ ├── PartyNotFoundException.cs │ │ ├── Extensions │ │ │ ├── IntExtensions.cs │ │ │ ├── EnumerableExtensions.cs │ │ │ ├── DialogDtoExtensions.cs │ │ │ ├── PolicyExtensions.cs │ │ │ ├── StorageTypeExtensions.cs │ │ │ ├── AuthorizationExtensions.cs │ │ │ ├── SpanExtensions.cs │ │ │ ├── ApiResponseExtensions.cs │ │ │ ├── ServiceCollectionExtensions.cs │ │ │ ├── ConfigurationExtensions.cs │ │ │ ├── GuidExtensions.cs │ │ │ └── TaskExtentions.cs │ │ ├── MediaTypes.cs │ │ ├── AllowAnonymousHandler.cs │ │ ├── Health │ │ │ ├── HealthCheckFilterProcessor.cs │ │ │ └── HealthCheck.cs │ │ ├── LanguageCodes.cs │ │ ├── Constants.cs │ │ └── FourHundredLoggingDelegatingHandler.cs │ ├── Infrastructure │ │ ├── Storage │ │ │ ├── ApplicationTexts.cs │ │ │ ├── IApplicationsApi.cs │ │ │ ├── IStorageApi.cs │ │ │ └── IApplicationRepository.cs │ │ ├── Register │ │ │ ├── IRegisterApi.cs │ │ │ └── IRegisterRepository.cs │ │ └── Dialogporten │ │ │ ├── IDialogportenApi.cs │ │ │ └── MockDialogportenApi.cs │ ├── Features │ │ └── Command │ │ │ ├── Sync │ │ │ ├── SyncDialogOnInstanceUpdatedHandler.cs │ │ │ ├── ReceiptAttachmentVisibilityDecider.cs │ │ │ ├── ApplicationTextParser.cs │ │ │ ├── ActivityDtoTransformer.cs │ │ │ └── ISyncInstanceToDialogService.cs │ │ │ └── Delete │ │ │ └── InstanceService.cs │ ├── appsettings.json │ ├── appsettings.Development.json │ ├── Altinn.DialogportenAdapter.WebApi.csproj │ └── Settings.cs ├── Altinn.DialogportenAdapter.EventSimulator │ ├── Common │ │ ├── Constants.cs │ │ ├── Extensions │ │ │ ├── QueryStringExtensions.cs │ │ │ ├── TableKeyExtensions.cs │ │ │ ├── InstanceDtoExtensions.cs │ │ │ ├── ConfigurationExtensions.cs │ │ │ └── ServiceCollectionExtensions.cs │ │ ├── HealthCheck.cs │ │ ├── StartupLoaders │ │ │ ├── AzureTableStartupLoader.cs │ │ │ ├── OrganizationStartupLoader.cs │ │ │ └── StartupLoader.cs │ │ └── BackoffHandler.cs │ ├── requests.http │ ├── Infrastructure │ │ ├── Adapter │ │ │ └── IStorageAdapterApi.cs │ │ ├── Storage │ │ │ ├── IStorageApi.cs │ │ │ ├── IOrganizationRepository.cs │ │ │ └── IInstanceStreamer.cs │ │ └── Persistance │ │ │ ├── NullMigrationPartitionRepository.cs │ │ │ ├── IMigrationPartitionRepository.cs │ │ │ └── MigrationPartitionRepository.cs │ ├── Properties │ │ └── launchSettings.json │ ├── HttpRequests │ │ └── migrate.http │ ├── Dockerfile │ ├── appsettings.json │ ├── appsettings.Development.json │ ├── Altinn.DialogportenAdapter.EventSimulator.csproj │ ├── Settings.cs │ ├── Features │ │ ├── UpdateStream │ │ │ └── InstanceUpdateStreamBackgroundService.cs │ │ └── HistoryStream │ │ │ ├── MigrationPartitionCommandHandler.cs │ │ │ └── MigrationPartitionService.cs │ └── Program.cs └── Altinn.DialogportenAdapter.Contracts │ ├── SyncInstanceCommand.cs │ ├── Constants.cs │ ├── Altinn.DialogportenAdapter.Contracts.csproj │ ├── LambdaEnvelopeRule.cs │ └── WolverineOptionsExtentions.cs ├── .dockerignore ├── .github └── workflows │ ├── auto-add-items.yml │ ├── container-scan.yml │ ├── codeql-analysis.yml │ └── build-and-analyze.yml ├── renovate.json ├── AzureServiceBusEmulator ├── .env ├── docker-compose.yaml └── config.json ├── Dockerfile ├── tests └── Altinn.DialogportenAdapter.Unit.Tests │ ├── Infrastructure │ └── Storage │ │ └── ApplicationRepositoryTests.cs │ ├── Altinn.DialogportenAdapter.Unit.Tests.csproj │ └── Features │ └── Command │ └── Sync │ ├── StorageDialogportenDataMergerTest.cs │ ├── ReceiptAttachmentVisibilityDeciderTests.cs │ └── ApplicationTextParserTests.cs ├── LICENSE ├── Altinn.DialogportenAdapter.sln └── .gitignore /README.md: -------------------------------------------------------------------------------- 1 | # altinn-dialogporten-adapter 2 | Altinn App Storage adapter that handles synchronization of instances to dialogs 3 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/HttpRequests/http-client.env.json: -------------------------------------------------------------------------------- 1 | { 2 | "dev": { 3 | "baseUri": "https://localhost:7241/storage/dialogporten" 4 | } 5 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly: InternalsVisibleTo("Altinn.DialogportenAdapter.Unit.Tests")] 4 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/HttpRequests/DeleteInstance.http: -------------------------------------------------------------------------------- 1 | ### Delete 2 | DELETE {{baseUri}}/api/v1/instance/51131495/4839f7ee-252f-4734-9444-f6bfa1b90361?hard=false 3 | Authorization: bearer mdspogfsjgpsdjpjgpse -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/PartyNotFoundException.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.WebApi.Common; 2 | 3 | public class PartyNotFoundException(string? partyId) : InvalidOperationException($"Party with id {partyId} not found"); -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Common/Constants.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.EventSimulator.Common; 2 | 3 | internal static class Constants 4 | { 5 | public const string MaskinportenClientDefinitionKey = "MaskinportenClient"; 6 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/requests.http: -------------------------------------------------------------------------------- 1 | @baseUri = https://localhost:7242 2 | 3 | ### Resume 4 | POST {{baseUri}}/api/v1/orgSync 5 | Content-Type: application/json 6 | 7 | { 8 | "org": "digdir", 9 | "from": "2025-03-13T00:00:00Z", 10 | "to": "2025-03-14T00:00:00Z" 11 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.Contracts/SyncInstanceCommand.cs: -------------------------------------------------------------------------------- 1 | using Wolverine.Attributes; 2 | 3 | namespace Altinn.DialogportenAdapter.Contracts; 4 | 5 | [MessageIdentity("Altinn.DialogportenAdapter.SyncInstanceCommand")] 6 | public record SyncInstanceCommand( 7 | string AppId, 8 | string PartyId, 9 | Guid InstanceId, 10 | DateTimeOffset InstanceCreatedAt, 11 | bool IsMigration); -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/IntExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 2 | 3 | public static class IntExtensions 4 | { 5 | // Gives an int approximation, ensure that we always get at least 1 and round up. 6 | public static int PercentOf(this int value, int percent) 7 | => Math.Max((int)Math.Ceiling((decimal)value * percent / 100), 1); 8 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.Contracts/Constants.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.Contracts; 2 | 3 | public static class Constants 4 | { 5 | public const string AdapterQueueName = "altinn.dialogportenadapter.webapi"; 6 | public const string AdapterHistoryQueueName = "altinn.dialogportenadapter-history.webapi"; 7 | public const string EventSimulatorQueueName = "altinn.dialogportenadapter.eventsim"; 8 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Common/Extensions/QueryStringExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.EventSimulator.Common.Extensions; 2 | 3 | internal static class QueryStringExtensions 4 | { 5 | public static QueryString AddIf(this QueryString queryString, bool predicate, string key, string? value) 6 | { 7 | return predicate ? queryString.Add(key, value ?? "null") : queryString; 8 | } 9 | } -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.dockerignore 2 | **/.env 3 | **/.git 4 | **/.gitignore 5 | **/.project 6 | **/.settings 7 | **/.toolstarget 8 | **/.vs 9 | **/.vscode 10 | **/.idea 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Infrastructure/Adapter/IStorageAdapterApi.cs: -------------------------------------------------------------------------------- 1 | using Altinn.DialogportenAdapter.Contracts; 2 | using Refit; 3 | 4 | namespace Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Adapter; 5 | 6 | public interface IStorageAdapterApi 7 | { 8 | [Post("/storage/dialogporten/api/v1/syncDialog")] 9 | Task Sync([Body] SyncInstanceCommand syncDialogDto, CancellationToken cancellationToken); 10 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/EnumerableExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 2 | 3 | internal static class EnumerableExtensions 4 | { 5 | public static IEnumerable DequeueWhile(this Queue queue, Func predicate) 6 | { 7 | while (queue.TryPeek(out var next) && predicate(next)) 8 | { 9 | yield return queue.Dequeue(); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.Contracts/Altinn.DialogportenAdapter.Contracts.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Infrastructure/Storage/ApplicationTexts.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.WebApi.Infrastructure.Storage; 2 | 3 | public class ApplicationTexts 4 | { 5 | public List Translations { get; set; } = new(); 6 | } 7 | 8 | public class ApplicationTextsTranslation 9 | { 10 | public string Language { get; set; } = string.Empty; 11 | public Dictionary Texts { get; set; } = new(); 12 | } 13 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "https": { 5 | "commandName": "Project", 6 | "dotnetRunMessages": true, 7 | "launchBrowser": false, 8 | "applicationUrl": "https://localhost:7242;http://localhost:5012", 9 | "environmentVariables": { 10 | "ASPNETCORE_ENVIRONMENT": "Development" 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Common/HealthCheck.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Diagnostics.HealthChecks; 2 | 3 | namespace Altinn.DialogportenAdapter.EventSimulator.Common; 4 | 5 | internal sealed class HealthCheck : IHealthCheck 6 | { 7 | public Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) 8 | { 9 | return Task.FromResult( 10 | HealthCheckResult.Healthy("A healthy result.")); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Features/Command/Sync/SyncDialogOnInstanceUpdatedHandler.cs: -------------------------------------------------------------------------------- 1 | using Altinn.DialogportenAdapter.Contracts; 2 | 3 | namespace Altinn.DialogportenAdapter.WebApi.Features.Command.Sync; 4 | 5 | public static class SyncDialogOnInstanceUpdatedHandler 6 | { 7 | public static Task Handle(SyncInstanceCommand message, 8 | ISyncInstanceToDialogService syncService, 9 | CancellationToken cancellationToken) => 10 | syncService.Sync(message, cancellationToken); 11 | } 12 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Infrastructure/Storage/IStorageApi.cs: -------------------------------------------------------------------------------- 1 | using Refit; 2 | 3 | namespace Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Storage; 4 | 5 | internal interface IStorageApi 6 | { 7 | [Get("/storage/api/v1/applications")] 8 | Task GetApplications(CancellationToken cancellationToken); 9 | } 10 | 11 | internal sealed class ApplicationResponse 12 | { 13 | public List Applications { get; set; } = null!; 14 | } 15 | 16 | internal sealed record Application(string Id, string Org); -------------------------------------------------------------------------------- /.github/workflows/auto-add-items.yml: -------------------------------------------------------------------------------- 1 | name: Add issues and PRs to project 2 | 3 | on: 4 | issues: 5 | types: [opened, reopened, transferred, labeled] 6 | pull_request: 7 | types: [opened, reopened, labeled] 8 | 9 | jobs: 10 | add-to-project: 11 | name: Add issue to project 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/add-to-project@244f685bbc3b7adfa8466e08b698b5577571133e # v1.0.2 15 | with: 16 | project-url: https://github.com/orgs/Altinn/projects/146 17 | github-token: ${{ secrets.ADD_TO_PROJECT_PAT }} 18 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/MediaTypes.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.WebApi.Common; 2 | 3 | public static class MediaTypes 4 | { 5 | public const string EmbeddablePrefix = "application/vnd.dialogporten.frontchannelembed"; 6 | public const string EmbeddableMarkdown = $"{EmbeddablePrefix}+json;type=markdown"; 7 | public const string LegacyEmbeddableHtml = $"{EmbeddablePrefix}+json;type=html"; 8 | 9 | public const string LegacyHtml = "text/html"; 10 | public const string Markdown = "text/markdown"; 11 | public const string PlainText = "text/plain"; 12 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/DialogDtoExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Dialogporten; 3 | 4 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 5 | 6 | public static class DialogDtoExtensions 7 | { 8 | public static DialogDto? DeepClone(this DialogDto? dialog) 9 | { 10 | // TODO! Create something more efficient 11 | if (dialog == null) return null; 12 | var json = JsonSerializer.Serialize(dialog); 13 | return JsonSerializer.Deserialize(json)!; 14 | } 15 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/HttpRequests/migrate.http: -------------------------------------------------------------------------------- 1 | @eventsimulator = https://localhost:7242 2 | 3 | ### MIGRATE 4 | # @timeout 10000 m 5 | POST {{eventsimulator}}/api/migrate 6 | Content-Type: application/json 7 | 8 | { 9 | "From": "2024-01-01", 10 | "To": "2025-01-01", 11 | "Organizations": ["skd"], 12 | "Force": true 13 | } 14 | 15 | ### 16 | 17 | //{ 18 | // "From": "2024-01-01", 19 | // "To": "2024-01-01", 20 | // "Organizations": ["digdir"], 21 | // "Force": true 22 | //} 23 | 24 | ### DELETE 25 | DELETE {{eventsimulator}}/api/table/truncate 26 | Content-Type: application/json -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.Contracts/LambdaEnvelopeRule.cs: -------------------------------------------------------------------------------- 1 | using Wolverine; 2 | 3 | namespace Altinn.DialogportenAdapter.Contracts; 4 | 5 | public class LambdaEnvelopeRule : IEnvelopeRule 6 | { 7 | private readonly Action _configure; 8 | 9 | public LambdaEnvelopeRule(Action configure) 10 | { 11 | _configure = configure ?? throw new ArgumentNullException(nameof(configure)); 12 | } 13 | 14 | public void Modify(Envelope envelope) 15 | { 16 | if (envelope.Message is T message) 17 | { 18 | _configure(envelope, message); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Infrastructure/Storage/IApplicationsApi.cs: -------------------------------------------------------------------------------- 1 | using Altinn.Platform.Storage.Interface.Models; 2 | using Refit; 3 | 4 | namespace Altinn.DialogportenAdapter.WebApi.Infrastructure.Storage; 5 | 6 | public interface IApplicationsApi 7 | { 8 | [Get("/storage/api/v1/applications/{**appId}")] 9 | Task> GetApplication(string appId, CancellationToken cancellationToken = default); 10 | 11 | [Get("/storage/api/v1/applications/{org}/{app}/texts/{language}")] 12 | Task> GetApplicationTexts(string org, string app, string language, CancellationToken cancellationToken = default); 13 | } 14 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/AllowAnonymousHandler.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | 3 | namespace Altinn.DialogportenAdapter.WebApi.Common; 4 | 5 | /// 6 | /// This authorization handler will bypass all requirements 7 | /// 8 | internal sealed class AllowAnonymousHandler : IAuthorizationHandler 9 | { 10 | public Task HandleAsync(AuthorizationHandlerContext context) 11 | { 12 | foreach (var requirement in context.PendingRequirements) 13 | { 14 | //Simply pass all requirements 15 | context.Succeed(requirement); 16 | } 17 | 18 | return Task.CompletedTask; 19 | } 20 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Health/HealthCheckFilterProcessor.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using OpenTelemetry; 3 | 4 | namespace Altinn.DialogportenAdapter.WebApi.Common.Health; 5 | 6 | internal sealed class HealthCheckFilterProcessor : BaseProcessor 7 | { 8 | public override void OnEnd(Activity activity) 9 | { 10 | var requestPath = activity.Tags.FirstOrDefault(t => t.Key == "http.route").Value; 11 | if (requestPath?.EndsWith("/health") ?? false) 12 | { 13 | // Drop this telemetry 14 | activity.IsAllDataRequested = false; 15 | return; 16 | } 17 | 18 | base.OnEnd(activity); 19 | } 20 | } -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "local>Altinn/renovate-config" 5 | ], 6 | "customManagers": [ 7 | { 8 | "customType": "regex", 9 | "description": "Manage Alpine OS versions in container image tags", 10 | "managerFilePatterns": [ 11 | "/Dockerfile/" 12 | ], 13 | "matchStrings": [ 14 | "(?:FROM\\s+)(?[\\S]+):(?[\\S]+)@(?sha256:[a-f0-9]+)" 15 | ], 16 | "versioningTemplate": "regex:^(?[\\S]*\\d+\\.\\d+(?:\\.\\d+)?(?:[\\S]*)?-alpine-?)(?\\d+)\\.(?\\d+)(?:\\.(?\\d+))?$", 17 | "datasourceTemplate": "docker" 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Infrastructure/Register/IRegisterApi.cs: -------------------------------------------------------------------------------- 1 | using Refit; 2 | 3 | namespace Altinn.DialogportenAdapter.WebApi.Infrastructure.Register; 4 | 5 | internal interface IRegisterApi 6 | { 7 | [Post("/register/api/v1/dialogporten/parties/query?fields=identifiers,display-name")] 8 | Task GetPartiesByUrns(PartyQueryRequest request, CancellationToken cancellationToken); 9 | } 10 | 11 | internal sealed record PartyQueryResponse( 12 | List Data 13 | ); 14 | 15 | internal sealed record PartyIdentifier( 16 | int? PartyId, 17 | string DisplayName, 18 | string? PersonIdentifier, 19 | string? OrganizationIdentifier 20 | ); 21 | 22 | internal sealed record PartyQueryRequest(List Data); -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "http": { 5 | "commandName": "Project", 6 | "dotnetRunMessages": true, 7 | "launchBrowser": false, 8 | "applicationUrl": "http://localhost:5011", 9 | "environmentVariables": { 10 | "ASPNETCORE_ENVIRONMENT": "Development" 11 | } 12 | }, 13 | "https": { 14 | "commandName": "Project", 15 | "dotnetRunMessages": true, 16 | "launchBrowser": false, 17 | "applicationUrl": "https://localhost:7241;http://localhost:5011", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/PolicyExtensions.cs: -------------------------------------------------------------------------------- 1 | using Wolverine.ErrorHandling; 2 | 3 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 4 | 5 | public static class PolicyExtensions 6 | { 7 | public static IAdditionalActions RetryWithJitteredCooldown(this PolicyExpression policyExpression, params TimeSpan[] delays) 8 | { 9 | var jittered = new TimeSpan[delays.Length]; 10 | 11 | for (var i = 0; i < delays.Length; i++) 12 | { 13 | var delay = delays[i]; 14 | var factor = 0.5 + Random.Shared.NextDouble(); // +/- 50 % 15 | jittered[i] = TimeSpan.FromMilliseconds(delay.TotalMilliseconds * factor); 16 | } 17 | 18 | return policyExpression.RetryWithCooldown(jittered); 19 | } 20 | } -------------------------------------------------------------------------------- /AzureServiceBusEmulator/.env: -------------------------------------------------------------------------------- 1 | 2 | # Environment file for user defined variables in docker-compose.yml 3 | 4 | # 1. CONFIG_PATH: Path to Config.json file 5 | # Ex: CONFIG_PATH="C:\\Config\\Config.json" 6 | CONFIG_PATH="C:\work\altinn-dialogporten-adapter\AzureServiceBusEmulator\config.json" 7 | 8 | # 2. ACCEPT_EULA: Pass 'Y' to accept license terms for Azure SQL Edge and Azure Service Bus emulator. 9 | # Service Bus emulator EULA : https://github.com/Azure/azure-service-bus-emulator-installer/blob/main/EMULATOR_EULA.txt 10 | # SQL Edge EULA : https://go.microsoft.com/fwlink/?linkid=2139274 11 | ACCEPT_EULA="Y" 12 | 13 | # 3. MSSQL_SA_PASSWORD to be filled by user as per policy : https://learn.microsoft.com/en-us/sql/relational-databases/security/strong-passwords?view=sql-server-linux-ver16 14 | MSSQL_SA_PASSWORD: "Jegvilinn123!" -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Common/Extensions/TableKeyExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | 3 | namespace Altinn.DialogportenAdapter.EventSimulator.Common.Extensions; 4 | 5 | public static class TableKeyExtensions 6 | { 7 | const string DateFormat = "yyyyMMdd"; 8 | public static string ToPartitionKey(this DateOnly date) 9 | => date.ToString(DateFormat, CultureInfo.InvariantCulture); 10 | 11 | public static DateOnly ToDateOnly(this string partitionKey) 12 | => DateOnly.ParseExact(partitionKey, DateFormat, CultureInfo.InvariantCulture); 13 | 14 | // This method is a placeholder for potential future transformation logic for row keys, 15 | // or to provide a semantic marker for row key usage in the codebase. 16 | public static string ToRowKey(this string org) 17 | => org; 18 | 19 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Health/HealthCheck.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Diagnostics.HealthChecks; 2 | 3 | namespace Altinn.DialogportenAdapter.WebApi.Common.Health; 4 | 5 | /// 6 | /// Health check service configured in startup 7 | /// Listen to 8 | /// 9 | public class HealthCheck : IHealthCheck 10 | { 11 | /// 12 | /// Verifies the healht status 13 | /// 14 | /// The healtcheck context 15 | /// The cancellationtoken 16 | /// 17 | public Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) 18 | { 19 | return Task.FromResult( 20 | HealthCheckResult.Healthy("A healthy result.")); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/dotnet/sdk:9.0.102-alpine3.20 AS build 2 | WORKDIR /app 3 | 4 | # Copy csproj and restore as distinct layers 5 | COPY src/Altinn.DialogportenAdapter.WebApi/*.csproj ./src/Altinn.DialogportenAdapter.WebApi/ 6 | RUN dotnet restore ./src/Altinn.DialogportenAdapter.WebApi/Altinn.DialogportenAdapter.WebApi.csproj 7 | 8 | # Copy everything else and build 9 | COPY src ./src 10 | RUN dotnet build -c Release -o out ./src/Altinn.DialogportenAdapter.WebApi/Altinn.DialogportenAdapter.WebApi.csproj 11 | 12 | # Build runtime image 13 | FROM mcr.microsoft.com/dotnet/aspnet:9.0.1-alpine3.20 AS final 14 | WORKDIR /app 15 | EXPOSE 5011 16 | 17 | COPY --from=build /app/out . 18 | 19 | RUN addgroup -g 3000 dotnet && adduser -u 1000 -G dotnet -D -s /bin/false dotnet 20 | USER dotnet 21 | RUN mkdir /tmp/logtelemetry 22 | 23 | ENTRYPOINT [ "dotnet", "Altinn.DialogportenAdapter.WebApi.dll" ] 24 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Common/StartupLoaders/AzureTableStartupLoader.cs: -------------------------------------------------------------------------------- 1 | using Azure.Data.Tables; 2 | 3 | namespace Altinn.DialogportenAdapter.EventSimulator.Common.StartupLoaders; 4 | 5 | internal sealed class AzureTableStartupLoader : IStartupLoader 6 | { 7 | private readonly IHostEnvironment _env; 8 | private readonly Settings _settings; 9 | 10 | public AzureTableStartupLoader(IHostEnvironment env, Settings settings) 11 | { 12 | _env = env ?? throw new ArgumentNullException(nameof(env)); 13 | _settings = settings ?? throw new ArgumentNullException(nameof(settings)); 14 | } 15 | 16 | public Task Load(CancellationToken cancellationToken) 17 | { 18 | var serviceClient = new TableServiceClient(_settings.DialogportenAdapter.AzureStorage.ConnectionString); 19 | return serviceClient.CreateTableIfNotExistsAsync(AzureStorageSettings.GetTableName(_env), cancellationToken); 20 | } 21 | } -------------------------------------------------------------------------------- /AzureServiceBusEmulator/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | name: microsoft-azure-servicebus-emulator 2 | services: 3 | emulator: 4 | container_name: "servicebus-emulator" 5 | image: mcr.microsoft.com/azure-messaging/servicebus-emulator:latest 6 | volumes: 7 | - "${CONFIG_PATH}:/ServiceBus_Emulator/ConfigFiles/Config.json" 8 | ports: 9 | - "5672:5672" 10 | environment: 11 | SQL_SERVER: sqledge 12 | MSSQL_SA_PASSWORD: ${MSSQL_SA_PASSWORD} 13 | ACCEPT_EULA: ${ACCEPT_EULA} 14 | depends_on: 15 | - sqledge 16 | networks: 17 | sb-emulator: 18 | aliases: 19 | - "sb-emulator" 20 | sqledge: 21 | container_name: "sqledge" 22 | image: "mcr.microsoft.com/azure-sql-edge:latest" 23 | networks: 24 | sb-emulator: 25 | aliases: 26 | - "sqledge" 27 | environment: 28 | ACCEPT_EULA: ${ACCEPT_EULA} 29 | MSSQL_SA_PASSWORD: ${MSSQL_SA_PASSWORD} 30 | networks: 31 | sb-emulator: -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/dotnet/sdk:9.0.102-alpine3.20 AS build 2 | WORKDIR /app 3 | 4 | # Copy csproj and restore as distinct layers 5 | COPY src/Altinn.DialogportenAdapter.EventSimulator/*.csproj ./src/Altinn.DialogportenAdapter.EventSimulator/ 6 | RUN dotnet restore ./src/Altinn.DialogportenAdapter.EventSimulator/Altinn.DialogportenAdapter.EventSimulator.csproj 7 | 8 | # Copy everything else and build 9 | COPY src ./src 10 | RUN dotnet build -c Release -o out ./src/Altinn.DialogportenAdapter.EventSimulator/Altinn.DialogportenAdapter.EventSimulator.csproj 11 | 12 | # Build runtime image 13 | FROM mcr.microsoft.com/dotnet/aspnet:9.0.1-alpine3.20 AS final 14 | WORKDIR /app 15 | EXPOSE 5012 16 | 17 | COPY --from=build /app/out . 18 | 19 | RUN addgroup -g 3000 dotnet && adduser -u 1000 -G dotnet -D -s /bin/false dotnet 20 | USER dotnet 21 | RUN mkdir /tmp/logtelemetry 22 | 23 | ENTRYPOINT [ "dotnet", "Altinn.DialogportenAdapter.EventSimulator.dll" ] 24 | -------------------------------------------------------------------------------- /tests/Altinn.DialogportenAdapter.Unit.Tests/Infrastructure/Storage/ApplicationRepositoryTests.cs: -------------------------------------------------------------------------------- 1 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Storage; 2 | using Altinn.Platform.Storage.Interface.Models; 3 | 4 | namespace Altinn.DialogportenAdapter.Unit.Tests.Infrastructure.Storage; 5 | 6 | public class ApplicationRepositoryTests 7 | { 8 | [Fact] 9 | public void CreateTextsDictionary_KeepsFirstOccurrenceForDuplicateIds() 10 | { 11 | var resources = new List 12 | { 13 | new() { Id = "dp.title", Value = "first-title" }, 14 | new() { Id = "dp.title", Value = "second-title" }, 15 | new() { Id = "dp.summary", Value = "summary" } 16 | }; 17 | 18 | var result = ApplicationRepository.CreateTextsDictionary(resources); 19 | 20 | Assert.Equal(2, result.Count); 21 | Assert.Equal("first-title", result["dp.title"]); 22 | Assert.Equal("summary", result["dp.summary"]); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "DialogportenAdapter": { 8 | "Maskinporten": { 9 | "Environment": "PopulateFromEnvironmentVariable", 10 | "TokenExchangeEnvironment": "PopulateFromEnvironmentVariable", 11 | "Scope": "altinn:serviceowner/instances.read altinn:storage/instances.syncadapter", 12 | "ClientId": "TODO: Add to local secrets", 13 | "EncodedJwk": "TODO: Add to local secrets", 14 | "ExhangeToAltinnToken": true, 15 | "EnableDebugLogging": false 16 | }, 17 | "Altinn": { 18 | "ApiStorageEndpoint": "PopulateFromEnvironmentVariable", 19 | }, 20 | "Adapter": { 21 | "InternalBaseUri": "PopulateFromEnvironmentVariable" 22 | }, 23 | "AzureStorage": { 24 | "ConnectionString": "TODO: Add to local secrets" 25 | }, 26 | "EventSimulator": { 27 | "EnableUpdateStream": false 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning", 5 | "Altinn.DialogportenAdapter.EventSimulator": "Information" 6 | } 7 | }, 8 | "DialogportenAdapter": { 9 | "Maskinporten": { 10 | "Environment": "test", 11 | "TokenExchangeEnvironment": "tt02", 12 | "Scope": "altinn:serviceowner/instances.read altinn:storage/instances.syncadapter", 13 | "ClientId": "TODO: Add to local secrets", 14 | "EncodedJwk": "TODO: Add to local secrets", 15 | "ExhangeToAltinnToken": true, 16 | "EnableDebugLogging": false 17 | }, 18 | "Altinn": { 19 | "ApiStorageEndpoint": "https://platform.tt02.altinn.no" 20 | }, 21 | "Adapter": { 22 | "InternalBaseUri": "https://localhost:7241" 23 | }, 24 | "AzureStorage": { 25 | "ConnectionString": "TODO: Add to local secrets" 26 | }, 27 | "EventSimulator": { 28 | "EnableUpdateStream": true 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Altinn 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Common/StartupLoaders/OrganizationStartupLoader.cs: -------------------------------------------------------------------------------- 1 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Storage; 2 | 3 | namespace Altinn.DialogportenAdapter.EventSimulator.Common.StartupLoaders; 4 | 5 | internal sealed class OrganizationStartupLoader : IStartupLoader 6 | { 7 | private readonly IOrganizationRepository _organizationRepository; 8 | 9 | public OrganizationStartupLoader(IOrganizationRepository organizationRepository) 10 | { 11 | _organizationRepository = organizationRepository ?? throw new ArgumentNullException(nameof(organizationRepository)); 12 | } 13 | 14 | public static DateOnly LocalLoadDate { get; private set; } = DateOnly.MinValue; 15 | 16 | public async Task Load(CancellationToken cancellationToken) 17 | { 18 | await _organizationRepository.GetOrganizations(cancellationToken); 19 | 20 | // Set the load date to yesterday, as today's data is not yet 21 | // available and new organizations might be added today. 22 | LocalLoadDate = DateOnly.FromDateTime(DateTime.Now.AddDays(-1)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Infrastructure/Persistance/NullMigrationPartitionRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | 3 | namespace Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Persistance; 4 | 5 | internal sealed class NullMigrationPartitionRepository : IMigrationPartitionRepository 6 | { 7 | public Task> GetExistingPartitions(List partitions, CancellationToken cancellationToken) 8 | { 9 | return Task.FromResult(Array.Empty().AsReadOnly()); 10 | } 11 | 12 | public Task Get(DateOnly partition, string organization, CancellationToken cancellationToken) 13 | { 14 | return Task.FromResult(null); 15 | } 16 | 17 | public Task Upsert(List partitionEntities, CancellationToken cancellationToken) 18 | { 19 | return Task.CompletedTask; 20 | } 21 | 22 | public Task Truncate(CancellationToken cancellationToken = default) 23 | { 24 | return Task.CompletedTask; 25 | } 26 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/StorageTypeExtensions.cs: -------------------------------------------------------------------------------- 1 | using Altinn.Platform.Storage.Interface.Models; 2 | 3 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 4 | 5 | internal static class StorageTypeExtensions 6 | { 7 | public static bool ShouldBeHidden(this Application application, Instance instance) 8 | { 9 | var hideSettings = application.MessageBoxConfig?.HideSettings; 10 | if (hideSettings is null) 11 | { 12 | return false; 13 | } 14 | 15 | if (hideSettings.HideAlways) 16 | { 17 | return true; 18 | } 19 | 20 | var processId = instance.Process?.CurrentTask?.ElementId; 21 | return hideSettings.HideOnTask is not null 22 | && processId is not null 23 | && hideSettings.HideOnTask.Contains(processId); 24 | } 25 | 26 | public static SyncAdapterSettings GetSyncAdapterSettings(this Application? application) 27 | { 28 | return application? 29 | .MessageBoxConfig? 30 | .SyncAdapterSettings 31 | ?? new SyncAdapterSettings(); 32 | } 33 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/AuthorizationExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | 3 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 4 | 5 | internal static class AuthorizationExtensions 6 | { 7 | public const string ScopeClaim = "scope"; 8 | private const char ScopeClaimSeparator = ' '; 9 | 10 | public static AuthorizationPolicyBuilder RequireScope(this AuthorizationPolicyBuilder builder, string scope) => 11 | builder.RequireAssertion(ctx => ctx.User.Claims 12 | .Where(x => x.Type == ScopeClaim) 13 | .Select(x => x.Value) 14 | .Any(scopeValue => scopeValue.AsSpan().SplitContains(ScopeClaimSeparator, scope))); 15 | 16 | private static bool SplitContains(this ReadOnlySpan span, char separator, ReadOnlySpan value) 17 | { 18 | var enumerator = span.Split(separator); 19 | while (enumerator.MoveNext()) 20 | { 21 | if (span[enumerator.Current].Equals(value, StringComparison.OrdinalIgnoreCase)) 22 | { 23 | return true; 24 | } 25 | } 26 | 27 | return false; 28 | } 29 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Infrastructure/Storage/IStorageApi.cs: -------------------------------------------------------------------------------- 1 | using Altinn.Platform.Storage.Interface.Models; 2 | using Refit; 3 | 4 | namespace Altinn.DialogportenAdapter.WebApi.Infrastructure.Storage; 5 | 6 | internal interface IStorageApi 7 | { 8 | 9 | [Get("/storage/api/v1/instances/{partyId}/{instanceId}")] 10 | Task> GetInstance(string partyId, Guid instanceId, CancellationToken cancellationToken = default); 11 | 12 | [Put("/storage/api/v1/instances/{partyId}/{instanceId}/datavalues")] 13 | Task UpdateDataValues(string partyId, Guid instanceId, [Body] DataValues dataValues, CancellationToken cancellationToken = default); 14 | 15 | [Get("/storage/api/v1/instances/{partyId}/{instanceId}/events")] 16 | Task> GetInstanceEvents(string partyId, Guid instanceId, 17 | [Query(CollectionFormat.Multi)] IEnumerable eventTypes, 18 | CancellationToken cancellationToken = default); 19 | 20 | [Delete("/storage/api/v1/sbl/instances/{partyId}/{instanceId}")] 21 | Task DeleteInstance(string partyId, Guid instanceId, [Query] bool hard = false, CancellationToken cancellationToken = default); 22 | 23 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.Contracts/WolverineOptionsExtentions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Hosting; 2 | using Wolverine; 3 | using Wolverine.AzureServiceBus; 4 | 5 | namespace Altinn.DialogportenAdapter.Contracts; 6 | 7 | public static class WolverineOptionsExtentions 8 | { 9 | public static WolverineOptions ConfigureAdapterDefaults( 10 | this WolverineOptions opts, 11 | IHostEnvironment env, 12 | string azureServiceBusConnectionString) 13 | { 14 | ArgumentNullException.ThrowIfNull(opts); 15 | ArgumentNullException.ThrowIfNull(env); 16 | ArgumentException.ThrowIfNullOrWhiteSpace(azureServiceBusConnectionString); 17 | 18 | opts.Policies.DisableConventionalLocalRouting(); 19 | opts.EnableAutomaticFailureAcks = false; 20 | opts.EnableRemoteInvocation = false; 21 | opts.MultipleHandlerBehavior = MultipleHandlerBehavior.Separated; 22 | var azureBusConfig = opts 23 | .UseAzureServiceBus(azureServiceBusConnectionString) 24 | .AutoProvision(); 25 | 26 | if (env.IsDevelopment()) 27 | { 28 | azureBusConfig.AutoPurgeOnStartup(); 29 | } 30 | 31 | return opts; 32 | } 33 | } -------------------------------------------------------------------------------- /.github/workflows/container-scan.yml: -------------------------------------------------------------------------------- 1 | name: Notifications scan 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | paths: 7 | - 'src/**' 8 | - 'Dockerfile' 9 | pull_request: 10 | branches: [main] 11 | paths: 12 | - 'src/**' 13 | - 'Dockerfile' 14 | schedule: 15 | - cron: '0 8 * * 1,4' 16 | 17 | jobs: 18 | build: 19 | runs-on: ubuntu-latest 20 | steps: 21 | - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1 22 | - name: Build the Docker image 23 | run: docker build . --tag altinn-dialogporten-adapter:${{github.sha}} 24 | 25 | - name: Run Trivy vulnerability scanner 26 | uses: aquasecurity/trivy-action@b6643a29fecd7f34b3597bc6acb0a98b03d33ff8 # 0.33.1 27 | with: 28 | image-ref: 'altinn-dialogporten-adapter:${{ github.sha }}' 29 | format: 'table' 30 | exit-code: '1' 31 | ignore-unfixed: true 32 | vuln-type: 'os,library' 33 | severity: 'CRITICAL,HIGH' 34 | env: 35 | TRIVY_DB_REPOSITORY: public.ecr.aws/aquasecurity/trivy-db,aquasec/trivy-db,ghcr.io/aquasecurity/trivy-db 36 | TRIVY_JAVA_DB_REPOSITORY: public.ecr.aws/aquasecurity/trivy-java-db,aquasec/trivy-java-db,ghcr.io/aquasecurity/trivy-java-db 37 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Common/Extensions/InstanceDtoExtensions.cs: -------------------------------------------------------------------------------- 1 | using Altinn.DialogportenAdapter.Contracts; 2 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Storage; 3 | 4 | namespace Altinn.DialogportenAdapter.EventSimulator.Common.Extensions; 5 | 6 | internal static class InstanceDtoExtensions 7 | { 8 | public static SyncInstanceCommand ToSyncInstanceCommand(this InstanceDto instance, bool isMigration = true) 9 | { 10 | var (partyId, instanceId) = ParseInstanceId(instance.Id); 11 | return new SyncInstanceCommand(instance.AppId, partyId, instanceId, instance.Created, isMigration); 12 | } 13 | 14 | private static (string PartyId, Guid InstanceId) ParseInstanceId(ReadOnlySpan id) 15 | { 16 | var partsEnumerator = id.Split("/"); 17 | if (!partsEnumerator.MoveNext() || !int.TryParse(id[partsEnumerator.Current], out var party)) 18 | { 19 | throw new InvalidOperationException("Invalid instance id"); 20 | } 21 | 22 | if (!partsEnumerator.MoveNext() || !Guid.TryParse(id[partsEnumerator.Current], out var instance)) 23 | { 24 | throw new InvalidOperationException("Invalid instance id"); 25 | } 26 | 27 | return (party.ToString(), instance); 28 | } 29 | } -------------------------------------------------------------------------------- /tests/Altinn.DialogportenAdapter.Unit.Tests/Altinn.DialogportenAdapter.Unit.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | enable 6 | enable 7 | 8 | false 9 | true 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | 19 | 20 | all 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/HttpRequests/SyncByInstanceId.http: -------------------------------------------------------------------------------- 1 | @instanceId = 51356992/017c0906-1470-416b-b0c2-ebe2d30dc1f1 2 | 3 | ### Log into maskinporten 4 | // @no-log 5 | GET https://altinn-testtools-token-generator.azurewebsites.net/api/GetEnterpriseToken?org=digdir&env={{env}}&scopes=altinn:storage/instances.syncadapter&ttl=86400 6 | Authorization: Basic {{username}} {{password}} 7 | 8 | > {% client.global.set("maskinportenToken", response.body) %} 9 | 10 | ### Get instance data 11 | // @no-log 12 | GET {{altinnPlatformBaseUri}}/storage/api/v1/instances/{{instanceId}} 13 | Authorization: Bearer {{maskinportenToken}} 14 | 15 | > {% 16 | const idParts = response.body.id.split('/'); 17 | client.global.set("syncDialogDto", JSON.stringify({ 18 | "appId": response.body.appId, 19 | "partyId": idParts[0], 20 | "instanceId": idParts[1], 21 | "instanceCreatedAt": response.body.created, 22 | "isMigration": true 23 | })) 24 | %} 25 | 26 | ### Sync 27 | // @no-log 28 | POST {{baseUri}}/api/v1/syncDialog 29 | Authorization: Bearer {{maskinportenToken}} 30 | Content-Type: application/json 31 | 32 | {{syncDialogDto}} 33 | 34 | > {% 35 | if (response.status < 200 || response.status >= 300) { 36 | client.test("Request failed with status: " + response.status, function() { 37 | throw new Error("HTTP " + response.status + ": " + response.body); 38 | }); 39 | } 40 | %} 41 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Altinn.DialogportenAdapter.EventSimulator.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | enable 6 | enable 7 | f15beaf9-69f4-454a-8605-6586ecad451d 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/SpanExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 2 | 3 | internal static class SpanExtensions 4 | { 5 | /// 6 | /// Will try to copy the source span to the destination span from offset, and return true if the entire source span was copied. 7 | /// If the destination span reminder is too small, the source span will be truncated and "..." will be appended to the destination span. 8 | /// 9 | /// The span to copy from. 10 | /// The span to copy to. 11 | /// The offset in the destination span to start copying to. Will be updated with the new offset after copying. 12 | /// True if the entire source span was copied, false otherwise. 13 | public static bool TryCopyTo(this ReadOnlySpan source, Span destination, ref int offset) 14 | { 15 | const string andMore = "..."; 16 | var remaining = destination.Length - offset; 17 | if (remaining < source.Length) 18 | { 19 | source[..remaining].CopyTo(destination[offset..]); 20 | andMore.CopyTo(destination[^andMore.Length..]); 21 | offset = destination.Length; 22 | return false; 23 | } 24 | 25 | source.CopyTo(destination[offset..]); 26 | offset += source.Length; 27 | return true; 28 | } 29 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Common/StartupLoaders/StartupLoader.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace Altinn.DialogportenAdapter.EventSimulator.Common.StartupLoaders; 4 | 5 | internal sealed class StartupLoader : IHostedService 6 | { 7 | private readonly IEnumerable _loaders; 8 | 9 | public StartupLoader(IEnumerable loaders) 10 | { 11 | _loaders = loaders ?? throw new ArgumentNullException(nameof(loaders)); 12 | } 13 | 14 | public Task StartAsync(CancellationToken cancellationToken) => 15 | Task.WhenAll(_loaders.Select(x => x.Load(cancellationToken))); 16 | 17 | public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; 18 | } 19 | 20 | internal static class StartupLoaderExtensions 21 | { 22 | public static IServiceCollection AddStartupLoaders(this IServiceCollection services) 23 | { 24 | var startupLoaderType = typeof(IStartupLoader); 25 | var loaders = Assembly 26 | .GetExecutingAssembly() 27 | .DefinedTypes 28 | .Where(x => !x.IsInterface && !x.IsAbstract && x.IsAssignableTo(startupLoaderType)); 29 | 30 | foreach (var loader in loaders) 31 | { 32 | services.Add(ServiceDescriptor.Transient(startupLoaderType, loader)); 33 | } 34 | 35 | services.AddHostedService(); 36 | 37 | return services; 38 | } 39 | } 40 | 41 | internal interface IStartupLoader 42 | { 43 | Task Load(CancellationToken cancellationToken); 44 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning", 5 | "Altinn.DialogportenAdapter.WebApi.Common.FourHundredLoggingDelegatingHandler": "Information" 6 | } 7 | }, 8 | "DialogportenAdapter": { 9 | "Maskinporten": { 10 | "Environment": "PopulateFromEnvironmentVariable", 11 | "TokenExchangeEnvironment": "PopulateFromEnvironmentVariable", 12 | "Scope": "digdir:dialogporten.serviceprovider.admin digdir:dialogporten.serviceprovider.legacyhtml altinn:serviceowner/instances.write digdir:dialogporten.serviceprovider altinn:serviceowner/instances.read altinn:storage/instances.syncadapter altinn:register/partylookup.admin", 13 | "ClientId": "TODO: Add to local secrets", 14 | "EncodedJwk": "TODO: Add to local secrets", 15 | "ExhangeToAltinnToken": true, 16 | "EnableDebugLogging": false 17 | }, 18 | "Altinn": { 19 | "BaseUri": "PopulateFromEnvironmentVariable", 20 | "InternalStorageEndpoint": "PopulateFromEnvironmentVariable", 21 | "InternalRegisterEndpoint": "PopulateFromEnvironmentVariable", 22 | "SubscriptionKey": "PopulateFromEnvironmentVariable" 23 | }, 24 | "Dialogporten": { 25 | "BaseUri": "PopulateFromEnvironmentVariable" 26 | }, 27 | "Adapter": { 28 | "BaseUri": "PopulateFromEnvironmentVariable", 29 | "InternalBaseUri": "PopulateFromEnvironmentVariable" 30 | }, 31 | "Authentication": { 32 | "JwtBearerWellKnown": "PopulateFromEnvironmentVariable" 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Infrastructure/Storage/IOrganizationRepository.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Storage; 2 | 3 | internal interface IOrganizationRepository 4 | { 5 | ValueTask> GetOrganizations(CancellationToken cancellationToken); 6 | } 7 | 8 | internal class OrganizationRepository : IOrganizationRepository 9 | { 10 | private static readonly SemaphoreSlim Semaphore = new(1, 1); 11 | 12 | private readonly IStorageApi _storageApi; 13 | private static List? _cachedOrganizations; 14 | 15 | public OrganizationRepository(IStorageApi storageApi) 16 | { 17 | _storageApi = storageApi ?? throw new ArgumentNullException(nameof(storageApi)); 18 | } 19 | 20 | public async ValueTask> GetOrganizations(CancellationToken cancellationToken) 21 | { 22 | if (_cachedOrganizations is not null) 23 | { 24 | return _cachedOrganizations; 25 | } 26 | await Semaphore.WaitAsync(cancellationToken); 27 | try 28 | { 29 | if (_cachedOrganizations is not null) 30 | { 31 | return _cachedOrganizations; 32 | } 33 | 34 | var apps = await _storageApi.GetApplications(cancellationToken); 35 | return _cachedOrganizations = apps.Applications 36 | .Select(x => x.Org) 37 | .Distinct() 38 | .ToList(); 39 | } 40 | finally 41 | { 42 | Semaphore.Release(); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/ApiResponseExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Net; 3 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Dialogporten; 4 | using Refit; 5 | 6 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 7 | 8 | internal static class ApiResponseExtensions 9 | { 10 | public static async Task ContentOrDefault(this Task> responseTask) 11 | { 12 | var response = await responseTask; 13 | if (response.StatusCode == HttpStatusCode.NotFound) 14 | { 15 | return default; 16 | } 17 | 18 | return response.IsSuccessful 19 | ? response.Content 20 | : throw response.Error; 21 | } 22 | 23 | public static async Task EnsureSuccess(this Task responseTask) 24 | where T : IApiResponse 25 | { 26 | var response = await responseTask; 27 | return response.IsSuccessful 28 | ? response 29 | : throw response.Error; 30 | } 31 | 32 | public static Guid GetEtagHeader(this IApiResponse response) => 33 | !response.TryGetEtagHeader(out var etag) 34 | ? throw new UnreachableException("ETag header was not found or could not be parsed.") 35 | : etag; 36 | 37 | public static bool TryGetEtagHeader(this IApiResponse response, out Guid etag) 38 | { 39 | etag = Guid.Empty; 40 | return response.Headers.TryGetValues(IDialogportenApi.ETagHeader, out var etags) && 41 | Guid.TryParse(etags.FirstOrDefault(), out etag); 42 | } 43 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning", 5 | "Altinn.DialogportenAdapter.WebApi.Common.FourHundredLoggingDelegatingHandler": "Information" 6 | } 7 | }, 8 | "DialogportenAdapter": { 9 | "Maskinporten": { 10 | "Environment": "test", 11 | "TokenExchangeEnvironment": "tt02", 12 | "Scope": "digdir:dialogporten.serviceprovider digdir:dialogporten.serviceprovider.admin altinn:serviceowner/instances.write altinn:serviceowner/instances.read altinn:storage/instances.syncadapter altinn:register/partylookup.admin", 13 | "ClientId": "TODO: Add to local secrets", 14 | "EncodedJwk": "TODO: Add to local secrets", 15 | "ExhangeToAltinnToken": true, 16 | "EnableDebugLogging": false 17 | }, 18 | "Altinn": { 19 | "BaseUri": "https://tt02.altinn.no", 20 | "InternalStorageEndpoint": "https://platform.tt02.altinn.no", 21 | "InternalRegisterEndpoint": "https://platform.tt02.altinn.no", 22 | "SubscriptionKey": "PopulateFromEnvironmentVariable" 23 | }, 24 | "Dialogporten": { 25 | "BaseUri": "https://altinn-dev-api.azure-api.net/dialogporten" //, "https://localhost:7214" //https://altinn-dev-api.azure-api.net/dialogporten" 26 | }, 27 | "Adapter": { 28 | "BaseUri": "https://platform.tt02.altinn.no/storage/dialogporten", 29 | "InternalBaseUri": "TODO: populate" 30 | }, 31 | "Authentication": { 32 | "JwtBearerWellKnown": "https://platform.tt02.altinn.no/authentication/api/v1/openid/.well-known/openid-configuration" 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Altinn.DialogportenAdapter.WebApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | enable 6 | enable 7 | f15beaf9-69f4-454a-8605-6586ecad451d 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: 'CodeQL' 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | paths: 7 | - 'src/**' 8 | pull_request: 9 | # The branches below must be a subset of the branches above 10 | branches: [main] 11 | paths: 12 | - 'src/**' 13 | schedule: 14 | - cron: '18 22 * * 3' 15 | 16 | jobs: 17 | analyze: 18 | name: Analyze 19 | runs-on: ubuntu-latest 20 | permissions: 21 | actions: read 22 | contents: read 23 | security-events: write 24 | 25 | strategy: 26 | fail-fast: false 27 | matrix: 28 | language: ['csharp'] 29 | steps: 30 | - name: Checkout repository 31 | uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1 32 | - name: Setup .NET 9.0.* SDK 33 | uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1 34 | with: 35 | dotnet-version: | 36 | 9.0.x 37 | - name: Initialize CodeQL 38 | uses: github/codeql-action/init@497990dfed22177a82ba1bbab381bc8f6d27058f # v3.31.6 39 | with: 40 | languages: ${{ matrix.language }} 41 | # If you wish to specify custom queries, you can do so here or in a config file. 42 | # By default, queries listed here will override any specified in a config file. 43 | # Prefix the list here with "+" to use these queries and those in the config file. 44 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 45 | 46 | - name: Autobuild 47 | uses: github/codeql-action/autobuild@497990dfed22177a82ba1bbab381bc8f6d27058f # v3.31.6 48 | 49 | - name: Perform CodeQL Analysis 50 | uses: github/codeql-action/analyze@497990dfed22177a82ba1bbab381bc8f6d27058f # v3.31.6 51 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Common/Extensions/ConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | using Azure.Identity; 2 | using Microsoft.Extensions.FileProviders; 3 | 4 | namespace Altinn.DialogportenAdapter.EventSimulator.Common.Extensions; 5 | 6 | internal static class ConfigurationExtensions 7 | { 8 | public static IConfigurationManager AddCoreClusterSettings(this IConfigurationManager config) 9 | { 10 | const string settingsVolume = "/altinn-appsettings"; 11 | const string jsonFileName = "altinn-dbsettings-secret.json"; 12 | IFileProvider fileProvider = Directory.Exists(settingsVolume) 13 | ? new PhysicalFileProvider(settingsVolume) 14 | : new NullFileProvider(); 15 | config.AddJsonFile(fileProvider, jsonFileName, optional: true, reloadOnChange: true); 16 | return config; 17 | } 18 | 19 | public static IConfigurationManager AddAzureKeyVault(this IConfigurationManager config) 20 | { 21 | var kvSettings = config 22 | .GetSection("kvSetting") 23 | .Get(); 24 | 25 | if (kvSettings is null || 26 | string.IsNullOrWhiteSpace(kvSettings.ClientId) || 27 | string.IsNullOrWhiteSpace(kvSettings.TenantId) || 28 | string.IsNullOrWhiteSpace(kvSettings.ClientSecret) || 29 | string.IsNullOrWhiteSpace(kvSettings.SecretUri)) 30 | { 31 | return config; 32 | } 33 | 34 | var azureCredentials = new ClientSecretCredential( 35 | tenantId: kvSettings.TenantId, 36 | clientId: kvSettings.ClientId, 37 | clientSecret: kvSettings.ClientSecret); 38 | 39 | config.AddAzureKeyVault(new Uri(kvSettings.SecretUri), azureCredentials); 40 | return config; 41 | } 42 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/LanguageCodes.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.WebApi.Common; 2 | 3 | public static class LanguageCodes 4 | { 5 | /// 6 | /// ISO 639-1 language codes (2-letter). 7 | /// Source: ISO 639-2/RA (Library of Congress) – https://www.loc.gov/standards/iso639-2/php/code_list.php 8 | /// 9 | private static readonly HashSet Codes = new(StringComparer.OrdinalIgnoreCase) 10 | { 11 | "aa","ab","ae","af","ak","am","an","ar","as","av","ay","az", 12 | "ba","be","bg","bh","bi","bm","bn","bo","br","bs", 13 | "ca","ce","ch","co","cr","cs","cu","cv","cy", 14 | "da","de","dv","dz", 15 | "ee","el","en","eo","es","et","eu", 16 | "fa","ff","fi","fj","fo","fr","fy", 17 | "ga","gd","gl","gn","gu","gv", 18 | "ha","he","hi","ho","hr","ht","hu","hy","hz", 19 | "ia","id","ie","ig","ii","ik","io","is","it","iu", 20 | "ja","jv", 21 | "ka","kg","ki","kj","kk","kl","km","kn","ko","kr","ks","ku","kv","kw","ky", 22 | "la","lb","lg","li","ln","lo","lt","lu","lv", 23 | "mg","mh","mi","mk","ml","mn","mr","ms","mt","my", 24 | "na","nb","nd","ne","ng","nl","nn","nr","nv","ny", 25 | "oc","oj","om","or","os", 26 | "pa","pi","pl","ps","pt", 27 | "qu", 28 | "rm","rn","ro","ru","rw", 29 | "sa","sc","sd","se","sg","si","sk","sl","sm","sn","so","sq","sr","ss","st","su","sv","sw", 30 | "ta","te","tg","th","ti","tk","tl","tn","to","tr","ts","tt","tw","ty", 31 | "ug","uk","ur","uz", 32 | "ve","vi","vo", 33 | "wa","wo", 34 | "xh", 35 | "yi","yo", 36 | "za","zh","zu" 37 | }; 38 | 39 | public static bool IsValidTwoLetterLanguageCode(string? languageCode) => 40 | languageCode is not null && Codes.Contains(languageCode); 41 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Common/BackoffHandler.cs: -------------------------------------------------------------------------------- 1 | namespace Altinn.DialogportenAdapter.EventSimulator.Common; 2 | 3 | internal sealed class BackoffHandler 4 | { 5 | public const double JitterPercentage = 10; 6 | private readonly bool _withJitter; 7 | private readonly List _delays; 8 | private int _currentIndex; 9 | 10 | public BackoffHandler(bool withJitter, Position startPosition, params IEnumerable delays) 11 | { 12 | _withJitter = withJitter; 13 | _delays = delays.ToList(); 14 | if (_delays.Count == 0) 15 | { 16 | throw new ArgumentException("Delays list cannot be empty."); 17 | } 18 | 19 | _currentIndex = startPosition switch 20 | { 21 | Position.First => 0, 22 | Position.Last => _delays.Count - 1, 23 | _ => throw new ArgumentException($"Invalid backoff position: {startPosition}") 24 | }; 25 | } 26 | 27 | public TimeSpan Current => _delays[_currentIndex]; 28 | 29 | public void Next() 30 | { 31 | if (_currentIndex < _delays.Count - 1) 32 | _currentIndex++; 33 | } 34 | 35 | public void Reset() 36 | { 37 | _currentIndex = 0; 38 | } 39 | 40 | public Task Delay(CancellationToken cancellationToken) 41 | { 42 | return Task.Delay(GetDelayTimeSpan(), cancellationToken); 43 | } 44 | 45 | private TimeSpan GetDelayTimeSpan() 46 | { 47 | return _withJitter ? GetJitter() + Current : Current; 48 | } 49 | 50 | private TimeSpan GetJitter() 51 | { 52 | var jitterRange = (Current * (JitterPercentage / 100)).Ticks; 53 | var randomJitter = Random.Shared.NextInt64(-jitterRange, jitterRange); 54 | return TimeSpan.FromTicks(randomJitter); 55 | } 56 | 57 | internal enum Position { First, Last } 58 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Dialogporten; 2 | using Microsoft.AspNetCore.Authorization; 3 | 4 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 5 | 6 | internal static class ServiceCollectionExtensions 7 | { 8 | public static IHostApplicationBuilder ReplaceLocalDevelopmentResources(this IHostApplicationBuilder builder) 9 | { 10 | if (!builder.Environment.IsDevelopment() || 11 | !builder.Configuration.TryGetLocalDevelopmentSettings(out var opt)) 12 | { 13 | return builder; 14 | } 15 | 16 | builder.Services 17 | .DoIf(opt.MockDialogportenApi, x => x.Replace(ServiceLifetime.Transient)) 18 | .DoIf(opt.DisableAuth, x => x.Replace(ServiceLifetime.Singleton)); 19 | 20 | return builder; 21 | } 22 | 23 | private static IServiceCollection DoIf(this IServiceCollection services, bool predicate, Action action) 24 | { 25 | if (predicate) action(services); 26 | return services; 27 | } 28 | 29 | private static IServiceCollection Replace( 30 | this IServiceCollection services, 31 | ServiceLifetime lifetime) 32 | where TService : class 33 | where TImplementation : class, TService 34 | { 35 | var serviceType = typeof(TService); 36 | var implementationType = typeof(TImplementation); 37 | // Remove all matching service registrations 38 | for (var i = services.Count - 1; i >= 0; i--) 39 | { 40 | if (services[i].ServiceType == serviceType) services.RemoveAt(i); 41 | } 42 | 43 | services.Add(ServiceDescriptor.Describe(serviceType, implementationType, lifetime)); 44 | return services; 45 | } 46 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Infrastructure/Dialogporten/IDialogportenApi.cs: -------------------------------------------------------------------------------- 1 | 2 | using Refit; 3 | 4 | namespace Altinn.DialogportenAdapter.WebApi.Infrastructure.Dialogporten; 5 | 6 | internal interface IDialogportenApi 7 | { 8 | public const string IfMatchHeader = "If-Match"; 9 | public const string ETagHeader = "ETag"; 10 | 11 | [Get("/api/v1/serviceowner/dialogs/{dialogId}")] 12 | Task> Get(Guid dialogId, CancellationToken cancellationToken = default); 13 | 14 | [Post("/api/v1/serviceowner/dialogs")] 15 | Task Create([Body] DialogDto dto, [Query] bool isSilentUpdate = false, CancellationToken cancellationToken = default); 16 | 17 | [Put("/api/v1/serviceowner/dialogs/{dto.Id}")] 18 | Task Update([Body] DialogDto dto, [Header(IfMatchHeader)] Guid revision, [Query] bool isSilentUpdate = false, CancellationToken cancellationToken = default); 19 | 20 | [Delete("/api/v1/serviceowner/dialogs/{dialogId}")] 21 | Task Delete(Guid dialogId, [Header(IfMatchHeader)] Guid revision, [Query] bool isSilentUpdate = false, CancellationToken cancellationToken = default); 22 | 23 | [Post("/api/v1/serviceowner/dialogs/{dialogId}/actions/purge")] 24 | Task Purge(Guid dialogId, [Header(IfMatchHeader)] Guid revision, [Query] bool isSilentUpdate = false, CancellationToken cancellationToken = default); 25 | 26 | [Post("/api/v1/serviceowner/dialogs/{dialogId}/actions/restore")] 27 | Task Restore(Guid dialogId, [Header(IfMatchHeader)] Guid revision, [Query] bool isSilentUpdate = false, CancellationToken cancellationToken = default); 28 | 29 | [Post("/api/v1/serviceowner/dialogs/{dialogId}/activities/{activityId}/actions/updateFormSavedActivityTime")] 30 | Task UpdateFormSavedActivityTime( 31 | Guid dialogId, 32 | Guid activityId, 33 | [Header(IfMatchHeader)] Guid revision, 34 | [Body] DateTimeOffset newCreatedAt, 35 | CancellationToken cancellationToken = default); 36 | } 37 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/HttpRequests/Requests.http: -------------------------------------------------------------------------------- 1 | @AdapterHost = https://localhost:7241 2 | @DialogportenHost = https://altinn-dev-api.azure-api.net/dialogporten 3 | 4 | ### Authorize 5 | GET https://altinn-testtools-token-generator.azurewebsites.net/api/GetEnterpriseToken 6 | ?env=tt02 7 | &org=digdir 8 | &orgNo=991825827 9 | &scopes=altinn:register/partylookup.admin 10 | &ttl=86400 11 | Authorization: Basic {{username}} {{password}} 12 | 13 | > {% 14 | client.global.set("auth_token", response.body) 15 | %} 16 | 17 | ### Lookup party and user 18 | POST https://platform.tt02.altinn.no/register/api/v1/dialogporten/parties/query?fields=identifiers,display-name 19 | Authorization: Bearer {{auth_token}} 20 | Ocp-Apim-Subscription-Key: {{subscriptionKey}} 21 | Content-Type: application/json 22 | 23 | { 24 | "data": [ 25 | "urn:altinn:user:id:92496", 26 | "urn:altinn:user:id:1433493" 27 | ] 28 | } 29 | 30 | 31 | 32 | 33 | ### Lala 34 | #{ 35 | # "data": [ 36 | #// "urn:altinn:party:uuid:643bec9a-05c5-464a-a994-72586a6b47eb", 37 | #// "urn:altinn:party:uuid:011e4a3e-3a4e-4971-95c2-ce7e53f3a1ae", 38 | #// "urn:altinn:party:uuid:6be1ab97-0bbe-4419-911d-da56a8b0cc0d", 39 | #// "urn:altinn:organization:identifier-no:311654799", 40 | # "urn:altinn:party:id:51693618" 41 | # ] 42 | #} 43 | 44 | #### Get dialog 45 | #GET {{DialogportenHost}}/api/v1/serviceowner/dialogs/019368e0-71f5-72fc-a1d8-3bb85540b14e 46 | #Authorization: Bearer {{auth_token}} 47 | # 48 | #### Purge dialog 49 | #POST {{DialogportenHost}}/api/v1/serviceowner/dialogs/019368e0-71f5-72fc-a1d8-3bb85540b14e/actions/purge 50 | #Authorization: Bearer {{auth_token}} 51 | # 52 | #### Sync 53 | #POST {{AdapterHost}}/api/v1/syncDialog 54 | #Content-Type: application/json 55 | # 56 | #{ 57 | # "AppId": "altinn-test", 58 | # "PartyId": "50892513", 59 | # "InstanceId": "434fe9b5-0605-4b27-a9a7-1c0750e78e02", 60 | # "InstanceCreatedAt": "2021-09-01T12:00:00Z", 61 | # "IsMigration": true 62 | #} 63 | # 64 | #### Health 65 | #GET {{AdapterHost}}/health -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Infrastructure/Persistance/IMigrationPartitionRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | using System.Runtime.Serialization; 3 | using Altinn.DialogportenAdapter.EventSimulator.Common.Extensions; 4 | using Azure; 5 | using Azure.Data.Tables; 6 | 7 | namespace Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Persistance; 8 | 9 | public interface IMigrationPartitionRepository 10 | { 11 | Task> GetExistingPartitions( 12 | List partitions, 13 | CancellationToken cancellationToken); 14 | 15 | Task Get(DateOnly partition, string organization, CancellationToken cancellationToken); 16 | Task Upsert(List partitionEntities, CancellationToken cancellationToken); 17 | Task Truncate(CancellationToken cancellationToken = default); 18 | } 19 | 20 | public sealed class MigrationPartitionEntity : ITableEntity 21 | { 22 | [Obsolete("Used by Table Storage SDK, do not use directly.", error: true)] 23 | public MigrationPartitionEntity() { } 24 | 25 | public MigrationPartitionEntity(DateOnly partition, string organization) 26 | { 27 | Partition = partition; 28 | Organization = organization ?? throw new ArgumentNullException(nameof(organization)); 29 | } 30 | 31 | [IgnoreDataMember] 32 | public DateOnly Partition { get; private set; } 33 | 34 | [IgnoreDataMember] 35 | public string Organization { get; private set; } 36 | 37 | public DateTimeOffset? Checkpoint { get; set; } 38 | 39 | public int? TotalAmount { get; set; } 40 | 41 | public bool Complete { get; set; } 42 | 43 | public string PartitionKey 44 | { 45 | get => Partition.ToPartitionKey(); 46 | set => Partition = value.ToDateOnly(); 47 | } 48 | public string RowKey 49 | { 50 | get => Organization; 51 | set => Organization = value; 52 | } 53 | public DateTimeOffset? Timestamp { get; set; } 54 | public ETag ETag { get; set; } 55 | 56 | public void InstanceHandled(DateTimeOffset lastChanged) 57 | { 58 | Checkpoint = lastChanged < Checkpoint ? lastChanged : Checkpoint; 59 | TotalAmount = TotalAmount is null ? 1 : TotalAmount + 1; 60 | } 61 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Features/Command/Delete/InstanceService.cs: -------------------------------------------------------------------------------- 1 | using Altinn.ApiClients.Dialogporten; 2 | using Altinn.DialogportenAdapter.WebApi.Common.Extensions; 3 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Storage; 4 | 5 | namespace Altinn.DialogportenAdapter.WebApi.Features.Command.Delete; 6 | 7 | internal sealed record DeleteInstanceDto(string PartyId, Guid InstanceGuid, string DialogToken); 8 | 9 | internal enum DeleteInstanceResult 10 | { 11 | Success, 12 | InstanceNotFound, 13 | Unauthorized 14 | } 15 | 16 | internal sealed class InstanceService 17 | { 18 | private readonly IStorageApi _storageApi; 19 | private readonly IDialogTokenValidator _dialogTokenValidator; 20 | 21 | public InstanceService(IStorageApi storageApi, IDialogTokenValidator dialogTokenValidator) 22 | { 23 | _storageApi = storageApi ?? throw new ArgumentNullException(nameof(storageApi)); 24 | _dialogTokenValidator = dialogTokenValidator ?? throw new ArgumentNullException(nameof(dialogTokenValidator)); 25 | } 26 | 27 | public async Task Delete(DeleteInstanceDto request, CancellationToken cancellationToken) 28 | { 29 | var instance = await _storageApi 30 | .GetInstance(request.PartyId, request.InstanceGuid, cancellationToken) 31 | .ContentOrDefault(); 32 | 33 | if (instance is null) 34 | { 35 | return DeleteInstanceResult.InstanceNotFound; 36 | } 37 | 38 | var dialogId = request.InstanceGuid.ToVersion7(instance.Created!.Value); 39 | if (!ValidateDialogToken(request.DialogToken, dialogId)) 40 | { 41 | return DeleteInstanceResult.Unauthorized; 42 | } 43 | 44 | // TODO: Skal vi utlede hard delete i noen tilfeller? Basert på status = draft? 45 | await _storageApi.DeleteInstance(request.PartyId, request.InstanceGuid, hard: false, cancellationToken); 46 | return DeleteInstanceResult.Success; 47 | } 48 | 49 | private bool ValidateDialogToken(ReadOnlySpan token, Guid dialogId) 50 | { 51 | const string bearerPrefix = "Bearer "; 52 | token = token.StartsWith(bearerPrefix, StringComparison.OrdinalIgnoreCase) 53 | ? token[bearerPrefix.Length..] 54 | : token; 55 | var result = _dialogTokenValidator.Validate(token, dialogId, ["delete"]); 56 | return result.IsValid; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Common/Extensions/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Altinn.DialogportenAdapter.EventSimulator.Common.StartupLoaders; 2 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Persistance; 3 | 4 | namespace Altinn.DialogportenAdapter.EventSimulator.Common.Extensions; 5 | 6 | internal static class ServiceCollectionExtensions 7 | { 8 | public static IHostApplicationBuilder ReplaceLocalDevelopmentResources(this IHostApplicationBuilder builder) 9 | { 10 | if (!builder.Environment.IsDevelopment() || 11 | !builder.Configuration.TryGetLocalDevelopmentSettings(out var opt)) 12 | { 13 | return builder; 14 | } 15 | 16 | builder.Services 17 | .DoIf(opt.DisableAzureStorage, x => x.Replace(ServiceLifetime.Transient)) 18 | .DoIf(opt.DisableAzureStorage, x => x.RemoveAllImplementationTypes(typeof(AzureTableStartupLoader))); 19 | 20 | return builder; 21 | } 22 | 23 | private static IServiceCollection Replace( 24 | this IServiceCollection services, 25 | ServiceLifetime lifetime) 26 | where TService : class 27 | where TImplementation : class, TService 28 | { 29 | var serviceType = typeof(TService); 30 | var implementationType = typeof(TImplementation); 31 | // Remove all matching service registrations 32 | for (var i = services.Count - 1; i >= 0; i--) 33 | { 34 | if (services[i].ServiceType == serviceType) services.RemoveAt(i); 35 | } 36 | 37 | services.Add(ServiceDescriptor.Describe(serviceType, implementationType, lifetime)); 38 | return services; 39 | } 40 | 41 | private static IServiceCollection DoIf(this IServiceCollection services, bool predicate, Action action) 42 | { 43 | if (predicate) action(services); 44 | return services; 45 | } 46 | 47 | private static IServiceCollection RemoveAllImplementationTypes(this IServiceCollection collection, Type implementationType) 48 | { 49 | ArgumentNullException.ThrowIfNull(implementationType); 50 | 51 | for (var i = collection.Count - 1; i >= 0; i--) 52 | { 53 | if (collection[i].ImplementationType == implementationType) collection.RemoveAt(i); 54 | } 55 | 56 | return collection; 57 | } 58 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Settings.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using Altinn.ApiClients.Maskinporten.Config; 3 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Persistance; 4 | 5 | namespace Altinn.DialogportenAdapter.EventSimulator; 6 | 7 | public sealed record Settings( 8 | DialogportenAdapterSettings DialogportenAdapter, 9 | WolverineSettings WolverineSettings); 10 | 11 | public sealed record WolverineSettings(string ServiceBusConnectionString, int ListenerCount = 50); 12 | 13 | public sealed record DialogportenAdapterSettings( 14 | MaskinportenSettings Maskinporten, 15 | AltinnPlatformSettings Altinn, 16 | AdapterSettings Adapter, 17 | AzureStorageSettings AzureStorage, 18 | EventSimulatorSettings EventSimulator); 19 | 20 | public sealed record EventSimulatorSettings(bool EnableUpdateStream = false); 21 | 22 | public record AzureStorageSettings(string ConnectionString) 23 | { 24 | public static string GetTableName(IHostEnvironment hostEnvironment) => 25 | $"{hostEnvironment.EnvironmentName}{nameof(MigrationPartitionEntity)}"; 26 | } 27 | 28 | public record AdapterSettings(Uri InternalBaseUri); 29 | 30 | public sealed record AltinnPlatformSettings(Uri ApiStorageEndpoint); 31 | 32 | public record KeyVaultSettings(string ClientId, string ClientSecret, string TenantId, string SecretUri); 33 | 34 | internal sealed record LocalDevelopmentSettings(bool DisableAzureStorage) 35 | { 36 | public const string ConfigurationSectionName = "LocalDevelopment"; 37 | } 38 | 39 | internal static class LocalDevelopmentExtensions 40 | { 41 | public static bool TryGetLocalDevelopmentSettings(this IConfiguration configuration, [NotNullWhen(true)] out LocalDevelopmentSettings? settings) 42 | { 43 | settings = configuration 44 | .GetSection(LocalDevelopmentSettings.ConfigurationSectionName) 45 | .Get(); 46 | return settings is not null; 47 | } 48 | 49 | public static IConfigurationBuilder AddLocalDevelopmentSettings(this IConfigurationBuilder config, IHostEnvironment hostingEnvironment) 50 | { 51 | const string localAppsettingsJsonFileName = "appsettings.local.json"; 52 | if (!hostingEnvironment.IsDevelopment()) 53 | { 54 | return config; 55 | } 56 | 57 | config.AddJsonFile(localAppsettingsJsonFileName, optional: true, reloadOnChange: true); 58 | return config; 59 | } 60 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/ConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using Azure.Extensions.AspNetCore.Configuration.Secrets; 3 | using Azure.Identity; 4 | using Microsoft.Extensions.FileProviders; 5 | 6 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 7 | 8 | internal static class ConfigurationExtensions 9 | { 10 | public static IConfigurationManager AddCoreClusterSettings(this IConfigurationManager config) 11 | { 12 | const string settingsVolume = "/altinn-appsettings"; 13 | const string jsonFileName = "altinn-dbsettings-secret.json"; 14 | IFileProvider fileProvider = Directory.Exists(settingsVolume) 15 | ? new PhysicalFileProvider(settingsVolume) 16 | : new NullFileProvider(); 17 | config.AddJsonFile(fileProvider, jsonFileName, optional: true, reloadOnChange: true); 18 | return config; 19 | } 20 | 21 | public static IConfigurationManager AddAzureKeyVault(this IConfigurationManager config) 22 | { 23 | var kvSettings = config 24 | .GetSection("kvSetting") 25 | .Get(); 26 | 27 | if (kvSettings is null || 28 | string.IsNullOrWhiteSpace(kvSettings.ClientId) || 29 | string.IsNullOrWhiteSpace(kvSettings.TenantId) || 30 | string.IsNullOrWhiteSpace(kvSettings.ClientSecret) || 31 | string.IsNullOrWhiteSpace(kvSettings.SecretUri)) 32 | { 33 | return config; 34 | } 35 | 36 | var azureCredentials = new ClientSecretCredential( 37 | tenantId: kvSettings.TenantId, 38 | clientId: kvSettings.ClientId, 39 | clientSecret: kvSettings.ClientSecret); 40 | 41 | config.AddAzureKeyVault(new Uri(kvSettings.SecretUri), azureCredentials, 42 | new AzureKeyVaultConfigurationOptions{ ReloadInterval = TimeSpan.FromMinutes(5) }); 43 | 44 | return config; 45 | } 46 | 47 | public static bool TryGetApplicationInsightsConnectionString(this IConfiguration config, [NotNullWhen(true)] out string? applicationInsightsConnectionString) 48 | { 49 | const string vaultApplicationInsightsKey = "ApplicationInsights:InstrumentationKey"; 50 | var foo = config[vaultApplicationInsightsKey]; 51 | applicationInsightsConnectionString = foo is not null 52 | ? $"InstrumentationKey={foo}" 53 | : null; 54 | return applicationInsightsConnectionString is not null; 55 | } 56 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Constants.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Dialogporten; 3 | using Altinn.Platform.Storage.Interface.Enums; 4 | 5 | namespace Altinn.DialogportenAdapter.WebApi.Common; 6 | 7 | internal static class Constants 8 | { 9 | public const int DefaultMaxStringLength = 255; 10 | 11 | public const string InstanceDataValueDialogIdKey = "dialog.id"; 12 | public const string InstanceDataValueDisableSyncKey = "dialog.disableAutomaticSync"; 13 | 14 | public const string PartyIdUrnPrefix = "urn:altinn:party:id:"; 15 | public const string UserIdUrnPrefix = "urn:altinn:user:id:"; 16 | public const string PersonUrnPrefix = "urn:altinn:person:identifier-no:"; 17 | public const string OrganizationUrnPrefix = "urn:altinn:organization:identifier-no:"; 18 | public const string DisplayNameUrnPrefix = "urn:altinn:displayName:"; 19 | 20 | public const string DefaultMaskinportenClientDefinitionKey = "DefaultMaskinportenClientDefinitionKey"; 21 | 22 | public static readonly ImmutableArray SupportedEventTypes = 23 | [ 24 | InstanceEventType.Created.ToString(), 25 | InstanceEventType.Deleted.ToString(), 26 | InstanceEventType.Saved.ToString(), 27 | InstanceEventType.Submited.ToString(), 28 | InstanceEventType.Undeleted.ToString(), 29 | InstanceEventType.SubstatusUpdated.ToString(), 30 | InstanceEventType.Signed.ToString(), 31 | InstanceEventType.SentToSign.ToString(), 32 | InstanceEventType.SentToPayment.ToString(), 33 | InstanceEventType.SentToSendIn.ToString(), 34 | InstanceEventType.SentToFormFill.ToString(), 35 | InstanceEventType.InstanceForwarded.ToString(), 36 | InstanceEventType.InstanceRightRevoked.ToString(), 37 | InstanceEventType.NotificationSentSms.ToString(), 38 | InstanceEventType.MessageArchived.ToString(), 39 | InstanceEventType.MessageRead.ToString(), 40 | ]; 41 | 42 | public static readonly ImmutableArray<(DialogGuiActionPriority Priority, int Limit)> PriorityLimits = [ 43 | (DialogGuiActionPriority.Primary, 1), 44 | (DialogGuiActionPriority.Secondary, 1), 45 | (DialogGuiActionPriority.Tertiary, 5 ) 46 | ]; 47 | 48 | internal static class GuiAction 49 | { 50 | public const string GoTo = "DialogGuiActionGoTo"; 51 | public const string Delete = "DialogGuiActionDelete"; 52 | public const string Copy = "DialogGuiActionCopy"; 53 | 54 | public static readonly List Keys = [ GoTo, Delete, Copy ]; 55 | } 56 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Settings.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using Altinn.ApiClients.Maskinporten.Config; 3 | 4 | namespace Altinn.DialogportenAdapter.WebApi; 5 | 6 | public sealed class Settings 7 | { 8 | public required DialogportenAdapterSettings DialogportenAdapter { get; init; } 9 | public required WolverineSettings WolverineSettings { get; init; } 10 | } 11 | 12 | public sealed record WolverineSettings(string ServiceBusConnectionString, int ListenerCount = 50); 13 | 14 | public sealed record DialogportenAdapterSettings( 15 | MaskinportenSettings Maskinporten, 16 | AltinnPlatformSettings Altinn, 17 | DialogportenSettings Dialogporten, 18 | AdapterSettings Adapter, 19 | AuthenticationSettings Authentication); 20 | 21 | public sealed record AuthenticationSettings(string JwtBearerWellKnown); 22 | 23 | public sealed record AdapterSettings(Uri BaseUri, AdapterFeatureFlagSettings? FeatureFlag = null) 24 | { 25 | public AdapterFeatureFlagSettings FeatureFlag { get; } = FeatureFlag ?? new AdapterFeatureFlagSettings(); 26 | } 27 | 28 | public sealed record AdapterFeatureFlagSettings(bool EnableSubmissionTransmissions = false); 29 | 30 | public sealed record DialogportenSettings(Uri BaseUri); 31 | 32 | public sealed record AltinnPlatformSettings(Uri BaseUri, Uri InternalStorageEndpoint, Uri InternalRegisterEndpoint, string SubscriptionKey) 33 | { 34 | public Uri GetAppUriForOrg(string org, string appId) => new($"{BaseUri.Scheme}://{org}.apps.{BaseUri.Host}/{appId}"); 35 | public Uri GetPlatformUri() => new($"{BaseUri.Scheme}://platform.{BaseUri.Host}"); 36 | } 37 | 38 | public sealed record KeyVaultSettings(string ClientId, string ClientSecret, string TenantId, string SecretUri); 39 | 40 | internal sealed record LocalDevelopmentSettings(bool MockDialogportenApi, bool DisableAuth) 41 | { 42 | public const string ConfigurationSectionName = "LocalDevelopment"; 43 | } 44 | 45 | internal static class LocalDevelopmentExtensions 46 | { 47 | public static bool TryGetLocalDevelopmentSettings(this IConfiguration configuration, [NotNullWhen(true)] out LocalDevelopmentSettings? settings) 48 | { 49 | settings = configuration 50 | .GetSection(LocalDevelopmentSettings.ConfigurationSectionName) 51 | .Get(); 52 | return settings is not null; 53 | } 54 | 55 | public static IConfigurationBuilder AddLocalDevelopmentSettings(this IConfigurationBuilder config, IHostEnvironment hostingEnvironment) 56 | { 57 | const string localAppsettingsJsonFileName = "appsettings.local.json"; 58 | if (!hostingEnvironment.IsDevelopment()) 59 | { 60 | return config; 61 | } 62 | 63 | config.AddJsonFile(localAppsettingsJsonFileName, optional: true, reloadOnChange: true); 64 | return config; 65 | } 66 | } -------------------------------------------------------------------------------- /.github/workflows/build-and-analyze.yml: -------------------------------------------------------------------------------- 1 | name: .NET Analysis 2 | on: 3 | push: 4 | branches: [main] 5 | paths-ignore: 6 | - 'test/k6/**' 7 | - '.github/**' 8 | pull_request: 9 | branches: [main] 10 | types: [opened, synchronize, reopened] 11 | workflow_dispatch: 12 | jobs: 13 | build-test-analyze: 14 | name: Build, test & analyze 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Setup .NET 18 | uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1 19 | with: 20 | dotnet-version: | 21 | 9.0.x 22 | - name: Set up Java 23 | uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1 24 | with: 25 | distribution: 'temurin' 26 | java-version: 17 27 | - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1 28 | with: 29 | fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis 30 | - name: Install SonarCloud scanners 31 | run: | 32 | dotnet tool install --global dotnet-sonarscanner 33 | - name: Build & Test 34 | env: 35 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any 36 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 37 | run: | 38 | dotnet-sonarscanner begin /k:"Altinn_altinn-dialogporten-adapter" /o:"altinn" /d:sonar.token="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml" 39 | 40 | dotnet build Altinn.DialogportenAdapter.sln -v q 41 | 42 | dotnet test Altinn.DialogportenAdapter.sln \ 43 | -v q \ 44 | --collect:"XPlat Code Coverage" \ 45 | --results-directory TestResults/ \ 46 | --logger "trx;" \ 47 | --configuration release \ 48 | -- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover 49 | - name: Complete sonar analysis 50 | if: always() 51 | env: 52 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any 53 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 54 | run: | 55 | dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}" 56 | - name: Upload test results 57 | if: always() 58 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 59 | with: 60 | name: TestResults 61 | path: '**/TestResults/*.trx' 62 | - name: Process unit test result 63 | if: always() 64 | uses: NasAmin/trx-parser@359b39f5319df4478443ef1f0eb952f159896995 # v0.7.0 65 | with: 66 | TRX_PATH: ${{ github.workspace }}/TestResults 67 | REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} 68 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/FourHundredLoggingDelegatingHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | 3 | namespace Altinn.DialogportenAdapter.WebApi.Common; 4 | 5 | internal sealed class FourHundredLoggingDelegatingHandler : DelegatingHandler 6 | { 7 | private readonly IHostEnvironment _hostEnvironment; 8 | private readonly ILogger _logger; 9 | 10 | public FourHundredLoggingDelegatingHandler(IHostEnvironment hostEnvironment, ILogger logger) 11 | { 12 | _hostEnvironment = hostEnvironment; 13 | _logger = logger; 14 | } 15 | 16 | protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 17 | { 18 | return /*!_hostEnvironment.IsProduction() &&*/ _logger.IsEnabled(LogLevel.Information) 19 | ? SendAsync_Internal(request, cancellationToken) 20 | : base.SendAsync(request, cancellationToken); 21 | } 22 | 23 | private async Task SendAsync_Internal(HttpRequestMessage request, CancellationToken cancellationToken) 24 | { 25 | await (request.Content?.LoadIntoBufferAsync(cancellationToken) ?? Task.CompletedTask); 26 | var requestContent = new Lazy>(() => 27 | request.Content?.ReadAsStringAsync(cancellationToken) ?? Task.FromResult(string.Empty)); 28 | HttpResponseMessage? response; 29 | 30 | try 31 | { 32 | response = await base.SendAsync(request, cancellationToken); 33 | } 34 | catch (Refit.ApiException e) 35 | { 36 | if (ShouldLog(e.StatusCode)) 37 | { 38 | _logger.LogRequestError(e, request.Method, request.RequestUri, await requestContent.Value, e.StatusCode, e.Content); 39 | } 40 | throw; 41 | } 42 | 43 | if (!ShouldLog(response.StatusCode)) 44 | { 45 | return response; 46 | } 47 | 48 | await response.Content.LoadIntoBufferAsync(cancellationToken); 49 | var responseContent = await response.Content.ReadAsStringAsync(cancellationToken); 50 | _logger.Log400Response(request.Method, request.RequestUri, await requestContent.Value, response.StatusCode, responseContent); 51 | return response; 52 | } 53 | 54 | private static bool ShouldLog(HttpStatusCode statusCode) => 55 | (int)statusCode is >= 400 and < 500 and not 404; 56 | } 57 | 58 | 59 | internal static partial class LogMessages 60 | { 61 | [LoggerMessage(EventId = 0, Level = LogLevel.Warning, Message = "{Method} {RequestUri} resulted in {StatusCode}.\nRequest: {Request}\nResponse: {Response}")] 62 | public static partial void Log400Response(this ILogger logger, HttpMethod method, Uri? requestUri, string? request, HttpStatusCode statusCode, string? response); 63 | 64 | [LoggerMessage(EventId = 0, Level = LogLevel.Warning, Message = "{Method} {RequestUri} resulted in {StatusCode}.\nRequest: {Request}\nResponse: {Response}")] 65 | public static partial void LogRequestError(this ILogger logger, Exception exception, HttpMethod method, Uri? requestUri, string? request, HttpStatusCode statusCode, string? response); 66 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Infrastructure/Register/IRegisterRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using Altinn.DialogportenAdapter.WebApi.Common; 3 | using ZiggyCreatures.Caching.Fusion; 4 | 5 | namespace Altinn.DialogportenAdapter.WebApi.Infrastructure.Register; 6 | 7 | internal interface IRegisterRepository 8 | { 9 | Task> GetActorUrnByUserId(IEnumerable userIds, CancellationToken cancellationToken); 10 | Task> GetActorUrnByPartyId(IEnumerable partyIds, CancellationToken cancellationToken); 11 | } 12 | 13 | internal sealed class RegisterRepository : IRegisterRepository 14 | { 15 | private readonly IRegisterApi _registerApi; 16 | private readonly IFusionCache _cache; 17 | 18 | public RegisterRepository(IRegisterApi registerApi, IFusionCache cache) 19 | { 20 | _registerApi = registerApi; 21 | _cache = cache; 22 | } 23 | 24 | public async Task> GetActorUrnByUserId(IEnumerable userIds, 25 | CancellationToken cancellationToken) 26 | { 27 | var results = await FetchUrns( 28 | userIds.Select(x => Constants.UserIdUrnPrefix + x), 29 | cancellationToken); 30 | return results 31 | .Where(x => x.AktorUrn is not null) 32 | .ToDictionary(x => x.RegisterUrn[Constants.UserIdUrnPrefix.Length..], x => x.AktorUrn!); 33 | } 34 | 35 | public async Task> GetActorUrnByPartyId(IEnumerable partyIds, 36 | CancellationToken cancellationToken) 37 | { 38 | var results = await FetchUrns( 39 | partyIds.Select(x => Constants.PartyIdUrnPrefix + x), 40 | cancellationToken); 41 | return results 42 | .Where(x => x.AktorUrn is not null) 43 | .ToDictionary(x => x.RegisterUrn[Constants.PartyIdUrnPrefix.Length..], x => x.AktorUrn!); 44 | } 45 | 46 | private Task<(string RegisterUrn, string? AktorUrn)[]> FetchUrns( 47 | IEnumerable registerUrns, 48 | CancellationToken cancellationToken) => 49 | Task.WhenAll(registerUrns 50 | .Distinct() 51 | .Select(urn => _cache 52 | .GetOrSetAsync( 53 | key: urn, 54 | factory: ct => FetchUrn(urn, ct), 55 | token: cancellationToken) 56 | .AsTask())); 57 | 58 | private async Task<(string RegisterUrn, string? ActorUrn)> FetchUrn(string registerUrn, 59 | CancellationToken cancellationToken) 60 | { 61 | var results = await _registerApi.GetPartiesByUrns(new PartyQueryRequest([registerUrn]), cancellationToken); 62 | return results.Data.FirstOrDefault() switch 63 | { 64 | null => (registerUrn, null), 65 | { OrganizationIdentifier: { } organizationId } => (registerUrn, Constants.OrganizationUrnPrefix + organizationId), 66 | { PersonIdentifier: { } personId } => (registerUrn, Constants.PersonUrnPrefix + personId), 67 | { DisplayName: { } displayName } => (registerUrn, Constants.DisplayNameUrnPrefix + displayName), 68 | _ => throw new UnreachableException("Invalid response from register.") 69 | }; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/GuidExtensions.cs: -------------------------------------------------------------------------------- 1 | using UUIDNext; 2 | 3 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 4 | 5 | internal static class GuidExtensions 6 | { 7 | /// 8 | /// Creates a deterministic UUID v7 by first creating a UUID v5 based 9 | /// on the parent UUID (namespace) and name, then converting that to 10 | /// a UUID v7 by copying the UUID v7 parts from the parent UUID. 11 | /// 12 | /// 13 | /// Assumes that parentV7Id is on UUID v7 format. 14 | /// 15 | /// 16 | /// 17 | /// 18 | public static Guid CreateDeterministicSubUuidV7(this Guid parentV7Id, string name) 19 | => Uuid.NewNameBased(parentV7Id, name).CopyUuidV7PartsFrom(parentV7Id); 20 | 21 | public static Guid ToVersion7(this Guid guid, DateTimeOffset timestamp) 22 | { 23 | // Create a buffer for the UUID (16 bytes) 24 | Span uuidBytes = stackalloc byte[16]; 25 | // Copy data from the input GUID into the buffer 26 | guid.TryWriteBytes(uuidBytes, bigEndian: true, out _); 27 | // Get the timestamp in milliseconds since Unix epoch 28 | var unixTimestampMillis = timestamp.ToUnixTimeMilliseconds(); 29 | 30 | // Write the timestamp (48 bits) into the UUID buffer 31 | uuidBytes[0] = (byte)((unixTimestampMillis >> 40) & 0xFF); 32 | uuidBytes[1] = (byte)((unixTimestampMillis >> 32) & 0xFF); 33 | uuidBytes[2] = (byte)((unixTimestampMillis >> 24) & 0xFF); 34 | uuidBytes[3] = (byte)((unixTimestampMillis >> 16) & 0xFF); 35 | uuidBytes[4] = (byte)((unixTimestampMillis >> 8) & 0xFF); 36 | uuidBytes[5] = (byte)(unixTimestampMillis & 0xFF); 37 | 38 | // Set the version to 7 (4 high bits of the 7th byte) 39 | uuidBytes[6] = (byte)((uuidBytes[6] & 0x0F) | 0x70); 40 | 41 | // Set the variant to RFC 4122 (2 most significant bits of the 9th byte to 10) 42 | uuidBytes[8] = (byte)((uuidBytes[8] & 0x3F) | 0x80); 43 | 44 | // Construct and return the UUID 45 | return new Guid(uuidBytes, bigEndian: true); 46 | } 47 | 48 | private static Guid CopyUuidV7PartsFrom(this Guid target, Guid source) 49 | { 50 | // Create buffers for the source and target GUIDs (16 bytes each) 51 | Span sourceBytes = stackalloc byte[16]; 52 | Span targetBytes = stackalloc byte[16]; 53 | 54 | // Copy data from the source and target GUIDs into the buffers 55 | source.TryWriteBytes(sourceBytes, bigEndian: true, out _); 56 | target.TryWriteBytes(targetBytes, bigEndian: true, out _); 57 | 58 | // Copy the first 48 bits (6 bytes) from the source to the target (timestamp) 59 | sourceBytes[..6].CopyTo(targetBytes[..6]); 60 | 61 | // Copy only the four most significant bits of the 7th byte (version) from the source to the target 62 | targetBytes[6] = (byte)((targetBytes[6] & 0x0F) | (sourceBytes[6] & 0xF0)); 63 | 64 | // Copy only the two most significant bits of the 9th byte (variant) from the source to the target 65 | targetBytes[8] = (byte)((targetBytes[8] & 0x3F) | (sourceBytes[8] & 0xC0)); 66 | 67 | // Construct and return the new target GUID 68 | return new Guid(targetBytes, bigEndian: true); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Features/UpdateStream/InstanceUpdateStreamBackgroundService.cs: -------------------------------------------------------------------------------- 1 | using Altinn.DialogportenAdapter.EventSimulator.Common.Extensions; 2 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Storage; 3 | using Wolverine; 4 | 5 | namespace Altinn.DialogportenAdapter.EventSimulator.Features.UpdateStream; 6 | 7 | internal sealed class InstanceUpdateStreamBackgroundService : BackgroundService 8 | { 9 | private readonly IOrganizationRepository _organizationRepository; 10 | private readonly IInstanceStreamer _instanceStreamer; 11 | private readonly ILogger _logger; 12 | private readonly Settings _settings; 13 | private readonly IServiceProvider _serviceProvider; 14 | 15 | public InstanceUpdateStreamBackgroundService( 16 | IInstanceStreamer instanceStreamer, 17 | ILogger logger, 18 | IOrganizationRepository organizationRepository, 19 | Settings settings, 20 | IServiceProvider serviceProvider) 21 | { 22 | _instanceStreamer = instanceStreamer ?? throw new ArgumentNullException(nameof(instanceStreamer)); 23 | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); 24 | _organizationRepository = organizationRepository ?? throw new ArgumentNullException(nameof(organizationRepository)); 25 | _settings = settings ?? throw new ArgumentNullException(nameof(settings)); 26 | _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); 27 | } 28 | 29 | protected override async Task ExecuteAsync(CancellationToken cancellationToken) 30 | { 31 | if (!_settings.DialogportenAdapter.EventSimulator.EnableUpdateStream) 32 | { 33 | _logger.LogDebug("Update stream processing is disabled."); 34 | return; 35 | } 36 | 37 | var orgs = await _organizationRepository.GetOrganizations(cancellationToken); 38 | _logger.LogInformation("Found {OrgCount} orgs.", orgs.Count); 39 | if (orgs is null || orgs.Count == 0) 40 | { 41 | throw new InvalidOperationException("No orgs were found."); 42 | } 43 | 44 | var from = DateTimeOffset.UtcNow.AddMinutes(-10); 45 | await Task.WhenAll(orgs.Select(org => Produce(org, from, cancellationToken))); 46 | } 47 | 48 | private async Task Produce(string org, DateTimeOffset from, CancellationToken cancellationToken) 49 | { 50 | while (!cancellationToken.IsCancellationRequested) 51 | { 52 | try 53 | { 54 | await foreach (var instanceDto in _instanceStreamer.InstanceUpdateStream( 55 | org, 56 | from: from, 57 | cancellationToken)) 58 | { 59 | using var scope = _serviceProvider.CreateScope(); 60 | var bus = scope.ServiceProvider.GetRequiredService(); 61 | await bus.SendAsync(instanceDto.ToSyncInstanceCommand(isMigration: false)); 62 | from = instanceDto.LastChanged > from ? instanceDto.LastChanged : from; 63 | } 64 | } 65 | catch (OperationCanceledException) { /* Swallow by design */ } 66 | catch (Exception e) 67 | { 68 | _logger.LogError(e, "Error while consuming instance update stream for org {org}. Attempting to reset stream in 5 seconds.", org); 69 | await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); 70 | } 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Infrastructure/Storage/IApplicationRepository.cs: -------------------------------------------------------------------------------- 1 | using Altinn.DialogportenAdapter.WebApi.Common.Extensions; 2 | using Altinn.Platform.Storage.Interface.Models; 3 | using ZiggyCreatures.Caching.Fusion; 4 | 5 | namespace Altinn.DialogportenAdapter.WebApi.Infrastructure.Storage; 6 | 7 | internal interface IApplicationRepository 8 | { 9 | Task GetApplication(string appId, CancellationToken cancellationToken); 10 | Task<(bool, Application?)> TryGetApplicationIfCached(string appId, CancellationToken cancellationToken); 11 | Task GetApplicationTexts(string appId, CancellationToken cancellationToken); 12 | } 13 | 14 | internal sealed class ApplicationRepository(IApplicationsApi applicationsApi, IFusionCache cache) : IApplicationRepository 15 | { 16 | public Task GetApplication(string appId, CancellationToken cancellationToken) => 17 | cache.GetOrSetAsync( 18 | key: $"{nameof(Application)}:{appId}", 19 | factory: (ct) => FetchApplication(appId, ct), 20 | token: cancellationToken).AsTask(); 21 | 22 | public async Task<(bool, Application?)> TryGetApplicationIfCached(string appId, CancellationToken cancellationToken) 23 | { 24 | var maybeApplication = await cache.TryGetAsync(key: $"{nameof(Application)}:{appId}", token: cancellationToken); 25 | return maybeApplication.HasValue ? (true, maybeApplication.Value) : (false, null); 26 | } 27 | 28 | public Task GetApplicationTexts(string appId, CancellationToken cancellationToken) => 29 | cache.GetOrSetAsync( 30 | key: $"{nameof(ApplicationTexts)}:{appId}", 31 | factory: (ct) => FetchApplicationTexts(appId, ct), 32 | token: cancellationToken).AsTask(); 33 | 34 | private async Task FetchApplicationTexts(string appId, CancellationToken cancellationToken) 35 | { 36 | string[] predefinedLanguages = ["nb", "nn", "en"]; 37 | var orgApp = appId.Split('/', StringSplitOptions.RemoveEmptyEntries); 38 | if (orgApp.Length != 2) 39 | { 40 | throw new ArgumentException($"Expected appId in 'org/app' format, got '{appId}'.", nameof(appId)); 41 | } 42 | var tasks = predefinedLanguages.Select(lang => applicationsApi.GetApplicationTexts(orgApp[0], orgApp[1], lang, cancellationToken)); 43 | var responses = await Task.WhenAll(tasks); 44 | 45 | var textResources = responses 46 | .Where(response => response.IsSuccessful) 47 | .Select(response => response.Content!) 48 | .ToList(); 49 | 50 | return new ApplicationTexts 51 | { 52 | Translations = textResources.Select(textResource => new ApplicationTextsTranslation 53 | { 54 | Language = textResource.Language, 55 | Texts = CreateTextsDictionary(textResource.Resources) 56 | }).ToList() 57 | }; 58 | } 59 | 60 | internal static Dictionary CreateTextsDictionary(IEnumerable resources) 61 | { 62 | var texts = new Dictionary(); 63 | 64 | foreach (var resource in resources) 65 | { 66 | if (resource.Id is null) 67 | { 68 | continue; 69 | } 70 | 71 | texts.TryAdd(resource.Id, resource.Value); 72 | } 73 | 74 | return texts; 75 | } 76 | 77 | private async Task FetchApplication(string appId, CancellationToken cancellationToken) => 78 | await applicationsApi.GetApplication(appId, cancellationToken).ContentOrDefault(); 79 | } 80 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Features/HistoryStream/MigrationPartitionCommandHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | using Altinn.DialogportenAdapter.Contracts; 3 | using Altinn.DialogportenAdapter.EventSimulator.Common.Extensions; 4 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Persistance; 5 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Storage; 6 | using Wolverine.Attributes; 7 | 8 | namespace Altinn.DialogportenAdapter.EventSimulator.Features.HistoryStream; 9 | 10 | public static class MigrationPartitionCommandHandler 11 | { 12 | public static async Task<(MigrationPartitionEntity, IAsyncEnumerable)> Before( 13 | MigratePartitionCommand command, 14 | IMigrationPartitionRepository repo, 15 | IInstanceStreamer instanceStreamer, 16 | CancellationToken cancellationToken) 17 | { 18 | var entity = command.IsTest 19 | ? ToEntity(command) 20 | : await repo.Get(command.Partition, command.Organization, cancellationToken) ?? ToEntity(command); 21 | 22 | DateTimeOffset from = command.Partition.ToDateTime(TimeOnly.MinValue, DateTimeKind.Local); 23 | DateTimeOffset to = entity.Checkpoint ??= command.Partition.ToDateTime(TimeOnly.MaxValue, DateTimeKind.Local); 24 | 25 | var stream = instanceStreamer.InstanceStream( 26 | org: command.Organization, 27 | partyId: command.Party, 28 | from: from, 29 | to: to, 30 | sortOrder: IInstanceStreamer.Order.Descending, 31 | cancellationToken: cancellationToken); 32 | 33 | return (entity, stream); 34 | } 35 | 36 | public static async IAsyncEnumerable Handle( 37 | MigratePartitionCommand _, 38 | MigrationPartitionEntity entity, 39 | IAsyncEnumerable instanceStream, 40 | [EnumeratorCancellation] CancellationToken cancellationToken) 41 | { 42 | if (entity.Complete) yield break; 43 | 44 | await foreach (var instanceDto in instanceStream.WithCancellation(cancellationToken)) 45 | { 46 | yield return instanceDto.ToSyncInstanceCommand(isMigration: true); 47 | entity.InstanceHandled(instanceDto.LastChanged); 48 | } 49 | 50 | entity.Complete = true; 51 | } 52 | 53 | // There is a chance that the same instance will be counted multiple times due to using lte instead of lt 54 | // in the instance streamer. However, if we were to use lt we run the risk of missing instances with equal 55 | // LastChanged timestamps on error recovery. It is better to count instances multiple times, than to skip 56 | // some of them. 57 | // We could use the continuation token of the instance api to resume from the last succeeded instance if the 58 | // instance api were to expose their internal instance ids. That is because the format for the continuation 59 | // token is $"{lastChanged.Ticks};{id}" url encoded twice, where id is the internal instance id. 60 | public static Task After( 61 | MigratePartitionCommand command, 62 | MigrationPartitionEntity entity, 63 | IMigrationPartitionRepository repo, 64 | CancellationToken cancellationToken) => 65 | command.IsTest 66 | ? Task.CompletedTask 67 | : repo.Upsert([entity], cancellationToken); 68 | 69 | private static MigrationPartitionEntity ToEntity(MigratePartitionCommand item) => 70 | new(item.Partition, item.Organization); 71 | } 72 | 73 | [MessageTimeout(60*60)] // 60 minutes to handle very large partitions 74 | public sealed record MigratePartitionCommand(DateOnly Partition, string Organization, string? Party) 75 | { 76 | public bool IsTest => Party is not null; 77 | } -------------------------------------------------------------------------------- /Altinn.DialogportenAdapter.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34322.80 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{530DD6C7-2F29-4B27-9FEE-0F2612F5391B}" 7 | ProjectSection(SolutionItems) = preProject 8 | docker-compose.yml = docker-compose.yml 9 | EndProjectSection 10 | EndProject 11 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Altinn.DialogportenAdapter.WebApi", "src\Altinn.DialogportenAdapter.WebApi\Altinn.DialogportenAdapter.WebApi.csproj", "{3FB848BE-8FD5-4DA2-BC83-EE7CBA8359E3}" 12 | EndProject 13 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Altinn.DialogportenAdapter.EventSimulator", "src\Altinn.DialogportenAdapter.EventSimulator\Altinn.DialogportenAdapter.EventSimulator.csproj", "{330DB9CD-6B16-4138-836C-51383653264B}" 14 | EndProject 15 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A44EA8A5-0709-4630-A781-E3E7F757F129}" 16 | EndProject 17 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{A7008E07-41BC-4D6B-8CD6-FF875D655392}" 18 | EndProject 19 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Altinn.DialogportenAdapter.Unit.Tests", "tests\Altinn.DialogportenAdapter.Unit.Tests\Altinn.DialogportenAdapter.Unit.Tests.csproj", "{B901DA9F-91C7-4AA1-A21E-82A80C4EE59E}" 20 | EndProject 21 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Altinn.DialogportenAdapter.Contracts", "src\Altinn.DialogportenAdapter.Contracts\Altinn.DialogportenAdapter.Contracts.csproj", "{CE2481DE-5070-485C-9956-DAECB13503D5}" 22 | EndProject 23 | Global 24 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 25 | Debug|Any CPU = Debug|Any CPU 26 | Release|Any CPU = Release|Any CPU 27 | EndGlobalSection 28 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 29 | {3FB848BE-8FD5-4DA2-BC83-EE7CBA8359E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {3FB848BE-8FD5-4DA2-BC83-EE7CBA8359E3}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {3FB848BE-8FD5-4DA2-BC83-EE7CBA8359E3}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {3FB848BE-8FD5-4DA2-BC83-EE7CBA8359E3}.Release|Any CPU.Build.0 = Release|Any CPU 33 | {330DB9CD-6B16-4138-836C-51383653264B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {330DB9CD-6B16-4138-836C-51383653264B}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {330DB9CD-6B16-4138-836C-51383653264B}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {330DB9CD-6B16-4138-836C-51383653264B}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {B901DA9F-91C7-4AA1-A21E-82A80C4EE59E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {B901DA9F-91C7-4AA1-A21E-82A80C4EE59E}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {B901DA9F-91C7-4AA1-A21E-82A80C4EE59E}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {B901DA9F-91C7-4AA1-A21E-82A80C4EE59E}.Release|Any CPU.Build.0 = Release|Any CPU 41 | {CE2481DE-5070-485C-9956-DAECB13503D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 42 | {CE2481DE-5070-485C-9956-DAECB13503D5}.Debug|Any CPU.Build.0 = Debug|Any CPU 43 | {CE2481DE-5070-485C-9956-DAECB13503D5}.Release|Any CPU.ActiveCfg = Release|Any CPU 44 | {CE2481DE-5070-485C-9956-DAECB13503D5}.Release|Any CPU.Build.0 = Release|Any CPU 45 | EndGlobalSection 46 | GlobalSection(SolutionProperties) = preSolution 47 | HideSolutionNode = FALSE 48 | EndGlobalSection 49 | GlobalSection(NestedProjects) = preSolution 50 | {330DB9CD-6B16-4138-836C-51383653264B} = {A44EA8A5-0709-4630-A781-E3E7F757F129} 51 | {3FB848BE-8FD5-4DA2-BC83-EE7CBA8359E3} = {A44EA8A5-0709-4630-A781-E3E7F757F129} 52 | {B901DA9F-91C7-4AA1-A21E-82A80C4EE59E} = {A7008E07-41BC-4D6B-8CD6-FF875D655392} 53 | {CE2481DE-5070-485C-9956-DAECB13503D5} = {A44EA8A5-0709-4630-A781-E3E7F757F129} 54 | EndGlobalSection 55 | EndGlobal 56 | -------------------------------------------------------------------------------- /tests/Altinn.DialogportenAdapter.Unit.Tests/Features/Command/Sync/StorageDialogportenDataMergerTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Altinn.DialogportenAdapter.WebApi.Features.Command.Sync; 3 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Storage; 4 | using Altinn.Platform.Storage.Interface.Models; 5 | 6 | namespace Altinn.DialogportenAdapter.Unit.Tests.Features.Command.Sync; 7 | 8 | public class StorageDialogportenDataMergerTest 9 | { 10 | 11 | [Fact] 12 | public void SimpleTest() 13 | { 14 | var instance = new Instance 15 | { 16 | Process = new ProcessState() 17 | { 18 | CurrentTask = new ProcessElementInfo 19 | { 20 | ElementId = "Task1" 21 | } 22 | } 23 | }; 24 | var texts = new ApplicationTexts 25 | { 26 | Translations = 27 | [ 28 | new ApplicationTextsTranslation 29 | { 30 | Language = "nb", 31 | Texts = new Dictionary 32 | { 33 | { "dp.title.Task1.awaitingsignature", "wait!" }, 34 | { "dp.title.Task2.rejected", "begone task 2" }, 35 | { "dp.title._any_.rejected", "begone task any" } 36 | } 37 | } 38 | ] 39 | }; 40 | var localizations = ApplicationTextParser.GetLocalizationsFromApplicationTexts("title", instance, texts, InstanceDerivedStatus.Rejected); 41 | 42 | Assert.Single(localizations); 43 | Assert.Equal("begone task any", localizations.First().Value); 44 | } 45 | 46 | [Fact] 47 | public void TrimStringExceedingMaxLength() 48 | { 49 | var instance = new Instance 50 | { 51 | Process = new ProcessState() 52 | { 53 | CurrentTask = new ProcessElementInfo 54 | { 55 | ElementId = "Task1" 56 | } 57 | } 58 | }; 59 | var texts = new ApplicationTexts 60 | { 61 | Translations = 62 | [ 63 | new ApplicationTextsTranslation 64 | { 65 | Language = "nb", 66 | Texts = new Dictionary 67 | { 68 | { "dp.title.Task1.awaitingsignature", new string('a', 1000) }, 69 | { "dp.summary.Task1.awaitingsignature", new string('b', 1000) }, 70 | { "dp.summary.Task1.rejected", new string('b', 120) }, 71 | } 72 | } 73 | ] 74 | }; 75 | 76 | var localizations = ApplicationTextParser.GetLocalizationsFromApplicationTexts("title", instance, texts, InstanceDerivedStatus.AwaitingSignature); 77 | var summaryLocalizations = ApplicationTextParser.GetLocalizationsFromApplicationTexts("summary", instance, texts, InstanceDerivedStatus.AwaitingSignature); 78 | var summaryLocalizationsShort = ApplicationTextParser.GetLocalizationsFromApplicationTexts("summary", instance, texts, InstanceDerivedStatus.Rejected); 79 | 80 | Assert.Single(localizations); 81 | var title = localizations.First().Value; 82 | Assert.Equal(255, title.Length); 83 | Assert.EndsWith("a...", title, StringComparison.Ordinal); 84 | 85 | 86 | Assert.Single(summaryLocalizations); 87 | var summary = summaryLocalizations.First().Value; 88 | Assert.Equal(255, summary.Length); 89 | Assert.EndsWith("b...", summary, StringComparison.Ordinal); 90 | 91 | 92 | Assert.Single(summaryLocalizationsShort); 93 | var summaryShort = summaryLocalizationsShort.First().Value; 94 | Assert.Equal(120, summaryShort.Length); 95 | Assert.EndsWith("bbb", summaryShort, StringComparison.Ordinal); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /AzureServiceBusEmulator/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "UserConfig": { 3 | "Namespaces": [ 4 | { 5 | "Name": "sbemulatorns", 6 | "Queues": [ 7 | // { 8 | // "Name": "queue.1", 9 | // "Properties": { 10 | // "DeadLetteringOnMessageExpiration": false, 11 | // "DefaultMessageTimeToLive": "PT1H", 12 | // "DuplicateDetectionHistoryTimeWindow": "PT20S", 13 | // "ForwardDeadLetteredMessagesTo": "", 14 | // "ForwardTo": "", 15 | // "LockDuration": "PT1M", 16 | // "MaxDeliveryCount": 10, 17 | // "RequiresDuplicateDetection": false, 18 | // "RequiresSession": false 19 | // } 20 | // } 21 | ], 22 | 23 | "Topics": [ 24 | { 25 | "Name": "topic.1", 26 | "Properties": { 27 | "DefaultMessageTimeToLive": "PT1H", 28 | "DuplicateDetectionHistoryTimeWindow": "PT20S", 29 | "RequiresDuplicateDetection": false 30 | }, 31 | "Subscriptions": [ 32 | { 33 | "Name": "subscription.1", 34 | "Properties": { 35 | "DeadLetteringOnMessageExpiration": false, 36 | "DefaultMessageTimeToLive": "PT1H", 37 | "LockDuration": "PT1M", 38 | "MaxDeliveryCount": 10, 39 | "ForwardDeadLetteredMessagesTo": "", 40 | "ForwardTo": "", 41 | "RequiresSession": false 42 | }, 43 | "Rules": [ 44 | { 45 | "Name": "app-prop-filter-1", 46 | "Properties": { 47 | "FilterType": "Correlation", 48 | "CorrelationFilter": { 49 | "ContentType": "application/text", 50 | "CorrelationId": "id1", 51 | "Label": "subject1", 52 | "MessageId": "msgid1", 53 | "ReplyTo": "someQueue", 54 | "ReplyToSessionId": "sessionId", 55 | "SessionId": "session1", 56 | "To": "xyz" 57 | } 58 | } 59 | } 60 | ] 61 | }, 62 | { 63 | "Name": "subscription.2", 64 | "Properties": { 65 | "DeadLetteringOnMessageExpiration": false, 66 | "DefaultMessageTimeToLive": "PT1H", 67 | "LockDuration": "PT1M", 68 | "MaxDeliveryCount": 10, 69 | "ForwardDeadLetteredMessagesTo": "", 70 | "ForwardTo": "", 71 | "RequiresSession": false 72 | }, 73 | "Rules": [ 74 | { 75 | "Name": "user-prop-filter-1", 76 | "Properties": { 77 | "FilterType": "Correlation", 78 | "CorrelationFilter": { 79 | "Properties": { 80 | "prop3": "value3" 81 | } 82 | } 83 | } 84 | } 85 | ] 86 | }, 87 | { 88 | "Name": "subscription.3", 89 | "Properties": { 90 | "DeadLetteringOnMessageExpiration": false, 91 | "DefaultMessageTimeToLive": "PT1H", 92 | "LockDuration": "PT1M", 93 | "MaxDeliveryCount": 10, 94 | "ForwardDeadLetteredMessagesTo": "", 95 | "ForwardTo": "", 96 | "RequiresSession": false 97 | } 98 | } 99 | ] 100 | } 101 | ] 102 | } 103 | ], 104 | "Logging": { 105 | "Type": "File" 106 | } 107 | } 108 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Features/HistoryStream/MigrationPartitionService.cs: -------------------------------------------------------------------------------- 1 | using Altinn.DialogportenAdapter.EventSimulator.Common.StartupLoaders; 2 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Persistance; 3 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Storage; 4 | using Wolverine; 5 | 6 | namespace Altinn.DialogportenAdapter.EventSimulator.Features.HistoryStream; 7 | 8 | internal sealed class MigrationPartitionService 9 | { 10 | private readonly IOrganizationRepository _organizationRepository; 11 | private readonly IMigrationPartitionRepository _migrationPartitionRepository; 12 | private readonly IMessageBus _messageBus; 13 | 14 | public MigrationPartitionService( 15 | IOrganizationRepository organizationRepository, 16 | IMigrationPartitionRepository migrationPartitionRepository, 17 | IMessageBus messageBus) 18 | { 19 | _organizationRepository = organizationRepository ?? throw new ArgumentNullException(nameof(organizationRepository)); 20 | _migrationPartitionRepository = migrationPartitionRepository ?? throw new ArgumentNullException(nameof(migrationPartitionRepository)); 21 | _messageBus = messageBus ?? throw new ArgumentNullException(nameof(messageBus)); 22 | } 23 | 24 | public async Task Handle(MigrationCommand command, CancellationToken cancellationToken) 25 | { 26 | if (command.Party is not null && string.IsNullOrWhiteSpace(command.Party)) 27 | { 28 | throw new ArgumentException("Party cannot be empty when provided.", nameof(command)); 29 | } 30 | 31 | if (OrganizationStartupLoader.LocalLoadDate < command.To && !command.Force) 32 | { 33 | throw new InvalidOperationException($"Cannot migrate instances after {OrganizationStartupLoader.LocalLoadDate} (use force:true to override)"); 34 | } 35 | 36 | var organizations = await GetOrganizations(command, cancellationToken); 37 | 38 | var partitionEntities = Enumerable 39 | .Range(0, command.To.DayNumber - command.From.DayNumber + 1) 40 | .Select(offset => command.To.AddDays(-offset)) 41 | .SelectMany(_ => organizations, (day, org) => new MigrationPartitionEntity(day, org)) 42 | .ToList(); 43 | 44 | if (ShouldSkipExistingPartitions(command)) 45 | { 46 | partitionEntities = partitionEntities 47 | .Except(await _migrationPartitionRepository.GetExistingPartitions(partitionEntities, cancellationToken)) 48 | .ToList(); 49 | } 50 | 51 | if (!command.IsTest) 52 | { 53 | await _migrationPartitionRepository.Upsert(partitionEntities, cancellationToken); 54 | } 55 | 56 | await Task.WhenAll(partitionEntities 57 | .Select(x => new MigratePartitionCommand(x.Partition, x.Organization, command.Party)) 58 | .Select(x => _messageBus 59 | .SendAsync(x) 60 | .AsTask())); 61 | } 62 | 63 | private static bool ShouldSkipExistingPartitions(MigrationCommand command) => 64 | !command.Force && !command.IsTest; 65 | 66 | private async Task> GetOrganizations(MigrationCommand command, CancellationToken cancellationToken) 67 | { 68 | var validOrganizations = await _organizationRepository.GetOrganizations(cancellationToken); 69 | if (!(command.Organizations?.Count > 0)) 70 | { 71 | return validOrganizations; 72 | } 73 | 74 | var invalid = command.Organizations 75 | .Except(validOrganizations) 76 | .ToList(); 77 | 78 | if (invalid.Count > 0) 79 | { 80 | throw new InvalidOperationException( 81 | $"Invalid organizations: {string.Join(", ", invalid)}. Valid " + 82 | $"organizations are: {string.Join(", ", validOrganizations)}"); 83 | } 84 | return command.Organizations; 85 | 86 | } 87 | } 88 | 89 | internal sealed record MigrationCommand( 90 | DateOnly From, 91 | DateOnly To, 92 | List? Organizations, 93 | string? Party, 94 | bool Force = false) 95 | { 96 | public bool IsTest => Party is not null; 97 | } -------------------------------------------------------------------------------- /tests/Altinn.DialogportenAdapter.Unit.Tests/Features/Command/Sync/ReceiptAttachmentVisibilityDeciderTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | using Altinn.DialogportenAdapter.WebApi.Features.Command.Sync; 4 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Dialogporten; 5 | using Altinn.Platform.Storage.Interface.Models; 6 | 7 | namespace Altinn.DialogportenAdapter.Unit.Tests.Features.Command.Sync; 8 | 9 | public class ReceiptAttachmentVisibilityDeciderTests 10 | { 11 | [Fact] 12 | public void GetConsumerType_DataTypeWithAppLogic_ReturnsApi() 13 | { 14 | var application = new Application 15 | { 16 | DataTypes = 17 | [ 18 | new() { Id = "main", AppLogic = new ApplicationLogic() } 19 | ] 20 | }; 21 | 22 | var decider = ReceiptAttachmentVisibilityDecider.Create(application); 23 | var result = decider.GetConsumerType(CreateDataElement("main")); 24 | 25 | Assert.Equal(AttachmentUrlConsumerType.Api, result); 26 | } 27 | 28 | [Fact] 29 | public void GetConsumerType_DataTypeWithAllowedContributorsAppOwned_ReturnsApi() 30 | { 31 | var application = new Application 32 | { 33 | DataTypes = 34 | [ 35 | new() { Id = "attachment", AllowedContributors = ["endUser", "app:owned"] } 36 | ] 37 | }; 38 | 39 | var decider = ReceiptAttachmentVisibilityDecider.Create(application); 40 | var result = decider.GetConsumerType(CreateDataElement("attachment")); 41 | 42 | Assert.Equal(AttachmentUrlConsumerType.Api, result); 43 | } 44 | 45 | [Fact] 46 | public void GetConsumerType_DataTypeWithLegacyAppOwnedContributers_ReturnsApi() 47 | { 48 | var legacyDataType = new DataType { Id = "legacy" }; 49 | #pragma warning disable CS0618 // AllowedContributers is kept for backwards compatibility 50 | legacyDataType.AllowedContributers = ["app:owned"]; 51 | #pragma warning restore CS0618 52 | 53 | var application = new Application 54 | { 55 | DataTypes = [legacyDataType] 56 | }; 57 | 58 | var decider = ReceiptAttachmentVisibilityDecider.Create(application); 59 | var result = decider.GetConsumerType(CreateDataElement("legacy")); 60 | 61 | Assert.Equal(AttachmentUrlConsumerType.Api, result); 62 | } 63 | 64 | [Fact] 65 | public void GetConsumerType_RefDataAsPdf_ReturnsGui() 66 | { 67 | var application = new Application 68 | { 69 | DataTypes = 70 | [ 71 | new() { Id = "ref-data-as-pdf" } 72 | ] 73 | }; 74 | 75 | var decider = ReceiptAttachmentVisibilityDecider.Create(application); 76 | var result = decider.GetConsumerType(CreateDataElement("ref-data-as-pdf")); 77 | 78 | Assert.Equal(AttachmentUrlConsumerType.Gui, result); 79 | } 80 | 81 | [Fact] 82 | public void GetConsumerType_DataTypeWithHiddenGrouping_ReturnsApi() 83 | { 84 | var application = new Application 85 | { 86 | DataTypes = 87 | [ 88 | new() { Id = "formsource", Grouping = "group.formdatasource" } 89 | ] 90 | }; 91 | 92 | var decider = ReceiptAttachmentVisibilityDecider.Create(application); 93 | var result = decider.GetConsumerType(CreateDataElement("formsource")); 94 | 95 | Assert.Equal(AttachmentUrlConsumerType.Api, result); 96 | } 97 | 98 | [Fact] 99 | public void GetConsumerType_DataTypeNotConfigured_UsesGui() 100 | { 101 | var application = new Application { DataTypes = [] }; 102 | 103 | var decider = ReceiptAttachmentVisibilityDecider.Create(application); 104 | var result = decider.GetConsumerType(CreateDataElement("unknown")); 105 | 106 | Assert.Equal(AttachmentUrlConsumerType.Gui, result); 107 | } 108 | 109 | [Fact] 110 | public void GetConsumerType_DataElementWithoutDataType_UsesGui() 111 | { 112 | var application = new Application { DataTypes = [] }; 113 | 114 | var decider = ReceiptAttachmentVisibilityDecider.Create(application); 115 | var result = decider.GetConsumerType(CreateDataElement(null)); 116 | 117 | Assert.Equal(AttachmentUrlConsumerType.Gui, result); 118 | } 119 | 120 | private static DataElement CreateDataElement(string? dataType) => 121 | new() 122 | { 123 | Id = Guid.NewGuid().ToString(), 124 | DataType = dataType 125 | }; 126 | } 127 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Features/Command/Sync/ReceiptAttachmentVisibilityDecider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | using Altinn.Platform.Storage.Interface.Models; 6 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Dialogporten; 7 | 8 | namespace Altinn.DialogportenAdapter.WebApi.Features.Command.Sync; 9 | 10 | internal sealed class ReceiptAttachmentVisibilityDecider 11 | { 12 | private const string RefDataAsPdfDataTypeId = "ref-data-as-pdf"; 13 | private const string AppOwnedContributor = "app:owned"; 14 | private static readonly HashSet HiddenGroupingResourceKeys = 15 | // Sourced from https://raw.githubusercontent.com/Altinn/altinn-receipt/main/src/backend/Altinn.Receipt/appsettings.json 16 | new(["group.formdatahtml", "group.formdatasource", "group.signaturesource", "group.paymentsource", "group.activities"], StringComparer.Ordinal); 17 | 18 | private readonly Dictionary _dataTypesById; 19 | private readonly HashSet _dataTypeIdsExcludedFromGui; 20 | 21 | private ReceiptAttachmentVisibilityDecider( 22 | Dictionary dataTypesById, 23 | HashSet dataTypeIdsExcludedFromGui) 24 | { 25 | _dataTypesById = dataTypesById; 26 | _dataTypeIdsExcludedFromGui = dataTypeIdsExcludedFromGui; 27 | } 28 | 29 | public static ReceiptAttachmentVisibilityDecider Create(Application application) 30 | { 31 | var dataTypes = application?.DataTypes ?? []; 32 | 33 | var dataTypesById = new Dictionary(StringComparer.OrdinalIgnoreCase); 34 | foreach (var dataType in dataTypes) 35 | { 36 | if (!string.IsNullOrWhiteSpace(dataType.Id)) 37 | { 38 | dataTypesById[dataType.Id] = dataType; 39 | } 40 | } 41 | 42 | var excludedDataTypes = dataTypes 43 | .Where(ShouldExcludeFromGui) 44 | .Select(dt => dt.Id) 45 | .Where(id => !string.IsNullOrWhiteSpace(id)) 46 | .ToHashSet(StringComparer.OrdinalIgnoreCase); 47 | 48 | return new ReceiptAttachmentVisibilityDecider(dataTypesById, excludedDataTypes); 49 | } 50 | 51 | public AttachmentUrlConsumerType GetConsumerType(DataElement dataElement) 52 | { 53 | return ShouldBeVisible(dataElement) 54 | ? AttachmentUrlConsumerType.Gui 55 | : AttachmentUrlConsumerType.Api; 56 | } 57 | 58 | private bool ShouldBeVisible(DataElement? dataElement) 59 | { 60 | if (dataElement is null) 61 | { 62 | return false; 63 | } 64 | 65 | var dataTypeId = dataElement.DataType; 66 | if (string.IsNullOrWhiteSpace(dataTypeId)) 67 | { 68 | // No data type metadata means we fall back to making the attachment visible 69 | return true; 70 | } 71 | 72 | if (string.Equals(dataTypeId, RefDataAsPdfDataTypeId, StringComparison.OrdinalIgnoreCase)) 73 | { 74 | return true; 75 | } 76 | 77 | if (_dataTypeIdsExcludedFromGui.Contains(dataTypeId)) 78 | { 79 | return false; 80 | } 81 | 82 | if (_dataTypesById.TryGetValue(dataTypeId, out var dataType) && 83 | !string.IsNullOrWhiteSpace(dataType.Grouping) && 84 | HiddenGroupingResourceKeys.Contains(dataType.Grouping)) 85 | { 86 | return false; 87 | } 88 | 89 | return true; 90 | } 91 | 92 | private static bool ShouldExcludeFromGui(DataType dataType) 93 | { 94 | if (string.IsNullOrWhiteSpace(dataType.Id)) 95 | { 96 | return false; 97 | } 98 | 99 | if (string.Equals(dataType.Id, RefDataAsPdfDataTypeId, StringComparison.OrdinalIgnoreCase)) 100 | { 101 | return false; 102 | } 103 | 104 | if (dataType.AppLogic is not null) 105 | { 106 | return true; 107 | } 108 | 109 | if (ContainsAppOwned(dataType.AllowedContributors)) 110 | { 111 | return true; 112 | } 113 | 114 | #pragma warning disable CS0618 // AllowedContributers is kept for backwards compatibility 115 | if (ContainsAppOwned(dataType.AllowedContributers)) 116 | { 117 | #pragma warning restore CS0618 118 | return true; 119 | } 120 | 121 | return false; 122 | } 123 | 124 | private static bool ContainsAppOwned(IEnumerable? values) => 125 | values is not null && values.Any(value => string.Equals(value, AppOwnedContributor, StringComparison.Ordinal)); 126 | } 127 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Features/Command/Sync/ApplicationTextParser.cs: -------------------------------------------------------------------------------- 1 | using Altinn.DialogportenAdapter.WebApi.Common; 2 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Dialogporten; 3 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Storage; 4 | using Altinn.Platform.Storage.Interface.Models; 5 | 6 | namespace Altinn.DialogportenAdapter.WebApi.Features.Command.Sync; 7 | 8 | public static class ApplicationTextParser 9 | { 10 | private const int DefaultMaxLength = 255; 11 | private const string TruncateSuffix = "..."; 12 | 13 | /// 14 | /// This will attempt to find a particular key from the application texts for this app. The order of keys are as follows: 15 | /// 1. Active task for derived status 16 | /// 2. Active task 17 | /// 3. Any task for derived status 18 | /// 4. Any task and any derived status 19 | /// The keys have the following format (all lowercase): dp.<content_type>[.<task>[.<derived_status>]] 20 | /// 21 | /// EBNF: 22 | /// identifier ::= "dp." content_type ( "." task_part )? 23 | /// task_part ::= task ( "." state )? 24 | /// content_type ::= "title" | "summary" | "additionalinfo" | "primaryactionlabel" | "deleteactionlabel" | "copyactionlabel" 25 | /// task ::= specific_task | "_any_" 26 | /// specific_task ::= alphanumeric_with_internal_dash_or_underscore 27 | /// state ::= "archivedunconfirmed" | "archivedconfirmed" | "rejected" 28 | /// | "awaitingserviceownerfeedback" | "awaitingconfirmation" 29 | /// | "awaitingsignature" | "awaitingadditionaluserinput" 30 | /// | "awaitinginitialuserinput" 31 | /// | "awaitinginitialuserinputfromprefill" 32 | /// alphanumeric_with_internal_dash_or_underscore ::= alphanumeric ( internal_char* alphanumeric ) 33 | /// internal_char ::= alphanumeric | "_" | "-" 34 | /// alphanumeric ::= letter | digit 35 | /// letter ::= "a".."z" | "A".."Z" 36 | /// digit ::= "0".."9" 37 | /// 38 | /// 39 | /// 40 | /// dp.title 41 | /// dp.summary 42 | /// dp.summary.Task_1 43 | /// dp.summary.Task_1.archivedunconfirmed 44 | /// dp.summary._any_.rejected 45 | /// 46 | /// The requested content type. Should be title, summary, additionalinfo, primaryactionlabel, deleteactionlabel, or copyactionlabel (case-insensitive) 47 | /// The app instance 48 | /// The application texts for all languages 49 | /// The instance derived status 50 | /// The max length of the field (default: 255) 51 | /// A list of localizations (empty if not defined) 52 | internal static List GetLocalizationsFromApplicationTexts( 53 | string contentType, 54 | Instance instance, 55 | ApplicationTexts applicationTexts, 56 | InstanceDerivedStatus instanceDerivedStatus, 57 | int maxLength = DefaultMaxLength) 58 | { 59 | var keysToCheck = new List(4); 60 | var prefix = $"dp.{contentType.ToLower()}"; 61 | var instanceTask = instance.Process?.CurrentTask?.ElementId; 62 | var instanceDerivedStatusString = instanceDerivedStatus.ToString().ToLower(); 63 | if (instanceTask is not null) 64 | { 65 | keysToCheck.Add($"{prefix}.{instanceTask}.{instanceDerivedStatusString}"); 66 | keysToCheck.Add($"{prefix}.{instanceTask}"); 67 | } 68 | keysToCheck.Add($"{prefix}._any_.{instanceDerivedStatusString}"); 69 | keysToCheck.Add(prefix); 70 | 71 | #if DEBUG 72 | Console.WriteLine("Keys to check for content type '{0}': {1}", contentType, string.Join(", ", keysToCheck)); 73 | #endif 74 | 75 | var localizations = new List(); 76 | foreach (var translation in applicationTexts.Translations) 77 | { 78 | if (!LanguageCodes.IsValidTwoLetterLanguageCode(translation.Language)) 79 | { 80 | continue; 81 | } 82 | 83 | foreach (var key in keysToCheck) 84 | { 85 | if (!translation.Texts.TryGetValue(key, out var textResource)) 86 | { 87 | continue; 88 | } 89 | 90 | if (textResource.Length > maxLength) 91 | { 92 | textResource = TruncateText(textResource, maxLength); 93 | } 94 | 95 | localizations.Add(new LocalizationDto 96 | { 97 | LanguageCode = translation.Language, 98 | Value = textResource 99 | }); 100 | break; 101 | } 102 | } 103 | 104 | return localizations; 105 | } 106 | private static string TruncateText(ReadOnlySpan textResource, int maxLength = DefaultMaxLength) 107 | { 108 | // Creates the truncated string without any intermediate string allocations 109 | return string.Create(maxLength, textResource, (span, text) => 110 | { 111 | text[..(maxLength - TruncateSuffix.Length)].CopyTo(span); 112 | TruncateSuffix.AsSpan().CopyTo(span[^TruncateSuffix.Length..]); 113 | }); 114 | 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Common/Extensions/TaskExtentions.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | namespace Altinn.DialogportenAdapter.WebApi.Common.Extensions; 4 | 5 | internal static class TaskExtentions 6 | { 7 | public static TaskAwaiter<(T1, T2)> GetAwaiter( 8 | this (Task, Task) taskTuple) 9 | { 10 | return CombineTasks().GetAwaiter(); 11 | async Task<(T1, T2)> CombineTasks() 12 | { 13 | var (task1, task2) = taskTuple; 14 | await Task.WhenAll(task1, task2).WithAggregatedExceptions(); 15 | return (task1.Result, task2.Result); 16 | } 17 | } 18 | 19 | public static TaskAwaiter<(T1, T2, T3)> GetAwaiter( 20 | this (Task, Task, Task) taskTuple) 21 | { 22 | return CombineTasks().GetAwaiter(); 23 | async Task<(T1, T2, T3)> CombineTasks() 24 | { 25 | var (task1, task2, task3) = taskTuple; 26 | await Task.WhenAll(task1, task2, task3).WithAggregatedExceptions(); 27 | return (task1.Result, task2.Result, task3.Result); 28 | } 29 | } 30 | 31 | public static TaskAwaiter<(T1, T2, T3, T4)> GetAwaiter( 32 | this (Task, Task, Task, Task) taskTuple) 33 | { 34 | return CombineTasks().GetAwaiter(); 35 | async Task<(T1, T2, T3, T4)> CombineTasks() 36 | { 37 | var (task1, task2, task3, task4) = taskTuple; 38 | await Task.WhenAll(task1, task2, task3, task4).WithAggregatedExceptions(); 39 | return (task1.Result, task2.Result, task3.Result, task4.Result); 40 | } 41 | } 42 | 43 | public static TaskAwaiter<(T1, T2, T3, T4, T5)> GetAwaiter( 44 | this (Task, Task, Task, Task, Task) taskTuple) 45 | { 46 | return CombineTasks().GetAwaiter(); 47 | async Task<(T1, T2, T3, T4, T5)> CombineTasks() 48 | { 49 | var (task1, task2, task3, task4, task5) = taskTuple; 50 | await Task.WhenAll(task1, task2, task3, task4, task5).WithAggregatedExceptions(); 51 | return (task1.Result, task2.Result, task3.Result, task4.Result, task5.Result); 52 | } 53 | } 54 | 55 | public static TaskAwaiter<(T1, T2, T3, T4, T5, T6)> GetAwaiter( 56 | this (Task, Task, Task, Task, Task, Task) taskTuple) 57 | { 58 | return CombineTasks().GetAwaiter(); 59 | async Task<(T1, T2, T3, T4, T5, T6)> CombineTasks() 60 | { 61 | var (task1, task2, task3, task4, task5, task6) = taskTuple; 62 | await Task.WhenAll(task1, task2, task3, task4, task5, task6).WithAggregatedExceptions(); 63 | return (task1.Result, task2.Result, task3.Result, task4.Result, task5.Result, task6.Result); 64 | } 65 | } 66 | 67 | public static TaskAwaiter<(T1, T2, T3, T4, T5, T6, T7)> GetAwaiter( 68 | this (Task, Task, Task, Task, Task, Task, Task) taskTuple) 69 | { 70 | return CombineTasks().GetAwaiter(); 71 | async Task<(T1, T2, T3, T4, T5, T6, T7)> CombineTasks() 72 | { 73 | var (task1, task2, task3, task4, task5, task6, task7) = taskTuple; 74 | await Task.WhenAll(task1, task2, task3, task4, task5, task6, task7).WithAggregatedExceptions(); 75 | return (task1.Result, task2.Result, task3.Result, task4.Result, task5.Result, task6.Result, task7.Result); 76 | } 77 | } 78 | 79 | public static TaskAwaiter<(T1, T2, T3, T4, T5, T6, T7, T8)> GetAwaiter( 80 | this (Task, Task, Task, Task, Task, Task, Task, Task) taskTuple) 81 | { 82 | return CombineTasks().GetAwaiter(); 83 | async Task<(T1, T2, T3, T4, T5, T6, T7, T8)> CombineTasks() 84 | { 85 | var (task1, task2, task3, task4, task5, task6, task7, task8) = taskTuple; 86 | await Task.WhenAll(task1, task2, task3, task4, task5, task6, task7, task8).WithAggregatedExceptions(); 87 | return (task1.Result, task2.Result, task3.Result, task4.Result, task5.Result, task6.Result, task7.Result, 88 | task8.Result); 89 | } 90 | } 91 | 92 | public static TaskAwaiter<(T1, T2, T3, T4, T5, T6, T7, T8, T9)> GetAwaiter( 93 | this (Task, Task, Task, Task, Task, Task, Task, Task, Task) taskTuple) 94 | { 95 | return CombineTasks().GetAwaiter(); 96 | async Task<(T1, T2, T3, T4, T5, T6, T7, T8, T9)> CombineTasks() 97 | { 98 | var (task1, task2, task3, task4, task5, task6, task7, task8, task9) = taskTuple; 99 | await Task.WhenAll(task1, task2, task3, task4, task5, task6, task7, task8, task9).WithAggregatedExceptions(); 100 | return (task1.Result, task2.Result, task3.Result, task4.Result, task5.Result, task6.Result, task7.Result, 101 | task8.Result, task9.Result); 102 | } 103 | } 104 | 105 | public static Task WithAggregatedExceptions(this Task @this) 106 | { 107 | return @this 108 | .ContinueWith( 109 | continuationFunction: anteTask => 110 | anteTask is { IsFaulted: true, Exception: not null } && 111 | (anteTask.Exception.InnerExceptions.Count > 1 112 | || anteTask.Exception.InnerException is AggregateException) 113 | ? Task.FromException(anteTask.Exception.Flatten()) 114 | : anteTask, 115 | cancellationToken: CancellationToken.None, 116 | TaskContinuationOptions.ExecuteSynchronously, 117 | scheduler: TaskScheduler.Default) 118 | .Unwrap(); 119 | } 120 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Infrastructure/Storage/IInstanceStreamer.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using System.Runtime.CompilerServices; 3 | using Altinn.DialogportenAdapter.EventSimulator.Common; 4 | using Altinn.DialogportenAdapter.EventSimulator.Common.Extensions; 5 | 6 | namespace Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Storage; 7 | 8 | public sealed record InstanceDto(string AppId, string Id, DateTimeOffset Created, DateTimeOffset LastChanged); 9 | 10 | public interface IInstanceStreamer 11 | { 12 | IAsyncEnumerable InstanceUpdateStream( 13 | string org, 14 | DateTimeOffset from, 15 | CancellationToken cancellationToken); 16 | 17 | IAsyncEnumerable InstanceStream( 18 | string? org = null, 19 | string? appId = null, 20 | string? partyId = null, 21 | DateTimeOffset? from = null, 22 | DateTimeOffset? to = null, 23 | int pageSize = 100, 24 | Order sortOrder = Order.Ascending, 25 | CancellationToken cancellationToken = default); 26 | 27 | public enum Order { Ascending, Descending } 28 | } 29 | 30 | internal sealed class InstanceStreamer : IInstanceStreamer 31 | { 32 | private static readonly List BackoffDelays = 33 | [ 34 | TimeSpan.FromSeconds(5), 35 | TimeSpan.FromSeconds(10), 36 | TimeSpan.FromSeconds(30), 37 | TimeSpan.FromMinutes(1), 38 | TimeSpan.FromMinutes(5), 39 | TimeSpan.FromMinutes(10) 40 | ]; 41 | 42 | private readonly IHttpClientFactory _clientFactory; 43 | private readonly ILogger _logger; 44 | 45 | public InstanceStreamer(IHttpClientFactory clientFactory, ILogger logger) 46 | { 47 | _clientFactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); 48 | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); 49 | } 50 | 51 | public async IAsyncEnumerable InstanceUpdateStream( 52 | string org, 53 | DateTimeOffset from, 54 | [EnumeratorCancellation] CancellationToken cancellationToken) 55 | { 56 | var backoffHandler = new BackoffHandler( 57 | withJitter: true, 58 | startPosition: BackoffHandler.Position.Last, 59 | delays: BackoffDelays); 60 | while (!cancellationToken.IsCancellationRequested) 61 | { 62 | await foreach (var instanceDto in InstanceStream( 63 | org: org, 64 | from: from, 65 | sortOrder: IInstanceStreamer.Order.Ascending, 66 | cancellationToken: cancellationToken)) 67 | { 68 | backoffHandler.Reset(); 69 | from = instanceDto.LastChanged > from ? instanceDto.LastChanged : from; 70 | yield return instanceDto; 71 | } 72 | _logger.LogDebug("Done fetching instances for {org}. New fetch in {delay} +- {jitter}%.", org, backoffHandler.Current, BackoffHandler.JitterPercentage); 73 | await backoffHandler.Delay(cancellationToken); 74 | backoffHandler.Next(); 75 | } 76 | } 77 | 78 | public async IAsyncEnumerable InstanceStream( 79 | string? org = null, 80 | string? appId = null, 81 | string? partyId = null, 82 | DateTimeOffset? from = null, 83 | DateTimeOffset? to = null, 84 | int pageSize = 100, 85 | IInstanceStreamer.Order sortOrder = IInstanceStreamer.Order.Ascending, 86 | [EnumeratorCancellation] CancellationToken cancellationToken = default) 87 | { 88 | if (org is null) ArgumentException.ThrowIfNullOrWhiteSpace(appId); 89 | if (appId is null) ArgumentException.ThrowIfNullOrWhiteSpace(org); 90 | ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize); 91 | 92 | var order = sortOrder switch 93 | { 94 | IInstanceStreamer.Order.Ascending => "asc", 95 | IInstanceStreamer.Order.Descending => "desc", 96 | _ => throw new ArgumentOutOfRangeException(nameof(sortOrder), sortOrder, null) 97 | }; 98 | 99 | if (from > to) yield break; 100 | var client = _clientFactory.CreateClient(Constants.MaskinportenClientDefinitionKey); 101 | var queryString = QueryString 102 | .Create("order", $"{order}:lastChanged") 103 | .Add("MainVersionExclude", "0") // Force inclusion of all Altinn versions (1, 2, 3) 104 | .Add("size", pageSize.ToString(CultureInfo.InvariantCulture)) 105 | .AddIf(from.HasValue, "lastChanged", $"gt:{from?.ToUniversalTime():O}") 106 | .AddIf(to.HasValue, "lastChanged", $"lte:{to?.ToUniversalTime():O}") 107 | .AddIf(org is not null, "org", org!) 108 | .AddIf(appId is not null, "appId", appId!) 109 | .AddIf(partyId is not null, "instanceOwner.partyId", partyId); 110 | 111 | var next = $"storage/api/v1/instances{queryString}"; 112 | 113 | while (next is not null) 114 | { 115 | InstanceQueryResponse? result; 116 | try 117 | { 118 | result = await client.GetFromJsonAsync(next, cancellationToken); 119 | } 120 | catch (Exception e) 121 | { 122 | _logger.LogError(e, "Failed to fetch instance stream."); 123 | yield break; 124 | } 125 | 126 | if (result is null) 127 | { 128 | _logger.LogWarning("No instance response from storage."); 129 | break; 130 | } 131 | 132 | next = result.Next; 133 | foreach (var instance in result.Instances) 134 | { 135 | yield return instance; 136 | } 137 | } 138 | } 139 | 140 | private sealed record InstanceQueryResponse(List Instances, string? Next); 141 | } -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Infrastructure/Dialogporten/MockDialogportenApi.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using Refit; 3 | 4 | namespace Altinn.DialogportenAdapter.WebApi.Infrastructure.Dialogporten; 5 | 6 | internal sealed partial class MockDialogportenApi : IDialogportenApi 7 | { 8 | private static readonly RefitSettings _refitSettings = new(); 9 | 10 | private readonly ILogger _logger; 11 | 12 | public MockDialogportenApi(ILogger logger) 13 | { 14 | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); 15 | } 16 | 17 | public Task> Get(Guid dialogId, CancellationToken cancellationToken = default) 18 | { 19 | Log.LogGetCalled(_logger, dialogId); 20 | var apiResponse = new ApiResponse( 21 | response: new HttpResponseMessage(HttpStatusCode.NotFound), 22 | content: null, 23 | settings: _refitSettings, 24 | error: null); 25 | return Task.FromResult>(apiResponse); 26 | } 27 | 28 | public Task Create(DialogDto dto, bool isSilentUpdate = false, 29 | CancellationToken cancellationToken = default) 30 | { 31 | Log.LogCreateCalled(_logger, dto); 32 | var apiResponse = new ApiResponse( 33 | settings: _refitSettings, 34 | response: new HttpResponseMessage(HttpStatusCode.Created) 35 | { 36 | Headers = { ETag = new System.Net.Http.Headers.EntityTagHeaderValue($"\"{Guid.NewGuid()}\"") } 37 | }, 38 | content: Guid.NewGuid(), 39 | error: null); 40 | return Task.FromResult(apiResponse); 41 | } 42 | 43 | public Task Update(DialogDto dto, Guid revision, bool isSilentUpdate = false, 44 | CancellationToken cancellationToken = default) 45 | { 46 | Log.LogUpdateCalled(_logger, dto, revision); 47 | var apiResponse = new ApiResponse( 48 | settings: _refitSettings, 49 | response: new HttpResponseMessage(HttpStatusCode.NoContent) 50 | { 51 | Headers = { ETag = new System.Net.Http.Headers.EntityTagHeaderValue($"\"{Guid.NewGuid()}\"") } 52 | }, 53 | content: null, 54 | error: null); 55 | return Task.FromResult(apiResponse); 56 | } 57 | 58 | public Task Delete(Guid dialogId, Guid revision, bool isSilentUpdate = false, 59 | CancellationToken cancellationToken = default) 60 | { 61 | Log.LogDeleteCalled(_logger, dialogId, revision); 62 | return Task.CompletedTask; 63 | } 64 | 65 | public Task Purge(Guid dialogId, Guid revision, bool isSilentUpdate = false, 66 | CancellationToken cancellationToken = default) 67 | { 68 | Log.LogPurgeCalled(_logger, dialogId, revision); 69 | return Task.CompletedTask; 70 | } 71 | 72 | public Task Restore(Guid dialogId, Guid revision, bool isSilentUpdate = false, 73 | CancellationToken cancellationToken = default) 74 | { 75 | Log.LogRestoreCalled(_logger, dialogId, revision); 76 | var apiResponse = new ApiResponse( 77 | response: new HttpResponseMessage(HttpStatusCode.NotFound), 78 | content: null, 79 | settings: _refitSettings, 80 | error: null); 81 | return Task.FromResult(apiResponse); 82 | } 83 | 84 | public Task UpdateFormSavedActivityTime(Guid dialogId, Guid activityId, Guid revision, DateTimeOffset newCreatedAt, 85 | CancellationToken cancellationToken = default) 86 | { 87 | Log.LogUpdateFormSavedActivityTimeCalled(_logger, dialogId, activityId, revision, newCreatedAt); 88 | var apiResponse = new ApiResponse( 89 | response: new HttpResponseMessage(HttpStatusCode.NoContent), 90 | content: null, 91 | settings: _refitSettings, 92 | error: null); 93 | return Task.FromResult(apiResponse); 94 | } 95 | 96 | private static partial class Log 97 | { 98 | [LoggerMessage(EventId = 1, Level = LogLevel.Debug, Message = "MockDialogportenApi.Get called with dialogId: {DialogId}")] 99 | public static partial void LogGetCalled(ILogger logger, Guid dialogId); 100 | 101 | [LoggerMessage(EventId = 2, Level = LogLevel.Debug, Message = "MockDialogportenApi.Create called with dialog: {@Dialog}")] 102 | public static partial void LogCreateCalled(ILogger logger, DialogDto dialog); 103 | 104 | [LoggerMessage(EventId = 3, Level = LogLevel.Debug, Message = "MockDialogportenApi.Update called with dialog: {@Dialog}, revision: {Revision}")] 105 | public static partial void LogUpdateCalled(ILogger logger, DialogDto dialog, Guid revision); 106 | 107 | [LoggerMessage(EventId = 4, Level = LogLevel.Debug, Message = "MockDialogportenApi.Delete called with dialogId: {DialogId}, revision: {Revision}")] 108 | public static partial void LogDeleteCalled(ILogger logger, Guid dialogId, Guid revision); 109 | 110 | [LoggerMessage(EventId = 5, Level = LogLevel.Debug, Message = "MockDialogportenApi.Purge called with dialogId: {DialogId}, revision: {Revision}")] 111 | public static partial void LogPurgeCalled(ILogger logger, Guid dialogId, Guid revision); 112 | 113 | [LoggerMessage(EventId = 6, Level = LogLevel.Debug, Message = "MockDialogportenApi.Restore called with dialogId: {DialogId}, revision: {Revision}")] 114 | public static partial void LogRestoreCalled(ILogger logger, Guid dialogId, Guid revision); 115 | 116 | [LoggerMessage(EventId = 7, Level = LogLevel.Debug, Message = "MockDialogportenApi.UpdateFormSavedActivityTime called with dialogId: {DialogId}, activityId: {ActivityId}, revision: {Revision}, newCreatedAt: {NewCreatedAt}")] 117 | public static partial void LogUpdateFormSavedActivityTimeCalled(ILogger logger, Guid dialogId, Guid activityId, Guid revision, DateTimeOffset newCreatedAt); 118 | } 119 | } 120 | 121 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Program.cs: -------------------------------------------------------------------------------- 1 | using Altinn.ApiClients.Maskinporten.Extensions; 2 | using Altinn.ApiClients.Maskinporten.Services; 3 | using Altinn.DialogportenAdapter.Contracts; 4 | using Altinn.DialogportenAdapter.EventSimulator; 5 | using Altinn.DialogportenAdapter.EventSimulator.Common; 6 | using Altinn.DialogportenAdapter.EventSimulator.Common.Extensions; 7 | using Altinn.DialogportenAdapter.EventSimulator.Common.StartupLoaders; 8 | using Altinn.DialogportenAdapter.EventSimulator.Features.HistoryStream; 9 | using Altinn.DialogportenAdapter.EventSimulator.Features.UpdateStream; 10 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Adapter; 11 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Persistance; 12 | using Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Storage; 13 | using Azure.Data.Tables; 14 | using JasperFx; 15 | using Microsoft.AspNetCore.Mvc; 16 | using Refit; 17 | using Wolverine; 18 | using Wolverine.AzureServiceBus; 19 | using Constants = Altinn.DialogportenAdapter.EventSimulator.Common.Constants; 20 | using ContractConstants = Altinn.DialogportenAdapter.Contracts.Constants; 21 | 22 | using var loggerFactory = CreateBootstrapLoggerFactory(); 23 | var bootstrapLogger = loggerFactory.CreateLogger(); 24 | 25 | try 26 | { 27 | await BuildAndRun(args); 28 | } 29 | catch (Exception e) 30 | { 31 | bootstrapLogger.LogCritical(e, "Application terminated unexpectedly"); 32 | throw; 33 | } 34 | 35 | return; 36 | 37 | static Task BuildAndRun(string[] args) 38 | { 39 | var builder = WebApplication.CreateBuilder(args); 40 | 41 | builder.Logging 42 | .ClearProviders() 43 | .AddConsole(); 44 | 45 | builder.Configuration 46 | .AddCoreClusterSettings() 47 | .AddAzureKeyVault() 48 | .AddLocalDevelopmentSettings(builder.Environment); 49 | 50 | var settings = builder.Configuration.Get()!; 51 | 52 | builder.Services.AddWolverine(opts => 53 | { 54 | opts.ConfigureAdapterDefaults(builder.Environment, 55 | settings.WolverineSettings.ServiceBusConnectionString); 56 | opts.Policies.AllListeners(x => x 57 | .ListenerCount(settings.WolverineSettings.ListenerCount) 58 | .ProcessInline()); 59 | opts.Policies.AllSenders(x => x.SendInline()); 60 | 61 | opts.ListenToAzureServiceBusQueue(ContractConstants.EventSimulatorQueueName); 62 | opts.PublishMessage() 63 | .ToAzureServiceBusQueue(ContractConstants.EventSimulatorQueueName); 64 | opts.PublishMessage() 65 | .ToAzureServiceBusQueue(ContractConstants.AdapterHistoryQueueName); 66 | 67 | // Do we need to use duplicate detection? 68 | // .ConfigureQueue(x => x.RequiresDuplicateDetection = true) 69 | // .AddOutgoingRule(new LambdaEnvelopeRule((e, m) => e.Id = m.InstanceId)); 70 | }); 71 | 72 | builder.Services.AddSingleton(settings); 73 | builder.Services.AddHostedService(); 74 | builder.Services.AddStartupLoaders(); 75 | builder.Services.AddSingleton(); 76 | builder.Services.AddTransient(); 77 | builder.Services.AddSingleton(_ => new TableClient( 78 | settings.DialogportenAdapter.AzureStorage.ConnectionString, 79 | AzureStorageSettings.GetTableName(builder.Environment), new TableClientOptions 80 | { 81 | Diagnostics = 82 | { 83 | IsLoggingContentEnabled = true, 84 | LoggedHeaderNames = { "x-ms-request-id", "x-ms-version" }, 85 | LoggedQueryParameters = { "comp" } 86 | } 87 | })); 88 | builder.Services.AddSingleton(); 89 | builder.Services.AddSingleton(); 90 | // Health checks 91 | builder.Services.AddHealthChecks() 92 | .AddCheck("event_simulator_health_check"); 93 | 94 | // Http clients 95 | builder.Services.RegisterMaskinportenClientDefinition( 96 | Constants.MaskinportenClientDefinitionKey, 97 | settings.DialogportenAdapter.Maskinporten); 98 | builder.Services.AddRefitClient() 99 | .ConfigureHttpClient(x => 100 | { 101 | x.BaseAddress = settings.DialogportenAdapter.Adapter.InternalBaseUri; 102 | x.Timeout = Timeout.InfiniteTimeSpan; 103 | }) 104 | .AddMaskinportenHttpMessageHandler(Constants.MaskinportenClientDefinitionKey); 105 | builder.Services.AddHttpClient(Constants.MaskinportenClientDefinitionKey) 106 | .ConfigureHttpClient(x => x.BaseAddress = settings.DialogportenAdapter.Altinn.ApiStorageEndpoint) 107 | .AddMaskinportenHttpMessageHandler(Constants.MaskinportenClientDefinitionKey); 108 | builder.Services.AddTransient(x => RestService 109 | .For(x.GetRequiredService() 110 | .CreateClient(Constants.MaskinportenClientDefinitionKey))); 111 | 112 | builder.ReplaceLocalDevelopmentResources(); 113 | 114 | var app = builder.Build(); 115 | app.UseHttpsRedirection(); 116 | app.MapHealthChecks("/health"); 117 | app.MapOpenApi(); 118 | app.MapPost("/api/migrate", ( 119 | [FromBody] MigrationCommand command, 120 | [FromServices] MigrationPartitionService migrationPartitionService, 121 | CancellationToken cancellationToken) => 122 | migrationPartitionService.Handle(command, cancellationToken)); 123 | app.MapDelete("/api/table/truncate", ( 124 | [FromServices] IMigrationPartitionRepository repo, 125 | CancellationToken cancellationToken) => 126 | repo.Truncate(cancellationToken)) 127 | .ExcludeFromDescription(); 128 | 129 | return app.RunJasperFxCommands(args); 130 | } 131 | 132 | ILoggerFactory CreateBootstrapLoggerFactory() => LoggerFactory.Create(builder => builder 133 | .SetMinimumLevel(LogLevel.Warning) 134 | .AddSimpleConsole(options => 135 | { 136 | options.IncludeScopes = true; 137 | options.UseUtcTimestamp = true; 138 | options.SingleLine = true; 139 | options.TimestampFormat = "yyyy-MM-dd HH:mm:ss "; 140 | })); -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Features/Command/Sync/ActivityDtoTransformer.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using Altinn.DialogportenAdapter.WebApi.Common; 3 | using System.Text.Json; 4 | using Altinn.DialogportenAdapter.WebApi.Common.Extensions; 5 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Dialogporten; 6 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Register; 7 | using Altinn.Platform.Storage.Interface.Enums; 8 | using Altinn.Platform.Storage.Interface.Models; 9 | 10 | namespace Altinn.DialogportenAdapter.WebApi.Features.Command.Sync; 11 | 12 | internal sealed class ActivityDtoTransformer 13 | { 14 | private readonly IRegisterRepository _registerRepository; 15 | 16 | public ActivityDtoTransformer(IRegisterRepository registerRepository) 17 | { 18 | _registerRepository = registerRepository ?? throw new ArgumentNullException(nameof(registerRepository)); 19 | } 20 | 21 | public async Task> GetActivities(InstanceEventList events, InstanceOwner instanceOwner, CancellationToken cancellationToken) 22 | { 23 | var activities = new List(); 24 | var createdFound = false; 25 | var actorUrnByUserId = await LookupUsers(events.InstanceEvents, cancellationToken); 26 | 27 | foreach (var @event in events.InstanceEvents.OrderBy(x => x.Created)) 28 | { 29 | if (!Enum.TryParse(@event.EventType, ignoreCase: true, out var eventType)) 30 | { 31 | continue; 32 | } 33 | 34 | var activityType = eventType switch 35 | { 36 | // When DataId is null the event refers to the instance itself 37 | InstanceEventType.Created when @event.DataId is null && !createdFound => DialogActivityType.DialogCreated, 38 | InstanceEventType.Submited => DialogActivityType.FormSubmitted, 39 | InstanceEventType.Deleted when @event.DataId is null => DialogActivityType.DialogDeleted, 40 | InstanceEventType.Undeleted when @event.DataId is null => DialogActivityType.DialogRestored, 41 | InstanceEventType.Signed => DialogActivityType.SignatureProvided, 42 | InstanceEventType.MessageArchived => DialogActivityType.DialogClosed, 43 | InstanceEventType.MessageRead => DialogActivityType.DialogOpened, 44 | InstanceEventType.SentToSign => DialogActivityType.SentToSigning, 45 | InstanceEventType.SentToPayment => DialogActivityType.SentToPayment, 46 | InstanceEventType.SentToSendIn => DialogActivityType.SentToSendIn, 47 | InstanceEventType.SentToFormFill => DialogActivityType.SentToFormFill, 48 | _ => (DialogActivityType?)null 49 | }; 50 | 51 | if (!activityType.HasValue) 52 | { 53 | continue; 54 | } 55 | 56 | createdFound = createdFound || activityType == DialogActivityType.DialogCreated; 57 | 58 | activities.Add(new ActivityDto 59 | { 60 | Id = @event.Id.Value.ToVersion7(@event.Created.Value), 61 | Type = activityType.Value, 62 | CreatedAt = @event.Created, 63 | PerformedBy = GetPerformedBy(@event.User, instanceOwner, actorUrnByUserId), 64 | Description = activityType == DialogActivityType.Information 65 | ? [ new LocalizationDto { LanguageCode = "nb", Value = eventType.ToString() } ] 66 | : [ ] 67 | }); 68 | } 69 | 70 | var savedEvents = events.InstanceEvents 71 | .OrderBy(x => x.Created) 72 | .Where(x => StringComparer.OrdinalIgnoreCase.Equals(x.EventType, "Saved")) 73 | .Aggregate((SavedActivities: new List(), PreviousActivity: (ActivityDto?)null), (state, @event) => 74 | { 75 | var currentActor = GetPerformedBy(@event.User, instanceOwner, actorUrnByUserId); 76 | if (IsPerformedBy(state.PreviousActivity, currentActor)) 77 | { 78 | state.PreviousActivity.CreatedAt = @event.Created; 79 | return state; 80 | } 81 | 82 | state.SavedActivities.Add(state.PreviousActivity = new ActivityDto 83 | { 84 | Id = @event.Id.Value.ToVersion7(@event.Created.Value), 85 | Type = DialogActivityType.FormSaved, 86 | CreatedAt = @event.Created, 87 | PerformedBy = currentActor 88 | }); 89 | return state; 90 | }, state => state.SavedActivities); 91 | 92 | activities.AddRange(savedEvents); 93 | return activities; 94 | } 95 | 96 | private static bool IsPerformedBy( 97 | [NotNullWhen(true)] ActivityDto? activity, 98 | [NotNullWhen(true)] ActorDto? actor) => 99 | activity?.PerformedBy.ActorId is not null 100 | && actor is not null 101 | && activity.PerformedBy.ActorId == actor.ActorId; 102 | 103 | private async Task> LookupUsers(List events, CancellationToken cancellationToken) 104 | { 105 | var actorUrnByUserUrn = await _registerRepository.GetActorUrnByUserId( 106 | events.Where(x => x.User?.UserId != null) 107 | .Select(x => x.User.UserId!.Value.ToString()) 108 | .Distinct(), 109 | cancellationToken 110 | ); 111 | 112 | return actorUrnByUserUrn.ToDictionary(x => int.Parse(x.Key), x => x.Value); 113 | } 114 | 115 | private static ActorDto GetPerformedBy(PlatformUser user, InstanceOwner instanceOwner, Dictionary actorUrnByUserId) 116 | { 117 | if (user.UserId.HasValue && actorUrnByUserId.TryGetValue(user.UserId.Value, out var actorUrn)) 118 | { 119 | return actorUrn.StartsWith(Constants.DisplayNameUrnPrefix) 120 | ? new ActorDto { ActorType = ActorType.PartyRepresentative, ActorName = actorUrn[Constants.DisplayNameUrnPrefix.Length..] } 121 | : new ActorDto { ActorType = ActorType.PartyRepresentative, ActorId = actorUrn }; 122 | } 123 | 124 | // Altinn 2 end user system id 125 | if (user.EndUserSystemId.HasValue) 126 | { 127 | return new ActorDto { ActorType = ActorType.PartyRepresentative, ActorName = $"EUS #{user.EndUserSystemId.Value}" }; 128 | } 129 | 130 | if (!string.IsNullOrWhiteSpace(user.SystemUserOwnerOrgNo)) 131 | { 132 | return new ActorDto { ActorType = ActorType.PartyRepresentative, ActorId = $"{Constants.OrganizationUrnPrefix}{user.SystemUserOwnerOrgNo}" }; 133 | } 134 | 135 | if (!string.IsNullOrWhiteSpace(user.OrgId)) 136 | { 137 | return new ActorDto { ActorType = ActorType.ServiceOwner }; 138 | } 139 | 140 | throw new InvalidOperationException($"{nameof(PlatformUser)} could not be converted to {nameof(ActorDto)}: {JsonSerializer.Serialize(user)}."); 141 | } 142 | } -------------------------------------------------------------------------------- /tests/Altinn.DialogportenAdapter.Unit.Tests/Features/Command/Sync/ApplicationTextParserTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Altinn.DialogportenAdapter.WebApi.Features.Command.Sync; 3 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Storage; 4 | using Altinn.Platform.Storage.Interface.Models; 5 | 6 | namespace Altinn.DialogportenAdapter.Unit.Tests.Features.Command.Sync; 7 | 8 | public class ApplicationTextParserTests 9 | { 10 | [Fact] 11 | public void ReturnsMostSpecificKeyForTaskAndDerivedStatus() 12 | { 13 | var instance = CreateInstance("Task1"); 14 | var texts = CreateTexts( 15 | ("nb", new Dictionary 16 | { 17 | { "dp.title.Task1.awaitingsignature", "specific" }, 18 | { "dp.title.Task1", "task-only" }, 19 | { "dp.title._any_.awaitingsignature", "any-status" }, 20 | { "dp.title", "fallback" } 21 | })); 22 | 23 | var localizations = ApplicationTextParser.GetLocalizationsFromApplicationTexts( 24 | "title", 25 | instance, 26 | texts, 27 | InstanceDerivedStatus.AwaitingSignature); 28 | 29 | Assert.Collection(localizations, loc => 30 | { 31 | Assert.Equal("nb", loc.LanguageCode); 32 | Assert.Equal("specific", loc.Value); 33 | }); 34 | } 35 | 36 | [Fact] 37 | public void FallsBackToTaskWithoutDerivedStatusWhenStatusSpecificKeyIsMissing() 38 | { 39 | var instance = CreateInstance("Task1"); 40 | var texts = CreateTexts( 41 | ("nb", new Dictionary 42 | { 43 | { "dp.title.Task1", "task-only" }, 44 | { "dp.title._any_.awaitingsignature", "any-status" }, 45 | { "dp.title", "fallback" } 46 | })); 47 | 48 | var localizations = ApplicationTextParser.GetLocalizationsFromApplicationTexts( 49 | "title", 50 | instance, 51 | texts, 52 | InstanceDerivedStatus.AwaitingSignature); 53 | 54 | Assert.Collection(localizations, loc => 55 | { 56 | Assert.Equal("nb", loc.LanguageCode); 57 | Assert.Equal("task-only", loc.Value); 58 | }); 59 | } 60 | 61 | [Fact] 62 | public void UsesAnyTaskEntryForDerivedStatusWhenTaskSpecificIsAbsent() 63 | { 64 | var instance = CreateInstance("Task1"); 65 | var texts = CreateTexts( 66 | ("nb", new Dictionary 67 | { 68 | { "dp.title._any_.awaitingsignature", "any-status" }, 69 | { "dp.title", "fallback" } 70 | })); 71 | 72 | var localizations = ApplicationTextParser.GetLocalizationsFromApplicationTexts( 73 | "title", 74 | instance, 75 | texts, 76 | InstanceDerivedStatus.AwaitingSignature); 77 | 78 | Assert.Collection(localizations, loc => 79 | { 80 | Assert.Equal("nb", loc.LanguageCode); 81 | Assert.Equal("any-status", loc.Value); 82 | }); 83 | } 84 | 85 | [Fact] 86 | public void FallsBackToBaseKeyWhenNoTaskOrStatusSpecificKeysExist() 87 | { 88 | var instance = CreateInstance("Task1"); 89 | var texts = CreateTexts( 90 | ("nb", new Dictionary 91 | { 92 | { "dp.title", "fallback" } 93 | })); 94 | 95 | var localizations = ApplicationTextParser.GetLocalizationsFromApplicationTexts( 96 | "title", 97 | instance, 98 | texts, 99 | InstanceDerivedStatus.AwaitingSignature); 100 | 101 | Assert.Collection(localizations, loc => 102 | { 103 | Assert.Equal("nb", loc.LanguageCode); 104 | Assert.Equal("fallback", loc.Value); 105 | }); 106 | } 107 | 108 | [Fact] 109 | public void ReturnsEmptyListWhenNoMatchingKeysExist() 110 | { 111 | var instance = CreateInstance("Task1"); 112 | var texts = CreateTexts( 113 | ("nb", new Dictionary())); 114 | 115 | var localizations = ApplicationTextParser.GetLocalizationsFromApplicationTexts( 116 | "title", 117 | instance, 118 | texts, 119 | InstanceDerivedStatus.AwaitingSignature); 120 | 121 | Assert.Empty(localizations); 122 | } 123 | 124 | [Fact] 125 | public void ResolvesEachLanguageIndependently() 126 | { 127 | var instance = CreateInstance("Task1"); 128 | var texts = CreateTexts( 129 | ("nb", new Dictionary 130 | { 131 | { "dp.summary._any_.awaitingsignature", "nb-any" } 132 | }), 133 | ("nn", new Dictionary 134 | { 135 | { "dp.summary", "nn-fallback" } 136 | })); 137 | 138 | var localizations = ApplicationTextParser.GetLocalizationsFromApplicationTexts( 139 | "summary", 140 | instance, 141 | texts, 142 | InstanceDerivedStatus.AwaitingSignature); 143 | 144 | Assert.Collection( 145 | localizations, 146 | nb => 147 | { 148 | Assert.Equal("nb", nb.LanguageCode); 149 | Assert.Equal("nb-any", nb.Value); 150 | }, 151 | nn => 152 | { 153 | Assert.Equal("nn", nn.LanguageCode); 154 | Assert.Equal("nn-fallback", nn.Value); 155 | }); 156 | } 157 | 158 | [Fact] 159 | public void FiltersOutInvalidLanguageCodes() 160 | { 161 | var instance = CreateInstance(null); 162 | var texts = CreateTexts( 163 | ("nb", new Dictionary 164 | { 165 | { "dp.summary", "valid" } 166 | }), 167 | ("xx", new Dictionary 168 | { 169 | { "dp.summary", "invalid" } 170 | })); 171 | 172 | var localizations = ApplicationTextParser.GetLocalizationsFromApplicationTexts( 173 | "summary", 174 | instance, 175 | texts, 176 | InstanceDerivedStatus.AwaitingSignature); 177 | 178 | Assert.Collection(localizations, loc => 179 | { 180 | Assert.Equal("nb", loc.LanguageCode); 181 | Assert.Equal("valid", loc.Value); 182 | }); 183 | } 184 | 185 | private static Instance CreateInstance(string? taskId) 186 | { 187 | var instance = new Instance(); 188 | if (taskId is null) 189 | { 190 | return instance; 191 | } 192 | 193 | instance.Process = new ProcessState 194 | { 195 | CurrentTask = new ProcessElementInfo 196 | { 197 | ElementId = taskId 198 | } 199 | }; 200 | 201 | return instance; 202 | } 203 | 204 | private static ApplicationTexts CreateTexts(params (string language, Dictionary texts)[] translations) 205 | { 206 | var storageTranslations = new List(translations.Length); 207 | foreach (var (language, textsDictionary) in translations) 208 | { 209 | storageTranslations.Add(new ApplicationTextsTranslation 210 | { 211 | Language = language, 212 | Texts = textsDictionary 213 | }); 214 | } 215 | 216 | return new ApplicationTexts 217 | { 218 | Translations = storageTranslations 219 | }; 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # Local User-specific application configuration 7 | appsettings.local.json 8 | 9 | # User-specific files 10 | *.rsuser 11 | *.suo 12 | *.user 13 | *.userosscache 14 | *.sln.docstates 15 | 16 | # User-specific files (MonoDevelop/Xamarin Studio) 17 | *.userprefs 18 | 19 | # Mono auto generated files 20 | mono_crash.* 21 | 22 | # Build results 23 | [Dd]ebug/ 24 | [Dd]ebugPublic/ 25 | [Rr]elease/ 26 | [Rr]eleases/ 27 | x64/ 28 | x86/ 29 | [Ww][Ii][Nn]32/ 30 | [Aa][Rr][Mm]/ 31 | [Aa][Rr][Mm]64/ 32 | bld/ 33 | [Bb]in/ 34 | [Oo]bj/ 35 | [Oo]ut/ 36 | [Ll]og/ 37 | [Ll]ogs/ 38 | 39 | # Visual Studio 2015/2017 cache/options directory 40 | .vs/ 41 | # Uncomment if you have tasks that create the project's static files in wwwroot 42 | #wwwroot/ 43 | 44 | # Visual Studio 2017 auto generated files 45 | Generated\ Files/ 46 | 47 | # JetBrains Rider 48 | .idea/ 49 | 50 | # MSTest test Results 51 | [Tt]est[Rr]esult*/ 52 | [Bb]uild[Ll]og.* 53 | 54 | # NUnit 55 | *.VisualState.xml 56 | TestResult.xml 57 | nunit-*.xml 58 | 59 | # VerifyTests 60 | # Ignoring received files from snapshot tests 61 | *.received.* 62 | 63 | # Build Results of an ATL Project 64 | [Dd]ebugPS/ 65 | [Rr]eleasePS/ 66 | dlldata.c 67 | 68 | # Benchmark Results 69 | BenchmarkDotNet.Artifacts/ 70 | 71 | # .NET Core 72 | project.lock.json 73 | project.fragment.lock.json 74 | artifacts/ 75 | 76 | # ASP.NET Scaffolding 77 | ScaffoldingReadMe.txt 78 | 79 | # StyleCop 80 | StyleCopReport.xml 81 | 82 | # Files built by Visual Studio 83 | *_i.c 84 | *_p.c 85 | *_h.h 86 | *.ilk 87 | *.meta 88 | *.obj 89 | *.iobj 90 | *.pch 91 | *.pdb 92 | *.ipdb 93 | *.pgc 94 | *.pgd 95 | *.rsp 96 | *.sbr 97 | *.tlb 98 | *.tli 99 | *.tlh 100 | *.tmp 101 | *.tmp_proj 102 | *_wpftmp.csproj 103 | *.log 104 | *.vspscc 105 | *.vssscc 106 | .builds 107 | *.pidb 108 | *.svclog 109 | *.scc 110 | 111 | # Chutzpah Test files 112 | _Chutzpah* 113 | 114 | # Visual C++ cache files 115 | ipch/ 116 | *.aps 117 | *.ncb 118 | *.opendb 119 | *.opensdf 120 | *.sdf 121 | *.cachefile 122 | *.VC.db 123 | *.VC.VC.opendb 124 | 125 | # Visual Studio profiler 126 | *.psess 127 | *.vsp 128 | *.vspx 129 | *.sap 130 | 131 | # Visual Studio Trace Files 132 | *.e2e 133 | 134 | # TFS 2012 Local Workspace 135 | $tf/ 136 | 137 | # Guidance Automation Toolkit 138 | *.gpState 139 | 140 | # ReSharper is a .NET coding add-in 141 | _ReSharper*/ 142 | *.[Rr]e[Ss]harper 143 | *.DotSettings.user 144 | 145 | # TeamCity is a build add-in 146 | _TeamCity* 147 | 148 | # DotCover is a Code Coverage Tool 149 | *.dotCover 150 | 151 | # AxoCover is a Code Coverage Tool 152 | .axoCover/* 153 | !.axoCover/settings.json 154 | 155 | # Coverlet is a free, cross platform Code Coverage Tool 156 | coverage*.json 157 | coverage*.xml 158 | coverage*.info 159 | 160 | # Visual Studio code coverage results 161 | *.coverage 162 | *.coveragexml 163 | 164 | # NCrunch 165 | _NCrunch_* 166 | .*crunch*.local.xml 167 | nCrunchTemp_* 168 | 169 | # MightyMoose 170 | *.mm.* 171 | AutoTest.Net/ 172 | 173 | # Web workbench (sass) 174 | .sass-cache/ 175 | 176 | # Installshield output folder 177 | [Ee]xpress/ 178 | 179 | # DocProject is a documentation generator add-in 180 | DocProject/buildhelp/ 181 | DocProject/Help/*.HxT 182 | DocProject/Help/*.HxC 183 | DocProject/Help/*.hhc 184 | DocProject/Help/*.hhk 185 | DocProject/Help/*.hhp 186 | DocProject/Help/Html2 187 | DocProject/Help/html 188 | 189 | # Click-Once directory 190 | publish/ 191 | 192 | # Publish Web Output 193 | *.[Pp]ublish.xml 194 | *.azurePubxml 195 | # Note: Comment the next line if you want to checkin your web deploy settings, 196 | # but database connection strings (with potential passwords) will be unencrypted 197 | *.pubxml 198 | *.publishproj 199 | 200 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 201 | # checkin your Azure Web App publish settings, but sensitive information contained 202 | # in these scripts will be unencrypted 203 | PublishScripts/ 204 | 205 | # NuGet Packages 206 | *.nupkg 207 | # NuGet Symbol Packages 208 | *.snupkg 209 | # The packages folder can be ignored because of Package Restore 210 | **/[Pp]ackages/* 211 | # except build/, which is used as an MSBuild target. 212 | !**/[Pp]ackages/build/ 213 | # Uncomment if necessary however generally it will be regenerated when needed 214 | #!**/[Pp]ackages/repositories.config 215 | # NuGet v3's project.json files produces more ignorable files 216 | *.nuget.props 217 | *.nuget.targets 218 | 219 | # Microsoft Azure Build Output 220 | csx/ 221 | *.build.csdef 222 | 223 | # Microsoft Azure Emulator 224 | ecf/ 225 | rcf/ 226 | 227 | # Windows Store app package directories and files 228 | AppPackages/ 229 | BundleArtifacts/ 230 | Package.StoreAssociation.xml 231 | _pkginfo.txt 232 | *.appx 233 | *.appxbundle 234 | *.appxupload 235 | 236 | # Visual Studio cache files 237 | # files ending in .cache can be ignored 238 | *.[Cc]ache 239 | # but keep track of directories ending in .cache 240 | !?*.[Cc]ache/ 241 | 242 | # Others 243 | ClientBin/ 244 | ~$* 245 | *~ 246 | *.dbmdl 247 | *.dbproj.schemaview 248 | *.jfm 249 | *.pfx 250 | *.publishsettings 251 | orleans.codegen.cs 252 | 253 | # Including strong name files can present a security risk 254 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 255 | #*.snk 256 | 257 | # Since there are multiple workflows, uncomment next line to ignore bower_components 258 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 259 | #bower_components/ 260 | 261 | # RIA/Silverlight projects 262 | Generated_Code/ 263 | 264 | # Backup & report files from converting an old project file 265 | # to a newer Visual Studio version. Backup files are not needed, 266 | # because we have git ;-) 267 | _UpgradeReport_Files/ 268 | Backup*/ 269 | UpgradeLog*.XML 270 | UpgradeLog*.htm 271 | ServiceFabricBackup/ 272 | *.rptproj.bak 273 | 274 | # SQL Server files 275 | *.mdf 276 | *.ldf 277 | *.ndf 278 | 279 | # Business Intelligence projects 280 | *.rdl.data 281 | *.bim.layout 282 | *.bim_*.settings 283 | *.rptproj.rsuser 284 | *- [Bb]ackup.rdl 285 | *- [Bb]ackup ([0-9]).rdl 286 | *- [Bb]ackup ([0-9][0-9]).rdl 287 | 288 | # Microsoft Fakes 289 | FakesAssemblies/ 290 | 291 | # GhostDoc plugin setting file 292 | *.GhostDoc.xml 293 | 294 | # Node.js Tools for Visual Studio 295 | .ntvs_analysis.dat 296 | node_modules/ 297 | 298 | # Visual Studio 6 build log 299 | *.plg 300 | 301 | # Visual Studio 6 workspace options file 302 | *.opt 303 | 304 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 305 | *.vbw 306 | 307 | # Visual Studio LightSwitch build output 308 | **/*.HTMLClient/GeneratedArtifacts 309 | **/*.DesktopClient/GeneratedArtifacts 310 | **/*.DesktopClient/ModelManifest.xml 311 | **/*.Server/GeneratedArtifacts 312 | **/*.Server/ModelManifest.xml 313 | _Pvt_Extensions 314 | 315 | # Paket dependency manager 316 | .paket/paket.exe 317 | paket-files/ 318 | 319 | # FAKE - F# Make 320 | .fake/ 321 | 322 | # CodeRush personal settings 323 | .cr/personal 324 | 325 | # Python Tools for Visual Studio (PTVS) 326 | __pycache__/ 327 | *.pyc 328 | 329 | # Cake - Uncomment if you are using it 330 | # tools/** 331 | # !tools/packages.config 332 | 333 | # Tabs Studio 334 | *.tss 335 | 336 | # Telerik's JustMock configuration file 337 | *.jmconfig 338 | 339 | # BizTalk build output 340 | *.btp.cs 341 | *.btm.cs 342 | *.odx.cs 343 | *.xsd.cs 344 | 345 | # OpenCover UI analysis results 346 | OpenCover/ 347 | 348 | # Azure Stream Analytics local run output 349 | ASALocalRun/ 350 | 351 | # MSBuild Binary and Structured Log 352 | *.binlog 353 | 354 | # NVidia Nsight GPU debugger configuration file 355 | *.nvuser 356 | 357 | # MFractors (Xamarin productivity tool) working folder 358 | .mfractor/ 359 | 360 | # Local History for Visual Studio 361 | .localhistory/ 362 | 363 | # BeatPulse healthcheck temp database 364 | healthchecksdb 365 | 366 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 367 | MigrationBackup/ 368 | 369 | # Ionide (cross platform F# VS Code tools) working folder 370 | .ionide/ 371 | 372 | # Fody - auto-generated XML schema 373 | FodyWeavers.xsd 374 | 375 | # MacOS 376 | .DS_Store 377 | 378 | # Secrets file used by act 379 | .secrets 380 | 381 | # Generated files with tokens 382 | **/.endusers-with-tokens.csv 383 | **/.serviceowners-with-tokens.csv 384 | 385 | # Private http client configuration 386 | **/http-client.private.env.json 387 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.EventSimulator/Infrastructure/Persistance/MigrationPartitionRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | using System.Globalization; 3 | using System.Reflection; 4 | using Altinn.DialogportenAdapter.EventSimulator.Common.Extensions; 5 | using Azure.Data.Tables; 6 | 7 | namespace Altinn.DialogportenAdapter.EventSimulator.Infrastructure.Persistance; 8 | 9 | internal sealed class MigrationPartitionRepository : IMigrationPartitionRepository 10 | { 11 | private readonly TableClient _tableClient; 12 | private readonly ILogger _logger; 13 | 14 | public MigrationPartitionRepository(TableClient tableClient, ILogger logger) 15 | { 16 | _tableClient = tableClient ?? throw new ArgumentNullException(nameof(tableClient)); 17 | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); 18 | } 19 | 20 | public async Task> GetExistingPartitions( 21 | List partitions, 22 | CancellationToken cancellationToken) 23 | { 24 | if (partitions.Count == 0) 25 | { 26 | return Array.Empty().AsReadOnly(); 27 | } 28 | 29 | var partitionKeyStrings = partitions 30 | .GroupBy(x => x.Partition) 31 | .Select(x => x.Key.ToPartitionKey()) 32 | .ToList(); 33 | 34 | var filter = string.Join(" or ", partitionKeyStrings.Select(pk => $"PartitionKey eq '{pk}'")); 35 | 36 | var queryResult = _tableClient.QueryAsync( 37 | filter: filter, 38 | maxPerPage: 1000, 39 | select: [nameof(TableEntity.PartitionKey), nameof(TableEntity.RowKey)], 40 | cancellationToken: cancellationToken); 41 | 42 | var partitionsByKey = partitions 43 | .GroupBy(x => (x.Partition, x.Organization)) 44 | .ToDictionary(x => x.Key, x => x.Single()); 45 | 46 | var result = new List(); 47 | await foreach (var entity in queryResult) 48 | { 49 | var key = (entity.PartitionKey.ToDateOnly(), entity.RowKey); 50 | if (partitionsByKey.TryGetValue(key, out var partition)) 51 | { 52 | result.Add(partition); 53 | } 54 | } 55 | 56 | return result.AsReadOnly(); 57 | } 58 | 59 | public async Task Get(DateOnly partition, string organization, CancellationToken cancellationToken) 60 | { 61 | var entity = await _tableClient.GetEntityIfExistsAsync( 62 | partitionKey: partition.ToPartitionKey(), 63 | rowKey: organization.ToRowKey(), 64 | cancellationToken: cancellationToken); 65 | 66 | return entity.Value; 67 | } 68 | 69 | public async Task Upsert(List partitionEntities, CancellationToken cancellationToken) 70 | { 71 | if (partitionEntities.Count == 0) 72 | return; 73 | 74 | var batchTasks = partitionEntities 75 | .GroupBy(e => e.PartitionKey) 76 | .SelectMany(group => group.Chunk(100)) 77 | .Select(async (chunk, batchIndex) => 78 | { 79 | var actions = chunk 80 | .Select(entity => new TableTransactionAction(TableTransactionActionType.UpsertReplace, entity)) 81 | .ToList(); 82 | 83 | var pk = chunk.First().PartitionKey; 84 | 85 | try 86 | { 87 | await _tableClient.SubmitTransactionAsync(actions, cancellationToken); 88 | } 89 | catch (TableTransactionFailedException ex) 90 | { 91 | var failedIndex = ex.FailedTransactionActionIndex ?? -1; 92 | 93 | // Build a compact, single log entry with all meaningful details 94 | string actionType = ""; 95 | string failedPk = pk; 96 | string failedRk = ""; 97 | string properties = ""; 98 | 99 | if (failedIndex >= 0 && failedIndex < actions.Count) 100 | { 101 | var failedAction = actions[failedIndex]; 102 | actionType = failedAction.ActionType.ToString(); 103 | 104 | if (failedAction.Entity is MigrationPartitionEntity mpe) 105 | { 106 | failedPk = mpe.PartitionKey; 107 | failedRk = mpe.RowKey; 108 | properties = FormatEntityProperties(mpe); 109 | } 110 | else if (failedAction.Entity is ITableEntity te) 111 | { 112 | failedPk = te.PartitionKey; 113 | failedRk = te.RowKey; 114 | properties = FormatITableEntityProperties(te); 115 | } 116 | } 117 | 118 | _logger.LogError(ex, 119 | "Batch {BatchIndex} FAILED. Status: {Status}, ErrorCode: {ErrorCode}, FailedIndex: {FailedIndex}, Action: {Action}, PK: {FailedPK}, RK: {FailedRK}, Properties: {Properties}", 120 | batchIndex, ex.Status, ex.ErrorCode, failedIndex, actionType, failedPk, failedRk, properties); 121 | 122 | if (failedIndex < 0 || failedIndex >= actions.Count) 123 | { 124 | _logger.LogWarning("No valid failed index provided — failure may be at the changeset level."); 125 | } 126 | 127 | throw; // preserve existing behavior 128 | } 129 | }); 130 | 131 | await Task.WhenAll(batchTasks); 132 | } 133 | 134 | public async Task Truncate(CancellationToken cancellationToken = default) 135 | { 136 | const int batchSize = 100; // Max allowed per batch 137 | var deleteTasks = new List(); 138 | 139 | await foreach (var page in _tableClient 140 | .QueryAsync(maxPerPage: batchSize, cancellationToken: cancellationToken) 141 | .AsPages() 142 | .WithCancellation(cancellationToken)) 143 | { 144 | var groups = page.Values.GroupBy(e => e.PartitionKey); 145 | 146 | foreach (var group in groups) 147 | { 148 | var batch = new List(); 149 | 150 | foreach (var entity in group) 151 | { 152 | batch.Add(new TableTransactionAction(TableTransactionActionType.Delete, entity)); 153 | 154 | if (batch.Count == batchSize) 155 | { 156 | deleteTasks.Add(_tableClient.SubmitTransactionAsync(batch, cancellationToken)); 157 | batch = new List(); 158 | } 159 | } 160 | 161 | if (batch.Count > 0) 162 | { 163 | deleteTasks.Add(_tableClient.SubmitTransactionAsync(batch, cancellationToken)); 164 | } 165 | } 166 | } 167 | 168 | await Task.WhenAll(deleteTasks); 169 | _logger.LogInformation("Truncate completed."); 170 | } 171 | 172 | // ------- Helpers (ILogger-based) ------- 173 | 174 | private static string FormatEntityProperties(object entity) 175 | { 176 | var pairs = new List(); 177 | 178 | foreach (var prop in entity.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) 179 | { 180 | if (prop.Name is nameof(ITableEntity.PartitionKey) or nameof(ITableEntity.RowKey) or nameof(ITableEntity.Timestamp) or nameof(ITableEntity.ETag)) 181 | continue; 182 | 183 | try 184 | { 185 | var value = prop.GetValue(entity); 186 | pairs.Add($"{prop.Name}={FormatValue(value)}"); 187 | } 188 | catch (Exception ex) 189 | { 190 | pairs.Add($"{prop.Name}="); 191 | } 192 | } 193 | 194 | return string.Join(", ", pairs); 195 | } 196 | 197 | private static string FormatITableEntityProperties(ITableEntity e) 198 | { 199 | if (e is TableEntity te) 200 | { 201 | var pairs = new List(); 202 | 203 | foreach (var kv in te) 204 | { 205 | if (kv.Key is nameof(ITableEntity.PartitionKey) or nameof(ITableEntity.RowKey) or nameof(ITableEntity.Timestamp) or nameof(ITableEntity.ETag)) 206 | continue; 207 | 208 | pairs.Add($"{kv.Key}={FormatValue(kv.Value)}"); 209 | } 210 | 211 | return string.Join(", ", pairs); 212 | } 213 | 214 | return FormatEntityProperties(e); 215 | } 216 | 217 | private static string FormatValue(object? v) => 218 | v switch 219 | { 220 | null => "", 221 | byte[] bytes => $"[byte[{bytes.Length}]]", 222 | DateTime dt => $"{dt:o} (DateTime) # Prefer DateTimeOffset", 223 | DateTimeOffset dto => dto.ToString("o"), 224 | _ => v.ToString() ?? "" 225 | }; 226 | } 227 | -------------------------------------------------------------------------------- /src/Altinn.DialogportenAdapter.WebApi/Features/Command/Sync/ISyncInstanceToDialogService.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Diagnostics.CodeAnalysis; 3 | using Altinn.DialogportenAdapter.Contracts; 4 | using Altinn.DialogportenAdapter.WebApi.Common.Extensions; 5 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Dialogporten; 6 | using Altinn.DialogportenAdapter.WebApi.Infrastructure.Storage; 7 | using Altinn.Platform.Storage.Interface.Models; 8 | using Constants = Altinn.DialogportenAdapter.WebApi.Common.Constants; 9 | 10 | namespace Altinn.DialogportenAdapter.WebApi.Features.Command.Sync; 11 | 12 | public interface ISyncInstanceToDialogService 13 | { 14 | Task Sync(SyncInstanceCommand dto, CancellationToken cancellationToken = default); 15 | } 16 | 17 | internal sealed class SyncInstanceToDialogService : ISyncInstanceToDialogService 18 | { 19 | private readonly IStorageApi _storageApi; 20 | private readonly IDialogportenApi _dialogportenApi; 21 | private readonly StorageDialogportenDataMerger _dataMerger; 22 | private readonly IApplicationRepository _applicationRepository; 23 | private readonly ILogger _logger; 24 | 25 | public SyncInstanceToDialogService( 26 | IStorageApi storageApi, 27 | IDialogportenApi dialogportenApi, 28 | StorageDialogportenDataMerger dataMerger, 29 | IApplicationRepository applicationRepository, 30 | ILogger logger) 31 | { 32 | _storageApi = storageApi ?? throw new ArgumentNullException(nameof(storageApi)); 33 | _dialogportenApi = dialogportenApi ?? throw new ArgumentNullException(nameof(dialogportenApi)); 34 | _dataMerger = dataMerger ?? throw new ArgumentNullException(nameof(dataMerger)); 35 | _applicationRepository = applicationRepository ?? throw new ArgumentNullException(nameof(applicationRepository)); 36 | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); 37 | } 38 | 39 | public async Task Sync(SyncInstanceCommand dto, CancellationToken cancellationToken = default) 40 | { 41 | // To avoid performing requests needlessly, we attempt to load the app from cache first to see if 42 | // sync is disabled in which case we can skip the rest of the processing. 43 | var (isCached, cachedApp) = 44 | await _applicationRepository.TryGetApplicationIfCached(dto.AppId, cancellationToken); 45 | 46 | if (isCached && cachedApp is not null && cachedApp.GetSyncAdapterSettings().DisableSync) 47 | { 48 | return; 49 | } 50 | 51 | // Create a uuid7 from the instance id and created timestamp to use as dialog id 52 | var dialogId = dto.InstanceId.ToVersion7(dto.InstanceCreatedAt); 53 | 54 | // Fetch events, application, instance and existing dialog in parallel 55 | var (existingDialog, application, applicationTexts, instance, events) = await ( 56 | _dialogportenApi.Get(dialogId, cancellationToken).ContentOrDefault(), 57 | _applicationRepository.GetApplication(dto.AppId, cancellationToken), 58 | _applicationRepository.GetApplicationTexts(dto.AppId, cancellationToken), 59 | _storageApi.GetInstance(dto.PartyId, dto.InstanceId, cancellationToken).ContentOrDefault(), 60 | _storageApi.GetInstanceEvents(dto.PartyId, dto.InstanceId, Constants.SupportedEventTypes, cancellationToken).ContentOrDefault() 61 | ); 62 | 63 | if (instance is null && existingDialog is null) 64 | { 65 | _logger.LogWarning("No dialog or instance found for request. {PartyId},{InstanceId},{InstanceCreatedAt},{IsMigration}.", 66 | dto.PartyId, 67 | dto.InstanceId, 68 | dto.InstanceCreatedAt, 69 | dto.IsMigration); 70 | return; 71 | } 72 | 73 | if (ShouldUpdateInstanceWithDialogId(instance, dialogId)) 74 | { 75 | // Update the instance with the dialogId before we start to modify the dialog 76 | // This way we can keep track of which instances that have been attempted synced 77 | // to dialogporten even if the dialogporten api is down or we have a bug in the 78 | // sync process. 79 | await UpdateInstanceWithDialogId(dto, dialogId, cancellationToken); 80 | } 81 | 82 | if (InstanceOwnerIsSelfIdentified(instance)) 83 | { 84 | // We skip these for now as we do not have a good way to identify the user in dialogporten 85 | _logger.LogWarning("Skipping sync for self-identified instance owner on id={Id} username={Username} appid={AppId}.", 86 | instance?.Id, 87 | instance?.InstanceOwner.Username, 88 | instance?.AppId); 89 | return; 90 | } 91 | 92 | if (BothIsDeleted(instance, existingDialog)) 93 | { 94 | return; 95 | } 96 | 97 | var forceSilentUpsert = false; 98 | var shouldDeleteAfterCreate = false; 99 | if (InstanceSoftDeletedAndDialogNotExisting(instance, existingDialog)) 100 | { 101 | _logger.LogInformation( 102 | "Instance id={Id} is soft-deleted in storage and does not exist in Dialogporten. Creating and deleting immediately afterwards.", 103 | instance?.Id); 104 | forceSilentUpsert = true; 105 | shouldDeleteAfterCreate = true; 106 | } 107 | 108 | var syncAdapterSettings = application.GetSyncAdapterSettings(); 109 | if (syncAdapterSettings.DisableSync || IsDialogSyncDisabled(instance)) 110 | { 111 | return; 112 | } 113 | 114 | if (ShouldPurgeDialog(instance, existingDialog)) 115 | { 116 | if (syncAdapterSettings.DisableDelete) return; 117 | await _dialogportenApi.Purge( 118 | dialogId, 119 | existingDialog.Revision!.Value, 120 | isSilentUpdate: dto.IsMigration, 121 | cancellationToken: cancellationToken); 122 | return; 123 | } 124 | 125 | if (ShouldSoftDeleteDialog(instance, existingDialog)) 126 | { 127 | if (syncAdapterSettings.DisableDelete) return; 128 | await _dialogportenApi.Delete( 129 | dialogId, 130 | existingDialog.Revision!.Value, 131 | isSilentUpdate: dto.IsMigration, 132 | cancellationToken: cancellationToken); 133 | return; 134 | } 135 | 136 | if (ShouldRestoreDialog(instance, existingDialog)) 137 | { 138 | existingDialog.Revision = await RestoreDialog(dialogId, 139 | existingDialog.Revision!.Value, 140 | disableAltinnEvents: dto.IsMigration, 141 | cancellationToken); 142 | existingDialog.Deleted = false; 143 | } 144 | 145 | EnsureNotNull(application, instance, events); 146 | 147 | // Create or update the dialog with the fetched data 148 | var mergeDto = new MergeDto(dialogId, existingDialog, application, applicationTexts, instance, events, dto.IsMigration || forceSilentUpsert); 149 | var updatedDialog = await _dataMerger.Merge(mergeDto, cancellationToken); 150 | var revision = await UpsertDialog(updatedDialog, existingDialog, syncAdapterSettings, dto.IsMigration || forceSilentUpsert, cancellationToken); 151 | 152 | if (!syncAdapterSettings.DisableDelete && shouldDeleteAfterCreate && revision.HasValue) 153 | { 154 | await _dialogportenApi.Delete( 155 | dialogId, 156 | revision.Value, 157 | isSilentUpdate: true, 158 | cancellationToken: cancellationToken); 159 | } 160 | } 161 | 162 | private static bool InstanceOwnerIsSelfIdentified(Instance? instance) 163 | { 164 | return instance is not null 165 | && instance.InstanceOwner.OrganisationNumber is null 166 | && instance.InstanceOwner.PersonNumber is null 167 | && instance.InstanceOwner.PartyId is not null 168 | && instance.InstanceOwner.Username is not null; 169 | } 170 | 171 | private static void EnsureNotNull( 172 | [NotNull] Application? application, 173 | [NotNull] Instance? instance, 174 | [NotNull] InstanceEventList? events) 175 | { 176 | if (application is null || instance is null || events is null) 177 | { 178 | throw new UnreachableException( 179 | $"Application ({application is not null}), " + 180 | $"instance ({instance is not null}) " + 181 | $"and events ({events is not null}) " + 182 | $"should exist at this point."); 183 | } 184 | } 185 | 186 | private static bool ShouldSoftDeleteDialog([NotNullWhen(true)] Instance? instance, [NotNullWhen(true)] DialogDto? existingDialog) 187 | { 188 | return instance is { Status.IsSoftDeleted: true } && existingDialog is not null; 189 | } 190 | 191 | private static bool IsDialogSyncDisabled(Instance? instance) 192 | { 193 | return instance?.DataValues is not null 194 | && instance.DataValues.TryGetValue(Constants.InstanceDataValueDisableSyncKey, out var disableSyncString) 195 | && bool.TryParse(disableSyncString, out var disableSync) 196 | && disableSync; 197 | } 198 | 199 | private static bool BothIsDeleted(Instance? instance, DialogDto? existingDialog) 200 | { 201 | return BothIsHardDeleted(instance, existingDialog) || BothIsSoftDeleted(instance, existingDialog); 202 | } 203 | 204 | private static bool BothIsHardDeleted(Instance? instance, [NotNullWhen(false)] DialogDto? existingDialog) 205 | { 206 | return instance is null or { Status.IsHardDeleted: true } && existingDialog is null; 207 | } 208 | 209 | private static bool BothIsSoftDeleted([NotNullWhen(true)] Instance? instance, [NotNullWhen(true)] DialogDto? existingDialog) 210 | { 211 | return instance is { Status.IsSoftDeleted: true } && existingDialog is { Deleted: true }; 212 | } 213 | 214 | private static bool ShouldRestoreDialog([NotNullWhen(true)] Instance? instance, [NotNullWhen(true)] DialogDto? existingDialog) 215 | { 216 | return instance is { Status.IsSoftDeleted: false } && existingDialog is { Deleted: true }; 217 | } 218 | 219 | private static bool ShouldPurgeDialog(Instance? instance, [NotNullWhen(true)] DialogDto? existingDialog) 220 | { 221 | return instance is null or { Status.IsHardDeleted: true } && existingDialog is not null; 222 | } 223 | 224 | private static bool InstanceSoftDeletedAndDialogNotExisting(Instance? instance, DialogDto? existingDialog) 225 | { 226 | return instance is { Status.IsSoftDeleted: true } && existingDialog is null; 227 | } 228 | 229 | private static bool ShouldUpdateInstanceWithDialogId([NotNullWhen(true)] Instance? instance, Guid dialogId) 230 | { 231 | if (instance is null) 232 | { 233 | return false; 234 | } 235 | 236 | return instance.DataValues is null 237 | || !instance.DataValues.TryGetValue(Constants.InstanceDataValueDialogIdKey, out var dialogIdString) 238 | || !Guid.TryParse(dialogIdString, out var instanceDialogId) 239 | || instanceDialogId != dialogId; 240 | } 241 | 242 | private async Task UpsertDialog(DialogDto updated, 243 | DialogDto? existing, 244 | SyncAdapterSettings settings, 245 | bool isMigration, 246 | CancellationToken cancellationToken) => 247 | existing is null 248 | ? await CreateDialog(updated, settings, isMigration, cancellationToken) 249 | : await UpdateDialog(updated, existing, isMigration, cancellationToken); 250 | 251 | private async Task CreateDialog( 252 | DialogDto dto, 253 | SyncAdapterSettings settings, 254 | bool isMigration, 255 | CancellationToken cancellationToken) 256 | { 257 | if (settings.DisableCreate) return null; 258 | 259 | var createResult = await _dialogportenApi 260 | .Create(dto, isSilentUpdate: isMigration, cancellationToken: cancellationToken) 261 | .EnsureSuccess(); 262 | 263 | return createResult.GetEtagHeader(); 264 | } 265 | 266 | // PostgreSQL has a minimum time precision of 1 microsecond. To avoid issues with updates where the CreatedAt time is changed by less than this precision, 267 | // we define an epsilon value of 1 microsecond to use when comparing timestamps. 268 | private static readonly TimeSpan Epsilon = TimeSpan.FromMicroseconds(1); 269 | private async Task UpdateDialog(DialogDto updated, DialogDto? existing, bool isMigration, 270 | CancellationToken cancellationToken) 271 | { 272 | var activityUpdateRequests = existing?.Activities 273 | .Join(updated.Activities, x => x.Id, x => x.Id, (prev, next) => (prev, next)) 274 | .Where(x => x.prev.Type == DialogActivityType.FormSaved && (x.next.CreatedAt!.Value - x.prev.CreatedAt!.Value) > Epsilon) 275 | .Select(x => new { ActivityId = x.next.Id!.Value, NewCreatedAt = x.next.CreatedAt!.Value }) 276 | .ToArray() ?? []; 277 | 278 | PruneExistingImmutableEntities(updated, existing); 279 | 280 | var updateResult = await _dialogportenApi.Update(updated, updated.Revision!.Value, 281 | isSilentUpdate: isMigration, 282 | cancellationToken: cancellationToken).EnsureSuccess(); 283 | 284 | updated.Revision = updateResult.GetEtagHeader(); 285 | 286 | foreach (var activityUpdateRequest in activityUpdateRequests) 287 | { 288 | var result = await _dialogportenApi.UpdateFormSavedActivityTime( 289 | updated.Id!.Value, 290 | activityUpdateRequest.ActivityId, 291 | updated.Revision.Value, 292 | activityUpdateRequest.NewCreatedAt, 293 | cancellationToken: cancellationToken).EnsureSuccess(); 294 | updated.Revision = result.GetEtagHeader(); 295 | } 296 | 297 | return updated.Revision.Value; 298 | } 299 | 300 | private async Task RestoreDialog(Guid dialogId, 301 | Guid revision, 302 | bool disableAltinnEvents, 303 | CancellationToken cancellationToken) 304 | { 305 | var response = await _dialogportenApi 306 | .Restore(dialogId, revision, disableAltinnEvents, cancellationToken) 307 | .EnsureSuccess(); 308 | 309 | return response.GetEtagHeader(); 310 | } 311 | 312 | private static void PruneExistingImmutableEntities(DialogDto updated, DialogDto? existing) 313 | { 314 | if (existing is null) return; 315 | 316 | updated.Transmissions = updated.Transmissions 317 | .ExceptBy(existing.Transmissions.Select(x => x.Id), x => x.Id) 318 | .ToList(); 319 | 320 | updated.Activities = updated.Activities 321 | .ExceptBy(existing.Activities.Select(x => x.Id), x => x.Id) 322 | .ToList(); 323 | } 324 | 325 | private Task UpdateInstanceWithDialogId(SyncInstanceCommand dto, Guid dialogId, 326 | CancellationToken cancellationToken) 327 | { 328 | return _storageApi.UpdateDataValues(dto.PartyId, dto.InstanceId, new() 329 | { 330 | Values = new() 331 | { 332 | { Constants.InstanceDataValueDialogIdKey, dialogId.ToString() } 333 | } 334 | }, cancellationToken); 335 | } 336 | } 337 | --------------------------------------------------------------------------------