Skip to content

FHIR facade server (dhis2w_fhir_serve)

dhis2w_fhir_serve is the package behind d2w fhir serve: a FastAPI application that serves one generated IG as a FHIR endpoint and receives QuestionnaireResponse captures against it. It is its own workspace member because it needs FastAPI and uvicorn, and dhis2w-fhir - which generates a file tree - needs neither; pip install 'dhis2w-cli[serve]' (or uv add dhis2w-fhir-serve) is what puts the command on the CLI.

Everything a running facade serves is loaded once at startup and held on app.state.context, so a request is index lookups and nothing else. The store is either the compiled IG on disk or - under --live - the same read set built off a DHIS2 instance through one client opened during startup. That client stays open for the life of the process, because GET /Patient and the enrollment listing answer from the instance per request; no read of the store ever touches DHIS2 again.

The receipt spool is the one exception, and deliberately so: it is a path rather than a loaded index, and every read of it re-reads the directory. The server's own retries and d2w fhir forward both rename receipt files between the spool's four lifecycle directories while the server is up, so anything cached would be stale within seconds of a drain.

When to reach for it

  • Serve as a library in another ASGI process (create_app, ServeSettings), or mount its routers beside your own routes over a runtime you opened yourself (resolve_serve_settings, open_serve_runtime, attach_serve_runtime, serve_routers, register_error_handlers) - see Serve as a library.
  • Get the settings d2w fhir serve gets for the same project and the same flags, precedence rules included (resolve_serve_settings, ServeInvocation). That includes when captures go to DHIS2: a ServeSettings you build by hand holds them until told otherwise.
  • Load a project's store, spool, and register surface without an HTTP server at all (open_serve_runtime, ServeRuntime, ServeContext).
  • Build the served read set off a live DHIS2 instance, over a client you hold open (open_live_client, build_live_store, build_store).
  • Translate a concept through the ConceptMaps a project publishes, with no server running (find_translations, TranslateRequest, TranslationMatch).
  • Run one FHIRPath expression, CQL library, or ELM library over a resource and read what the parser and the evaluator said about it (evaluate_source, EvaluationLanguage, EvaluationOutcome, EvaluationResult, EvaluationDiagnostic, json_safe, syntax_diagnostic).
  • Read an evaluation's Parameters input, and say an evaluation's answer as the Parameters a FHIR client reads (evaluation_ask, evaluation_parameters, EVALUATE_OPERATION_PATH).
  • Ask what a code means in the vocabularies one project publishes, with no server running (load_terminology, TerminologyState, LookedUpCode, ValidatedCode, ConceptProperty).
  • Answer a CDS Hooks invocation with cards built from a CQL library (CdsService, CdsDiscovery, CdsHookRequest, CdsHookResponse, CdsCard, CqlLibraryHookContext).
  • Page through the receipts a facade holds the way GET /facade/spool pages through them (page_of, SpoolCursor, SpoolPage, requested_page_size, requested_cursor).
  • Load a project's served resources without an HTTP server (load_compiled_store, ResourceStore, SearchQuery, IdentifierToken).
  • Read or write the receipt spool a running facade keeps, in any of its four lifecycle states (ResponseSpool, StoredReceipt, StoredResponseEnvelope, ResponseLifecycle, RECEIVED_RESPONSES_RELATIVE_PATH, WITHDRAWN_RESPONSES_RELATIVE_PATH).
  • Validate a QuestionnaireResponse against a served IG outside the endpoint (validate_response, build_capture_index, CaptureNaming, CodingResolverSet).
  • Generate a synthetic response against a served form (generate_response, draw_seed, resolve_period_type, MAXIMUM_SEED).
  • Render the FHIR error and outcome bodies the facade answers with (outcome, rejection_outcome, success_outcome, build_server_capability).
  • Read what a guide states about the tracked entities an instance holds, or search a DHIS2 instance for one, without an HTTP server (TrackedEntityIndex, PublishedAttribute, PublishedTrackedEntityType, RegisterSurface, ServedRegister, registered_entity_for, search_tracked_entities, fetch_tracked_entity, TrackedEntityEnrollment, TrackedEntityEnrollments).
  • Read a register's value filter, or narrow a search of your own by one (AttributeFilter, requested_attribute_filters, ATTRIBUTE_FILTER_PARAMETER, ATTRIBUTE_FILTER_OPERATOR).
  • Put something other than the DHIS2 instance behind a register search, or hold a copy of an instance as FHIR resources (NameSearchIndex, NameQuery, NameMatch, NameMatches, Dhis2NameSearchIndex, build_name_search_index, ProjectionStore, ProjectedResource, ProjectionBatch, ProjectionCursor).

Worked example - load a store and read one resource

from dhis2w_fhir_engine.facade.config import load_project
from dhis2w_fhir_engine.facade.store import SearchQuery, load_compiled_store

project = load_project()
store = load_compiled_store(project)

store.summary().counts_by_type
# {'CodeSystem': 42, 'Location': 1332, 'Organization': 1332, 'Questionnaire': 9, 'ValueSet': 42}

entry = store.by_type_and_id("Questionnaire", "BfMAe6Itzgt")
entry.body["title"]
# 'Child Health'

store.search("Questionnaire", SearchQuery(urls=("http://example.org/fhir/demo/Questionnaire/BfMAe6Itzgt",)))
# (StoreEntry(resource_type='Questionnaire', resource_id='BfMAe6Itzgt', ...),)

Serve as a library

create_app builds the whole server, and an application that already runs FastAPI wants the FHIR surface inside the process it has. That is four steps, and each one is a name:

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from dhis2w_fhir_engine.facade.config import load_project
from dhis2w_fhir_engine.facade.api.error_handlers import register_error_handlers
from dhis2w_fhir_engine.facade.api.routes.mounting import accept_head_wherever_get_is_served
from dhis2w_fhir_engine.facade.api.routes.negotiation import require_json_is_acceptable
from dhis2w_fhir_engine.facade.api.runtime import attach_serve_runtime
from dhis2w_fhir_engine.facade.settings import ServeSettings
from dhis2w_fhir_serve import open_serve_runtime, serve_routers
from fastapi import Depends, FastAPI

settings = resolve_serve_settings(load_project()).settings


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    async with open_serve_runtime(settings) as runtime:
        attach_serve_runtime(app, runtime)
        yield


application = FastAPI(lifespan=lifespan)
register_error_handlers(application)

routers = serve_routers(capture=settings.capture)
for router in routers.in_mount_order():
    accept_head_wherever_get_is_served(router)
for router in routers.fhir:
    application.include_router(router, dependencies=[Depends(require_json_is_acceptable)])
for router in routers.facade:
    application.include_router(router)
application.include_router(routers.read, dependencies=[Depends(require_json_is_acceptable)])

What each step is for:

  1. The settings. resolve_serve_settings applies the flag-over-[serve] precedence, resolves the DHIS2 profile, and refuses a project that has never been built. Constructing ServeSettings directly is supported too, and a facade built that way differs from d2w fhir serve on purpose rather than by accident.
  2. The runtime. open_serve_runtime loads the project, the store, the spool, the register surface, and the CapabilityStatement, and holds the DHIS2 client a live run reads through open for as long as the context manager is entered. Under auth = "dhis2" it holds a second connection beside it - ServeRuntime.caller_client, pointed at the same instance and carrying no credential - which is the pool a register read forwards each caller's own Authorization over; see credential pass-through. attach_serve_runtime puts all three things the handlers read onto the application, and nothing serves a request before it has been called.
  3. The routers. serve_routers states the mount requirements as data: the FHIR routers carry Depends(require_json_is_acceptable), the facade routers do not, the read catch-alls mount after every fixed path your application serves - /{resource_type} claims any one-segment path, so your own /health mounts first or it is gone - and every router gets the HEAD sweep, or a liveness probe asking HEAD /metadata reads a live facade as down. ServeRouters.guarded is the fourth requirement, and the one an application usually answers itself: see bring your own authentication.
  4. The error handlers. Without register_error_handlers, every typed refusal the facade raises - RegisterDisabledError, NotServedError, CaptureDisabledError - is a 500 with no OperationOutcome in it.

Pick what you mount

serve_routers answers every router this facade has, and an embedding application rarely wants all of them. The two collections it answers - fhir and facade - are what you narrow, and the route modules are where each router is imported from:

from dhis2w_fhir_engine.facade.api.metadata import router as metadata_router
from dhis2w_fhir_engine.facade.api.routes.capture import refusal_router as capture_refusal_router
from dhis2w_fhir_engine.facade.api.routes.capture import router as capture_router
from dhis2w_fhir_engine.facade.api.routes.cds import router as cds_router
from dhis2w_fhir_engine.facade.api.routes.enrollments import router as enrollments_router
from dhis2w_fhir_engine.facade.api.routes.evaluate import router as evaluate_router
from dhis2w_fhir_engine.facade.api.routes.spool import router as spool_router
from dhis2w_fhir_engine.facade.api.routes.terminology import router as terminology_router

Five named picks, each a pair of tuples in place of routers.fhir and routers.facade in the loop above. Every one of them still mounts serve_routers().read last, still wants the HEAD sweep, and still needs register_error_handlers - those three are not part of the choice.

Capture only. Receive submissions, and publish the forms they answer.

fhir = (metadata_router, capture_router)
facade = (spool_router,)

Capture and register. The same, plus who the submissions are about. The register itself claims no router - GET /Patient is the read catch-all dispatching to it - so what this pick adds beyond the one above is the enrollment listing a stage form picks from. Live runs only.

fhir = (metadata_router, capture_router)
facade = (spool_router, enrollments_router)

Read-only guide server. Publish the guide and receive nothing. The refusal router claims POST /QuestionnaireResponse so the address answers 405 naming [serve] capture = false, rather than falling through to a 405 that says nothing.

fhir = (metadata_router, capture_refusal_router)
facade = ()

Evaluate playground. The guide, and the three surfaces that run over it: FHIRPath, CQL, and ELM evaluation, this guide's own vocabularies, and CDS Hooks.

fhir = (metadata_router,)
facade = (evaluate_router, terminology_router, cds_router)

The full facade. Every line above, in one call.

routers = serve_routers(capture=settings.capture)

Bring your own authentication

serve_routers answers a fourth value beside the three collections: guarded, the routers the authentication check belongs on for the posture and scope it was called with. It is a subset of the routers already in fhir, facade, and read, compared by identity through routers.is_guarded, so a router is mounted once and the guard is one more dependency on that mount.

d2w fhir serve mounts dhis2w_fhir_engine.facade.api.auth.require_authenticated over it. An application that already knows who its callers are mounts its own dependency instead - the set is the same set, and nothing else about the facade changes:

from dhis2w_fhir_engine.facade.api.routes.mounting import ServeRouters
from dhis2w_fhir_serve import serve_routers
from fastapi import Depends, Request


async def whoever_this_application_says(request: Request) -> None: ...  # raise your own 401 here


routers = serve_routers(capture=settings.capture, auth=settings.auth, auth_scope=settings.auth_scope)
for router in routers.fhir:
    guard = [Depends(whoever_this_application_says)] if routers.is_guarded(router) else []
    application.include_router(router, dependencies=[*guard, Depends(require_json_is_acceptable)])

A dependency mounted this way that wants its captures attributed writes a dhis2w_fhir_engine.facade.api.auth.RequestIdentity onto request.state under dhis2w_fhir_engine.facade.api.auth.REQUEST_IDENTITY_ATTRIBUTE; the capture route reads it there and stamps the username onto the receipt. An identity written with posture=ServeAuth.DHIS2 also puts the register reads on the pass-through path, where the request's own Authorization header is what reaches DHIS2 - so write that posture only for an identity whose credential DHIS2 itself would accept. register_routes takes the same seam as its authentication argument for an application that wants the facade's own mounting and its own check.

Two things stay outside this contract. The capture UI is not a router and is reached by running create_app with settings.ui; see the UI boundary. And a facade served under a path is mounted rather than included under a prefix: every fullUrl, self, and paging link is built from request.base_url, which carries an ASGI mount's path and not an include_router prefix.

A worked example of all of this is coming to the facade ladder in Write the route yourself, as the level above complex_facade.py: an application that mounts these routers rather than reimplementing them.

Reference

Settings

What one running facade is built from: the project it serves, whether the store is built live, which DHIS2 profile that build reads with, and how strictly a received code is checked - and how one invocation resolves all of that from a project's [serve] table and the dials it was given.

settings

The settings the FHIR facade app factory is built from, and how one invocation resolves them.

Classes

ServeInvocation

Bases: BaseModel

What one run of the facade resolved to: what it serves, where it listens, and the profile behind it.

The address is here rather than on ServeSettings because it is what the process binds and not what the app serves - the factory reads the settings and never asks where the socket is. The resolved profile is here for the sharper reason: it carries the credentials the store connects with, and the settings are handed to the app and read out again by /facade/uiconfig, so a profile on them would be a credential one HTTP response away from a browser. What the screens are entitled to - the instance's address - is on the settings as dhis2_base_url, and the name and the origin stay here, where the command that resolved them can say which profile it used.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/settings.py
class ServeInvocation(BaseModel):
    """What one run of the facade resolved to: what it serves, where it listens, and the profile behind it.

    The address is here rather than on `ServeSettings` because it is what the process binds and not
    what the app serves - the factory reads the settings and never asks where the socket is. The
    resolved profile is here for the sharper reason: it carries the credentials the store connects
    with, and the settings are handed to the app and read out again by `/facade/uiconfig`, so a profile on
    them would be a credential one HTTP response away from a browser. What the screens are entitled
    to - the instance's address - is on the settings as `dhis2_base_url`, and the name and the origin
    stay here, where the command that resolved them can say which profile it used.
    """

    model_config = ConfigDict(frozen=True)

    settings: ServeSettings
    host: str
    port: int
    generation: GenerationProfile | None = None

    held_until_asked: bool = False
    """Whether captures stay on this server because nothing asked for them to be sent, which a run says as it starts."""
Attributes
held_until_asked = False class-attribute instance-attribute

Whether captures stay on this server because nothing asked for them to be sent, which a run says as it starts.

Functions:

resolve_serve_settings(project, *, live=False, host=None, port=None, strict_codes=None, ui=None, basemaps=None, profile=None, auth=None, auth_scope=None, registry_package=None, delivery=None)

Resolve one invocation of the facade: a stated dial wins, then [serve], then this model's defaults.

Every argument is what one run stated and None is "stated nothing", which is why the booleans are bool | None rather than bool: --no-ui on a project whose table says ui = true has to be able to say False and be heard. live is the exception and takes a plain bool, because no [serve] key answers it - a live store is a property of the run.

basemaps are the raw --basemap strings, read through basemaps_from_options; stating none leaves the table's layers alone. A value that names nothing servable raises ValueError, which is the caller's to render - d2w fhir serve renders it against the flag the value came from.

Two of [serve] have no dial at all and are carried across verbatim: capture, which says what this server offers rather than what one run does, and spool_dir, which says where the receipts a previous run wrote already live.

The profile is resolved here, before anything is built, so a named profile that does not exist refuses the run rather than failing under a banner saying the server is starting. A machine that names no profile at all resolves to None and serves its compiled guide offline, which is a whole posture rather than a degraded one; live makes the profile required, since a live store has an instance to read. The address it resolved is what the screens link an identity out to, and it is the only part of the profile that reaches the settings - the name, the origin, and the credentials stay on the invocation, which never leaves the process that opened it.

The compiled guide is checked last, and only when the store is the one on disk: a project that has never run SUSHI has nothing to serve, and refusing here says so in one line rather than answering every read with a 404.

THE AUTH POSTURE IS PREFLIGHTED HERE TOO, and for the same reason every other refusal is: a server that starts and then cannot honour what it was asked for is a failure nobody reads until somebody meets it. Five refusals, in dhis2w_fhir_engine.facade.api.auth.preflight_auth: an interface other than loopback while neither this run nor fhir.toml has stated a posture, the token posture with its environment variable unset, the dhis2 posture on a run that reads a compiled guide and so has no instance to check anybody against, the jwt posture with no [serve.jwt] issuer, and [serve.jwt] forward_bearer on a run with no instance to forward to. Whether the posture was STATED is what the first of those turns on - auth = "none" written down is a decision, an absent key is not - so a stated flag counts as much as a stated table key, and only the two of them being silent is silence.

The sixth thing that could stop a jwt run - an issuer this machine cannot reach - is a round trip, so it is not made here: open_serve_runtime reads the issuer while the server starts and refuses with the same error type. This function reads values.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/settings.py
def resolve_serve_settings(
    project: FhirProject,
    *,
    live: bool = False,
    host: str | None = None,
    port: int | None = None,
    strict_codes: bool | None = None,
    ui: bool | None = None,
    basemaps: list[str] | None = None,
    profile: str | None = None,
    auth: ServeAuth | None = None,
    auth_scope: ServeAuthScope | None = None,
    registry_package: Path | None = None,
    delivery: CaptureDelivery | None = None,
) -> ServeInvocation:
    """Resolve one invocation of the facade: a stated dial wins, then `[serve]`, then this model's defaults.

    Every argument is what one run stated and None is "stated nothing", which is why the
    booleans are `bool | None` rather than `bool`: `--no-ui` on a project whose table says
    `ui = true` has to be able to say False and be heard. `live` is the exception and takes a
    plain bool, because no `[serve]` key answers it - a live store is a property of the run.

    `basemaps` are the raw `--basemap` strings, read through `basemaps_from_options`; stating
    none leaves the table's layers alone. A value that names nothing servable raises
    `ValueError`, which is the caller's to render - `d2w fhir serve` renders it against the
    flag the value came from.

    Two of `[serve]` have no dial at all and are carried across verbatim: `capture`, which says
    what this server offers rather than what one run does, and `spool_dir`, which says where the
    receipts a previous run wrote already live.

    The profile is resolved here, before anything is built, so a named profile that does not
    exist refuses the run rather than failing under a banner saying the server is starting. A
    machine that names no profile at all resolves to None and serves its compiled guide offline,
    which is a whole posture rather than a degraded one; `live` makes the profile required,
    since a live store has an instance to read. The address it resolved is what the screens link
    an identity out to, and it is the only part of the profile that reaches the settings - the
    name, the origin, and the credentials stay on the invocation, which never leaves the process
    that opened it.

    The compiled guide is checked last, and only when the store is the one on disk: a project
    that has never run SUSHI has nothing to serve, and refusing here says so in one line rather
    than answering every read with a 404.

    THE AUTH POSTURE IS PREFLIGHTED HERE TOO, and for the same reason every other refusal is: a
    server that starts and then cannot honour what it was asked for is a failure nobody reads
    until somebody meets it. Five refusals, in `dhis2w_fhir_engine.facade.api.auth.preflight_auth`: an
    interface other than loopback while neither this run nor fhir.toml has stated a posture, the
    `token` posture with its environment variable unset, the `dhis2` posture on a run that reads
    a compiled guide and so has no instance to check anybody against, the `jwt` posture with no
    `[serve.jwt] issuer`, and `[serve.jwt] forward_bearer` on a run with no instance to forward
    to. Whether the posture was STATED is what the first of those turns on - `auth = "none"`
    written down is a decision, an absent key is not - so a stated flag counts as much as a
    stated table key, and only the two of them being silent is silence.

    The sixth thing that could stop a `jwt` run - an issuer this machine cannot reach - is a
    round trip, so it is not made here: `open_serve_runtime` reads the issuer while the server
    starts and refuses with the same error type. This function reads values.
    """
    serve_config = project.config.serve
    stated_basemaps = list(basemaps or [])
    # The refusals are ordered as a reader meets them: a value this run stated and cannot mean
    # is answered before a profile is looked up, and both before the guide on disk is counted.
    resolved_basemaps = basemaps_from_options(stated_basemaps) if stated_basemaps else list(serve_config.basemaps)
    resolved_host = host if host is not None else serve_config.host
    resolved_auth = auth if auth is not None else serve_config.auth
    preflight_auth(
        posture=resolved_auth if resolved_auth is not None else ServeAuth.NONE,
        host=resolved_host,
        live=live,
        stated=auth is not None or serve_config.auth is not None,
        jwt=serve_config.jwt,
    )
    generation = _resolved_generation(project, profile, required=live)
    stated_delivery = delivery if delivery is not None else serve_config.delivery
    posts_as_each_caller = resolved_auth is ServeAuth.DHIS2 or (
        resolved_auth is ServeAuth.JWT and serve_config.jwt.forward_bearer
    )
    # `profile` says which DHIS2 to read metadata from, and a project can point it at a national instance to build a
    # guide. One test submission must not be able to write there, so writing as this run's one account has to be asked
    # for. A caller presenting their own account has asked, and DHIS2 applies their rights rather than an admin's.
    resolved_delivery = stated_delivery or (CaptureDelivery.AT_ONCE if posts_as_each_caller else CaptureDelivery.HOLD)
    held_until_asked = stated_delivery is None and resolved_delivery is CaptureDelivery.HOLD
    if not live and not any((project.ig_directory / COMPILED_RESOURCES_RELATIVE_PATH).glob("*.json")):
        raise compiled_guide_missing(project.config.registry_dependency)
    # The registry a guide depends on is preflighted for the reason every other refusal is: a
    # facade that starts and then serves no organisation unit is a failure nobody meets until
    # they open the picker. Both store modes read the package, so both are preflighted: a live
    # run over a registry-mode guide serves the package's units rather than building its own,
    # and a run that can reach neither source refuses here rather than publishing a second
    # identity for every place at the guide's base URL.
    resolve_registry_source(project, package=registry_package)
    return ServeInvocation(
        settings=ServeSettings(
            project_dir=project.project_root,
            publishes=project.config.ig.publishes,
            organisation_unit_geometry=(
                None
                if project.config.registry_dependency is not None
                else project.config.generate.organisation_units.geometry
            ),
            registry_package=registry_package,
            live=live,
            profile=profile,
            auth=resolved_auth if resolved_auth is not None else ServeAuth.NONE,
            auth_scope=auth_scope if auth_scope is not None else serve_config.auth_scope,
            jwt=serve_config.jwt,
            strict_codes=strict_codes if strict_codes is not None else serve_config.strict_codes,
            capture=serve_config.capture,
            capture_delivery=resolved_delivery,
            delivery_retry_seconds=serve_config.delivery_retry_seconds,
            ui=ui if ui is not None else serve_config.ui,
            spool_dir=serve_config.spool_dir,
            basemaps=resolved_basemaps,
            dhis2_base_url=None if generation is None else generation.profile.base_url,
            tracked_entities=serve_config.tracked_entities,
            data_sets=serve_config.data_sets,
            search=serve_config.search,
            projection=serve_config.projection,
        ),
        host=resolved_host,
        port=port if port is not None else serve_config.port,
        generation=generation,
        held_until_asked=held_until_asked,
    )

The runtime

What one loaded facade holds - the project, its store, its spool, its register surface, the statement it answers /metadata with, and the DHIS2 client a live run reads through - as a value a caller can open without starting a server. The lifespan is its first caller.

runtime

What one running facade holds, as a value a caller can open without starting a server.

A facade is a project, the resources it serves, the spool it writes receipts into, the register it answers for, and - under --live - one DHIS2 client held open for the life of the process. Loading all of that is what the ASGI lifespan does, and it is the only thing the lifespan does: this module is those steps, in order, behind an async context manager, and dhis2w_fhir_serve.app is its first caller.

That split is what lets a test, a batch job, or an embedding application have a loaded store, a spool, and a register surface for a project without building an application it never intends to serve - and it is what lets an application that already runs FastAPI mount the facade's routers over a runtime it opened itself, which is the contract attach_serve_runtime states.

The client's lifetime is the context manager's: entering opens it when the settings say the store is built live, leaving closes it, and a caller that already holds an authenticated one hands it in and keeps ownership of it. It rides beside the served context rather than on it, for the reason dhis2w_fhir_engine.facade.api.routes.context gives - a Pydantic model of what a facade serves is not the place for a live HTTP connection - and ServeRuntime is the name for the pair.

A live run that forwards credentials - [serve] auth = "dhis2", or "jwt" with [serve.jwt] forward_bearer = true - opens a second connection to the same instance, and this one carries no credential: it is the pool a register read sends the CALLER'S own Authorization over, so DHIS2 decides per caller what comes back. dhis2w_fhir_engine.facade.api.passthrough states why, and opens it; the lifespan owns it exactly as it owns the client, so both close when the process unwinds.

A project holding a materialized projection opens it here too - [serve.projection] store names the backend, dhis2w_fhir_serve.projection.factory builds it, and this context manager owns it exactly as it owns the two HTTP connections, so the database closes when the process unwinds. It is opened whether or not [serve.search] reads it, because a projection is a thing this project holds rather than a thing one search does.

A run under [serve] auth = "jwt" also reads its issuer here, before anything is served: the discovery document and then the keys it names. That is a network read at startup and it is a deliberate one - an issuer this machine cannot reach is a posture this process cannot honour, and finding that out on a caller's behalf would mean a server that starts and 401s everybody for a reason none of them can act on. dhis2w_fhir_serve.oidc does the reading and auth.open_jwt_verifier turns a failure into the same refusal the other postures raise.

Classes

Functions:

open_serve_runtime(settings, *, client=None) async

Load one facade: the project, its store, its spool, its register, and the statement it answers /metadata with.

Entering opens the DHIS2 client a live run reads through and leaving closes it. A caller that already holds an authenticated client hands it in instead, and keeps it open afterwards - the runtime never closes a connection it did not open. Handing one to a run that is not live is refused rather than ignored: live is what says this facade reads an instance, and a client beside live = False is two statements that disagree.

A live run under a forwarding posture opens the credential-free pool beside it, which is what a register read forwards the caller's own header over. It is opened here, rather than lazily at the first request, because it is the connection that decides whose rights an answer is read under: a process that could not open it should refuse to serve rather than discover that on a caller's behalf. A run under the jwt posture reads its issuer here for the same reason - the discovery document and the keys it names, before a single request is taken.

Nothing here is retried and nothing is defaulted. CompiledIgMissingError from a project that has never been built, or an unreachable instance, propagates out and the server refuses to start, rather than serving an empty guide that reads to a client as a project that published nothing.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/runtime.py
@asynccontextmanager
async def open_serve_runtime(
    settings: ServeSettings, *, client: Dhis2Client | None = None
) -> AsyncGenerator[ServeRuntime]:
    """Load one facade: the project, its store, its spool, its register, and the statement it answers `/metadata` with.

    Entering opens the DHIS2 client a live run reads through and leaving closes it. A caller that
    already holds an authenticated client hands it in instead, and keeps it open afterwards - the
    runtime never closes a connection it did not open. Handing one to a run that is not live is
    refused rather than ignored: `live` is what says this facade reads an instance, and a client
    beside `live = False` is two statements that disagree.

    A live run under a forwarding posture opens the credential-free pool beside it, which is what a
    register read forwards the caller's own header over. It is opened here, rather than lazily at
    the first request, because it is the connection that decides whose rights an answer is read
    under: a process that could not open it should refuse to serve rather than discover that on a
    caller's behalf. A run under the `jwt` posture reads its issuer here for the same reason - the
    discovery document and the keys it names, before a single request is taken.

    Nothing here is retried and nothing is defaulted. `CompiledIgMissingError` from a project that
    has never been built, or an unreachable instance, propagates out and the server refuses to
    start, rather than serving an empty guide that reads to a client as a project that published
    nothing.
    """
    if client is not None and not settings.live:
        raise ValueError("a DHIS2 client is only read through by a live run: build the settings with live=True")
    project = load_project(settings.project_dir)
    async with AsyncExitStack() as connections:
        live = client
        if settings.live and live is None:
            live = await connections.enter_async_context(open_live_client(project, settings))
        caller = None
        if live is not None and settings.forwards_credentials and settings.dhis2_base_url is not None:
            caller = await connections.enter_async_context(
                open_pass_through_client(settings.dhis2_base_url, provenance=facade_provenance())
            )
        verifier = await open_jwt_verifier(settings.jwt) if settings.auth is ServeAuth.JWT else None
        projection = await connections.enter_async_context(
            open_projection_store(settings.projection, project_root=project.project_root)
        )
        store = await build_store(settings, project, live)
        spool = ResponseSpool.at(project.project_root, settings.spool_dir)
        delivery = CaptureDeliverer(
            project=project,
            spool=spool,
            mode=settings.capture_delivery,
            posts_as_caller=settings.forwards_credentials,
            connect=_delivery_connection(project, settings, live),
            retry_seconds=settings.delivery_retry_seconds,
            held_note=HELD_UNTIL_ASKED,
        )
        if settings.capture:
            delivery.start()
            connections.push_async_callback(delivery.stop)
        register_surface = RegisterSurface.resolve(
            TrackedEntityIndex.from_store(project, store), settings.tracked_entities
        )
        metadata = build_served_metadata(
            project=project,
            store_summary=store.summary(),
            settings=settings,
            register_surface=register_surface,
            server_version=server_version(),
        )
        yield ServeRuntime(
            context=ServeContext(
                project=project,
                store=store,
                spool=spool,
                settings=settings,
                register_surface=register_surface,
                capability_body=metadata.body,
                declared_resource_types=metadata.declared_resource_types,
            ),
            live_client=live,
            caller_client=caller,
            jwt_verifier=verifier,
            projection_store=projection,
            delivery=delivery,
        )

build_store(settings, project, client) async

Select the store the facade serves from: the compiled IG on disk, or one built live from DHIS2.

client is the connection a live run holds open, and None in the default mode - the two are the same fact stated once, which is why the caller opens it rather than this function.

Both paths are deliberate about failing loudly, and neither is retried: CompiledIgMissingError or an unreachable instance propagates out of the lifespan and the server refuses to start, rather than serving an empty IG that reads to a client as a project that published nothing.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/runtime.py
async def build_store(settings: ServeSettings, project: FhirProject, client: Dhis2Client | None) -> ResourceStore:
    """Select the store the facade serves from: the compiled IG on disk, or one built live from DHIS2.

    `client` is the connection a live run holds open, and None in the default mode - the two are the
    same fact stated once, which is why the caller opens it rather than this function.

    Both paths are deliberate about failing loudly, and neither is retried: `CompiledIgMissingError`
    or an unreachable instance propagates out of the lifespan and the server refuses to start,
    rather than serving an empty IG that reads to a client as a project that published nothing.
    """
    if client is not None:
        return attach_builtin_conformance(await build_live_store(project, settings, client))
    return attach_builtin_conformance(load_compiled_store(project, registry_package=settings.registry_package))

open_projection_store(config, *, project_root) async

Open the projection this project holds, closing it on the way out, or hold none where it names none.

Nothing is read while it opens and nothing is refused: a projection nobody has synced into is a valid state of a valid file, and the surface that would answer out of it says so per request rather than stopping the server. That keeps R11 true - a facade configured with a projection is not a facade that fails differently from one without.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/runtime.py
@asynccontextmanager
async def open_projection_store(
    config: ProjectionConfig, *, project_root: Path
) -> AsyncGenerator[ProjectionStore | None]:
    """Open the projection this project holds, closing it on the way out, or hold none where it names none.

    Nothing is read while it opens and nothing is refused: a projection nobody has synced into is a
    valid state of a valid file, and the surface that would answer out of it says so per request
    rather than stopping the server. That keeps R11 true - a facade configured with a projection is
    not a facade that fails differently from one without.
    """
    store = build_projection_store(config, project_root=project_root)
    if store is None:
        yield None
        return
    try:
        yield store
    finally:
        await _closed(store)

Application

The app factory and the lifespan that opens the runtime and attaches it.

app

The FastAPI application: what the process loads at startup, and what every route reads from.

The factory takes settings and returns an app; everything the app serves is loaded once in the lifespan and held on app.state.context. That is what makes the facade cheap - the store is parsed once, the CapabilityStatement is rendered once, and a request does index lookups and nothing else. What the lifespan loads is dhis2w_fhir_serve.runtime's to say: this module opens one runtime, attaches it, and says in one log line what was loaded.

The spool is the one exception, and deliberately so: it is a path, not a loaded index, and every read of it re-reads the directory. d2w fhir forward runs as a separate process and moves receipt files between the spool's three states while this server is up, so anything cached here would go stale within seconds of a drain. See dhis2w_fhir_engine.facade.response_spool.

The default mode is fully offline: a compiled IG on disk is the whole world, and no DHIS2 client is constructed anywhere in this module. --live swaps the store for one built from a DHIS2 instance, and keeps the client that built it open for the life of the process, because the register routes answer from the instance per request rather than from anything loaded here. That client is the only thing in a running facade that is neither the store nor the spool, and it lives on app.state rather than on the context for the reason dhis2w_fhir_engine.facade.api.routes.context states. It is closed when the lifespan unwinds; the default mode never opens one, which is what makes the register routes live-only.

Classes

Functions:

create_app(settings)

Build the FHIR facade for one project, loading nothing until the lifespan runs.

THE APPLICATION THIS RETURNS PUBLISHES NO OPENAPI DOCUMENT, and that is about the base URL rather than about the process. The base URL is a FHIR endpoint, its contract is the CapabilityStatement at /metadata, and the two routes it mostly serves are catch-alls over application/fhir+json bodies that an OpenAPI document could only misdescribe as untyped JSON on a path variable.

The facade's OWN API - the receipts, the settings, the caller, the evaluator, the vocabularies, the register listings - is a different contract and gets a document of its own: register_routes mounts it as an application at /facade, with its OpenAPI at /facade/openapi.json and the interactive page at /facade/docs. The mounted application shares this one's state, so the runtime the lifespan attaches here is the runtime its handlers read. dhis2w_fhir_serve.routes states the whole arrangement.

settings.ui adds the built capture UI as a static mount at /, after every FHIR route. A missing bundle raises here, while the app is being built, so --ui on a checkout that has never built the frontend fails as one line rather than as a white page on the first request.

settings.capture decides which router claims POST /QuestionnaireResponse - the create route, or the refusal that names the key. It is settled here, at build time, because it is what this server offers rather than something a request could be judged against. settings.publishes beats it on a package, which claims that address with the refusal saying a package holds no form.

settings.auth and settings.auth_scope decide which routers carry the authentication check, which is settled at build time for the same reason. What the check then DOES is a request-time question and lives in dhis2w_fhir_engine.facade.api.auth; an application embedding the facade mounts its own dependency over the same set. Nothing secret reaches this factory: the tokens a token posture compares against are read from the environment by the check itself, never from the settings.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/app.py
def create_app(settings: ServeSettings) -> FastAPI:
    """Build the FHIR facade for one project, loading nothing until the lifespan runs.

    THE APPLICATION THIS RETURNS PUBLISHES NO OPENAPI DOCUMENT, and that is about the base URL rather
    than about the process. The base URL is a FHIR endpoint, its contract is the CapabilityStatement
    at `/metadata`, and the two routes it mostly serves are catch-alls over `application/fhir+json`
    bodies that an OpenAPI document could only misdescribe as untyped JSON on a path variable.

    The facade's OWN API - the receipts, the settings, the caller, the evaluator, the vocabularies,
    the register listings - is a different contract and gets a document of its own: `register_routes`
    mounts it as an application at `/facade`, with its OpenAPI at `/facade/openapi.json` and the
    interactive page at `/facade/docs`. The mounted application shares this one's `state`, so the
    runtime the lifespan attaches here is the runtime its handlers read. `dhis2w_fhir_serve.routes`
    states the whole arrangement.

    `settings.ui` adds the built capture UI as a static mount at `/`, after every FHIR route.
    A missing bundle raises here, while the app is being built, so `--ui` on a checkout that has
    never built the frontend fails as one line rather than as a white page on the first request.

    `settings.capture` decides which router claims `POST /QuestionnaireResponse` - the create route,
    or the refusal that names the key. It is settled here, at build time, because it is what this
    server offers rather than something a request could be judged against. `settings.publishes` beats
    it on a package, which claims that address with the refusal saying a package holds no form.

    `settings.auth` and `settings.auth_scope` decide which routers carry the authentication check,
    which is settled at build time for the same reason. What the check then DOES is a request-time
    question and lives in `dhis2w_fhir_engine.facade.api.auth`; an application embedding the facade mounts its own
    dependency over the same set. Nothing secret reaches this factory: the tokens a `token` posture
    compares against are read from the environment by the check itself, never from the settings.
    """
    app = FastAPI(
        title=APPLICATION_TITLE,
        version=server_version(),
        docs_url=None,
        redoc_url=None,
        openapi_url=None,
        lifespan=_lifespan,
    )
    app.state.settings = settings
    app.add_middleware(RequestLogMiddleware)
    register_error_handlers(app)
    register_routes(
        app,
        serve_ui=settings.ui,
        capture=settings.capture,
        auth=settings.auth,
        auth_scope=settings.auth_scope,
        publishes=settings.publishes,
    )
    return app

The routers

Every router the facade mounts, with what mounting it requires stated as data: which carry the Accept negotiation, which answer plain JSON about the facade rather than FHIR resources out of it, which claim every path of their shape and therefore mount last, and where the runtime state the handlers read is written and read back.

Two surfaces, two addresses. The base URL is FHIR's and /metadata is its contract; the routers that answer about the facade itself are mounted as an application of their own at FACADE_MOUNT_PATH (/facade), which publishes its own OpenAPI document at /facade/openapi.json and an interactive page at /facade/docs. Both stay readable under every [serve] auth_scope, for the reason /metadata does. /cds-services is the third family and stays at the base URL, because CDS Hooks fixes its discovery path there. An application embedding this facade beside its own routes gets the order, the split, and the guarded set as values from serve_routers, and mounts the facade API under whichever prefix it prefers.

routes

The two routers this package adds to the facade's own, and how it mounts them beside the capture UI.

Classes

Functions:

serve_routers(*, capture=True, serve_ui=False, auth=ServeAuth.NONE, auth_scope=ServeAuthScope.WRITE, publishes=None)

The facade's routers plus the two this server adds: the screens' document and the metadata health report.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/routes/__init__.py
def serve_routers(
    *,
    capture: bool = True,
    serve_ui: bool = False,
    auth: ServeAuth = ServeAuth.NONE,
    auth_scope: ServeAuthScope = ServeAuthScope.WRITE,
    publishes: str | None = None,
) -> ServeRouters:
    """The facade's routers plus the two this server adds: the screens' document and the metadata health report."""
    return facade_routers(
        capture=capture,
        serve_ui=serve_ui,
        auth=auth,
        auth_scope=auth_scope,
        publishes=publishes,
        instance_documents=(ui_config_router, metadata_health_router),
    )

register_routes(app, serve_ui=False, capture=True, auth=ServeAuth.NONE, auth_scope=ServeAuthScope.WRITE, authentication=None, publishes=None)

Mount what d2w fhir serve serves: the facade's routers, with the capture UI around them when asked for.

The UI mounts are not in ServeRouters: they are StaticFiles rather than routers, and their order requirement only makes sense inside this server's own route table. See dhis2w_fhir_serve.ui.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/routes/__init__.py
def register_routes(
    app: FastAPI,
    serve_ui: bool = False,
    capture: bool = True,
    auth: ServeAuth = ServeAuth.NONE,
    auth_scope: ServeAuthScope = ServeAuthScope.WRITE,
    authentication: Any = None,
    publishes: str | None = None,
) -> None:
    """Mount what `d2w fhir serve` serves: the facade's routers, with the capture UI around them when asked for.

    The UI mounts are not in `ServeRouters`: they are `StaticFiles` rather than routers, and their order
    requirement only makes sense inside this server's own route table. See `dhis2w_fhir_serve.ui`.
    """
    check = require_authenticated if authentication is None else authentication
    routers = serve_routers(capture=capture, serve_ui=serve_ui, auth=auth, auth_scope=auth_scope, publishes=publishes)
    if serve_ui:
        mount_ui_assets(app)
    mount_routers(app, routers, check)
    if serve_ui:
        mount_ui_shell(app)

The external issuer

Under [serve] auth = "jwt", callers arrive with a token an OpenID Connect issuer this facade does not run has minted. The issuer's discovery document and its JWKS are read once while the server starts - an issuer this machine cannot reach refuses the run - and every token is then verified in memory against those public keys: signature over the asymmetric algorithms only, iss, exp, nbf, and aud where one is configured. The keys are held for as long as their own Cache-Control asks, never below a floor, and an unknown kid forces one refetch so a key rotation is not an outage.

oidc

The jwt posture's machinery: one external OIDC issuer, its published keys, and what a token proves.

WHAT THIS POSTURE IS FOR. A ministry that already runs an identity provider has already answered "who is this person" for every system it fronts, and [serve] auth = "jwt" is this facade taking that answer instead of asking the question a second time. No authorization server is run here, no client secret is held here, and no token is minted here: a caller arrives with a token their own IdP gave them, and this module decides whether it is genuine, current, and meant for this server.

VALIDATION IS LOCAL AND OFFLINE-AFTER-THE-FIRST-FETCH. The issuer publishes its signing keys as a JWKS, this process reads that document, and every token is verified against those keys in memory. There is no introspection call, so a request costs no round trip to the IdP and the IdP is not in the path of every read. The cost of that is the one property token introspection would have bought: a token revoked before it expires stays valid here until it expires. That is the standard trade every JWKS validator makes, and the answer to it is short token lifetimes at the issuer.

THE KEYS ARE FETCHED ONCE AND HELD. Cache-Control: max-age on the JWKS answer is honoured, with a floor of JWKS_MINIMUM_CACHE_SECONDS: an issuer that sends max-age=0 would otherwise make every verification a round trip, which is the thing this design exists to avoid. There is no ceiling, and there does not need to be one - a key rotation shows up as a token signed by a kid this process does not hold, and an unknown kid forces one refetch on the spot. That refetch is itself floored by JWKS_REFETCH_FLOOR_SECONDS, so a caller sending nonsense kids cannot turn this facade into a load generator pointed at somebody's identity provider.

ONLY ASYMMETRIC SIGNATURES ARE ACCEPTED. JWT_ALGORITHMS is the RSA and ECDSA family and nothing else. A JWKS holds public keys, and accepting a symmetric algorithm beside them is the algorithm confusion attack in one line: a caller signs HS256 using the public modulus as the shared secret and the verifier, asked to accept "whatever the header says", agrees. The header is not asked.

WHAT A TOKEN HAS TO CARRY. A signature this issuer's keys verify; iss equal to the configured issuer; exp in the future; nbf in the past where it is stated; aud containing the configured audience where one is configured; and the claim [serve.jwt] username_claim names. That last one is the whole point of the exercise - it becomes the request identity, so a receipt captured under this posture records a person rather than a deployment.

CLOCK_LEEWAY_SECONDS is what a token's time claims are read with. Two machines that have never agreed on the second would otherwise refuse each other's perfectly good tokens for a minute either side of every boundary, and a minute of leeway is the standard allowance for that.

Classes

OidcIssuerUnavailableError

Bases: RuntimeError

The issuer this run was told to trust could not be read, so the posture cannot be honoured.

A startup failure rather than a request failure. dhis2w_fhir_engine.facade.api.auth.open_jwt_verifier turns it into the same ServeAuthConfigurationError the other posture refusals raise, so a deployer meets one line naming the key rather than a server that starts and 401s everybody.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/oidc.py
class OidcIssuerUnavailableError(RuntimeError):
    """The issuer this run was told to trust could not be read, so the posture cannot be honoured.

    A startup failure rather than a request failure. `dhis2w_fhir_engine.facade.api.auth.open_jwt_verifier`
    turns it into the same `ServeAuthConfigurationError` the other posture refusals raise, so a
    deployer meets one line naming the key rather than a server that starts and 401s everybody.
    """

PublishedKeys

Bases: BaseModel

One JWKS document as this process holds it, and until when it holds it.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/oidc.py
class PublishedKeys(BaseModel):
    """One JWKS document as this process holds it, and until when it holds it."""

    model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True)

    key_set: KeySet
    """The issuer's public keys, indexed by `kid` - what a signature is checked against."""

    fetched_at: float
    """A `time.monotonic` reading, so holding a document survives the machine's clock being set."""

    expires_at: float
    """When this document stops being reused, from `Cache-Control` and never below the floor."""
Attributes
key_set instance-attribute

The issuer's public keys, indexed by kid - what a signature is checked against.

fetched_at instance-attribute

A time.monotonic reading, so holding a document survives the machine's clock being set.

expires_at instance-attribute

When this document stops being reused, from Cache-Control and never below the floor.

JwtVerifier

Bases: BaseModel

One issuer's published keys, held for the life of the process, and the check they answer.

Built while the server starts, by discover_issuer, so a run whose issuer cannot be read is a line in a terminal rather than a 401 on every caller. It holds public keys and no secret of any kind, which is why it is safe to keep on the application where every request reaches it.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/oidc.py
class JwtVerifier(BaseModel):
    """One issuer's published keys, held for the life of the process, and the check they answer.

    Built while the server starts, by `discover_issuer`, so a run whose issuer cannot be read is a
    line in a terminal rather than a 401 on every caller. It holds public keys and no secret of any
    kind, which is why it is safe to keep on the application where every request reaches it.
    """

    model_config = ConfigDict(arbitrary_types_allowed=True)

    config: ServeJwtConfig
    """The `[serve.jwt]` table this run resolved - the issuer, the audience, and the claim to read."""

    issuer: str
    """The issuer identifier every token's `iss` is compared against, as the issuer publishes it."""

    jwks_uri: str
    """Where the keys come from, as `/.well-known/openid-configuration` named it."""

    held: PublishedKeys | None = Field(default=None, repr=False)
    """The keys this process is currently verifying against, or None until the first fetch."""

    forced_at: float | None = None
    """When an unknown `kid` last sent this process back to the issuer, or None while none has."""

    async def verify(self, token: str) -> VerifiedToken:
        """Accept one token, or say in one sentence why it is refused.

        The order is the order a reader would check it in: the signature first, because an unsigned
        assertion's claims are not evidence of anything; then what the claims say; then the claim
        that names the caller. An unknown `kid` is the one case that goes back to the issuer -
        a rotation is the ordinary reason a signature arrives under a key this process does not
        hold, and refusing it without looking would make every rotation an outage.
        """
        decoded = await self._decoded(token)
        self._claims_hold(decoded.claims)
        return VerifiedToken(
            username=self._named_caller(decoded.claims),
            subject=_string_claim(decoded.claims, "sub"),
            expires_at=_integer_claim(decoded.claims, "exp"),
        )

    async def keys(self, *, force: bool = False) -> PublishedKeys:
        """The issuer's keys, fetched when this process holds none, holds stale ones, or is forced.

        `force` is what an unknown `kid` asks for, and it is floored against the last FORCED read
        rather than against the last read of any kind: the first unknown `kid` after a rotation has
        to be able to see the new keys immediately, and every one after it within
        `JWKS_REFETCH_FLOOR_SECONDS` gets what is held. So a rotation costs one request and a stream
        of tokens naming keys that never existed costs this issuer one request a minute.
        """
        now = time.monotonic()
        held = self.held
        if held is not None and not force and held.expires_at > now:
            return held
        if (
            held is not None
            and force
            and self.forced_at is not None
            and now - self.forced_at < JWKS_REFETCH_FLOOR_SECONDS
        ):
            return held
        if force:
            self.forced_at = now
        fetched = await fetch_published_keys(self.jwks_uri)
        self.held = fetched
        return fetched

    async def _decoded(self, token: str) -> jose_jwt.Token:
        """Check one token's signature against the issuer's keys, refetching once for an unknown `kid`."""
        held = await self.keys()
        try:
            return self._decoded_against(token, held)
        except InvalidKeyIdError:
            pass
        except MissingKeyError:
            pass
        refetched = await self.keys(force=True)
        try:
            return self._decoded_against(token, refetched)
        except (InvalidKeyIdError, MissingKeyError) as error:
            raise TokenRefusedError(
                "the token this request carried is signed with a key this server could not find among "
                f"the ones `{self.issuer}` publishes, even after reading them again"
            ) from error

    def _decoded_against(self, token: str, held: PublishedKeys) -> jose_jwt.Token:
        """One decode against one set of keys, with every refusal but an unknown `kid` answered here."""
        try:
            return jose_jwt.decode(token, held.key_set, algorithms=list(JWT_ALGORITHMS))
        except (InvalidKeyIdError, MissingKeyError):
            raise
        except BadSignatureError as error:
            raise TokenRefusedError(
                "the token this request carried is not signed by the key it names, so this server "
                "cannot tell who issued it"
            ) from error
        except (JoseError, ValueError) as error:
            raise TokenRefusedError(
                "the value in `Authorization` is not a JSON Web Token this server can read "
                f"({error}); this server takes a token `{self.issuer}` minted"
            ) from error

    def _claims_hold(self, claims: dict[str, Any]) -> None:
        """Check what one token says about itself: who issued it, when it is good for, and for whom.

        `aud` is an option only where an audience is configured, and that is the difference between
        "this token is for somebody else" and "this server takes whatever this issuer signed". A
        registry that always required it would refuse every issuer that mints audience-less tokens.
        """
        required: dict[str, ClaimsOption] = {
            "iss": {"essential": True, "value": self.issuer},
            "exp": {"essential": True},
        }
        if self.config.audience is not None:
            required["aud"] = {"essential": True, "value": self.config.audience}
        registry = jose_jwt.JWTClaimsRegistry(now=int(time.time()), leeway=CLOCK_LEEWAY_SECONDS, **required)
        try:
            registry.validate(claims)
        except JoseError as error:
            raise TokenRefusedError(self._claim_refusal(claims, error)) from error

    def _claim_refusal(self, claims: dict[str, Any], error: JoseError) -> str:
        """What a caller is told about a token whose signature held and whose claims did not."""
        stated_issuer = _string_claim(claims, "iss")
        if stated_issuer is not None and stated_issuer.rstrip("/") != self.issuer:
            return (
                f"the token this request carried was issued by `{stated_issuer}`, and this server takes "
                f"tokens from `{self.issuer}`"
            )
        if self.config.audience is not None and not _audience_holds(claims, self.config.audience):
            return (
                f"the token this request carried is not for this server: it names no audience `{self.config.audience}`"
            )
        return f"the token this request carried is not currently valid ({error})"

    def _named_caller(self, claims: dict[str, Any]) -> str:
        """The claim `[serve.jwt] username_claim` names, refusing a token that names nobody."""
        named = _string_claim(claims, self.config.username_claim)
        if named is None or named.strip() == "":
            raise TokenRefusedError(
                f"the token this request carried carries no `{self.config.username_claim}` claim, and this "
                "server records who captured every response; state the claim your issuer puts the "
                "username in as `[serve.jwt] username_claim`"
            )
        return named.strip()
Attributes
config instance-attribute

The [serve.jwt] table this run resolved - the issuer, the audience, and the claim to read.

issuer instance-attribute

The issuer identifier every token's iss is compared against, as the issuer publishes it.

jwks_uri instance-attribute

Where the keys come from, as /.well-known/openid-configuration named it.

held = Field(default=None, repr=False) class-attribute instance-attribute

The keys this process is currently verifying against, or None until the first fetch.

forced_at = None class-attribute instance-attribute

When an unknown kid last sent this process back to the issuer, or None while none has.

Methods:
verify(token) async

Accept one token, or say in one sentence why it is refused.

The order is the order a reader would check it in: the signature first, because an unsigned assertion's claims are not evidence of anything; then what the claims say; then the claim that names the caller. An unknown kid is the one case that goes back to the issuer - a rotation is the ordinary reason a signature arrives under a key this process does not hold, and refusing it without looking would make every rotation an outage.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/oidc.py
async def verify(self, token: str) -> VerifiedToken:
    """Accept one token, or say in one sentence why it is refused.

    The order is the order a reader would check it in: the signature first, because an unsigned
    assertion's claims are not evidence of anything; then what the claims say; then the claim
    that names the caller. An unknown `kid` is the one case that goes back to the issuer -
    a rotation is the ordinary reason a signature arrives under a key this process does not
    hold, and refusing it without looking would make every rotation an outage.
    """
    decoded = await self._decoded(token)
    self._claims_hold(decoded.claims)
    return VerifiedToken(
        username=self._named_caller(decoded.claims),
        subject=_string_claim(decoded.claims, "sub"),
        expires_at=_integer_claim(decoded.claims, "exp"),
    )
keys(*, force=False) async

The issuer's keys, fetched when this process holds none, holds stale ones, or is forced.

force is what an unknown kid asks for, and it is floored against the last FORCED read rather than against the last read of any kind: the first unknown kid after a rotation has to be able to see the new keys immediately, and every one after it within JWKS_REFETCH_FLOOR_SECONDS gets what is held. So a rotation costs one request and a stream of tokens naming keys that never existed costs this issuer one request a minute.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/oidc.py
async def keys(self, *, force: bool = False) -> PublishedKeys:
    """The issuer's keys, fetched when this process holds none, holds stale ones, or is forced.

    `force` is what an unknown `kid` asks for, and it is floored against the last FORCED read
    rather than against the last read of any kind: the first unknown `kid` after a rotation has
    to be able to see the new keys immediately, and every one after it within
    `JWKS_REFETCH_FLOOR_SECONDS` gets what is held. So a rotation costs one request and a stream
    of tokens naming keys that never existed costs this issuer one request a minute.
    """
    now = time.monotonic()
    held = self.held
    if held is not None and not force and held.expires_at > now:
        return held
    if (
        held is not None
        and force
        and self.forced_at is not None
        and now - self.forced_at < JWKS_REFETCH_FLOOR_SECONDS
    ):
        return held
    if force:
        self.forced_at = now
    fetched = await fetch_published_keys(self.jwks_uri)
    self.held = fetched
    return fetched

Functions:

discover_issuer(config) async

Read one issuer's discovery document and its keys, or refuse the run that asked for it.

Both reads happen while the server starts, and both have to succeed. An issuer that cannot be reached is a posture this process cannot honour, and a facade that started anyway would refuse every caller for a reason none of them could act on.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/oidc.py
async def discover_issuer(config: ServeJwtConfig) -> JwtVerifier:
    """Read one issuer's discovery document and its keys, or refuse the run that asked for it.

    Both reads happen while the server starts, and both have to succeed. An issuer that cannot be
    reached is a posture this process cannot honour, and a facade that started anyway would refuse
    every caller for a reason none of them could act on.
    """
    if config.issuer is None:
        raise OidcIssuerUnavailableError("no issuer is configured")
    discovery = await fetch_issuer_discovery(config.issuer)
    verifier = JwtVerifier(config=config, issuer=discovery.issuer.rstrip("/"), jwks_uri=discovery.jwks_uri)
    verifier.held = await fetch_published_keys(discovery.jwks_uri)
    return verifier

fetch_issuer_discovery(issuer) async

Read {issuer}/.well-known/openid-configuration, which is where the keys are named.

The issuer the document states is taken over the one that was configured, because that is the value its tokens carry as iss - an issuer reached at one URL and identifying itself as another is a deployment behind a proxy, and comparing against what it says about itself is what makes that work. It has to identify itself as something, and a document that names no jwks_uri names no keys, so both are required fields on the model this parses into.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/oidc.py
async def fetch_issuer_discovery(issuer: str) -> OidcDiscovery:
    """Read `{issuer}/.well-known/openid-configuration`, which is where the keys are named.

    The issuer the document states is taken over the one that was configured, because that is the
    value its tokens carry as `iss` - an issuer reached at one URL and identifying itself as another
    is a deployment behind a proxy, and comparing against what it says about itself is what makes
    that work. It has to identify itself as something, and a document that names no `jwks_uri` names
    no keys, so both are required fields on the model this parses into.
    """
    url = issuer.rstrip("/") + DISCOVERY_PATH
    try:
        async with httpx2.AsyncClient(timeout=ISSUER_TIMEOUT_SECONDS, follow_redirects=True) as http:
            answer = await http.get(url, headers={"Accept": "application/json"})
    except httpx2.HTTPError as error:
        raise OidcIssuerUnavailableError(f"`{url}` could not be read ({error})") from error
    if answer.status_code >= 400:
        raise OidcIssuerUnavailableError(f"`{url}` answered {answer.status_code}")
    try:
        return OidcDiscovery.model_validate(answer.json())
    except ValueError as error:
        raise OidcIssuerUnavailableError(
            f"`{url}` did not answer with an OpenID Connect configuration naming an issuer and a `jwks_uri` ({error})"
        ) from error

fetch_published_keys(jwks_uri) async

Read one JWKS document and hold it for as long as its own Cache-Control asks, within the floor.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/oidc.py
async def fetch_published_keys(jwks_uri: str) -> PublishedKeys:
    """Read one JWKS document and hold it for as long as its own `Cache-Control` asks, within the floor."""
    try:
        async with httpx2.AsyncClient(timeout=ISSUER_TIMEOUT_SECONDS, follow_redirects=True) as http:
            answer = await http.get(jwks_uri, headers={"Accept": "application/json"})
    except httpx2.HTTPError as error:
        raise OidcIssuerUnavailableError(f"`{jwks_uri}` could not be read ({error})") from error
    if answer.status_code >= 400:
        raise OidcIssuerUnavailableError(f"`{jwks_uri}` answered {answer.status_code}")
    try:
        key_set = KeySet.import_key_set(answer.json())
    except (ValueError, KeyError, JoseError) as error:
        raise OidcIssuerUnavailableError(f"`{jwks_uri}` did not answer with a JSON Web Key Set ({error})") from error
    now = time.monotonic()
    return PublishedKeys(key_set=key_set, fetched_at=now, expires_at=now + cache_seconds(answer.headers))

cache_seconds(headers)

How long one JWKS answer is held: what it asked for, never below JWKS_MINIMUM_CACHE_SECONDS.

The floor is the whole of the policy. An issuer that sends max-age=0 - which several do, out of caution about a document that is not secret - would otherwise make every verified request a round trip to that issuer, which is slower than the introspection call this design exists to avoid. There is no ceiling, because a rotation is caught by the unknown-kid refetch rather than by an expiry nobody set.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/oidc.py
def cache_seconds(headers: httpx2.Headers) -> float:
    """How long one JWKS answer is held: what it asked for, never below `JWKS_MINIMUM_CACHE_SECONDS`.

    The floor is the whole of the policy. An issuer that sends `max-age=0` - which several do, out
    of caution about a document that is not secret - would otherwise make every verified request a
    round trip to that issuer, which is slower than the introspection call this design exists to
    avoid. There is no ceiling, because a rotation is caught by the unknown-`kid` refetch rather
    than by an expiry nobody set.
    """
    stated = _max_age(headers.get("cache-control", ""))
    if stated is None:
        return JWKS_DEFAULT_CACHE_SECONDS
    return max(stated, JWKS_MINIMUM_CACHE_SECONDS)

The projection seams

Reach for these when you are putting something other than the DHIS2 instance behind a register search, or holding a copy of an instance as FHIR resources. NameSearchIndex is what every register search runs through: it answers with tracked entity identifiers and scores and never with records, so the record behind a match is read back live, under the caller's own credentials, and DHIS2 authorizes each disclosure exactly as it does today. ProjectionStore is the durable document backend beside it, written by a sync and by nothing else. The design is the materialized projection, sections 7 and 9.

Two backends of each ship. Dhis2NameSearchIndex is the instance itself, which is what [serve.search] backend = "dhis2" selects and what a server that states no [serve.search] runs; it improves nothing over the search a live run has always run, and proving the seam is its whole job. SqliteProjectionStore and SqliteNameSearchIndex are the other half - one file under the project, selected together by [serve.projection] store = "sqlite" and [serve.search] backend = "projection".

factory

Which backend a projection is held in and a register search runs through, chosen from fhir.toml.

Two match statements over two config enums, rather than a registry, for the reason docs/design/projection.md section 7 gives for following AuthProvider: a backend a deployment has not installed should be a refusal the operator reads at the config key that asked for it, not an import error from inside a request.

build_projection_store answers what [serve.projection] store names, and None where it names nothing - which is the zero-ops default and the posture R11 says must stay the product rather than become a degraded mode. build_name_search_index answers what [serve.search] backend names, over the connection a live search reads and the store a synced one reads.

Classes

Functions:

projection_path(config, *, project_root)

Where this project's projection lives - relative to the project root unless it is absolute.

The same rule [serve] spool_dir follows, and stated once here so the process that fills the projection and the process that serves it can never land on two different files.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/factory.py
def projection_path(config: ProjectionConfig, *, project_root: Path) -> Path:
    """Where this project's projection lives - relative to the project root unless it is absolute.

    The same rule `[serve] spool_dir` follows, and stated once here so the process that fills the
    projection and the process that serves it can never land on two different files.
    """
    stated = Path(config.path)
    return stated if stated.is_absolute() else project_root / stated

build_projection_store(config, *, project_root)

Open the store [serve.projection] store names, or None where this project holds no projection.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/factory.py
def build_projection_store(config: ProjectionConfig, *, project_root: Path) -> ProjectionStore | None:
    """Open the store `[serve.projection] store` names, or None where this project holds no projection."""
    match config.store:
        case ProjectionBackend.NONE:
            return None
        case ProjectionBackend.SQLITE:
            return SqliteProjectionStore(projection_path(config, project_root=project_root))

The materialized projection

Reach for these when you are filling a projection, reading one, or serving an answer out of one. SqliteProjectionStore is the reference implementation of ProjectionStore and the Embedded posture's whole backend: SQLAlchemy over aiosqlite, one file, no service. run_sync is what fills it - the initial materialization, the incremental updatedAfter poll with includeDeleted=true as a constant (read again without it where DHIS2 2.42.6 refuses the flag, which SyncReport.tombstones_visible reports; DHIS2_ISSUES.md #116), and the full rebuild - and SyncReport is what it answers with. SqliteNameSearchIndex is the search over its keys, and projection.serving is how an answer served from it states the instant it is as of.

What none of them does is decide who may read what. A projection-served answer names candidates; the record behind each one is read from the instance under the caller's own credentials, so DHIS2 authorizes every disclosure per match per caller. That is R9's recommended posture (iii), and each module docstring says where its half of it sits.

schema

The four tables a materialized projection is held in, and the one connection they are reached over.

docs/design/projection.md step 3 asks for SQLAlchemy over aiosqlite with typed Mapped[...] columns, which is CLAUDE.md rule 10's own default for state - and a projection is state in the exact sense that rule draws: derived, mutable, queried by predicate. The spool stayed as files on the other side of that line, because a receipt is an immutable artifact; this is the side the line was drawn to put something on.

WHAT IS TYPED AND WHAT IS NOT. The document is held as the wire JSON it was projected into, in one text column, and every dimension a query runs over is a column beside it: which resource it is, which identifiers name it, which instant it was written at. That is the split StoreEntry.body already states - parse just enough to index, pass the rest through untouched - and it is what lets the projection hold a resource this toolkit gains a model for tomorrow without a schema change today.

THE INSTANTS ARE THE INSTANCE'S OWN CLOCK, AND THEY ARE NAIVE ON PURPOSE. DHIS2 2.43 answers updatedAt as a zone-less wall-clock reading in the instance's own zone (DHIS2_ISSUES.md 62), and a sync's watermark is compared against, and sent back as, exactly that reading. Stamping it with this host's zone would make the cursor a claim about a clock nobody consulted, and the first updatedAfter built from it would silently skip or re-read hours of rows. So the columns are naive, the values come from DHIS2 and never from datetime.now, and nothing here converts.

THERE IS NO MIGRATION AND THAT IS THE DESIGN. D3 makes rebuilding routine rather than a recovery step, so the way a schema change reaches a projection is d2w fhir sync --rebuild: the tables are created if they are absent, and a projection whose shape has moved on is refilled from the instance that is the record for all of it. A migration would be machinery for carrying forward a copy that is cheaper to make again.

Classes

ProjectionBase

Bases: DeclarativeBase

The declarative base every projection table is defined on.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/schema.py
class ProjectionBase(DeclarativeBase):
    """The declarative base every projection table is defined on."""

ProjectedResourceRow

Bases: ProjectionBase

One projected FHIR resource: what it is, when it was written, and the document verbatim.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/schema.py
class ProjectedResourceRow(ProjectionBase):
    """One projected FHIR resource: what it is, when it was written, and the document verbatim."""

    __tablename__ = "projected_resource"

    resource_type: Mapped[str] = mapped_column(String, primary_key=True)
    resource_id: Mapped[str] = mapped_column(String, primary_key=True)
    updated_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    body: Mapped[str] = mapped_column(Text, nullable=False)

    tracked_entity_type_uid: Mapped[str | None] = mapped_column(String, nullable=True)
    """Which DHIS2 tracked entity type the row is, so one resource's register narrows to one type.

    Nullable because the instance may state none, and a row whose type nothing states is a row no
    query naming a type can honestly claim - which is the same reading the live path takes of an
    entity carrying no `trackedEntityType`.
    """

    __table_args__ = (Index("ix_projected_resource_type", "resource_type", "tracked_entity_type_uid"),)
Attributes
tracked_entity_type_uid = mapped_column(String, nullable=True) class-attribute instance-attribute

Which DHIS2 tracked entity type the row is, so one resource's register narrows to one type.

Nullable because the instance may state none, and a row whose type nothing states is a row no query naming a type can honestly claim - which is the same reading the live path takes of an entity carrying no trackedEntityType.

ProjectedIdentifierRow

Bases: ProjectionBase

One identifier entry of one projected resource, as the token search matches it.

Every value of Resource.identifier[] lands here, system and all, so a system|value token and a bare value are the same index read with one predicate more or less. The row is a copy of what the document already says - the document stays the answer, and this is only how it is found.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/schema.py
class ProjectedIdentifierRow(ProjectionBase):
    """One `identifier` entry of one projected resource, as the token search matches it.

    Every value of `Resource.identifier[]` lands here, system and all, so a `system|value` token and
    a bare value are the same index read with one predicate more or less. The row is a copy of what
    the document already says - the document stays the answer, and this is only how it is found.
    """

    __tablename__ = "projected_identifier"

    resource_type: Mapped[str] = mapped_column(String, primary_key=True)
    resource_id: Mapped[str] = mapped_column(String, primary_key=True)
    system: Mapped[str] = mapped_column(String, primary_key=True, default=NO_IDENTIFIER_SYSTEM)
    value: Mapped[str] = mapped_column(String, primary_key=True)

    __table_args__ = (
        Index("ix_projected_identifier_value", "resource_type", "value"),
        Index("ix_projected_identifier_system_value", "resource_type", "system", "value"),
    )

ProjectedNameRow

Bases: ProjectionBase

One attribute value a tracked entity is searchable by, and the folded key a name search matches.

folded is value.casefold() and it is what makes a name search behave the way the :like: filter of docs/design/projection.md section 3.3 measured: a case-insensitive substring match, which is the finding that page tells any replacement index not to regress. Lao and Khmer are written without spaces, so a word-tokenising analyzer would find LESS than a substring does - the interior substring and the bare Khmer consonant both hit, and both keep hitting here.

What this column deliberately does not hold is a transliteration. Finding ສົມສັກ from Somsack is R8, it is an index-time ICU chain, and it arrives with the OpenSearch backend of step 6. A fold is honest about being a fold.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/schema.py
class ProjectedNameRow(ProjectionBase):
    """One attribute value a tracked entity is searchable by, and the folded key a name search matches.

    `folded` is `value.casefold()` and it is what makes a name search behave the way the `:like:`
    filter of `docs/design/projection.md` section 3.3 measured: a case-insensitive substring
    match, which is the finding that page tells any replacement index not to regress. Lao and Khmer
    are written without spaces, so a word-tokenising analyzer would find LESS than a substring does -
    the interior substring and the bare Khmer consonant both hit, and both keep hitting here.

    What this column deliberately does not hold is a transliteration. Finding `ສົມສັກ` from `Somsack`
    is R8, it is an index-time ICU chain, and it arrives with the OpenSearch backend of step 6. A
    fold is honest about being a fold.
    """

    __tablename__ = "projected_name"

    tracked_entity_uid: Mapped[str] = mapped_column(String, primary_key=True)
    attribute_uid: Mapped[str] = mapped_column(String, primary_key=True)
    value: Mapped[str] = mapped_column(String, primary_key=True)
    folded: Mapped[str] = mapped_column(String, nullable=False)
    tracked_entity_type_uid: Mapped[str | None] = mapped_column(String, nullable=True)

    __table_args__ = (
        Index("ix_projected_name_folded", "folded"),
        Index("ix_projected_name_attribute_folded", "attribute_uid", "folded"),
    )

ProjectionWatermarkRow

Bases: ProjectionBase

How far one tracker collection has been read, which is what the next poll asks from.

One row per ProjectionEndpoint, never one row for the projection, because the polled collections move independently and a single global cursor would be a guess about which of their clocks leads (docs/design/projection.md section 5.2, rule 3).

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/schema.py
class ProjectionWatermarkRow(ProjectionBase):
    """How far one tracker collection has been read, which is what the next poll asks from.

    One row per `ProjectionEndpoint`, never one row for the projection, because the polled collections
    move independently and a single global cursor would be a guess about which of their clocks leads
    (`docs/design/projection.md` section 5.2, rule 3).
    """

    __tablename__ = "projection_watermark"

    endpoint: Mapped[str] = mapped_column(String, primary_key=True)
    updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)

Functions:

open_projection_engine(database_path)

Open the aiosqlite engine one projection file is reached over, without touching the file yet.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/schema.py
def open_projection_engine(database_path: Path) -> AsyncEngine:
    """Open the aiosqlite engine one projection file is reached over, without touching the file yet."""
    return create_async_engine(f"sqlite+aiosqlite:///{database_path}", echo=False, future=True)

projection_sessions(engine)

The session factory every read and every write of a projection runs in, one transaction apiece.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/schema.py
def projection_sessions(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
    """The session factory every read and every write of a projection runs in, one transaction apiece."""
    return async_sessionmaker(engine, expire_on_commit=False)

create_projection_tables(engine) async

Create whatever of the four tables is absent, which is what opening an empty projection does.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/schema.py
async def create_projection_tables(engine: AsyncEngine) -> None:
    """Create whatever of the four tables is absent, which is what opening an empty projection does."""
    async with engine.begin() as connection:
        await connection.run_sync(ProjectionBase.metadata.create_all)

recreate_projection_tables(engine) async

Drop the four tables and create them at the current schema - what a rebuild stands on.

create_all adds absent tables and never alters a present one, so a projection file written by an older schema keeps its old columns for ever. A rebuild refills from zero anyway, which is exactly when dropping the tables costs nothing - so the rebuild is also the schema migration, as the store's doctrine states.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/schema.py
async def recreate_projection_tables(engine: AsyncEngine) -> None:
    """Drop the four tables and create them at the current schema - what a rebuild stands on.

    `create_all` adds absent tables and never alters a present one, so a projection file written by
    an older schema keeps its old columns for ever. A rebuild refills from zero anyway, which is
    exactly when dropping the tables costs nothing - so the rebuild is also the schema migration,
    as the store's doctrine states.
    """
    async with engine.begin() as connection:
        await connection.run_sync(ProjectionBase.metadata.drop_all)
        await connection.run_sync(ProjectionBase.metadata.create_all)

sqlite_store

The SQLite backend of ProjectionStore: one file under the project, written only by a sync.

This is step 3 of docs/design/projection.md and it is the Embedded posture's whole backend - no service, no port, no operator, one file make install already gave you the driver for. It is also the reference implementation of the Protocol, which is the part that outlives it: every later backend is measured against what this one does, and every test of the sync and of the serving path runs against it.

THE THREE CORRECTNESS RULES, EACH IN ONE PLACE HERE.

  1. The watermark advances only when the rows it describes are durable. write puts the resources, their identifiers, their search keys, the removals, and the new watermark in ONE session and ONE commit. A watermark ahead of its data is silent, permanent, undetectable data loss - the rows in the gap are never polled again - and this is the design that deletes the window rather than managing it (section 5.2, rule 1, and the sharpest argument in section 8.2).
  2. A write is idempotent by resource id. A sync re-polls from watermark - overlap and therefore re-reads rows it already holds; every one of them is an upsert, so re-reading a batch changes nothing but the instant it was written at. That is what makes the overlap window safe rather than duplicating (section 5.2, rule 2).
  3. A tombstone removes the row. removed deletes the resource, its identifiers, and its search keys. It never archives a last known state - the collection route enumerates a tombstone but the single-resource route answers 404 for it (docs/design/projection.md section 3.4, finding 3), so there is no final state to archive and pretending otherwise would be inventing one.

WHAT THIS CLASS IS, AND WHY IT IS NOT A PYDANTIC MODEL. It holds an open database engine and a file it creates on first use, which is a connection rather than a value - the same reading that keeps Dhis2Client off ServeContext and puts open_pass_through_client's pool on the runtime instead. dhis2w_core.token_store.SqliteTokenStore is the shape this follows; everything it hands back and takes in is a BaseModel.

WHAT IT DOES NOT DO. It does not write itself: D2 says the sync is the only writer, and nothing here is reachable from a route that changes anything. It does not reconcile: a row that disagrees with DHIS2 is a sync defect whose honest fix is rebuild. And it never decides who may read what - every answer it gives is a set of resources, and which caller may see which of them is settled by the instance, on the live read that resolves each one (docs/design/projection.md R9).

Classes

SqliteProjectionStore

Holds the FHIR projection of a DHIS2 instance in one SQLite file, written only by sync.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_store.py
class SqliteProjectionStore:
    """Holds the FHIR projection of a DHIS2 instance in one SQLite file, written only by sync."""

    def __init__(self, database_path: Path) -> None:
        """Bind an engine to one projection file, which is not created until something reads it."""
        self._database_path = database_path
        self._engine = open_projection_engine(database_path)
        self._sessions = projection_sessions(self._engine)
        self._created = False

    def name_search_index(self) -> NameSearchIndex:
        """The name index over this file; imported here because that module reads this store's rows."""
        from dhis2w_fhir_serve.projection.sqlite_names import SqliteNameSearchIndex

        return SqliteNameSearchIndex(self)

    @property
    def database_path(self) -> Path:
        """Where this projection lives, which is what a sync report names and an operator deletes."""
        return self._database_path

    @asynccontextmanager
    async def session(self) -> AsyncGenerator[AsyncSession]:
        """Open one session over this projection's database, creating the file and its tables if new.

        Public because the name index reads the same database through it. The projection has one
        connection, because it has one writer, and a second engine over the same file would be
        something SQLite has to arbitrate for no gain - see `sqlite_names`.
        """
        await self._ensure_tables()
        async with self._sessions() as opened:
            yield opened

    async def read(self, resource_type: str, resource_id: str) -> ProjectedResource | None:
        """Read one projected resource, or None where the projection holds none under that id."""
        async with self.session() as session:
            row = await session.get(ProjectedResourceRow, (resource_type, resource_id))
            if row is None:
                return None
            return _projected(row, await self._cursor_in(session))

    async def search(self, query: ProjectionQuery) -> ProjectionPage:
        """Answer one page of the projection, stating the cursor it was read at.

        `total` is the whole match set and never the page, which is what R4 defines `Bundle.total`
        as - so a client paging a register of eight hundred people is told eight hundred on the first
        page rather than twenty. The order is by resource id: a walk needs an order that does not
        move between two pages of it, and the id is the one thing every projected resource has.
        """
        async with self.session() as session:
            matched = _matching_ids(query)
            total = await session.scalar(select(func.count()).select_from(matched.subquery()))
            page = select(ProjectedResourceRow).where(
                ProjectedResourceRow.resource_type == query.resource_type,
                ProjectedResourceRow.resource_id.in_(matched),
            )
            page = page.order_by(ProjectedResourceRow.resource_id).offset(query.offset)
            if query.count is not None:
                page = page.limit(query.count)
            cursor = await self._cursor_in(session)
            rows = (await session.execute(page)).scalars().all()
            return ProjectionPage(
                resources=tuple(_projected(row, cursor) for row in rows),
                total=int(total or 0),
                cursor=cursor,
            )

    async def write(self, batch: ProjectionBatch) -> ProjectionCursor:
        """Write one sync's batch and answer the cursor the projection now stands at.

        One session, one commit, everything in it: the rows, the index entries beside them, the
        removals, and the watermark the batch advances. Nothing here is written that the commit does
        not cover, which is the whole of correctness rule 1.
        """
        async with self.session() as session:
            for key in batch.removed:
                await _forget(session, key.resource_type, key.resource_id)
            for resource in batch.resources:
                await _forget(session, resource.resource_type, resource.resource_id)
                session.add(
                    ProjectedResourceRow(
                        resource_type=resource.resource_type,
                        resource_id=resource.resource_id,
                        updated_at=resource.cursor.updated_at,
                        tracked_entity_type_uid=resource.tracked_entity_type_uid,
                        body=json.dumps(resource.body, ensure_ascii=False, sort_keys=True),
                    )
                )
                for system, value in _identifiers_of(resource.body):
                    session.add(
                        ProjectedIdentifierRow(
                            resource_type=resource.resource_type,
                            resource_id=resource.resource_id,
                            system=system,
                            value=value,
                        )
                    )
            for name in _distinct_names(batch):
                session.add(
                    ProjectedNameRow(
                        tracked_entity_uid=name.tracked_entity_uid,
                        attribute_uid=name.attribute_uid,
                        value=name.value,
                        folded=name.value.casefold(),
                        tracked_entity_type_uid=name.tracked_entity_type_uid,
                    )
                )
            if batch.endpoint is not None and batch.cursor.updated_at is not None:
                await session.execute(
                    sqlite_insert(ProjectionWatermarkRow)
                    .values(endpoint=batch.endpoint.value, updated_at=batch.cursor.updated_at)
                    .on_conflict_do_update(
                        index_elements=[ProjectionWatermarkRow.endpoint],
                        set_={"updated_at": batch.cursor.updated_at},
                    )
                )
            await session.commit()
            return (await self._watermarks_in(session)).cursor()

    async def cursor(self) -> ProjectionCursor:
        """How far this projection has been filled, which every answer served from it states."""
        async with self.session() as session:
            return await self._cursor_in(session)

    async def watermarks(self) -> ProjectionWatermarks:
        """How far each tracker collection has been read, which is what the next poll asks from."""
        async with self.session() as session:
            return await self._watermarks_in(session)

    async def rebuild(self) -> None:
        """Drop and recreate the projection's tables so a full materialization fills a current schema.

        The watermarks go with the rows. A projection emptied of documents but still claiming to have
        read up to yesterday would never poll for any of them again, which is correctness rule 1
        stated backwards - and it is exactly the state a rebuild exists to be unable to leave behind.

        Dropping rather than deleting is what makes the rebuild the schema migration: a file written
        by an older schema keeps its old columns through any DELETE, and the refill would then write
        columns the table does not have. A rebuild starts from zero anyway, so the tables are remade
        at the schema this process carries.
        """
        await self._ensure_tables()
        await recreate_projection_tables(self._engine)

    async def close(self) -> None:
        """Dispose of the connection, which is what the serve lifespan does when the process unwinds."""
        await self._engine.dispose()

    async def _ensure_tables(self) -> None:
        """Create the file and its tables on the first read or write, and never again in this process."""
        if self._created:
            return
        self._database_path.parent.mkdir(parents=True, exist_ok=True)
        await create_projection_tables(self._engine)
        if self._database_path.exists():
            self._database_path.chmod(PROJECTION_FILE_MODE)
        self._created = True

    async def _cursor_in(self, session: AsyncSession) -> ProjectionCursor:
        """The one instant this projection is as of, read inside a session a caller already opened."""
        return (await self._watermarks_in(session)).cursor()

    async def _watermarks_in(self, session: AsyncSession) -> ProjectionWatermarks:
        """The three watermarks as one value, read inside a session a caller already opened."""
        rows = (await session.execute(select(ProjectionWatermarkRow))).scalars().all()
        marks = {row.endpoint: row.updated_at for row in rows}
        return ProjectionWatermarks(
            tracked_entities=marks.get(ProjectionEndpoint.TRACKED_ENTITIES.value),
            enrollments=marks.get(ProjectionEndpoint.ENROLLMENTS.value),
        )
Attributes
database_path property

Where this projection lives, which is what a sync report names and an operator deletes.

Methods:
__init__(database_path)

Bind an engine to one projection file, which is not created until something reads it.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_store.py
def __init__(self, database_path: Path) -> None:
    """Bind an engine to one projection file, which is not created until something reads it."""
    self._database_path = database_path
    self._engine = open_projection_engine(database_path)
    self._sessions = projection_sessions(self._engine)
    self._created = False
name_search_index()

The name index over this file; imported here because that module reads this store's rows.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_store.py
def name_search_index(self) -> NameSearchIndex:
    """The name index over this file; imported here because that module reads this store's rows."""
    from dhis2w_fhir_serve.projection.sqlite_names import SqliteNameSearchIndex

    return SqliteNameSearchIndex(self)
session() async

Open one session over this projection's database, creating the file and its tables if new.

Public because the name index reads the same database through it. The projection has one connection, because it has one writer, and a second engine over the same file would be something SQLite has to arbitrate for no gain - see sqlite_names.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_store.py
@asynccontextmanager
async def session(self) -> AsyncGenerator[AsyncSession]:
    """Open one session over this projection's database, creating the file and its tables if new.

    Public because the name index reads the same database through it. The projection has one
    connection, because it has one writer, and a second engine over the same file would be
    something SQLite has to arbitrate for no gain - see `sqlite_names`.
    """
    await self._ensure_tables()
    async with self._sessions() as opened:
        yield opened
read(resource_type, resource_id) async

Read one projected resource, or None where the projection holds none under that id.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_store.py
async def read(self, resource_type: str, resource_id: str) -> ProjectedResource | None:
    """Read one projected resource, or None where the projection holds none under that id."""
    async with self.session() as session:
        row = await session.get(ProjectedResourceRow, (resource_type, resource_id))
        if row is None:
            return None
        return _projected(row, await self._cursor_in(session))
search(query) async

Answer one page of the projection, stating the cursor it was read at.

total is the whole match set and never the page, which is what R4 defines Bundle.total as - so a client paging a register of eight hundred people is told eight hundred on the first page rather than twenty. The order is by resource id: a walk needs an order that does not move between two pages of it, and the id is the one thing every projected resource has.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_store.py
async def search(self, query: ProjectionQuery) -> ProjectionPage:
    """Answer one page of the projection, stating the cursor it was read at.

    `total` is the whole match set and never the page, which is what R4 defines `Bundle.total`
    as - so a client paging a register of eight hundred people is told eight hundred on the first
    page rather than twenty. The order is by resource id: a walk needs an order that does not
    move between two pages of it, and the id is the one thing every projected resource has.
    """
    async with self.session() as session:
        matched = _matching_ids(query)
        total = await session.scalar(select(func.count()).select_from(matched.subquery()))
        page = select(ProjectedResourceRow).where(
            ProjectedResourceRow.resource_type == query.resource_type,
            ProjectedResourceRow.resource_id.in_(matched),
        )
        page = page.order_by(ProjectedResourceRow.resource_id).offset(query.offset)
        if query.count is not None:
            page = page.limit(query.count)
        cursor = await self._cursor_in(session)
        rows = (await session.execute(page)).scalars().all()
        return ProjectionPage(
            resources=tuple(_projected(row, cursor) for row in rows),
            total=int(total or 0),
            cursor=cursor,
        )
write(batch) async

Write one sync's batch and answer the cursor the projection now stands at.

One session, one commit, everything in it: the rows, the index entries beside them, the removals, and the watermark the batch advances. Nothing here is written that the commit does not cover, which is the whole of correctness rule 1.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_store.py
async def write(self, batch: ProjectionBatch) -> ProjectionCursor:
    """Write one sync's batch and answer the cursor the projection now stands at.

    One session, one commit, everything in it: the rows, the index entries beside them, the
    removals, and the watermark the batch advances. Nothing here is written that the commit does
    not cover, which is the whole of correctness rule 1.
    """
    async with self.session() as session:
        for key in batch.removed:
            await _forget(session, key.resource_type, key.resource_id)
        for resource in batch.resources:
            await _forget(session, resource.resource_type, resource.resource_id)
            session.add(
                ProjectedResourceRow(
                    resource_type=resource.resource_type,
                    resource_id=resource.resource_id,
                    updated_at=resource.cursor.updated_at,
                    tracked_entity_type_uid=resource.tracked_entity_type_uid,
                    body=json.dumps(resource.body, ensure_ascii=False, sort_keys=True),
                )
            )
            for system, value in _identifiers_of(resource.body):
                session.add(
                    ProjectedIdentifierRow(
                        resource_type=resource.resource_type,
                        resource_id=resource.resource_id,
                        system=system,
                        value=value,
                    )
                )
        for name in _distinct_names(batch):
            session.add(
                ProjectedNameRow(
                    tracked_entity_uid=name.tracked_entity_uid,
                    attribute_uid=name.attribute_uid,
                    value=name.value,
                    folded=name.value.casefold(),
                    tracked_entity_type_uid=name.tracked_entity_type_uid,
                )
            )
        if batch.endpoint is not None and batch.cursor.updated_at is not None:
            await session.execute(
                sqlite_insert(ProjectionWatermarkRow)
                .values(endpoint=batch.endpoint.value, updated_at=batch.cursor.updated_at)
                .on_conflict_do_update(
                    index_elements=[ProjectionWatermarkRow.endpoint],
                    set_={"updated_at": batch.cursor.updated_at},
                )
            )
        await session.commit()
        return (await self._watermarks_in(session)).cursor()
cursor() async

How far this projection has been filled, which every answer served from it states.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_store.py
async def cursor(self) -> ProjectionCursor:
    """How far this projection has been filled, which every answer served from it states."""
    async with self.session() as session:
        return await self._cursor_in(session)
watermarks() async

How far each tracker collection has been read, which is what the next poll asks from.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_store.py
async def watermarks(self) -> ProjectionWatermarks:
    """How far each tracker collection has been read, which is what the next poll asks from."""
    async with self.session() as session:
        return await self._watermarks_in(session)
rebuild() async

Drop and recreate the projection's tables so a full materialization fills a current schema.

The watermarks go with the rows. A projection emptied of documents but still claiming to have read up to yesterday would never poll for any of them again, which is correctness rule 1 stated backwards - and it is exactly the state a rebuild exists to be unable to leave behind.

Dropping rather than deleting is what makes the rebuild the schema migration: a file written by an older schema keeps its old columns through any DELETE, and the refill would then write columns the table does not have. A rebuild starts from zero anyway, so the tables are remade at the schema this process carries.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_store.py
async def rebuild(self) -> None:
    """Drop and recreate the projection's tables so a full materialization fills a current schema.

    The watermarks go with the rows. A projection emptied of documents but still claiming to have
    read up to yesterday would never poll for any of them again, which is correctness rule 1
    stated backwards - and it is exactly the state a rebuild exists to be unable to leave behind.

    Dropping rather than deleting is what makes the rebuild the schema migration: a file written
    by an older schema keeps its old columns through any DELETE, and the refill would then write
    columns the table does not have. A rebuild starts from zero anyway, so the tables are remade
    at the schema this process carries.
    """
    await self._ensure_tables()
    await recreate_projection_tables(self._engine)
close() async

Dispose of the connection, which is what the serve lifespan does when the process unwinds.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_store.py
async def close(self) -> None:
    """Dispose of the connection, which is what the serve lifespan does when the process unwinds."""
    await self._engine.dispose()

Functions:

sqlite_names

The projection backend of NameSearchIndex: the search keys the sync wrote, asked once.

WHAT IT IMPROVES OVER THE dhis2 BACKEND, STATED HONESTLY. Two things, and not a third.

  • It answers a name. The dhis2 backend puts filter=<attribute>:eq:<value> on the wire, so it finds a person only from the whole of a value spelled exactly. This matches a case-insensitive substring of one, which is what docs/design/projection.md section 3.3 measured :like: doing and what that section tells any replacement not to regress: the interior substring hits, the bare Khmer consonant hits, and neither would survive a word-tokenising analyzer over scripts that are written without spaces.
  • It costs one query. The dhis2 backend spends one round trip per search key per tracked entity type, sequentially, while the caller waits. This is one indexed read of one local file however many keys and types are in scope, and it is as of the cursor rather than as of now.

What it does NOT do is transliterate. Finding ສົມສັກ from Somsack is R8 and it is an index-time ICU chain that arrives with the OpenSearch backend of step 6; the four rows section 3.3's table marks fails still fail here, and the tests say so rather than assuming otherwise.

WHAT IT DISCLOSES. A tracked entity UID and a score. Not a name, not a value, not an organisation unit - the shape of NameMatch is what makes that a property rather than a promise. The register resolves each match through register.wire.fetch_tracked_entity under the caller's own credentials, so DHIS2 authorizes every record this facade hands over, per match, per caller, exactly as it does when the instance itself did the finding. That is R9's recommended posture (iii) in full, and it is the reason a projection can answer the finding half without this facade taking on one line of DHIS2's authorization model.

WHY IT READS THROUGH THE STORE RATHER THAN OPENING THE FILE ITSELF. The projection has exactly one connection, because it has exactly one writer, and a second engine over the same file would be a second thing SQLite has to arbitrate for no gain at all. The index is a reader of the store's database, and the store is what owns the file.

Classes

SqliteNameSearchIndex

Finds candidate tracked entities in the materialized projection, one indexed query per lookup.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_names.py
class SqliteNameSearchIndex:
    """Finds candidate tracked entities in the materialized projection, one indexed query per lookup."""

    def __init__(self, store: SqliteProjectionStore) -> None:
        """Read through the projection store that owns the file - see this module's docstring on why."""
        self._store = store

    async def index(self, entries: Sequence[IndexedName]) -> None:
        """Hold nothing on its own: a search key reaches this index on the batch its resource rides.

        The keys and the documents they find have to become true at the same instant, so they travel
        in one `ProjectionBatch` and land in one transaction. An `index` that wrote separately would
        be a second watermark with a second way of being wrong, which is the failure
        `docs/design/projection.md` section 5.2 rule 1 exists to make impossible.
        """
        return None

    async def find(self, query: NameQuery) -> NameMatches:
        """Answer the tracked entities one value matches, exact first, as of the projection's cursor.

        The value is folded and matched as a substring, which is the measured behaviour of the filter
        this replaces. An empty value matches nobody rather than everybody: a lookup that was given
        nothing to look for is not a request to hand over the register.
        """
        needle = query.value.strip().casefold()
        if not needle:
            return NameMatches(cursor=await self._store.cursor())
        async with self._store.session() as session:
            statement = select(ProjectedNameRow).where(
                ProjectedNameRow.folded.like(f"%{_escaped(needle)}%", escape=_LIKE_ESCAPE)
            )
            if query.attribute_uids:
                statement = statement.where(ProjectedNameRow.attribute_uid.in_(query.attribute_uids))
            if query.tracked_entity_type_uids:
                statement = statement.where(
                    ProjectedNameRow.tracked_entity_type_uid.in_(query.tracked_entity_type_uids)
                )
            rows = (await session.execute(statement)).scalars().all()
            cursor = await self._store.cursor()
        found: dict[str, NameMatch] = {}
        for row in sorted(rows, key=lambda row: (row.folded != needle, row.tracked_entity_uid)):
            found.setdefault(
                row.tracked_entity_uid,
                NameMatch(
                    tracked_entity_uid=row.tracked_entity_uid,
                    score=EXACT_MATCH_SCORE if row.folded == needle else SUBSTRING_MATCH_SCORE,
                ),
            )
        matches = tuple(found.values())
        return NameMatches(matches=matches if query.limit is None else matches[: query.limit], cursor=cursor)

    async def forget(self, tracked_entity_uids: Sequence[str]) -> None:
        """Drop nothing on its own: a tombstone reaches this index on the batch that removes the row.

        Same reason `index` holds nothing. `SqliteProjectionStore.write` deletes a removed resource's
        search keys in the transaction that deletes the resource, so the two can never disagree about
        whether somebody is still in the register.
        """
        return None
Methods:
__init__(store)

Read through the projection store that owns the file - see this module's docstring on why.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_names.py
def __init__(self, store: SqliteProjectionStore) -> None:
    """Read through the projection store that owns the file - see this module's docstring on why."""
    self._store = store
index(entries) async

Hold nothing on its own: a search key reaches this index on the batch its resource rides.

The keys and the documents they find have to become true at the same instant, so they travel in one ProjectionBatch and land in one transaction. An index that wrote separately would be a second watermark with a second way of being wrong, which is the failure docs/design/projection.md section 5.2 rule 1 exists to make impossible.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_names.py
async def index(self, entries: Sequence[IndexedName]) -> None:
    """Hold nothing on its own: a search key reaches this index on the batch its resource rides.

    The keys and the documents they find have to become true at the same instant, so they travel
    in one `ProjectionBatch` and land in one transaction. An `index` that wrote separately would
    be a second watermark with a second way of being wrong, which is the failure
    `docs/design/projection.md` section 5.2 rule 1 exists to make impossible.
    """
    return None
find(query) async

Answer the tracked entities one value matches, exact first, as of the projection's cursor.

The value is folded and matched as a substring, which is the measured behaviour of the filter this replaces. An empty value matches nobody rather than everybody: a lookup that was given nothing to look for is not a request to hand over the register.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_names.py
async def find(self, query: NameQuery) -> NameMatches:
    """Answer the tracked entities one value matches, exact first, as of the projection's cursor.

    The value is folded and matched as a substring, which is the measured behaviour of the filter
    this replaces. An empty value matches nobody rather than everybody: a lookup that was given
    nothing to look for is not a request to hand over the register.
    """
    needle = query.value.strip().casefold()
    if not needle:
        return NameMatches(cursor=await self._store.cursor())
    async with self._store.session() as session:
        statement = select(ProjectedNameRow).where(
            ProjectedNameRow.folded.like(f"%{_escaped(needle)}%", escape=_LIKE_ESCAPE)
        )
        if query.attribute_uids:
            statement = statement.where(ProjectedNameRow.attribute_uid.in_(query.attribute_uids))
        if query.tracked_entity_type_uids:
            statement = statement.where(
                ProjectedNameRow.tracked_entity_type_uid.in_(query.tracked_entity_type_uids)
            )
        rows = (await session.execute(statement)).scalars().all()
        cursor = await self._store.cursor()
    found: dict[str, NameMatch] = {}
    for row in sorted(rows, key=lambda row: (row.folded != needle, row.tracked_entity_uid)):
        found.setdefault(
            row.tracked_entity_uid,
            NameMatch(
                tracked_entity_uid=row.tracked_entity_uid,
                score=EXACT_MATCH_SCORE if row.folded == needle else SUBSTRING_MATCH_SCORE,
            ),
        )
    matches = tuple(found.values())
    return NameMatches(matches=matches if query.limit is None else matches[: query.limit], cursor=cursor)
forget(tracked_entity_uids) async

Drop nothing on its own: a tombstone reaches this index on the batch that removes the row.

Same reason index holds nothing. SqliteProjectionStore.write deletes a removed resource's search keys in the transaction that deletes the resource, so the two can never disagree about whether somebody is still in the register.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sqlite_names.py
async def forget(self, tracked_entity_uids: Sequence[str]) -> None:
    """Drop nothing on its own: a tombstone reaches this index on the batch that removes the row.

    Same reason `index` holds nothing. `SqliteProjectionStore.write` deletes a removed resource's
    search keys in the transaction that deletes the resource, so the two can never disagree about
    whether somebody is still in the register.
    """
    return None

sync

Filling the projection: the initial materialization, the incremental poll, and the report of both.

This is step 4 of docs/design/projection.md, and d2w fhir sync is the one thing that calls it. Section 5.1 states the shape in three sentences and this module is those three sentences:

  • Initial materialization. Walk the mapped scope - the tracked entity types [serve.tracked_entities] puts in scope - bulk-paged the way section 3.2 measured, project each page, write it.
  • Incremental runs. Poll the same collection with updatedAfter and includeDeleted=true, apply creates, updates, and tombstones, and advance the watermark. Measured idle cost: one request, 56 bytes.
  • Full rebuild. --rebuild drops to empty and refills. Per D3 that is routine rather than a recovery step, and it is how a fhir.toml mapping change reaches the projection.

NOTHING HERE MAPS ANYTHING. The projection of one tracked entity onto the FHIR resource its type is registered as is register.projection.registered_entity_for, which is the same function the live register answers a read with, and the search keys come off register.projection.attribute_values, which is the same function that decides what a served resource carries. A second mapping surface would be a second answer to "what is this person in FHIR", and the two would drift on the first mapping change. So a synced answer and a live answer are the same bytes, produced by the same code, and the only difference between them is the instant they are true as of.

WHY THE ENROLLMENTS ARE POLLED AND THE EVENTS ARE NOT. A tracked entity's own lastUpdated does not move when one of its enrollments does, and an enrollment carries program-level attribute values that the projected resource does carry - so an enrollment poll is how the projection learns whose copy has gone stale, and each entity it names is re-read through the one tracked entity path. An event carries data values, the projected resource carries none, so an event that moved is not a change to anything this projection holds; polling for one would be a request per interval spent to learn nothing. The event walk arrives with the resources that need it, at steps 8 and 9.

THE WATERMARK ADVANCES AFTER ITS WALK AND NEVER DURING IT. Pages are ordered by createdAt so the walk is stable, which means a later page can carry an EARLIER updatedAt than an earlier one - so no page knows the watermark, and only the finished walk does. Each page is written as its own batch, and the walk is closed by a batch carrying the new watermark once every row it describes is durable. That is section 5.2 rule 1 in the direction that matters: a watermark behind its data costs one re-read, and a watermark ahead of its data is silent permanent loss. A walk that fails halfway advances nothing and the next run re-reads it, which the idempotent write makes free.

WHOSE CREDENTIALS IT READS UNDER, AND WHAT THAT MEANS FOR WHAT IT HOLDS. Whatever the caller handed in - d2w fhir sync hands in the client for the profile the project resolves, which is the facade's own build identity. Section 6's one rule regardless of posture: the projection stores what a configured build identity could read, and the facade must never let a caller's own identity imply more than that. Which is why the serving path resolves every match live under the caller's credentials rather than handing over the row this sync wrote (R9, posture (iii)).

Classes

SyncNarrator

Bases: Protocol

What a run announces a finished step to, so a long materialization is not a silent one.

Narrow on purpose, and structurally satisfied by dhis2w_core.progress.ProgressReporter - the same reason RegisterReader is one method wide. A sync is a batch job that a district's whole register goes through, and the caller that started it is entitled to see it moving; what it is NOT entitled to is a dependency edge from this package to the CLI's console.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sync.py
@runtime_checkable
class SyncNarrator(Protocol):
    """What a run announces a finished step to, so a long materialization is not a silent one.

    Narrow on purpose, and structurally satisfied by `dhis2w_core.progress.ProgressReporter` - the
    same reason `RegisterReader` is one method wide. A sync is a batch job that a district's whole
    register goes through, and the caller that started it is entitled to see it moving; what it is
    NOT entitled to is a dependency edge from this package to the CLI's console.
    """

    def complete(self, index: int, total: int, label: str, summary: str, *, style: str | None = None) -> None:
        """Announce that step `index` finished, with a one-line summary."""
        ...
Methods:
complete(index, total, label, summary, *, style=None)

Announce that step index finished, with a one-line summary.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sync.py
def complete(self, index: int, total: int, label: str, summary: str, *, style: str | None = None) -> None:
    """Announce that step `index` finished, with a one-line summary."""
    ...

SyncMode

Bases: StrEnum

What one run of the sync was: how much it read, and why it read that much.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sync.py
class SyncMode(StrEnum):
    """What one run of the sync was: how much it read, and why it read that much."""

    #: The projection held no watermark, so the whole mapped scope was read. The one place the
    #: population-scale read cost of section 3.2 is paid.
    INITIAL = "initial"

    #: The projection held a watermark, so only what moved since it was read.
    INCREMENTAL = "incremental"

    #: `--rebuild`: the projection was dropped to empty first, then filled as an initial run.
    REBUILD = "rebuild"

SyncResourceCounts

Bases: BaseModel

What one run did to one FHIR resource type of the projection.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sync.py
class SyncResourceCounts(BaseModel):
    """What one run did to one FHIR resource type of the projection."""

    model_config = ConfigDict(frozen=True)

    resource_type: str
    created: int = 0
    updated: int = 0
    removed: int = 0
    """Rows a tombstone took out. A deletion means "remove the row", never "keep the last state"."""

    def changed(self) -> int:
        """How many rows of this type the run touched at all."""
        return self.created + self.updated + self.removed
Attributes
removed = 0 class-attribute instance-attribute

Rows a tombstone took out. A deletion means "remove the row", never "keep the last state".

Methods:
changed()

How many rows of this type the run touched at all.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sync.py
def changed(self) -> int:
    """How many rows of this type the run touched at all."""
    return self.created + self.updated + self.removed

SyncCursorMove

Bases: BaseModel

Where one collection's watermark stood before the run, and where it stands after it.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sync.py
class SyncCursorMove(BaseModel):
    """Where one collection's watermark stood before the run, and where it stands after it."""

    model_config = ConfigDict(frozen=True)

    endpoint: ProjectionEndpoint
    moved_from: datetime | None = None
    moved_to: datetime | None = None

    def moved(self) -> bool:
        """Whether this run learned anything new about how far the collection has been read."""
        return self.moved_to is not None and self.moved_to != self.moved_from
Methods:
moved()

Whether this run learned anything new about how far the collection has been read.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sync.py
def moved(self) -> bool:
    """Whether this run learned anything new about how far the collection has been read."""
    return self.moved_to is not None and self.moved_to != self.moved_from

SyncReport

Bases: BaseModel

What one d2w fhir sync did: what it read, what it changed, and where the cursor now stands.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sync.py
class SyncReport(BaseModel):
    """What one `d2w fhir sync` did: what it read, what it changed, and where the cursor now stands."""

    model_config = ConfigDict(frozen=True)

    mode: SyncMode
    dry_run: bool = False
    """True when the run read the instance, counted what it would change, and wrote nothing."""

    project_root: Path
    store_path: Path
    tracked_entity_types: tuple[str, ...] = ()
    """The types the mapped scope put in this run, which is what `[serve.tracked_entities]` narrowed."""

    programs: tuple[str, ...] = ()
    """The programs whose enrollments were polled - the ones the guide publishes, since the endpoint
    admits no other scope (DHIS2_ISSUES.md 102)."""

    pages_read: int = 0
    tombstones_visible: bool = True
    """False when the instance refused the tracked entity poll with `includeDeleted=true` and the
    pages were read without it (DHIS2 2.42.6, DHIS2_ISSUES.md #116): this run did not learn of an entity
    removed since the last one unless an enrollment of it moved."""

    counts: tuple[SyncResourceCounts, ...] = ()
    cursors: tuple[SyncCursorMove, ...] = ()
    cursor: ProjectionCursor = Field(default_factory=ProjectionCursor)
    """Where the projection as a whole now stands, which is what every answer served from it states."""

    def changed(self) -> int:
        """How many projection rows this run touched, across every resource type."""
        return sum(counts.changed() for counts in self.counts)

    def counts_line(self) -> str:
        """The one line a finished run closes with - the same shape a forward report closes with."""
        created = sum(counts.created for counts in self.counts)
        updated = sum(counts.updated for counts in self.counts)
        removed = sum(counts.removed for counts in self.counts)
        posture = "would create" if self.dry_run else "created"
        return f"{posture} {created}, updated {updated}, removed {removed} over {self.pages_read} page(s)"
Attributes
dry_run = False class-attribute instance-attribute

True when the run read the instance, counted what it would change, and wrote nothing.

tracked_entity_types = () class-attribute instance-attribute

The types the mapped scope put in this run, which is what [serve.tracked_entities] narrowed.

programs = () class-attribute instance-attribute

The programs whose enrollments were polled - the ones the guide publishes, since the endpoint admits no other scope (DHIS2_ISSUES.md 102).

tombstones_visible = True class-attribute instance-attribute

False when the instance refused the tracked entity poll with includeDeleted=true and the pages were read without it (DHIS2 2.42.6, DHIS2_ISSUES.md #116): this run did not learn of an entity removed since the last one unless an enrollment of it moved.

cursor = Field(default_factory=ProjectionCursor) class-attribute instance-attribute

Where the projection as a whole now stands, which is what every answer served from it states.

Methods:
changed()

How many projection rows this run touched, across every resource type.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sync.py
def changed(self) -> int:
    """How many projection rows this run touched, across every resource type."""
    return sum(counts.changed() for counts in self.counts)
counts_line()

The one line a finished run closes with - the same shape a forward report closes with.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sync.py
def counts_line(self) -> str:
    """The one line a finished run closes with - the same shape a forward report closes with."""
    created = sum(counts.created for counts in self.counts)
    updated = sum(counts.updated for counts in self.counts)
    removed = sum(counts.removed for counts in self.counts)
    posture = "would create" if self.dry_run else "created"
    return f"{posture} {created}, updated {updated}, removed {removed} over {self.pages_read} page(s)"

Functions:

run_sync(reader, *, surface, store, project_root, store_path, overlap, rebuild=False, dry_run=False, narrator=None) async

Fill or refresh the projection from one DHIS2 instance, and report exactly what changed.

The mode is read off the projection rather than asked for: a store holding no watermark has never been filled, so the first run is a full materialization whether or not anybody said so, and every run after it reads what moved. rebuild is the one that is asked for, because dropping a filled projection is a decision rather than an inference.

dry_run reads the instance exactly as a committing run does and writes nothing at all - not the rows, not the watermark. It is the posture [forward] import = false establishes for the other half of the loop: the real endpoint answers, the real work is counted, and the file on disk is the file that was there before.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/projection/sync.py
async def run_sync(
    reader: RegisterReader,
    *,
    surface: RegisterSurface,
    store: ProjectionStore,
    project_root: Path,
    store_path: Path,
    overlap: timedelta,
    rebuild: bool = False,
    dry_run: bool = False,
    narrator: SyncNarrator | None = None,
) -> SyncReport:
    """Fill or refresh the projection from one DHIS2 instance, and report exactly what changed.

    The mode is read off the projection rather than asked for: a store holding no watermark has never
    been filled, so the first run is a full materialization whether or not anybody said so, and every
    run after it reads what moved. `rebuild` is the one that is asked for, because dropping a filled
    projection is a decision rather than an inference.

    `dry_run` reads the instance exactly as a committing run does and writes nothing at all - not the
    rows, not the watermark. It is the posture `[forward] import = false` establishes for the other
    half of the loop: the real endpoint answers, the real work is counted, and the file on disk is
    the file that was there before.
    """
    before = await store.watermarks()
    mode = (
        SyncMode.REBUILD if rebuild else (SyncMode.INITIAL if before.tracked_entities is None else SyncMode.INCREMENTAL)
    )
    if rebuild:
        if not dry_run:
            await store.rebuild()
        before = ProjectionWatermarks()
    served = tuple((served.uid, served.resource_type) for served in surface.served_types)
    programs = surface.index.program_uids()
    _narrate(
        narrator,
        1,
        "register",
        f"{len(served)} tracked entity type(s), {len(programs)} program(s), mode {mode.value}",
    )

    run = _Run(reader=reader, surface=surface, store=store, dry_run=dry_run)
    entities_mark = await run.materialize(served, since=_since(before.tracked_entities, overlap))
    tombstones_note = (
        "" if run.tombstones_visible else "; tombstones not visible on this instance (DHIS2_ISSUES.md #116)"
    )
    _narrate(narrator, 2, "tracked entities", run.counts_line() + tombstones_note)
    enrollments_mark = await run.refresh_from_enrollments(
        served,
        programs,
        since=_since(before.enrollments, overlap),
        whole_scope_read=mode is not SyncMode.INCREMENTAL,
    )
    _narrate(narrator, 3, "enrollments", f"{run.touched} entity(s) re-read from an enrollment that moved")

    after = ProjectionWatermarks(
        tracked_entities=entities_mark or before.tracked_entities,
        enrollments=enrollments_mark or before.enrollments,
    )
    return SyncReport(
        mode=mode,
        dry_run=dry_run,
        project_root=project_root,
        store_path=store_path,
        tracked_entity_types=tuple(uid for uid, _ in served),
        programs=programs,
        pages_read=run.pages,
        tombstones_visible=run.tombstones_visible,
        counts=run.counts(),
        cursors=(
            SyncCursorMove(
                endpoint=ProjectionEndpoint.TRACKED_ENTITIES,
                moved_from=before.tracked_entities,
                moved_to=after.tracked_entities,
            ),
            SyncCursorMove(
                endpoint=ProjectionEndpoint.ENROLLMENTS,
                moved_from=before.enrollments,
                moved_to=after.enrollments,
            ),
        ),
        cursor=after.cursor() if dry_run else await store.cursor(),
    )

Metadata health

GET /facade/metadata-health - what the DHIS2 instance behind a live run holds that the guide cannot carry cleanly. The findings are d2w fhir validate's own, reread over the connection this process already holds, and the translation coverage beside them is this module's: which locales the selection carries translations in, how much of it each covers, and which objects are worth naming for it.

Each locale is answered on whichever side of it is the shorter list. Below MAJORITY_SHARE of the selection's translatable strings a locale is sparse and carries carriers - the objects somebody wrote it on - with an empty missing; at or above it the locale is majority and carries missing - the objects nobody has written it for - with an empty carriers. Three stray Spanish translations on a three-thousand-object instance are three translations, not three thousand absences, and no absent translation is graded anywhere: the severities on this answer are the validator's own.

translation_coverage is a pure function over the projected objects, so the arithmetic behind every number on the page answers with no server running. A run serving a compiled guide answers available: false with the reason in words rather than a refusal.

health

What is not right about the DHIS2 metadata behind this run: the validate findings, plus translation coverage.

TWO ANALYSES, ONE ANSWER. The first is d2w fhir validate run over the connection this process already holds - the same passes, the same graders, the same severity grading, and the same wording, because a finding a reader acts on must not be phrased one way in a terminal and another way in a browser. dhis2w_fhir.service.validate_instance_codes is the whole of it, and nothing here re-implements a predicate that lives there.

The second is new here: how much of the selection is translated. DHIS2 holds a translation per object, per property, per locale, and nothing in a published guide states which locales an instance is being maintained in - so the answer is read off the objects themselves. The locales in use are the union of the tags the selection's own translations carry, which needs no system-settings read and is honest on an instance nobody has configured.

THE SMALLER SIDE IS THE STORY, PER LOCALE. A tag three objects out of three thousand carry is not a language the instance is being maintained in, and listing the other two thousand nine hundred and ninety-seven as short of it turns three stray translations into a wall of deficiency. So each locale is read on its own: below half the selection's translatable strings it is SPARSE, and what it states is the objects that carry it; at or above half it is a MAJORITY locale, and what it states is the objects that do not. Either way the counts are the same two numbers - this decides which side is worth naming object by object.

COVERAGE IS A FACT, NOT A GRADE. No absence of a translation is a finding and none is a warning: the severities on this answer are d2w fhir validate's own, and the validator grades names and codes. A locale nobody has finished is a number here and nothing else.

READ ONCE PER RESOURCE KIND. The translation read is one request per scope surface - ten of them - rather than one per object, and the selection is applied to what comes back rather than written into a filter that would put a national instance's organisation-unit UIDs into a query string.

REPORTING ONLY. Nothing here writes to DHIS2, and nothing here offers to. Acting on a finding - changing the name, the code, or the translation in the instance - is the next slice, and the roadmap is where it is stated.

Classes

MetadataHealthFinding

Bases: BaseModel

One thing d2w fhir validate found about a DHIS2 object, as a row states it.

Every field but field and cost is the validator's own, carried across unchanged - the severity it graded, the scope it graded against, and the sentence it wrote. The two that are added here are derived from those: which DHIS2 field the finding is about, and what the grade costs this project.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
class MetadataHealthFinding(BaseModel):
    """One thing `d2w fhir validate` found about a DHIS2 object, as a row states it.

    Every field but `field` and `cost` is the validator's own, carried across unchanged - the
    severity it graded, the scope it graded against, and the sentence it wrote. The two that are
    added here are derived from those: which DHIS2 field the finding is about, and what the grade
    costs this project.
    """

    model_config = ConfigDict(frozen=True)

    severity: Literal["error", "warning", "info"]
    scope: Literal["selection", "instance"]
    category: str
    """The validator's own name for the kind of defect - `invalid-code`, `template-hostile-name`."""

    resource_type: str
    """The DHIS2 metadata collection the object belongs to, in DHIS2's own spelling."""

    uid: str
    name: str
    code: str | None = None
    field: str | None = None
    """The DHIS2 field at fault, or None where the category is about none of an object's own fields."""

    message: str
    """The exact problem, in the validator's own words - the same sentence the report file carries."""

    cost: str
    """What this grade costs the project, said in one sentence rather than as a severity word."""
Attributes
category instance-attribute

The validator's own name for the kind of defect - invalid-code, template-hostile-name.

resource_type instance-attribute

The DHIS2 metadata collection the object belongs to, in DHIS2's own spelling.

field = None class-attribute instance-attribute

The DHIS2 field at fault, or None where the category is about none of an object's own fields.

message instance-attribute

The exact problem, in the validator's own words - the same sentence the report file carries.

cost instance-attribute

What this grade costs the project, said in one sentence rather than as a severity word.

MetadataHealthCounts

Bases: BaseModel

How many findings there are of each severity, over the whole answer.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
class MetadataHealthCounts(BaseModel):
    """How many findings there are of each severity, over the whole answer."""

    model_config = ConfigDict(frozen=True)

    errors: int = 0
    warnings: int = 0
    infos: int = 0

LocaleCarrier

Bases: BaseModel

One selected object that carries a translation in a locale little of the selection carries.

Listed for a sparse locale and for no other, because on a sparse locale this is the short list: three objects out of three thousand is a fact somebody can read, and the two thousand nine hundred and ninety-seven that do not carry it are not news about anything.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
class LocaleCarrier(BaseModel):
    """One selected object that carries a translation in a locale little of the selection carries.

    Listed for a sparse locale and for no other, because on a sparse locale this is the short list:
    three objects out of three thousand is a fact somebody can read, and the two thousand nine
    hundred and ninety-seven that do not carry it are not news about anything.
    """

    model_config = ConfigDict(frozen=True)

    resource_type: str
    uid: str
    name: str
    carries_name: bool = False
    """Whether this object carries a NAME translation in this locale."""

    carries_form_name: bool = False
    """Whether this object has a DHIS2 form name and carries a FORM_NAME translation in this locale."""
Attributes
carries_name = False class-attribute instance-attribute

Whether this object carries a NAME translation in this locale.

carries_form_name = False class-attribute instance-attribute

Whether this object has a DHIS2 form name and carries a FORM_NAME translation in this locale.

LocaleUntranslated

Bases: BaseModel

One selected object holding no translation in a locale most of the selection is translated into.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
class LocaleUntranslated(BaseModel):
    """One selected object holding no translation in a locale most of the selection is translated into."""

    model_config = ConfigDict(frozen=True)

    resource_type: str
    uid: str
    name: str
    name_untranslated: bool = False
    """Whether this object holds no NAME translation in this locale."""

    form_name_untranslated: bool = False
    """Whether this object has a DHIS2 form name and holds no FORM_NAME translation in it."""
Attributes
name_untranslated = False class-attribute instance-attribute

Whether this object holds no NAME translation in this locale.

form_name_untranslated = False class-attribute instance-attribute

Whether this object has a DHIS2 form name and holds no FORM_NAME translation in it.

LocaleCoverage

Bases: BaseModel

How much of the selection one locale covers, and which side of it is worth listing.

The two counts are the whole arithmetic. standing decides which of the two lists is filled: a sparse locale carries carriers and an empty missing, a majority locale the other way round, so nothing on the wire is a list whose meaning depends on a sibling field.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
class LocaleCoverage(BaseModel):
    """How much of the selection one locale covers, and which side of it is worth listing.

    The two counts are the whole arithmetic. `standing` decides which of the two lists is filled:
    a sparse locale carries `carriers` and an empty `missing`, a majority locale the other way
    round, so nothing on the wire is a list whose meaning depends on a sibling field.
    """

    model_config = ConfigDict(frozen=True)

    locale: str
    """The BCP-47 tag, normalised from the Java locale DHIS2 stores - `pt_BR` reaches here as `pt-BR`."""

    name_count: int = 0
    """Selected objects carrying a NAME translation in this locale."""

    form_name_count: int = 0
    """Selected objects that have a DHIS2 form name and carry a FORM_NAME translation in this locale."""

    standing: Literal["sparse", "majority"] = "sparse"
    """Whether this locale covers less than half the selection's translatable strings, or half or more."""

    carriers: list[LocaleCarrier] = Field(default_factory=list)
    """The objects that carry this locale, filled for a sparse locale and empty for a majority one."""

    missing: list[LocaleUntranslated] = Field(default_factory=list)
    """The objects that do not, filled for a majority locale and empty for a sparse one."""
Attributes
locale instance-attribute

The BCP-47 tag, normalised from the Java locale DHIS2 stores - pt_BR reaches here as pt-BR.

name_count = 0 class-attribute instance-attribute

Selected objects carrying a NAME translation in this locale.

form_name_count = 0 class-attribute instance-attribute

Selected objects that have a DHIS2 form name and carry a FORM_NAME translation in this locale.

standing = 'sparse' class-attribute instance-attribute

Whether this locale covers less than half the selection's translatable strings, or half or more.

carriers = Field(default_factory=list) class-attribute instance-attribute

The objects that carry this locale, filled for a sparse locale and empty for a majority one.

missing = Field(default_factory=list) class-attribute instance-attribute

The objects that do not, filled for a majority locale and empty for a sparse one.

TranslationCoverage

Bases: BaseModel

How far the selection is translated, per locale.

locales is the union of the tags the selection's own translations carry, which is what "in use on this instance" means here: an instance is being maintained in the languages somebody has written into it, and no system setting states that more honestly than the objects do. An empty list is an instance nobody has translated, which is one language and a whole state.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
class TranslationCoverage(BaseModel):
    """How far the selection is translated, per locale.

    `locales` is the union of the tags the selection's own translations carry, which is what "in use
    on this instance" means here: an instance is being maintained in the languages somebody has
    written into it, and no system setting states that more honestly than the objects do. An empty
    list is an instance nobody has translated, which is one language and a whole state.
    """

    model_config = ConfigDict(frozen=True)

    locales: list[str] = Field(default_factory=list)
    object_count: int = 0
    """Selected objects the translation read covered."""

    form_named_count: int = 0
    """Of those, how many DHIS2 gives a form name - the denominator the form-name counts are read against."""

    per_locale: list[LocaleCoverage] = Field(default_factory=list)
Attributes
object_count = 0 class-attribute instance-attribute

Selected objects the translation read covered.

form_named_count = 0 class-attribute instance-attribute

Of those, how many DHIS2 gives a form name - the denominator the form-name counts are read against.

MetadataHealth

Bases: BaseModel

The whole answer: whether this run could look, what it found, and how far the selection is translated.

available false is a compiled run and nothing else. It is answered as a body rather than as a refusal because it is a state a screen renders in words - there is nothing wrong with serving a compiled guide, and a page that read a 4xx here would have to invent the sentence this carries.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
class MetadataHealth(BaseModel):
    """The whole answer: whether this run could look, what it found, and how far the selection is translated.

    `available` false is a compiled run and nothing else. It is answered as a body rather than as a
    refusal because it is a state a screen renders in words - there is nothing wrong with serving a
    compiled guide, and a page that read a 4xx here would have to invent the sentence this carries.
    """

    model_config = ConfigDict(frozen=True)

    available: bool = True
    reason: str | None = None
    """Why there is nothing to report, stated only when `available` is false."""

    graded_under: str | None = None
    """The `[generate] hostile_names` posture the severities were graded under, in the validator's own line."""

    object_count: int = 0
    """Metadata objects the validator swept, across every collection the instance holds."""

    counts: MetadataHealthCounts = Field(default_factory=MetadataHealthCounts)
    findings: list[MetadataHealthFinding] = Field(default_factory=list)
    translations: TranslationCoverage = Field(default_factory=TranslationCoverage)
Attributes
reason = None class-attribute instance-attribute

Why there is nothing to report, stated only when available is false.

graded_under = None class-attribute instance-attribute

The [generate] hostile_names posture the severities were graded under, in the validator's own line.

object_count = 0 class-attribute instance-attribute

Metadata objects the validator swept, across every collection the instance holds.

TranslatedObject

Bases: BaseModel

One selected DHIS2 object as the translation read projects it - what it is called, and in what locales.

The step between the wire and the coverage: read_selected_translations builds these off what DHIS2 answered, and translation_coverage is a pure function over them, so the arithmetic every number on the page is made of is testable without a request.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
class TranslatedObject(BaseModel):
    """One selected DHIS2 object as the translation read projects it - what it is called, and in what locales.

    The step between the wire and the coverage: `read_selected_translations` builds these off what
    DHIS2 answered, and `translation_coverage` is a pure function over them, so the arithmetic every
    number on the page is made of is testable without a request.
    """

    model_config = ConfigDict(frozen=True)

    resource_type: str
    uid: str
    name: str
    form_named: bool
    """Whether DHIS2 gives this object a form name - so whether it has one to be short a translation of."""

    name_locales: frozenset[str]
    """The normalised tags this object holds a NAME translation in."""

    form_name_locales: frozenset[str]
    """The normalised tags this object holds a FORM_NAME translation in, empty where it has no form name."""
Attributes
form_named instance-attribute

Whether DHIS2 gives this object a form name - so whether it has one to be short a translation of.

name_locales instance-attribute

The normalised tags this object holds a NAME translation in.

form_name_locales instance-attribute

The normalised tags this object holds a FORM_NAME translation in, empty where it has no form name.

Functions:

compiled_run_health()

What a run serving a compiled guide answers: nothing found, and the reason there is nothing.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
def compiled_run_health() -> MetadataHealth:
    """What a run serving a compiled guide answers: nothing found, and the reason there is nothing."""
    return MetadataHealth(available=False, reason=COMPILED_RUN_REASON)

read_metadata_health(client, config, *, publishes_forms=True) async

Grade the instance behind this run: the validate findings over the selection, and its translations.

The selection is resolved once and read by both halves - the validator grades severity against it, and the translation read narrows to it - so a national instance is scoped by one set of small reads rather than by two.

publishes_forms is False for a package publishing the organisation-unit registry alone, which grades the organisation units and nothing else - the same scoping d2w fhir validate reads off the project.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
async def read_metadata_health(
    client: Dhis2Client, config: GenerateConfig, *, publishes_forms: bool = True
) -> MetadataHealth:
    """Grade the instance behind this run: the validate findings over the selection, and its translations.

    The selection is resolved once and read by both halves - the validator grades severity against
    it, and the translation read narrows to it - so a national instance is scoped by one set of
    small reads rather than by two.

    `publishes_forms` is False for a package publishing the organisation-unit registry alone, which
    grades the organisation units and nothing else - the same scoping `d2w fhir validate` reads off
    the project.
    """
    scope = await resolve_validation_scope(client, config, publishes_forms=publishes_forms)
    report = await validate_instance_codes(client, config, scope=scope)
    objects = await read_selected_translations(client, scope)
    return MetadataHealth(
        graded_under=report.hostile_names_line,
        object_count=report.object_count,
        counts=MetadataHealthCounts(errors=report.error_count, warnings=report.warning_count, infos=report.info_count),
        findings=[health_finding(finding) for finding in report.findings],
        translations=translation_coverage(objects),
    )

health_finding(finding)

One validate finding as a row states it: its own grade and wording, plus the field and the cost.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
def health_finding(finding: ValidationFinding) -> MetadataHealthFinding:
    """One validate finding as a row states it: its own grade and wording, plus the field and the cost."""
    return MetadataHealthFinding(
        severity=finding.severity,
        scope=finding.scope,
        category=finding.category,
        resource_type=finding.resource_type,
        uid=finding.uid,
        name=finding.name,
        code=finding.code,
        field=field_at_fault(finding),
        message=finding.message,
        cost=cost_of(finding),
    )

field_at_fault(finding)

Which DHIS2 field one finding is about, or None where the category is about no field of the object.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
def field_at_fault(finding: ValidationFinding) -> str | None:
    """Which DHIS2 field one finding is about, or None where the category is about no field of the object."""
    if finding.category in _NAME_CATEGORIES:
        return next(
            (label for label in _FIELD_LABELS_BY_MESSAGE_PREFIX if finding.message.startswith(f"{label} ")),
            "name",
        )
    return FIELD_BY_CATEGORY.get(finding.category)

cost_of(finding)

What one finding's grade costs this project, in a sentence rather than in a severity word.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
def cost_of(finding: ValidationFinding) -> str:
    """What one finding's grade costs this project, in a sentence rather than in a severity word."""
    if finding.scope == "instance":
        return _INSTANCE_SCOPE_COST
    return _COST_BY_SEVERITY[finding.severity]

read_selected_translations(client, scope) async

Read the translations the selection's objects carry, one bounded request per resource kind.

Every collection a ValidationScope answers for is read whole and then narrowed to the scope, rather than filtered by a id:in:[...] a national organisation-unit selection would blow the query string with. A collection the selection holds nothing of costs no request at all.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
async def read_selected_translations(client: Dhis2Client, scope: ValidationScope) -> list[TranslatedObject]:
    """Read the translations the selection's objects carry, one bounded request per resource kind.

    Every collection a `ValidationScope` answers for is read whole and then narrowed to the scope,
    rather than filtered by a `id:in:[...]` a national organisation-unit selection would blow the
    query string with. A collection the selection holds nothing of costs no request at all.
    """
    objects: list[TranslatedObject] = []
    for resource_type in sorted(SCOPE_SURFACE_FIELDS):
        surface: frozenset[str] = getattr(scope, SCOPE_SURFACE_FIELDS[resource_type])
        if not surface:
            continue
        body = await client.get_raw(f"/api/{resource_type}", params={"fields": _TRANSLATION_FIELDS, "paging": "false"})
        objects.extend(_translated_objects(resource_type, body, surface))
    return objects

translation_coverage(objects)

How far the selection is translated: the locales in use, and each one read on the side that is smaller.

"In use" is the union of the tags these objects carry, so an instance nobody has translated has no locales and no coverage rows at all - which is the honest reading of an instance working in one language rather than a page full of everything being missing.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
def translation_coverage(objects: list[TranslatedObject]) -> TranslationCoverage:
    """How far the selection is translated: the locales in use, and each one read on the side that is smaller.

    "In use" is the union of the tags these objects carry, so an instance nobody has translated has
    no locales and no coverage rows at all - which is the honest reading of an instance working in
    one language rather than a page full of everything being missing.
    """
    locales = sorted({locale for item in objects for locale in item.name_locales | item.form_name_locales})
    return TranslationCoverage(
        locales=locales,
        object_count=len(objects),
        form_named_count=_form_named(objects),
        per_locale=[locale_coverage(objects, locale) for locale in locales],
    )

locale_coverage(objects, locale)

One locale's counts, and the shorter of the two lists it can be told through.

A locale under half the selection's translatable strings is told through the objects that carry it; one at or above half is told through the objects that do not. The threshold is the share the page draws its meter from, so the meter and the list under it are readings of one number.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/health.py
def locale_coverage(objects: list[TranslatedObject], locale: str) -> LocaleCoverage:
    """One locale's counts, and the shorter of the two lists it can be told through.

    A locale under half the selection's translatable strings is told through the objects that carry
    it; one at or above half is told through the objects that do not. The threshold is the share the
    page draws its meter from, so the meter and the list under it are readings of one number.
    """
    name_count = sum(1 for item in objects if locale in item.name_locales)
    form_name_count = sum(1 for item in objects if item.form_named and locale in item.form_name_locales)
    total = len(objects) + _form_named(objects)
    covered = name_count + form_name_count
    sparse = total > 0 and covered / total < MAJORITY_SHARE
    return LocaleCoverage(
        locale=locale,
        name_count=name_count,
        form_name_count=form_name_count,
        standing="sparse" if sparse else "majority",
        carriers=_carriers(objects, locale) if sparse else [],
        missing=[] if sparse else _untranslated(objects, locale),
    )

metadata_health

GET /facade/metadata-health - what is not right about the DHIS2 metadata this run publishes from.

WHAT IT ANSWERS. The d2w fhir validate analysis, run over the connection this process already holds, plus one analysis the command does not do: how far the selection is translated. A name the IG publisher cannot survive, a code no FHIR system will take, an object with no code at all, and a locale somebody stopped translating into halfway through are four different problems with one audience - whoever maintains the instance - so they are one page rather than four.

WHY IT IS NOT FHIR. There is no FHIR shape for "this DHIS2 name has a < in it". An OperationOutcome is what a server answers a request with, not a report about somebody else's metadata, and the translation coverage has no resource at all. So this is /spool's shape for /spool's reasons, at /spool's address: plain application/json, Pydantic models rather than a Bundle, served under the facade API's own mount rather than at the FHIR base. dhis2w_fhir_engine.facade.api.routes.spool argues that choice in full.

The name carries a hyphen and the address carries the mount, so nothing about it can be mistaken for /metadata - which is the FHIR base's CapabilityStatement and a different document about a different thing.

LIVE RUNS ONLY, AND A COMPILED RUN SAYS SO IN THE BODY. Grading metadata needs metadata to grade, and a compiled guide is a directory of resources with no instance behind it. The register routes refuse that state as an OperationOutcome because a FHIR client asked them a FHIR question; this route answers a body carrying available: false and the sentence a screen renders, because "there is nothing here to check and here is why" is a state rather than a failure - and a page that had to read it off a 4xx would end up inventing the sentence itself.

REPORTING ONLY. The route reads. Changing a name, a code, or a translation in DHIS2 from a finding is the next slice, and the FHIR roadmap's near-term section is where it is stated.

Classes

Functions:

read_metadata_health_report(request) async

Answer what the DHIS2 instance behind this run holds that the guide cannot carry cleanly.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/routes/metadata_health.py
@router.get(
    METADATA_HEALTH_PATH,
    tags=[METADATA_HEALTH_TAG],
    summary="Grade the DHIS2 metadata behind this run",
    description=(
        "The `d2w fhir validate` analysis over the connection this process already holds, plus how "
        "far the selection is translated: a name the IG publisher cannot survive, a code no FHIR "
        "system will take, an object with no code at all, and a locale somebody stopped translating "
        "into halfway.\n\n"
        "A run serving a compiled guide off disk answers 200 with `available` false and the sentence "
        "saying there is no instance to grade - a state rather than a failure, so a screen renders "
        "this server's own words instead of inventing them off a 4xx. Reporting only: nothing here "
        "changes anything in DHIS2."
    ),
    response_description=(
        "What the instance holds that the guide cannot carry cleanly, or why there is nothing to grade."
    ),
)
async def read_metadata_health_report(request: Request) -> MetadataHealth:
    """Answer what the DHIS2 instance behind this run holds that the guide cannot carry cleanly."""
    client = live_client(request)
    if client is None:
        return compiled_run_health()
    project = serve_context(request).project
    return await read_metadata_health(
        client, project.config.generate, publishes_forms=not project.config.publishes_organisation_units
    )

Live store

The store built off a DHIS2 instance instead of a compiled IG, over the same JSON builders the generate targets write to disk.

live

The live store: the resources the facade serves, built off a DHIS2 instance instead of a compiled IG.

--live is the mode with no build step in front of it - point the server at a project and an instance, and it answers with the documents d2w fhir generate would have written and SUSHI would have compiled. One connected client reads the whole instance side of the build and the JSON builders turn that into resources: the store is a snapshot of the instance at startup, exactly as the compiled store is a snapshot of the last build, and no read of it ever touches DHIS2 again.

That one client stays open for the life of the process, because the register is answered from the instance per request rather than from the store - see dhis2w_fhir_engine.facade.register. The caller owns it through open_live_client, so the store build and the register routes share one connection and one profile resolution.

What the builders here produce is the served read-set and nothing else. The definitional artifacts - StructureDefinitions, the extensions, the IG's kind #requirements CapabilityStatement - are authored as FSH and only exist as JSON once SUSHI has compiled them, and no FSH compiler runs in this process. That costs the read-set nothing: a capture server reads Questionnaire, CodeSystem, ValueSet, Location, and Organization (CAPTURE_SERVER_READ_RESOURCE_TYPES), every one of which comes out of a JSON builder here - the foundation terminology included.

The conformance resources join the store all the same, read off whatever SUSHI last compiled beside the project rather than built here (load_compiled_conformance_entries). A guide is one guide whichever way the process was started, and the profiles a served response claims have to resolve somewhere; a live run over a project that has also been compiled hosts them exactly as a compiled run does. A live run over a project that never has holds none, and the CapabilityStatement declares none - which is the honest answer, since there is nothing on disk to serve.

WHAT ONE MODE PUBLISHES, BOTH MODES PUBLISH. A guide is one guide whichever way the process was started, so every vocabulary a compiled build writes is built here too, from the same Python the other target reads:

  • The form-type, period-type, and program-rule-action pairs backing the D2FormType, D2Period, and D2ProgramRule bindings, and the organisation-unit level and whole-selection pairs. All five are declared inside FSH files a live run never compiles, so each has a JSON twin rendering the same Python vocabulary the template renders: a client resolving a served form's form-type code system gets the code system, not a 404.
  • The identifier namespaces the ConceptMaps target - the option, category-option, and category-option-combo UID and code systems - each enumerated as a complete CodeSystem beside the maps that name it. A NamingSystem states what a namespace is and answers no $validate-code, so a consumer validating a mapped identifier needs the enumeration whichever store it reads from.

All four ConceptMap families - option sets, categories, the attribute option combos an aggregate form is keyed by, and the resource type each tracked entity type is registered as - ride along with the terminology they map, so a live store serves the same reads, searches, and $translate answers over the maps that a compiled one does. The IG's own CapabilityStatement is still named by /metadata, which instantiates it by canonical - a URL derived from config, needing no artifact to state.

The example instances are the one thing a compiled store holds and a live one does not, and that is by design: an example is a teaching document a build writes into the guide, not a read a capture client resolves.

THE ORGANISATION UNITS ARE THE ONE READ-SET A GUIDE MAY NOT OWN. A guide naming [generate.organisation_units.registry] publishes no Organization and no Location of its own, and a live run honours that exactly as a compiled one does: the units come out of the registry package - the checkout beside the project, or the archive --registry-package names - and the instance's hierarchy is never walked. Synthesising units from DHIS2 here would publish a second identity for every place at the guide's own base URL, which is the one address a client developed against --live would then resolve nothing at once the guide is published. A guide that can reach neither source refuses before the banner, in dhis2w_fhir_serve.settings, with the message compiled mode gives.

Classes

Functions:

open_live_client(project, settings) async

Open the DHIS2 client a live run reads through, named by the profile the project resolves.

The server holds this open for the whole process rather than closing it after the store is built: the register answers from the instance per request, so a live facade has one connection to DHIS2 for its lifetime and closes it when the lifespan unwinds.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/live.py
@asynccontextmanager
async def open_live_client(project: FhirProject, settings: ServeSettings) -> AsyncGenerator[Dhis2Client]:
    """Open the DHIS2 client a live run reads through, named by the profile the project resolves.

    The server holds this open for the whole process rather than closing it after the store is
    built: the register answers from the instance per request, so a live facade has one connection to
    DHIS2 for its lifetime and closes it when the lifespan unwinds.
    """
    generation = resolve_generation_profile(project, settings.profile)
    logger.info(
        "live store: reading %s as profile %s (from %s)",
        generation.profile.base_url,
        generation.name,
        generation.origin,
    )
    async with open_client(generation.profile) as client:
        yield client

open_delivery_client(project, settings) async

Open the connection one capture reaches DHIS2 through, on a run that reads a compiled guide and holds no client.

Opened per attempt rather than held, because this server has to start, and to take captures, while DHIS2 is away.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/live.py
@asynccontextmanager
async def open_delivery_client(project: FhirProject, settings: ServeSettings) -> AsyncGenerator[Dhis2Client]:
    """Open the connection one capture reaches DHIS2 through, on a run that reads a compiled guide and holds no client.

    Opened per attempt rather than held, because this server has to start, and to take captures, while DHIS2 is away.
    """
    generation = resolve_generation_profile(project, settings.profile)
    async with open_client(generation.profile) as client:
        yield client

Starting up

What a run checks about its authentication posture before it starts, and the issuer it reads while starting.

auth_setup

What a run checks about its authentication posture before it starts, and the issuer it reads while starting.

Classes

ServeAuthConfigurationError

Bases: ValueError

A posture this run cannot honour, refused while the settings resolve rather than at a request.

A ValueError because that is what ServeSettings.resolve already raises for a stated value it cannot mean, and d2w fhir serve renders it as one line against the dial it came from.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/auth_setup.py
class ServeAuthConfigurationError(ValueError):
    """A posture this run cannot honour, refused while the settings resolve rather than at a request.

    A `ValueError` because that is what `ServeSettings.resolve` already raises for a stated value it
    cannot mean, and `d2w fhir serve` renders it as one line against the dial it came from.
    """

Functions:

open_jwt_verifier(config) async

Read the issuer this run trusts, while the server starts, or refuse to serve at all.

The refusal is a ServeAuthConfigurationError so it lands beside the other posture refusals - a deployer meets one line naming the key that has to change, whether the problem was an issuer nobody wrote down or one nobody could reach.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/auth_setup.py
async def open_jwt_verifier(config: ServeJwtConfig) -> JwtVerifier:
    """Read the issuer this run trusts, while the server starts, or refuse to serve at all.

    The refusal is a `ServeAuthConfigurationError` so it lands beside the other posture refusals - a
    deployer meets one line naming the key that has to change, whether the problem was an issuer
    nobody wrote down or one nobody could reach.
    """
    try:
        return await discover_issuer(config)
    except OidcIssuerUnavailableError as error:
        raise ServeAuthConfigurationError(
            f'`auth = "jwt"` verifies every caller\'s token against the keys `{config.issuer}` publishes, '
            f"and this server could not read them: {error}. Check `[serve.jwt] issuer` names the issuer "
            "identifier its own tokens carry as `iss`, and that this machine can reach it."
        ) from error

preflight_auth(*, posture, host, live, stated, jwt=None, environment=None)

Refuse, before anything binds, every posture this run could not actually honour.

Five refusals, each about a run rather than about a request, which is why they are here and not in the dependency. A server that starts and then refuses every caller - or worse, serves every caller from an interface the deployment thought was closed - is a failure nobody reads until it matters.

Two of them are the jwt posture's: an issuer nobody named, and forward_bearer asked for on a run with no instance to forward to. The third thing that posture needs - an issuer this machine can actually reach - is not checked here, because reading it is a round trip and this function is a reader of values. dhis2w_fhir_engine.facade.api.auth.open_jwt_verifier does it while the server starts and refuses with the same error type.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/auth_setup.py
def preflight_auth(
    *,
    posture: ServeAuth,
    host: str,
    live: bool,
    stated: bool,
    jwt: ServeJwtConfig | None = None,
    environment: dict[str, str] | None = None,
) -> None:
    """Refuse, before anything binds, every posture this run could not actually honour.

    Five refusals, each about a run rather than about a request, which is why they are here and not
    in the dependency. A server that starts and then refuses every caller - or worse, serves every
    caller from an interface the deployment thought was closed - is a failure nobody reads until it
    matters.

    Two of them are the `jwt` posture's: an issuer nobody named, and `forward_bearer` asked for on a
    run with no instance to forward to. The third thing that posture needs - an issuer this machine
    can actually reach - is not checked here, because reading it is a round trip and this function is
    a reader of values. `dhis2w_fhir_engine.facade.api.auth.open_jwt_verifier` does it while the server starts
    and refuses with the same error type.
    """
    if not stated and not _is_loopback(host):
        raise ServeAuthConfigurationError(
            f"`{host}` is not a loopback interface, and this project's fhir.toml states no `[serve] auth`. "
            "Write the posture down before serving the facade where other hosts can reach it - add one "
            'line under `[serve]` in fhir.toml: `auth = "none"` to serve every caller, `auth = "token"` '
            f'to take a static bearer token out of `{SERVE_TOKENS_VARIABLE}`, `auth = "dhis2"` to have '
            "every caller present the DHIS2 credentials this facade checks against the instance, or "
            '`auth = "jwt"` to take a token from an OpenID Connect issuer named in `[serve.jwt] issuer`. '
            "`--auth` states the same thing for one run."
        )
    if posture is ServeAuth.TOKEN and not read_serve_tokens(environment):
        raise ServeAuthConfigurationError(
            f'`auth = "token"` takes its tokens from the environment variable `{SERVE_TOKENS_VARIABLE}`, '
            "which is unset or empty. Set it to the tokens this deployment accepts, comma-separated, and "
            "serve again. The tokens are secrets and do not belong in fhir.toml, which is a file projects "
            "commit; rotating them is replacing the variable and restarting this process."
        )
    if posture is ServeAuth.DHIS2 and not live:
        raise ServeAuthConfigurationError(
            '`auth = "dhis2"` checks every caller\'s credentials against the DHIS2 instance this run reads, '
            "and this run reads a compiled implementation guide off disk instead - there is no instance to "
            'check anybody against. Serve with `--live`, or state `auth = "token"` or `auth = "none"`.'
        )
    if posture is ServeAuth.JWT:
        _preflight_jwt(jwt if jwt is not None else ServeJwtConfig(), live=live)

Routes this server adds

The screens' document and the metadata health report, mounted beside the engine's routers.

routes

The two routers this package adds to the facade's own, and how it mounts them beside the capture UI.

Classes

Functions:

serve_routers(*, capture=True, serve_ui=False, auth=ServeAuth.NONE, auth_scope=ServeAuthScope.WRITE, publishes=None)

The facade's routers plus the two this server adds: the screens' document and the metadata health report.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/routes/__init__.py
def serve_routers(
    *,
    capture: bool = True,
    serve_ui: bool = False,
    auth: ServeAuth = ServeAuth.NONE,
    auth_scope: ServeAuthScope = ServeAuthScope.WRITE,
    publishes: str | None = None,
) -> ServeRouters:
    """The facade's routers plus the two this server adds: the screens' document and the metadata health report."""
    return facade_routers(
        capture=capture,
        serve_ui=serve_ui,
        auth=auth,
        auth_scope=auth_scope,
        publishes=publishes,
        instance_documents=(ui_config_router, metadata_health_router),
    )

register_routes(app, serve_ui=False, capture=True, auth=ServeAuth.NONE, auth_scope=ServeAuthScope.WRITE, authentication=None, publishes=None)

Mount what d2w fhir serve serves: the facade's routers, with the capture UI around them when asked for.

The UI mounts are not in ServeRouters: they are StaticFiles rather than routers, and their order requirement only makes sense inside this server's own route table. See dhis2w_fhir_serve.ui.

Source code in packages/dhis2w-fhir-serve/src/dhis2w_fhir_serve/routes/__init__.py
def register_routes(
    app: FastAPI,
    serve_ui: bool = False,
    capture: bool = True,
    auth: ServeAuth = ServeAuth.NONE,
    auth_scope: ServeAuthScope = ServeAuthScope.WRITE,
    authentication: Any = None,
    publishes: str | None = None,
) -> None:
    """Mount what `d2w fhir serve` serves: the facade's routers, with the capture UI around them when asked for.

    The UI mounts are not in `ServeRouters`: they are `StaticFiles` rather than routers, and their order
    requirement only makes sense inside this server's own route table. See `dhis2w_fhir_serve.ui`.
    """
    check = require_authenticated if authentication is None else authentication
    routers = serve_routers(capture=capture, serve_ui=serve_ui, auth=auth, auth_scope=auth_scope, publishes=publishes)
    if serve_ui:
        mount_ui_assets(app)
    mount_routers(app, routers, check)
    if serve_ui:
        mount_ui_shell(app)

Package surface

The names below re-export from dhis2w_fhir_serve itself.

dhis2w_fhir_serve

FHIR facade over a generated IG project: serves its resources and receives QuestionnaireResponse captures.

Each module owns its schemas; this module is the one stable import surface over them, so from dhis2w_fhir_serve import ResourceStore keeps working however the internals are arranged.

What is deliberately NOT here is the capture UI. dhis2w_fhir_serve.ui and the /facade/uiconfig document exist so the built React bundle can work, they are reached by running the server with settings.ui, and create_app is the only thing that mounts them. The two refusals are the exception: create_app raises UiBundleMissingError where nothing was ever built and UiBundleStaleError where a checkout's bundle is older than the frontend source beside it, so a caller of create_app has to be able to catch either by name.