Skip to content

About

Prototype of pharma training plattform

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

pharma-training

Generated by Software Fabric. Every choice behind this project is recorded in fabric.yaml and explained in docs/adr/.

First steps

  • Connect the model, an Azure OpenAI resource in the EU: see Connect the model (Azure OpenAI, EU). The application starts without it.

  • For the evals workflow, add the repository secret AZURE_OPENAI_API_KEY and the repository variable AZURE_OPENAI_ENDPOINT, both for the same EU resource the application uses. Set the repository variable EVALS_SCHEDULED to true to run the evals weekly; they are off by default, and every run costs money.

  • Create the frontend's lockfile and commit it: cd web && pnpm install, then commit web/pnpm-lock.yaml. CI installs with --frozen-lockfile and fails until it is there.

Connect the model (Azure OpenAI, EU)

The project's AI actions (in MVP 1, drafting a course's questions and checking its content for the editorial team) call a model deployed in your own Azure OpenAI resource. Content sent to it is health-sector training material, so it stays in the EU (DSGVO; ADR 0001):

  1. Create the Azure OpenAI resource in an EU region, such as Sweden Central, Germany West Central, France Central or West Europe.

  2. Deploy the model with the deployment type Data Zone Standard (EU) or regional Standard, never Global Standard: a global deployment may process requests in any Azure region.

  3. Give the AppHost the resource's endpoint and key, which stay out of the repository:

    dotnet user-secrets set Parameters:azure-openai-endpoint https://<resource>.openai.azure.com --project src/AppHost
    dotnet user-secrets set Parameters:azure-openai-api-key <key> --project src/AppHost
    dotnet user-secrets set Parameters:azure-openai-deployment <deployment> --project src/AppHost

    The deployment is optional: it defaults to gpt-5-mini, and whatever it is, it must name a deployment in that resource.

In a deployment, set the same three parameters in the deployment's secret store; never in appsettings*.json or a commit.

Without an endpoint and key the application still starts, and everything but the AI actions works: a request that needs the model answers 503 problem details with the code model-not-configured. The tests never need them.

The evals workflow (.github/workflows/evals.yml) reads the repository secret AZURE_OPENAI_API_KEY and the repository variable AZURE_OPENAI_ENDPOINT; point them at the same EU resource.

The client also runs against an OpenAI-compatible endpoint that already ends in /v1: set azure-openai-endpoint to https://api.openai.com/v1, azure-openai-api-key to an OpenAI key and azure-openai-deployment to a model name. OpenAI's own API is not bound to the EU, so use it only with content that may leave the EU, never with the project's real training content.

Build

dotnet build build.proj

Run locally

You need:

  • The .NET SDK 11.0.100, or a later feature band of 11.0 (global.json).
  • Docker, installed and running: the AppHost starts the project's database and services in containers, and the integration tests do too. Messaging runs in Aspire's Azure Service Bus emulator, with a SQL Server of its own (ADR 0053): about 2.7 GB of images and 2 GB of memory, healthy about half a minute after it starts. SQL Server has no arm64 image, so on Apple Silicon Docker Desktop runs it under emulation (Rosetta, on by default); without it, the emulator does not start.
  • Node.js 26, the version web/Dockerfile builds the app with, and pnpm 10, the major web/package.json's packageManager pins. Node 26 ships no corepack, so install it first: npm install --global corepack@0.36.0 && corepack enable. The AppHost's web resource runs pnpm and does not start without both on PATH.

Then start the AppHost, which starts everything else:

dotnet run --project src/AppHost

Or, with the Aspire CLI, aspire run, which finds the AppHost through aspire.config.json. aspire doctor checks the prerequisites above when something does not start.

Starting the AppHost builds every project it runs, once; the edge, the services and the migration runners then start from that build and are not rebuilt when they restart. After editing a module while the AppHost runs, use the dashboard's Rebuild command on its service (Restart alone runs the old build), or stop and start the AppHost.

Blob storage

The AppHost runs Azurite, the Azure Storage emulator, as the resource storage, with a container per module (<module>-blobs, named after the module); each service reads only its own, as the connection string blobs, and signs short-lived upload and read URLs for it with the emulator's account key (IBlobUrls, docs/adr/0002). The web app's origin, http://localhost:5173, may PUT and GET with those URLs straight from the browser: the AppHost sets that CORS rule on the emulator when it starts. Deployed, the account has no key (shared-key access is off): each service signs with a user delegation key under its own managed identity, which may use its own container alone, and the account allows the edge's origin with the same rule.

Editorial settings

Four eyes (a version is published by an editor other than the one who submitted it) is off by default; Editorial__FourEyes=true in the editorial service's environment turns it on (docs/adr/0007).

Republishing Editorial's events

Run POST /editorial/course-versions/republish once, as an editor (editorial.edit), after a service that consumes CourseVersionPublishedV1, TestDefinitionPublishedV1, ChapterFilesReleasedV1 or CourseVersionRetiredV1 is deployed for the first time: its subscription exists only from the deploy that adds it, and what Editorial announced before reached no subscription of its. It sends again the events of every version that was published or retired, the files of its PDF and video chapters with read URLs signed when it runs (so a chapter Learning never copied, or whose first release expired, is copied then), and answers how many of each went out (courseVersions, testDefinitions, fileReleases, retirements). Every subscriber receives them again, not only the new one, and drops what it already has by the version id (Learning's files by the name it derives from the version and the chapter), so it is safe to repeat, and a run cut off part-way is simply run again (ADR 0019).

Since #547 (ADR 0054) the consumers read CourseVersionPublishedV3 and TestDefinitionPublishedV2, whose content travels by claim check; the republish sends both and releases their content documents again with fresh read URLs. Run it once after the deploy that brings #547. Since #553 the old events no longer go out, from the publish or the republish. On a broker that keeps its data, first remove the durable bindings of CourseVersionPublishedV1 (to learning, certification), CourseVersionPublishedV2 (to catalog, compliance) and TestDefinitionPublishedV1 (to assessment) by hand (ADR 0011), or one of them left over from before the deploy leaves a dead letter per module; on Service Bus, remove those subscriptions if the deployment leaves them.

One run goes at a time: a second answers 409 with editorial.republish-running while the first is running. A request that timed out means "run again": while the first run is still going, the rerun answers 409 and you wait and try again; otherwise it sends everything once more, and the subscribers drop the duplicates.

Local users

Keycloak imports these from src/AppHost/realms/realm.json, development only. Each one's password is its username.

  • developer: the realm role manager, which no policy requires (ADR 0055); an erasure leaves an account holding it alone (ADR 0041).
  • visitor: no role.
  • editor: the realm role editor, the platform's editors (the Redaktion), which editorial.edit requires.
  • owner, employee-a, employee-b: no realm role; their pharmacy roles (owner, employee) come from the Organisation module, not from Keycloak.
  • employee-c: no realm role, like employee-b; the MVP 1 end-to-end test (web/app/e2e/mvp1-register-to-certificate.spec.ts, #55) invites her, and no other test does, since an address is mailed an invitation at most every 10 minutes (#265).
  • former-employee: no realm role; the integration tests make her a member of a pharmacy in Learning and end it, so she is always a former member there (#194).
  • support: the realm role support, platform support staff, which organisation.erase-persons requires to request a person's erasure (#115). developer does not hold it, so end-to-end runs never erase anyone.

The development realm allows self-registration: Keycloak's login page has a Register link, and an account created there (or through the admin API) must verify its address before it can sign in. Keycloak mails the verification link to Mailpit (http://localhost:8025). The imported users are not asked to verify, unverified (whose address Keycloak has not verified) included. The published realm (#114) keeps registration closed (registrationAllowed: false) until #158 (limits on invitation mail) is merged, brute-force detection and bot protection on the registration form are on, and account enumeration on register has been considered (ADR 0014).

Keycloak imports the realm only when it does not exist yet, and keeps it in a data volume. After realm.json changes (a role, a user, a realm setting such as registration), an existing local Keycloak keeps the old realm: stop the AppHost, find the volume with docker volume ls (its name contains keycloak), remove it with docker volume rm <name>, and start the AppHost again.

The realm's confidential client pharma-training-erasure, with which Organisation deletes an erased person's account (#115, ADR 0041), came with that change too: a volume whose realm was imported before it has no such client, and every erasure then stops short of the step keycloak, its message dead-lettered after the retries. Its secret is the AppHost's parameter keycloak-erasure-client-secret, generated once and kept in the AppHost's user secrets like Keycloak's administrator password; the import reads it once. Remove the volume as above whenever you clear the AppHost's user secrets, or the imported client keeps the old secret and Organisation's token request is refused.

The realm's login pages wear the app's look, the login theme pharma-training (src/AppHost/keycloak/themes, #502, ADR 0050), which the AppHost mounts read-only into Keycloak and the realm names. A volume whose realm was imported before #502 keeps Keycloak's stock look. Remove the volume as above, or keep it and name the theme in its realm: with the AppHost running, docker exec -it <keycloak container> /opt/keycloak/bin/kcadm.sh config credentials --server http://localhost:8080 --realm master --user admin (it asks for the password from Parameters:keycloak-password in the AppHost's user secrets, which run mode generates), then docker exec <keycloak container> /opt/keycloak/bin/kcadm.sh update realms/pharma-training -s loginTheme=pharma-training -s 'displayNameHtml=Pharma Training'. Run mode serves the theme uncached: an edit to its files shows when the page is reloaded.

Demo data

The AppHost starts the resource demo-seeder once the edge, Keycloak and the web app are up. It seeds demo data through the edge's public API, as the people the data names, and exits; the dashboard shows it Finished, or failed with its log, and its last line says Demo data: <n> created (ADR 0042).

  • What it seeds: three pharmacies (Demo-Apotheke am Markt, Demo-Apotheke Rosenstraße, Demo-Löwen-Apotheke Großstadt, the last with 22 employees, so its members and its matrix have two pages), four published courses (Demo: …) and a second version of the Hygiene course, and assignments in every state: open, in progress, completed with a certificate, a failed attempt, an exhausted examination, a recurring assignment, and assignments due today, which are overdue from the next day.
  • Who: 35 users named demo-*, each with the address <username>@example.com and, like the local users above, their username as their password. demo-autorin writes, demo-pruefer approves and demo-freigabe publishes (all three editor); demo-markt-leitung, demo-rosen-leitung and demo-loewen-leitung manage the pharmacies; demo-markt-1…4, demo-rosen-1…3 and demo-loewen-01…22 are employees. Their invitations land in Mailpit.
  • Again: each start runs it again; it looks everything up first and finds it there, so it changes nothing (Demo data: 0 created). It never deletes; to start over, remove the volumes as above.
  • Off: dotnet user-secrets set DemoSeeder:Enabled false --project src/AppHost, or DemoSeeder__Enabled=false in the AppHost's environment. The integration tests switch it off.

It runs in run mode only: a published AppHost has no seeder, and the seeder itself refuses any target but Local or Staging before it makes any call. With Local, the edge, Keycloak, Mailpit and the realm the edge names must all be loopback. A refusal exits 2 and names the setting, never its value; a failed step exits 1 and names it.

On staging the same plan is seeded by .github/workflows/demo-seed-staging.yml: deploy.yml runs it after each staging deploy, and it can be started by hand (Actions, demo-seed-staging, Run workflow). Production never runs it.

  • Before any credential: its first request is the edge's /api/config.json, which must report environment: staging (the AppHost tells the edge the name it was published with); the realm it names must be https on the host of X1_KEYCLOAK_URL. Anything else ends the run with exit 2.
  • Users: the same 35 demo-* users, administered as the client demo-seeder (One-time setup, "The first deploy", step 6), never an administrator's password. Every demo user's password is DEMO_USERS_PASSWORD, set again on every run, so a rotated secret takes effect at the next run. Their invitations land in staging's Mailpit, which the run reads with MAILPIT_UI_AUTH.
  • Again: a second run adds nothing. It deletes nothing either; the demo data stays until staging is rebuilt.
  • Traces: none. The run uploads nothing and exports no telemetry; a failure is read from the job's log.

Test

dotnet test --project tests/Architecture.Tests/Architecture.Tests.csproj

dotnet test --project exists only on Microsoft.Testing.Platform, which global.json's "test": { "runner": "Microsoft.Testing.Platform" } selects. Keep that section when a tool rewrites global.json: without it dotnet test --project fails with MSB1001: Unknown switch. bash .github/scripts/check-test-runner.sh names the file instead, and .github/scripts/test.sh runs it before the tests; the architecture rule GlobalJsonSelectsTheTestingPlatform does the same where the tests run without dotnet test (an IDE, or dotnet run --project <test project>).

Evals

tests/Evals scores the project's LLM use cases with the project's own model, judged by that model: relevance for every example, groundedness for those with context, and the project's own checks. Each metric's mean over a use case's examples must reach settings.backend.llm.extras.evals.threshold in fabric.yaml. A run calls the real model and costs money, so the regular tests never run it; .github/workflows/evals.yml does, by hand or weekly when the repository variable EVALS_SCHEDULED is true, and uploads the report.

dotnet test --project tests/Evals/Evals.csproj
dotnet tool restore && dotnet aieval report --path TestResults/evals --output TestResults/evals/report.html

Deploy (Azure Container Apps)

aspire publish -e staging (or production) writes the whole application as Bicep from the AppHost (ADR 0005); .github/workflows/publish.yml does it on every pull request. .github/workflows/deploy.yml is the only path to Azure. It runs only when someone starts it (Actions, deploy, Run workflow, or gh workflow run deploy.yml --ref main), one run at a time:

  • staging signs in to Azure with the GitHub environment staging's federated credential (OIDC, no client secret), refuses a resource group outside northeurope, reads every parameter from that environment's secrets and variables, and runs aspire deploy -e staging. It builds the images (each service, the edge with the web app inside, Keycloak, the MigrationRunner), pushes them to the environment's registry and deploys the Bicep.
  • production runs only when the run asks for it (the input production, off by default: gh workflow run deploy.yml --ref main -f production=true), and then starts only after staging succeeded and the production environment's reviewers approved, and does the same with production's. Without it, the run ends with staging. Production's reviewers approve after the staging run's x1-staging run is green: it starts on its own once a run completes (ADR 0049), so deploy staging alone first, then start the run with production checked.
  • Staging's logs, traces and metrics are in its Aspire dashboard (ADR 0048): its address is https://aspire-dashboard.ext.<domain>, with the environment's domain (az containerapp env list -g <resource group> --query "[0].properties.defaultDomain" -o tsv), and Azure signs you in before it opens; it needs a role on the environment (Contributor on the resource group has it). Production has no dashboard; its logs are in Log Analytics.
  • Messaging is Azure Service Bus Standard, one namespace per environment (ADR 0053), without keys: each service sends to its own events' topics and receives from its own subscriptions under its managed identity, and the deployment declares every topic and subscription. No messaging secret or variable is needed.

A step that finds a secret or variable missing fails naming it, never its value.

database-roles-key is the key every module's database role password is derived from (guid(database-roles-key, '<module>')): each service logs in to its own database as <module>_app, never as the server's administrator. Give each environment a random key of its own, at least 32 characters long; changing it rotates every role's password at the next deploy. Publishing refuses a shorter one it is given, and the Bicep declares @minLength(32) on it, which Azure enforces however the key arrives. Neither says anything of how random it is: aaaa… is 32 characters too. Checking the key's entropy belongs to deploy.yml's check of its parameters (F2, #129), which does not make it yet. frontend-url must be the canonical https origin a browser sends, https://host or https://host:port in lower case, with no default port (:443), path, query, trailing slash or trailing dot; publishing refuses anything else it is given.

Each service's init container, the MigrationRunner, builds the module's database as the administrator: its migrations, its event store and Wolverine's message storage (schema wolverine). The module's role owns nothing there and may only read and write. To replay a dead letter (UPDATE wolverine.wolverine_dead_letters SET replayable = true), connect as the module's role, with its connection string from the Key Vault secret connectionstrings--<module>-database-app, never as the administrator (ADR 0005), from inside the environment (below).

Operators inside the network

The server and the Key Vault have no public endpoint: they answer the Container Apps environment's virtual network alone. The storage account keeps its public endpoint for the browsers' signed URLs, and the services reach it through a private endpoint (ADR 0038). psql or az keyvault secret show from your own machine is refused. Keycloak's administration is unchanged: az containerapp exec goes through Azure, not the network.

To work in a module's database, start a temporary app in the environment, under the module's own identity, with its role's connection string as a Key Vault reference, and remove it when you are done:

az containerapp create -g <resource group> -n psql-<module> --environment <environment> \
  --image postgres:16 --command sleep --args infinity --min-replicas 1 --max-replicas 1 \
  --user-assigned <the module's identity id> \
  --secrets "database=keyvaultref:https://<vault>.vault.azure.net/secrets/connectionstrings--<module>-database-app,identityref:<the module's identity id>" \
  --env-vars DATABASE=secretref:database
az containerapp exec -g <resource group> -n psql-<module> --command /bin/bash
#   inside: echo "$DATABASE" shows Host=…;Username=…;Password=…;Database=…; then
#   psql "host=<Host> user=<Username> dbname=<Database> sslmode=require", entering the password when asked
az containerapp delete -g <resource group> -n psql-<module> --yes

The app has no ingress, and only someone whose Entra sign-in may create apps in the resource group can start one. A restore (below) is checked the same way, against the new server. Nothing here has run against Azure before #129.

One-time setup (#129)

Do this once per environment, staging and production, with az signed in as someone who may create resource groups, app registrations and role assignments. Values go into the GitHub environment's secrets and variables, never into a commit, an issue or a chat.

  1. Resource providers, once per subscription: az provider register --namespace <namespace> --wait for Microsoft.App, Microsoft.OperationalInsights, Microsoft.ContainerRegistry, Microsoft.KeyVault, Microsoft.DBforPostgreSQL, Microsoft.Storage, Microsoft.ManagedIdentity, Microsoft.Network and Microsoft.ServiceBus.

  2. A resource group in North Europe (ADR 0047), created beforehand so the deploying identity's roles can be scoped to it: az group create --name <resource group> --location northeurope. aspire deploy creates everything else in it: the Container Apps environment aca with its Log Analytics workspace, the container registry, the Key Vault secrets, the PostgreSQL Flexible Server postgres, the virtual network network with the private endpoints of the server, the vault and the blobs (ADR 0038), the storage account, every app's managed identity and the Service Bus namespace (messaging), the Container Apps (host, auth, keycloak, each service, the migrations job). Azure's names carry a suffix Aspire adds; list them with az resource list -g <resource group> -o table.

  3. An Entra app registration for the deploy, one per environment so staging's identity cannot touch production:

    • az ad app create --display-name <name>, then az ad sp create --id <app id>.

    • A federated credential (az ad app federated-credential create --id <app id> --parameters <file>): issuer https://token.actions.githubusercontent.com, subject repo:<owner>/<repository>:environment:<staging or production>, or, where the repository uses GitHub's immutable subject claims, the prefix gh api repos/<owner>/<repository>/actions/oidc/customization/sub prints (repo:<owner>@<owner id>/<repository>@<repository id>) followed by :environment:<staging or production>; a subject that does not match fails azure/login, audience api://AzureADTokenExchange. No client secret is created.

    • On the resource group only: Contributor, and Role Based Access Control Administrator, since the deploy assigns roles to the apps' identities (Key Vault Secrets User per secret, the storage roles, AcrPull, and the Service Bus roles per topic and subscription). Give the second one a condition that lets it assign and remove those six roles alone, so the deploying identity cannot make itself or anyone else Owner:

      roles='4633458b-17de-408a-b874-0445c86b69e6, 7f951dda-4ed3-4680-a7ca-43fe172d538d, ba92f5b4-2d11-453d-a403-e96b0029c9fe, db58b8e5-c6ad-4a2a-8342-4190687cbf4a, 69a216fc-b8fb-44d8-bc22-1f3c2cd27a39, 4f6d3b9b-027b-4f4c-9142-0e5a2a2247e0'
      # Key Vault Secrets User, AcrPull, Storage Blob Data Contributor, Storage Blob Delegator, Azure Service Bus Data Sender,
      # Azure Service Bus Data Receiver: what the published Bicep assigns (AppHostDeployPermissionsTests checks the list).
      az role assignment create --assignee <app id> --role "Role Based Access Control Administrator" \
        --scope "$(az group show --name <resource group> --query id -o tsv)" --condition-version 2.0 --condition \
        "((!(ActionMatches{'Microsoft.Authorization/roleAssignments/write'})) OR (@Request[Microsoft.Authorization/roleAssignments:RoleDefinitionId] ForAnyOfAnyValues:GuidEquals {$roles})) AND ((!(ActionMatches{'Microsoft.Authorization/roleAssignments/delete'})) OR (@Resource[Microsoft.Authorization/roleAssignments:RoleDefinitionId] ForAnyOfAnyValues:GuidEquals {$roles}))"

      A deploy that assigns another role then fails with AuthorizationFailed naming it; add its id to the condition deliberately, never drop the condition.

  4. The GitHub environments staging and production (Settings, Environments). On production: required reviewers, with "Prevent self-review" on, so whoever started the run cannot approve it. On both: deployment branches and tags limited to main and the tags you deploy from (deploy/*, see "Roll back"), and "Allow administrators to bypass configured protection rules" off, so no administrator deploys past them. Check all of it, with the tag ruleset below, by bash .github/scripts/check-deploy-environments.sh <owner>/<repository>, with gh signed in as a repository administrator (GitHub shows a ruleset's bypass list and main's branch protection to administrators alone, and the check fails when it cannot read them): it names each environment that another branch or tag may deploy to or whose rules administrators may bypass, production without reviewers or with "Prevent self-review" off, and a missing or incomplete ruleset for deploy/* tags, and fails until none is left (#278). It also requires main to take pull requests alone and refuse force pushes (a branch ruleset on main, or branch protection), since both environments trust it, and refuses a tag ruleset that a repository role below admin may bypass. It prints who may bypass the tag ruleset; it cannot tell who the reviewers and those people are: check by hand that they are the people who may deploy.

    • A tag ruleset for deploy/* (Settings, Rules, Rulesets, New tag ruleset; target refs/tags/deploy/*): restrict creations, updates and deletions to the people who may deploy (the bypass list), so nobody else can point a deploy/* tag, which the environments accept, at a commit of their choosing.
  5. The environment's variables (gh variable set <NAME> --env <environment> --body <value>):

    • AZURE_CLIENT_ID (the app registration's), AZURE_TENANT_ID, AZURE_SUBSCRIPTION_ID, AZURE_RESOURCE_GROUP;
    • POSTGRES_USERNAME: the server's administrator login (not admin, postgres, azure_superuser or another name Flexible Server reserves);
    • SMTP_FROM: the sender of every mail Keycloak and the services send (ADR 0004);
    • OWNER_ADDRESS: the owner's address for operational alerts, mailed when one support account requests more erasures within the hour than the threshold (#514, ADR 0036); it has no default, and the deploy stops naming it while it is missing;
    • SMTP_HOST, production only: the relay (Azure Communication Services) they send through, on port 587 with STARTTLS. Staging sends to a Mailpit of its own instead (#130), whose inbox the staging end-to-end run reads;
    • X1_KEYCLOAK_URL and X1_MAILPIT_URL, staging only, set after the first deploy (below): https://auth.<domain> and https://mailpit.<domain>, where the staging end-to-end run signs in and reads mail;
    • FRONTEND_URL: https://host.invalid for the first deploy, then the edge's address (below);
    • AZURE_OPENAI_ENDPOINT: https://eu.api.openai.com/v1, the OpenAI project with EU data residency (ADR 0006).
  6. The environment's secrets (gh secret set <NAME> --env <environment>, which asks for the value, so it stays out of the shell's history):

    • POSTGRES_PASSWORD: without ;, ' or ";
    • DATABASE_ROLES_KEY: at least 32 random characters, its own per environment (openssl rand -base64 48); the AppHost refuses a shorter one;
    • KEYCLOAK_ADMIN_PASSWORD: Keycloak's administrator, admin;
    • KEYCLOAK_ERASURE_CLIENT_SECRET: the secret of the client pharma-training-erasure, with which Organisation deletes an erased person's Keycloak account (ADR 0041); openssl rand -hex 32, its own per environment. Keycloak's realm import reads it, so set it before the first deploy; an environment whose realm was imported before the client existed needs the runbook below;
    • SMTP_USERNAME, SMTP_PASSWORD, production only: the relay's, URI-safe;
    • MAILPIT_UI_AUTH, staging only: Mailpit's inbox's basic auth, x1:<password> (echo "x1:$(openssl rand -hex 24)"), which staging's Mailpit takes and the staging end-to-end run sends;
    • X1_RUNNER_SECRET, staging only, set after the first deploy (below): the secret of the client the staging end-to-end run creates its users with;
    • DEMO_SEEDER_SECRET and DEMO_USERS_PASSWORD, staging only, set after the first deploy (below): the secret of the client the demo seed administers its users with, and the password every demo user signs in with;
    • AZURE_OPENAI_API_KEY: the OpenAI project's key.

    URI-safe means letters, digits, -, ., _ and ~ alone (openssl rand -hex 24): Aspire puts these values unescaped into connection strings. Each environment gets values of its own.

The services and Keycloak are built from images whose bases come from mcr.microsoft.com, quay.io and Docker Hub (node for the web app). If a run fails on Docker Hub's pull rate limit, the job needs a Docker Hub login before the deploy step; there is none yet.

The first deploy

  1. Run bash .github/scripts/check-deploy-environments.sh <owner>/<repository> (step 4 above) and fix what it names; then run deploy.yml on main, which deploys staging alone; check staging, then run it again with production checked.

  2. Read staging's domain, az containerapp env list -g <resource group> --query "[0].properties.defaultDomain" -o tsv, set FRONTEND_URL to https://host.<domain> and run deploy.yml again. Until then invitation links and the second CORS origin point at https://host.invalid; Keycloak and sign-in already use the real addresses, which come from the domain itself. Do the same for production after its first deploy.

  3. Replace Keycloak's bootstrap administrator. admin, with KEYCLOAK_ADMIN_PASSWORD, is Keycloak's temporary bootstrap administrator, and the master realm has no brute-force protection of its own. Open a shell in Keycloak's container, az containerapp exec -g <resource group> -n keycloak --command /bin/bash, and there:

    cd /opt/keycloak/bin
    # Without --password, kcadm.sh asks for it, so it is in no shell history, no process list and no variable.
    ./kcadm.sh config credentials --server http://localhost:8080 --realm master --user admin
    ./kcadm.sh update realms/master -s bruteForceProtected=true -s failureFactor=10 -s eventsEnabled=true -s adminEventsEnabled=true
    ./kcadm.sh create users -r master -s username=<your name> -s enabled=true
    ./kcadm.sh set-password -r master --username <your name>   # asks for the new password: long, random, kept in your password manager
    ./kcadm.sh add-roles -r master --uusername <your name> --rolename admin
    ./kcadm-otp.sh enroll <your name>   # shows a key for your authenticator app; saves it once the app's code matches
    ./kcadm-otp.sh login <your name>    # asks for the password and the app's code: the new administrator works, with its second factor
    ./kcadm.sh delete users/$(./kcadm.sh get users -r master -q username=admin -q exact=true --fields id --format csv --noquotes) -r master

    Keycloak creates a bootstrap administrator only while the master realm has no user, so admin does not come back at the next start. Every later session signs in as the new administrator, with ./kcadm-otp.sh login <your name>: once a code is enrolled, Keycloak refuses the password alone, so kcadm.sh config credentials no longer signs you in. kcadm.sh cannot send a code, and the master realm's pages, where a browser would set one up, are not published (the auth proxy forwards the realm pharma-training alone); kcadm-otp.sh, in the published image beside kcadm.sh (src/AppHost/keycloak/KcadmOtp.java), enrols the code, ending the sessions the user signed in to without it, and signs kcadm.sh in with the password and the code. The key is shown once: add it to the app and to nothing else, and clear the terminal (clear) before you leave. Each administrator enrols a code of their own, and a later master administrator enrols one before being given the admin role. To replace a lost code, another administrator deletes it (./kcadm-otp.sh enroll names the command) and the administrator who lost it enrols the new one in person, at that terminal: the key is shown once, and only to the one whose app it goes into. Azure's sign-in stays in front of all of it: only someone whose Entra sign-in, with the tenant's MFA, may run az containerapp exec on keycloak reaches either script (ADR 0005).

  4. Create the first editor and manager in Keycloak. Registration is off in the published realm until #158, so every account is created this way for now. In Keycloak's container, signed in as the administrator:

    cd /opt/keycloak/bin
    ./kcadm-otp.sh login <your name>   # asks for the password and the app's code
    ./kcadm.sh create users -r pharma-training -s username=<email> -s email=<email> -s enabled=true
    ./kcadm.sh add-roles -r pharma-training --uusername <email> --rolename manager   # or editor
    ./kcadm.sh get users -r pharma-training -q username=<email> --fields id
    ./kcadm.sh update users/<id>/execute-actions-email -r pharma-training -b '["VERIFY_EMAIL","UPDATE_PASSWORD"]'

    The user receives a mail with a link to verify the address and set a password. Remove ~/.keycloak/kcadm.config before leaving the shell. On staging every mail goes to its Mailpit, not to the address: read it at https://mailpit.<domain> with MAILPIT_UI_AUTH (#130).

  5. Staging only: the staging end-to-end run's client (#130). The run creates its owner, editor and employee at set-up through Keycloak's admin API and deletes them afterwards, as the confidential client x1-runner, whose service account may manage users and nothing else. It is created here, on staging, and never in a realm file, so production never has it. In staging's Keycloak container:

    cd /opt/keycloak/bin
    ./kcadm-otp.sh login <your name>
    ./kcadm.sh create clients -r pharma-training -s clientId=x1-runner -s enabled=true -s publicClient=false \
      -s serviceAccountsEnabled=true -s standardFlowEnabled=false -s directAccessGrantsEnabled=false -s implicitFlowEnabled=false
    ./kcadm.sh add-roles -r pharma-training --uusername service-account-x1-runner --cclientid realm-management --rolename manage-users
    ./kcadm.sh get clients/$(./kcadm.sh get clients -r pharma-training -q clientId=x1-runner --fields id --format csv --noquotes)/client-secret -r pharma-training

    Put the secret the last command shows into staging's X1_RUNNER_SECRET (gh secret set X1_RUNNER_SECRET --env staging), then clear the terminal and remove ~/.keycloak/kcadm.config. x1-runner may set any staging user's password, so its secret is only as safe as the staging environment: keep that environment's deployment branches and tags limited to main and deploy/* (step 4, checked by check-deploy-environments.sh), so a workflow changed on another branch never receives it. x1-staging.yml keeps no trace and uploads nothing, since a trace would hold the secret. Set X1_KEYCLOAK_URL and X1_MAILPIT_URL too (step 5 of the one-time setup). To rotate the secret, ./kcadm.sh create clients/<id>/client-secret -r pharma-training and set it again.

  6. Staging only: the demo seed's client and password (#457, ADR 0042). demo-seed-staging.yml administers the demo-* users through Keycloak's admin API as the confidential client demo-seeder, whose service account may manage and view users and nothing else, and signs each of them in with one password. A client of its own, not x1-runner, so either can be rotated or removed alone; created here, on staging, and never in a realm file, so production never has it. In staging's Keycloak container:

    cd /opt/keycloak/bin
    ./kcadm-otp.sh login <your name>
    ./kcadm.sh create clients -r pharma-training -s clientId=demo-seeder -s enabled=true -s publicClient=false \
      -s serviceAccountsEnabled=true -s standardFlowEnabled=false -s directAccessGrantsEnabled=false -s implicitFlowEnabled=false
    ./kcadm.sh add-roles -r pharma-training --uusername service-account-demo-seeder --cclientid realm-management --rolename manage-users --rolename view-users
    ./kcadm.sh get clients/$(./kcadm.sh get clients -r pharma-training -q clientId=demo-seeder --fields id --format csv --noquotes)/client-secret -r pharma-training

    Put the secret the last command shows into staging's DEMO_SEEDER_SECRET (gh secret set DEMO_SEEDER_SECRET --env staging), then clear the terminal and remove ~/.keycloak/kcadm.config. Generate the demo users' password into DEMO_USERS_PASSWORD without showing it: openssl rand -base64 24 | gh secret set DEMO_USERS_PASSWORD --env staging. Give the demo password to whoever runs a demo; anyone who holds it can sign in as any demo-* user on staging. MAILPIT_UI_AUTH, FRONTEND_URL, X1_KEYCLOAK_URL and X1_MAILPIT_URL are the ones X1 reads (step 5). Like x1-runner, demo-seeder may set any staging user's password, so keep the staging environment's deployment branches limited as in step 4. To rotate the client's secret, run ./kcadm.sh create clients/<id>/client-secret -r pharma-training and set it again. To rotate the users' password, set DEMO_USERS_PASSWORD again: the next run resets every demo user to it.

  7. An environment whose realm was imported before the erasure client existed (#115, ADR 0041). Keycloak imports realm.json once, so an environment it was imported into before pharma-training-erasure was declared lacks the client Organisation deletes an erased person's account with, and every erasure stops short of the step keycloak (its message is dead-lettered after the retries and can be replayed once the client exists). Create it in Keycloak's container, as the administrator, with the same settings as the realm file:

    cd /opt/keycloak/bin
    ./kcadm-otp.sh login <your name>
    ./kcadm.sh create clients -r pharma-training -s clientId=pharma-training-erasure -s enabled=true -s publicClient=false \
      -s clientAuthenticatorType=client-secret -s serviceAccountsEnabled=true -s standardFlowEnabled=false \
      -s directAccessGrantsEnabled=false -s implicitFlowEnabled=false
    ./kcadm.sh add-roles -r pharma-training --uusername service-account-pharma-training-erasure --cclientid realm-management --rolename manage-users
    ERASURE=$(./kcadm.sh get clients -r pharma-training -q clientId=pharma-training-erasure --fields id --format csv --noquotes)
    MANAGEMENT=$(./kcadm.sh get clients -r pharma-training -q clientId=realm-management --fields id --format csv --noquotes)
    ./kcadm.sh update clients/$ERASURE -r pharma-training -s fullScopeAllowed=false
    ./kcadm.sh create clients/$ERASURE/scope-mappings/clients/$MANAGEMENT -r pharma-training -b "[$(./kcadm.sh get clients/$MANAGEMENT/roles/manage-users -r pharma-training)]"
    ./kcadm.sh get clients/$ERASURE/client-secret -r pharma-training

    The update and create …/scope-mappings lines keep the client's token to manage-users alone, whatever else its service account comes to hold (#462). An environment whose client already exists, created by an earlier version of this step or imported before #462, runs those four lines (the two variables, the update, the create) alone; ./kcadm.sh get clients/$ERASURE -r pharma-training --fields fullScopeAllowed then answers false.

    Put the secret the last command shows into the environment's KEYCLOAK_ERASURE_CLIENT_SECRET (gh secret set KEYCLOAK_ERASURE_CLIENT_SECRET --env <environment>), clear the terminal, remove ~/.keycloak/kcadm.config, and deploy, so Organisation reads it. The secret may delete every account of the realm: only Keycloak and Organisation read it. To rotate it, ./kcadm.sh create clients/<id>/client-secret -r pharma-training, set the new value and deploy; an environment imported after this client existed took its secret from KEYCLOAK_ERASURE_CLIENT_SECRET at the import, and is rotated the same way.

  8. An erasure that left a staff or service account (#115, ADR 0041). An erasure never deletes an account that holds the realm role support, editor or manager, any role of the client realm-management (a delegated realm administrator), or a client's service account: Organisation logs the Error Erasure <id> names a staff account in Keycloak … (or … a client's service account …), by the erasure's id alone, and the erasure's step keycloak stays open. The erasure log keeps no person id (ADR 0036): GET /organisation/erasures/<id>, as support, names who requested it (requestedBy), and the person's id comes from the request they worked from. Ask them for it, then check the account in Keycloak's container, as the administrator:

    cd /opt/keycloak/bin
    ./kcadm-otp.sh login <your name>
    ./kcadm.sh get users/<person id> -r pharma-training --fields id,username,serviceAccountClientId
    ./kcadm.sh get users/<person id>/role-mappings/realm/composite -r pharma-training --fields name
    ./kcadm.sh get users/<person id>/role-mappings/clients/$(./kcadm.sh get clients -r pharma-training -q clientId=realm-management --fields id --format csv --noquotes)/composite -r pharma-training --fields name

    A service account (service-account-…) is never removed this way: the erasure named the wrong id, so record that on the request and leave it. A staff member who really is to be erased loses their staff access with the account: confirm it with whoever runs that staff role, then ./kcadm.sh delete users/<person id> -r pharma-training. clear the terminal and remove ~/.keycloak/kcadm.config. Then, as support, record the step keycloak (#559), which forgets the person's id in the erasure log:

    curl -X POST https://host.<domain>/organisation/erasures/<erasure id>/steps/keycloak -H "Authorization: Bearer <support's token>"

    It answers the erasure, with the step keycloak, once Keycloak has no account for the person; 409 organisation.erasure-account-exists means the account still exists, so check the removal again. Record the erasure's id and the removal on the request.

What to check after the first deploy

ADR 0005 lists what is first observed in Azure, each with its fix in the AppHost, never in a service. After the first run of each environment:

  1. Key Vault references. Every revision is running (az containerapp revision list -g <resource group> -n <app> -o table). An "unable to fetch secret" that a retry clears is a role assignment still propagating; one that stays on an init container means the migrations identity's lifecycle None is not used for secrets, and it becomes Init (src/AppHost/Wiring/Migrations.cs).

  2. Ordering and images. No service failed its first revision with "image not found"; if one did, a second run succeeds and the order is recorded on #114.

  3. The database. Each init container (az containerapp logs show -g <resource group> -n <app> --container <init container>) applied its migrations and ensured its role without failing on database ownership (azure_pg_admin); note whether it warned that CONNECT on postgres could not be revoked; if it did, open a follow-up issue to revoke it another way (the security review of #114), since every module role can then connect to the maintenance database. Keycloak's init container created keycloak_app and the schema keycloak.

  4. Sign-in. https://auth.<domain>/realms/pharma-training/.well-known/openid-configuration answers an issuer of exactly https://auth.<domain>/realms/pharma-training; https://auth.<domain>/admin and /realms/master answer 404. https://host.<domain> loads the web app, and the first manager signs in and sees the modules. curl -sI https://host.<domain>/ answers Content-Security-Policy, X-Content-Type-Options: nosniff, Referrer-Policy and Strict-Transport-Security, and the browser's console shows no Content Security Policy violation while the manager uploads a chapter's file.

  5. Messaging (#532, ADR 0053). Every service's revision is Running and its log shows no UnauthorizedAccessException or 401 from Service Bus: a start-up 401 points at a missing role, not a missing entity, since no service creates or checks an entity. az servicebus namespace show -g <resource group> -n <namespace> --query disableLocalAuth answers true, and az servicebus topic list -g <resource group> --namespace-name <namespace> -o table lists one topic per integration event. Publish a course version as an editor: Catalog, Compliance and Learning store it within a minute, so an event crossed the namespace. The environment's old MESSAGING_USERNAME, MESSAGING_PASSWORD and MESSAGING_SERVICES_KEY can be deleted. A subscription's own dead-letter queue holds a message only if the service's database was unreachable for longer than its 20 deliveries (ADR 0053); az servicebus topic subscription show -g <resource group> --namespace-name <namespace> --topic-name <topic> -n <module> --query countDetails.deadLetterMessageCount answers 0 for each. To send such a message back once the database is up, open the subscription's dead-letter queue in the portal's Service Bus Explorer and re-send it.

  6. Mail. Keycloak's verification mail and an invitation mail arrive through SMTP_HOST. Invitations need #193's idempotent mail, which is merged; registration stays off until #158.

  7. Per-client limits (#292, ADR 0031). From one machine, for i in $(seq 31); do curl -s -o /dev/null -w '%{http_code}\n' https://host.<domain>/api/certification/verify/doesnotexist00000000000000000000; done ends in a 429 (the limit is 30 a minute); right after, the same request from another network (a phone off Wi-Fi) answers what the first request answered, not 429. If the second is refused too, the edge or the service counts the ingress, not the client: record it on #129 and #292 before Certification goes public. Then, a minute later, from the first machine again, forge a new address on every request: for i in $(seq 31); do curl -s -o /dev/null -w '%{http_code}\n' -H "X-Forwarded-For: 192.0.2.$i" https://host.<domain>/api/certification/verify/doesnotexist00000000000000000000; done must still end in a 429. If it does not, the ingress passed the caller's header on without appending its own hop, so whoever sends the header chooses their bucket and the limit does not hold: do not take Certification public; record it on #129 and #292, which then needs the trust moved off X-Forwarded-For (ADR 0031).

  8. Before real data (#278). bash .github/scripts/check-deploy-environments.sh <owner>/<repository> passes: both GitHub environments, staging and production, allow deployments from main and deploy/* tags alone, without an administrator's bypass, production waits for a reviewer other than the one who started the run, and only the tag ruleset's bypass list may create, move or delete a deploy/* tag; so a deploy.yml changed on another branch, or under a tag pushed by someone else, cannot get the environments' secrets or their Azure identity. In Keycloak's container, every user of the master realm has a code (./kcadm.sh get users/<id>/credentials -r master lists otp beside password), and ./kcadm.sh config credentials --server http://localhost:8080 --realm master --user <your name> with the password alone answers Invalid user credentials. No real data goes into an environment until both hold.

  9. The private network (#149, ADR 0038). az postgres flexible-server show -g <resource group> -n <server> --query network.publicNetworkAccess and az keyvault show -n <vault> --query properties.publicNetworkAccess answer Disabled; az postgres flexible-server firewall-rule list -g <resource group> -n <server> is empty; az network private-endpoint list -g <resource group> -o table lists the server's, the vault's and the storage account's; every revision is running (Key Vault references resolve through the private endpoint), and every init container reached the server. If a Key Vault reference does not resolve, check the zone privatelink.vaultcore.azure.net, its link to the network and the endpoint's record (az network private-dns record-set a list -g <resource group> -z privatelink.vaultcore.azure.net). The vault's bypass stays None: Container Apps is not a trusted service, so widening it would not help (ADR 0038).

  10. Upload URLs cannot copy (#159, ADR 0002). az storage account show -g <resource group> -n <account> --query allowedCopyScope answers AAD. Then sign two upload URLs as an editor (start two chapter uploads in the browser and copy each URL from the developer tools' network tab before it is used), and run bash .github/scripts/check-upload-sas-copy.sh <source url> <upload url> <second upload url> with a blob readable from Azure in another tenant as the source. Both attempts must answer 403. Record the output on #159, without the URLs' signatures (the script prints none). If either is accepted, no file uploads go live until #159 is reopened.

  11. The MVP 1 flow on staging (#130). x1-staging.yml runs on its own after each successful deploy run on main, against the commit it deployed (ADR 0049); it can also be started by hand (Actions, x1-staging, Run workflow). It registers a pharmacy, invites, assigns, learns, tests and verifies the certificate with three users it creates as x1-runner and deletes afterwards, however it ends; a failure is read from the job's log, since the run keeps no trace and uploads nothing (its secrets would be in them). Its pharmacy and course stay on staging, each named for its run alone (0 E2E <number> MVP 1, a number no other run repeats): no API deletes them yet, and the owner accepted that on #130. Remove them by hand when staging needs it. az containerapp logs show -g <resource group> -n mailpit shows the mails it received. Record the first green run on #130.

  12. The relay, by hand (#130). Staging never sends through Azure Communication Services, so production's relay is first exercised here, before real data: send one mail through it exactly as Keycloak and the services do, with STARTTLS on 587 and the relay's credentials, to an address you read. From your machine, with mail.txt holding a From: <SMTP_FROM>, a To: and a Subject: line, a blank line and a line of text: curl --ssl-reqd --url smtp://<SMTP_HOST>:587 --user <SMTP_USERNAME> --mail-from <SMTP_FROM> --mail-rcpt <your address> --upload-file mail.txt (curl asks for the password). The mail arrives, and its headers show it was sent with TLS. Record the result on #129. Keycloak reads its mail server's port, STARTTLS and authentication from its environment when it imports the published realm, which it does once, on its first start: a realm imported before a change to them keeps what it was imported with, so change them in the realm too (./kcadm.sh update realms/pharma-training -s 'smtpServer.starttls=true' …). A variable that is missing defaults to the relay's 587 with STARTTLS and authentication, never to plain text (#442).

  13. Login and admin events expire after 30 days (#448, #453, ADR 0040). In Keycloak's container, ./kcadm.sh get realms/pharma-training --fields 'eventsExpiration,attributes(adminEventsExpiration)' answers "eventsExpiration" : 2592000 and "attributes" : { "adminEventsExpiration" : "2592000" } (a plain attributes in --fields prints { } whatever the realm holds). A realm imported before these settings existed lacks them, since Keycloak imports the realm once: set them there with ./kcadm.sh update realms/pharma-training -s eventsExpiration=2592000 -s attributes.adminEventsExpiration=2592000 (after ./kcadm-otp.sh login <your name>), and read them back. The update keeps the realm's other attributes.

  14. Demo data on staging (#457). demo-seed-staging.yml runs on its own after each successful deploy run on main (ADR 0049), with the client and password of "The first deploy", step 6. Its log ends with Demo data: <n> created; a second run (Actions, demo-seed-staging, Run workflow) ends with Demo data: 0 created. Sign in at FRONTEND_URL as demo-markt-leitung with DEMO_USERS_PASSWORD and find Demo-Apotheke am Markt and its matrix. Exit 2 with /api/config.json's environment in the log means the edge does not report staging: check that the deploy ran with -e staging.

  15. The login pages wear the app's look (#502, ADR 0050). Open FRONTEND_URL signed out: Keycloak's sign-in page shows the app's tile and "Pharma Training" on one white card (dark when the system is dark) over the app's blue-to-turquoise backdrop, in Inter. A realm imported before #502 keeps Keycloak's stock look, since Keycloak imports the realm once; name the theme there, in Keycloak's container, as the administrator:

    cd /opt/keycloak/bin
    ./kcadm-otp.sh login <your name>
    ./kcadm.sh update realms/pharma-training -s loginTheme=pharma-training -s 'displayNameHtml=Pharma Training'
    ./kcadm.sh get realms/pharma-training --fields loginTheme,displayNameHtml

    The last command answers "loginTheme" : "pharma-training" and "displayNameHtml" : "Pharma Training". The update changes nothing else of the realm and can be run again; an environment whose realm is imported after #502 needs none of it. Then run E2E_BASE_URL=<FRONTEND_URL> pnpm exec playwright test e2e/login-theme.spec.ts from web/app and add its light and dark screenshots to #502.

  16. The environment's address changed (#588). Recreating the Container Apps environment gives it a new default domain (az containerapp env show -g <resource group> -n aca --query properties.defaultDomain). The PostgreSQL server, and with it Keycloak's database, stays. The workflows and the realm then still name the old domain, and x1-staging and demo-seed-staging fail with a name that does not resolve.

    • Set the environment's FRONTEND_URL to the edge's new address, https://host.<domain> (unless it is a domain of your own), and on staging also X1_KEYCLOAK_URL (https://auth.<domain>) and X1_MAILPIT_URL (https://mailpit.<domain>). Then run deploy.yml again, since the deploy reads FRONTEND_URL.
    • Keycloak imports the realm once, so the web client pharma-training-web keeps the redirect URIs and web origin of the address it was imported with, and refuses a sign-in from the new one with Invalid parameter: redirect_uri. Point it at the address the browser uses, in Keycloak's container, as the administrator:
    cd /opt/keycloak/bin
    ./kcadm-otp.sh login <your name>
    id=$(./kcadm.sh get clients -r pharma-training -q clientId=pharma-training-web --fields id --format csv --noquotes)
    ./kcadm.sh get clients/$id -r pharma-training --fields redirectUris,webOrigins
    ./kcadm.sh update clients/$id -r pharma-training -s 'redirectUris=["https://host.<domain>","https://host.<domain>/"]' -s 'webOrigins=["https://host.<domain>"]'
    • The second command shows the old address; after the update, the same command answers the new one. clear the terminal and remove ~/.keycloak/kcadm.config. Sign in at FRONTEND_URL, then start x1-staging and demo-seed-staging by hand (Actions, Run workflow), since the runs that followed the deploy used the old address.

Nothing in this repository has run against Azure before #129; record what you observed on #129 and in ADR 0005.

Deploy a release that adds a marker

A release whose migration backfills announced_events for a type the sweeps did not sweep before (Learning's and Assessment's AddAnnouncedEvents, #277; Assessment's AddAnnouncedFailuresAndExhaustions, #307) leaves a gap while the previous revision still runs: an event that revision stores after the migration ran has no marker, and the new sweep announces it a second time once the grace period has passed. For an ExaminationExhausted that is a second lock in Learning (ADR 0016). An environment that never ran a revision without the marker, such as one deployed for the first time with it, has no gap. Otherwise:

  1. Deploy it when nobody submits a test or reports progress (outside training hours), and note when the run starts.
  2. Once every app shows only the new revision active (az containerapp revision list -g <resource group> -n <app> -o table), search the services' logs for the sweep's Warning Re-announced <type> of stream <stream> at version <version>, stored at <time> without its announcement. with a stored time between the run's start and that moment. Each one is an announcement that went out twice. Record each on the release's issue with its stream and version, so that whoever owns Learning can correct the lock it counted twice.

Switch messaging from RabbitMQ to Service Bus (#532)

The first deploy with Service Bus (ADR 0053) replaces RabbitMQ in an environment that already runs. The new revisions have no RabbitMQ transport, so a message still on its way through RabbitMQ when they start would be lost or refused. Drain it first, then deploy. An environment deployed for the first time with Service Bus needs none of this.

Not before #547 and #553. #547 sends a course version's content by claim check, and #553 stops Editorial sending the older events that still embed it (CourseVersionPublishedV1 and V2, TestDefinitionPublishedV1). Until both have merged, a large course version's announcement exceeds Standard's 256 KB limit and stays in Editorial's outbox.

  1. Once per environment, before the deploy (as someone who may register providers and assign roles in the subscription):

    • Register the provider and wait until it is registered: az provider register --namespace Microsoft.ServiceBus --wait, which returns once az provider show --namespace Microsoft.ServiceBus --query registrationState answers "Registered". deploy.yml checks every provider of the one-time setup before it builds anything and fails naming the ones that are not registered.
    • Let the deploying identity assign the Service Bus roles: delete its Role Based Access Control Administrator assignment (az role assignment list --assignee <app id> --role "Role Based Access Control Administrator" --scope "$(az group show --name <resource group> --query id -o tsv)" --query "[].id" -o tsv, then az role assignment delete --ids <id>), and create it again with the six roles of the one-time setup's step 3.
  2. Stop new events. Outside training hours, turn off the edge's ingress, so nobody signs in or changes anything. Note its target port first, az containerapp ingress show -g <resource group> -n host --query targetPort, then az containerapp ingress disable -g <resource group> -n host. The services keep running and deliver what is still on its way. This changes no revision, which a Container App in single revision mode would not allow for its only active one, and the deploy in step 5 gives the edge its ingress back from the Bicep. Try it once on staging before production relies on it.

  3. Wait for the announcement sweeps, then until everything is delivered. Turning off the ingress stops new requests, not every publisher: Learning's and Assessment's announcement sweeps keep announcing events stored without an announcement once their grace period has passed (<module>:AnnouncementSweep, every minute with a two-minute grace period by default). Such an event is in none of the queries below until its sweep announces it.

    • Wait at least five minutes after step 2, longer if an environment sets a longer Interval or GracePeriod, and until no service has logged the sweep's Warning Re-announced <type> of stream <stream> at version <version>, … for a whole interval.
    • Then, in each module's database, as in Operators inside the network, repeat until all three answer 0:
    SELECT count(*) FROM wolverine.wolverine_outgoing_envelopes;
    SELECT count(*) FROM wolverine.wolverine_incoming_envelopes WHERE status <> 'Handled';
    SELECT count(*) FROM wolverine.wolverine_dead_letters WHERE replayable;

    and RabbitMQ holds nothing: az containerapp exec -g <resource group> -n messaging --command "rabbitmqctl list_queues name messages" lists 0 for every queue.

  4. Replay old dead letters now or never. A dead letter received from RabbitMQ (SELECT id, message_type, exception_type FROM wolverine.wolverine_dead_letters WHERE received_at LIKE 'rabbitmq://%';) cannot be replayed after the switch: a new revision refuses anything that did not come through its event's topic. Replay the ones worth it now (UPDATE wolverine.wolverine_dead_letters SET replayable = true WHERE id = '<id>';) and repeat step 3. The rest stay as a record.

  5. Deploy, and close the edge again at once. Run deploy.yml. Its MigrationRunner sends any outgoing envelope still addressed to RabbitMQ through its Service Bus topic instead (RabbitMqOutboxCutover), a backstop for what step 3 missed.

    • The deploy gives the edge its ingress back from the Bicep while the services' old revisions may still be running. As soon as the run has deployed the edge, turn its ingress off again: az containerapp ingress disable -g <resource group> -n host.
    • Leave it off until every app shows only the new revision active (az containerapp revision list -g <resource group> -n <app> -o table for the edge and each service), so no request reaches a service that still sends to RabbitMQ.
    • A request can still slip in between the deploy and that command; step 6 finds what it sent.
  6. Check, then remove RabbitMQ.

    • Run check 5 of What to check after the first deploy, apart from what needs the app in a browser, which comes with the last bullet.
    • In each module's database, SELECT count(*) FROM wolverine.wolverine_outgoing_envelopes WHERE destination LIKE 'rabbitmq://%'; answers 0. If an old revision stored one after the MigrationRunner ran, restart that module's service: az containerapp revision list -g <resource group> -n <service> -o table, then az containerapp revision restart -g <resource group> -n <service> --revision <revision>. Every new replica runs the MigrationRunner first, as its init container migrations, with the module's database and identity, and it retargets the rest. The migrations job only carries the image and has no module, connection string or identity, so starting it would retarget nothing.
    • rabbitmqctl list_queues name messages still lists 0 everywhere. A message there was sent after its consumer had switched. For Editorial's events, republish (POST /editorial/course-versions/republish, ADR 0019); record any other on #532 with its queue, type and count before going on.
    • Delete the RabbitMQ app, az containerapp delete -g <resource group> -n messaging, and the environment's MESSAGING_USERNAME, MESSAGING_PASSWORD and MESSAGING_SERVICES_KEY.
    • Open the app again: az containerapp ingress enable -g <resource group> -n host --type external --target-port <the port noted in step 2>. FRONTEND_URL answers, and the rest of check 5 (a published course version reaching Catalog, Compliance and Learning) can run.

Roll back

A deploy replaces every Container App's revision; the previous ones stay listed and can be activated, but the database stays where the newer revision left it.

  • Deploy an earlier commit: tag it and run deploy.yml at that tag, git tag deploy/<name> <commit> && git push origin deploy/<name> && gh workflow run deploy.yml --ref deploy/<name>. The commit must already have deploy.yml. It goes through staging and production's approval like any deploy.
  • One app, at once: az containerapp revision list -g <resource group> -n <app> -o table, then az containerapp revision copy -g <resource group> -n <app> --from-revision <revision> makes a new revision from the earlier one. The next deploy replaces it again.
  • Migrations run forward only. Nothing reverts a migration: an earlier revision runs its own (older) migrations, finds the newer ones already applied and starts against the newer schema. That works only because every migration is expand and contract, compatible with the release before it (ADR 0005); a migration that is not cannot be rolled back this way.
  • Data comes back only by a point-in-time restore of the Flexible Server into a new server, az postgres flexible-server restore -g <resource group> --name <new server> --source-server <server> --restore-time <UTC time> (backups kept 7 days in staging, 35 in production), and then pointing the deployment at it, which is a change in its own right. The restored server has a public endpoint of its own until its public access is disabled and it is given a private endpoint like the first (src/AppHost/network/network.bicep).

Frontend

cd web && pnpm install && pnpm build

The AppHost starts the web app with everything else (dotnet run --project src/AppHost).

web/package.json sets pnpm.ignoredOptionalDependencies: ["@napi-rs/canvas"] (JSON has no comments, so the reason is here). pdfjs-dist lists @napi-rs/canvas as an optional dependency for rendering in Node, which the browser never uses. Installed, it would also satisfy jsdom's optional canvas peer, so the unit tests would run on a real canvas and axe's label-content-name-mismatch rule would fail AppShell.axe.test.ts. Keep it out; drop the setting only when no package needs it excluded.

About

Prototype of pharma training plattform

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages