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 servegets for the same project and the same flags, precedence rules included (resolve_serve_settings,ServeInvocation). That includes when captures go to DHIS2: aServeSettingsyou 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
Parametersinput, and say an evaluation's answer as theParametersa 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/spoolpages 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:
- The settings.
resolve_serve_settingsapplies the flag-over-[serve]precedence, resolves the DHIS2 profile, and refuses a project that has never been built. ConstructingServeSettingsdirectly is supported too, and a facade built that way differs fromd2w fhir serveon purpose rather than by accident. - The runtime.
open_serve_runtimeloads 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. Underauth = "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 ownAuthorizationover; see credential pass-through.attach_serve_runtimeputs all three things the handlers read onto the application, and nothing serves a request before it has been called. - The routers.
serve_routersstates the mount requirements as data: the FHIR routers carryDepends(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/healthmounts first or it is gone - and every router gets the HEAD sweep, or a liveness probe askingHEAD /metadatareads a live facade as down.ServeRouters.guardedis the fourth requirement, and the one an application usually answers itself: see bring your own authentication. - The error handlers. Without
register_error_handlers, every typed refusal the facade raises -RegisterDisabledError,NotServedError,CaptureDisabledError- is a 500 with noOperationOutcomein 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.
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.
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.
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.
The full facade. Every line above, in one call.
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
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
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
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
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
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
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
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
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
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
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
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
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
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
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
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
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
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
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
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
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
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
¶
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
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
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
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
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
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
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
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
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.
- The watermark advances only when the rows it describes are durable.
writeputs 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). - A write is idempotent by resource id. A sync re-polls from
watermark - overlapand 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). - A tombstone removes the row.
removeddeletes 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.mdsection 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
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | |
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
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
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
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
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
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
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
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
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
close()
async
¶
Dispose of the connection, which is what the serve lifespan does when the process unwinds.
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
dhis2backend putsfilter=<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 whatdocs/design/projection.mdsection 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
dhis2backend 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
Methods:¶
__init__(store)
¶
Read through the projection store that owns the file - see this module's docstring on why.
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
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
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
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
updatedAfterandincludeDeleted=true, apply creates, updates, and tombstones, and advance the watermark. Measured idle cost: one request, 56 bytes. - Full rebuild.
--rebuilddrops to empty and refills. Per D3 that is routine rather than a recovery step, and it is how afhir.tomlmapping 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
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
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
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
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
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.
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
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
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
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
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
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
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
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
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
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
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
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.
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.