Skip to main content

service

Backend-neutral parts of EHR access, and the interface to read an EHR.

Module​

Submodules​

Functions​

build_ehr_data_service​

def build_ehr_data_service(    ehr_config: EHRConfig,    *,    ehr_secrets: RefreshableJWT | None = None,    knowledge_store: KnowledgeStore | None = None,    bitfount_session: BitfountSession | None = None,) ‑> EHRDataService:

Build the service for one EHR connection.

A NextGen config gets NextGenEHRDataService, which authenticates through SMART on FHIR with bitfount_session and keeps no knowledge store. Any other config whose provider ends in r4 gets FHIRR4EHRService. Each ignores the arguments only the other uses.

Arguments

  • ehr_config: The EHR's config.
  • ehr_secrets: JWT secrets for a FHIR R4 EHR, from the pod's secrets.
  • knowledge_store: Where a FHIR R4 connection keeps its findings about the server (see knowledge_store_for); in memory when not given.
  • bitfount_session: The Bitfount session a NextGen connection authenticates with.

Raises

  • ValueError: If no backend serves the config's provider, if a NextGen config comes without bitfount_session, or as FHIRR4EHRService raises it.

is_fhir_r4_provider​

def is_fhir_r4_provider(provider: str | None) ‑> bool:

Whether a provider is served by the FHIR R4 backend: it ends in r4.

Arguments

  • provider: The provider string from the EHR config.

knowledge_store_for​

def knowledge_store_for(    cache: CacheProtocol | None, ehr_config: EHRConfig,) ‑> KnowledgeStore | None:

Where a connection to this EHR keeps its findings, if anywhere.

Only the FHIR R4 backend keeps findings. Its store is the pod cache, keyed by the server's identity (ehr_server_key), so every process on the pod talking to the same EHR shares what is learned about it.

Arguments

  • cache: The pod's background cache, or None where there is none (the CLI, tests).
  • ehr_config: The EHR's config.

Returns A pod-cache store for a FHIR R4 EHR on a pod; None without a cache, for NextGen, or for a provider no backend serves (the builder raises for that). The backend is decided as build_ehr_data_service decides it.

nextgen_urls​

def nextgen_urls(ehr_config: NextGenEHRConfig) ‑> NextGenURLs:

A NextGen config's endpoints, defaulting each the config leaves unset.

An unset (or empty) base_url is NextGen's production FHIR URL, and an unset enterprise_url its production Enterprise URL.

Arguments

  • ehr_config: The NextGen EHR's config.

unsupported_provider_error​

def unsupported_provider_error(provider: str | None) ‑> ValueError:

The error for a provider no backend, or not the backend asked, serves.

Arguments

  • provider: The provider string from the EHR config.

Classes​

AuthFailureBudget​

class AuthFailureBudget(limit: int = 3):

Tracks consecutive EHR authentication failures.

Arguments

  • limit: How many consecutive failures are tolerated before the budget is exhausted.

Variables​

  • consecutive_failures : int - Failures recorded since the last success.

Methods​


check​

def check(self, cause: BaseException | None = None) ‑> None:

Abort the run if the budget is spent.

Arguments

  • cause: The authentication error that led here, if any, chained onto the raised EHRConnectionError so the original response survives.

Raises

  • EHRConnectionError: If the failures counted since the last success have reached the limit.

count_failure​

def count_failure(self) ‑> None:

Count an authentication failure, without acting on it.

record_failure​

def record_failure(self, cause: BaseException | None = None) ‑> None:

Record an authentication failure, aborting once the budget is spent.

Arguments

  • cause: The authentication error, chained onto the raised EHRConnectionError so the original response survives.

Raises

  • EHRConnectionError: If this failure exhausts the budget.

record_success​

def record_success(self) ‑> None:

Reset the count.

FHIRClient calls this only for a successful response, to a request other than its CapabilityStatement request: a request that fails other than as unauthenticated (a 400, 404 or 5xx) neither counts nor resets. The per-patient callers also call it for a patient whose lookup failed for a reason other than authentication.

EHRDataService​

class EHRDataService(*args, **kwargs):

One EHR connection.

Built once per connection. It owns transport, auth and its give-up budget, timeouts, what is known about the server, retries and rechecks, the response cache and the provider's quirks. Callers ask it for patients and read their records; they never see a backend client.

Variables​

  • supports_mrn_lookup : bool - Whether find_by_mrn can find patients on this EHR.

Methods​


availability​

def availability(self) ‑> EHRPreflightResult:

Whether this EHR can be reached, before any patient is asked for.

find_by_mrn​

def find_by_mrn(    self, mrn: str | Sequence[str], *, system_qualified: bool = False,) ‑> PatientRecord:

The record of the one patient holding this medical record number.

Given several, each value is one identifier, and they are tried in turn, in the order given, one search each. The first value a patient holds wins: different patients holding different values is not non-specific, and the values after it are not searched. Only a value no patient holds moves on to the next. Any other outcome for a value (more than one patient holding it, a patient with no key, a rejection or a failed search) is raised there, and the values after it are not tried. When no patient holds any of them, NoMatchingPatientError is raised, with the last value's miss as its __cause__.

Arguments

  • mrn: The identifier, or several to try in turn, each as a literal
  • value: the backend escapes it for its search. Whitespace around a value is not part of it, and is stripped.
  • system_qualified: Read a value holding exactly one | as system|value, the value searched in that identifier system, as a person types it. A backend that searches identifiers without a system ignores it.

Raises

  • ValueError: If no identifier is given, or one is blank (empty or whitespace only).
  • NoMatchingPatientError: If no patient holds any of them.
  • NonSpecificPatientError: If more than one patient holds the value being tried.
  • NoPatientIDError: If the patient holding the value being tried has no key.
  • EHRAuthenticationError: If the EHR rejected the search.
  • EHRConnectionError: If authentication has failed too often in a row for the run to go on.
  • EHRRequestError: On FHIR R4, if the EHR answered the search with an error the backend reports as its own, such as an HTTP error status, or with an answer the backend could not read.
  • Exception: Whatever else the backend or its transport raised. Not a closed list; it includes requests connection and timeout errors left after the backend's retries, and for NextGen requests.HTTPError, a rejection included.

find_patient​

def find_patient(    self,    *,    given: str | None,    family: str | None,    dob: str | date,    narrows_last_search: bool = False,) ‑> PatientRecord:

The record of the one patient with these names and date of birth.

Arguments

  • given: The given name searched on.
  • family: The family name searched on.
  • dob: The date of birth, as a date or a YYYY-MM-DD string.
  • narrows_last_search: The caller is narrowing the name search it just made for this date of birth. A backend that searched by date of birth may answer from that search's candidates instead of searching again.

Raises

  • NoMatchingPatientError: If no patient matches.
  • NonSpecificPatientError: If more than one patient matches.
  • NoPatientIDError: If the patient found has no key.
  • EHRAuthenticationError: If the EHR rejected the search.
  • EHRConnectionError: If authentication has failed too often in a row for the run to go on.
  • EHRRequestError: On FHIR R4, if the EHR answered the search with an error the backend reports as its own, such as an HTTP error status, or with an answer the backend could not read.
  • Exception: Whatever else the backend or its transport raised. Not a closed list; it includes requests connection and timeout errors left after the backend's retries, and for NextGen requests.HTTPError, a rejection included.

lister​

def lister(self) ‑> BaseEHRPatientLister:

A lister paging through this EHR's patients' keys.

Raises

  • EHRConnectionError: If authentication has failed too often in a row for the run to go on.

patient_by_id​

def patient_by_id(    self, patient_id: str,) ‑> PatientRecord:

The record of the patient with this backend key.

Arguments

  • patient_id: The backend's key for the patient.

Raises

  • ValueError: If the key is blank (empty or whitespace only).
  • NoMatchingPatientError: If no patient has that key.
  • EHRAuthenticationError: If the EHR rejected the lookup.
  • EHRConnectionError: If authentication has failed too often in a row for the run to go on.
  • EHRRequestError: On FHIR R4, if the EHR answered the lookup with an error the backend reports as its own, such as an HTTP error status, or with an answer the backend could not read, or more than one patient has that key.
  • Exception: Whatever else the backend or its transport raised. Not a closed list; it includes requests connection and timeout errors left after the backend's retries, and for NextGen requests.HTTPError, a rejection included.

record_for_id​

def record_for_id(    self, patient_id: str,) ‑> PatientRecord:

A record for a backend key the caller already trusts.

Unlike patient_by_id, the patient is not confirmed to exist: the record is built for the key as given. A caller uses it where a key is all it has and the patient's data is wanted even when the patient resource cannot be read. Its demographics are None.

The patient resource is read best effort, if the backend reads it at all: found, it is the record's raw_patient. If no patient has the key, or the read fails (an API error or an error answer, an answer that cannot be read, or a connection or timeout error), the record has none, and a failure is logged without the key. Only three outcomes raise: the EHR rejecting the read, a second patient with that key, and the connection's budget stop. A backend that builds the record without a request (NextGen) has no read to fail.

Arguments

  • patient_id: The backend's key for the patient.

Raises

  • ValueError: If the key is blank (empty or whitespace only).
  • EHRAuthenticationError: If the EHR rejected the request for the patient resource.
  • EHRConnectionError: If authentication has failed too often in a row for the run to go on.
  • EHRRequestError: On FHIR R4, if reading the patient resource found more than one patient with that key.

reset_auth_budget​

def reset_auth_budget(self) ‑> None:

Forget the authentication failures counted so far.

A caller starting a pass over patients calls this, so a pass that ended because authentication kept failing does not stop every later pass on the same connection before it sends a request. A backend that keeps no budget does nothing.

stats​

def stats(self) ‑> EHRServiceStats:

What this connection has counted so far.

EHRServiceStats​

class EHRServiceStats(    forbidden_by_resource_type: Mapping[str, int] = {},    requests_timed: int = 0,    request_seconds: tuple[float, float] | None = None,):

Counts from one EHR connection, as they stood when read.

Arguments

  • forbidden_by_resource_type: HTTP 403 responses per resource type since the connection was built, cumulative over every step of the run that shares it; a caller wanting one step's share takes the difference across it.
  • requests_timed: How many EHR requests this process has timed under EHR_REQUEST_TIMER_NAME, on every connection.
  • request_seconds: The mean and standard deviation of those requests' durations, in seconds, or None before the first.

Variables​

  • forbidden_by_resource_type : Mapping[str, int]
  • request_seconds : tuple[float, float] | None
  • requests_timed : int

KnowledgeStore​

class KnowledgeStore(*args, **kwargs):

Holds findings about one EHR server, one per (kind, resource_type, subject).

Methods​


findings​

def findings(    self, kind: FindingKind | None = None,) ‑> list[Finding]:

Every finding, or every finding of one kind.

Arguments

  • kind: The kind to list, or None for all.

get​

def get(    self, kind: FindingKind, resource_type: str, subject: str = '',) ‑> Finding | None:

The finding under a key, or None.

Arguments

  • kind: What the finding is about.
  • resource_type: The resource type it concerns.
  • subject: Its subject (see Finding.subject).

put​

def put(self, finding: Finding) ‑> None:

Store a finding, replacing any under the same key.

Arguments

  • finding: The finding.

remove​

def remove(self, kind: FindingKind, resource_type: str, subject: str = '') ‑> None:

Forget the finding under a key, if there is one.

Arguments

  • kind: What the finding is about.
  • resource_type: The resource type it concerns.
  • subject: Its subject (see Finding.subject).

remove_if_unchanged​

def remove_if_unchanged(self, finding: Finding) ‑> None:

Forget a finding, unless another has been stored under its key since.

For a finding that has lapsed: a newer finding under the same key, such as one another process stored, is kept.

Arguments

  • finding: The finding as it was read.

NextGenURLs​

class NextGenURLs(fhir_url: ForwardRef('str'), enterprise_url: ForwardRef('str')):

A NextGen EHR's two endpoints, NextGen's own where the config sets none.

Arguments

  • fhir_url: The NextGen FHIR API's base URL.
  • enterprise_url: The NextGen Enterprise API's base URL.

Variables​

  • enterprise_url : str - Alias for field number 1
  • fhir_url : str - Alias for field number 0

PatientRecord​

class PatientRecord(*args, **kwargs):

One patient's record in an EHR.

Results honour the request: codes, categories, statuses and code types are filtered server-side where the backend can, and client-side where it cannot.

A failed fetch raises, unless the method names a result it gives instead (such as get_patient_code_states's None fields, or the documents download_documents failed to download, which it returns):

  • A fetch the backend cannot serve at all raises EHRFetchUnsupportedError, on both backends, with two exceptions on FHIR R4. Medications on a server that serves no medication type raise FHIRR4MedicationsUnsupportedError, a GetPatientInfoError only. get_previous_encounter_details on a server that does not serve Encounter raises FHIRR4GetPatientInfoError, with the unsupported error as its __cause__.
  • A request FHIR R4 rejects as unauthenticated after refreshing its token raises EHRAuthenticationError. NextGen raises none: a request it rejects is a failed fetch.
  • Any other failed fetch of the patient's clinical data raises a GetPatientInfoError: FHIRR4GetPatientInfoError on FHIR R4 and NextGenGetPatientInfoError on NextGen. A FHIR R4 server error or search given up on (each an EHRFetchUnavailableError) reaches the caller only as that error's __cause__. FHIR R4 conditions, procedures, observations, allergies and devices that were fetched but could not be read raise FHIRR4DataError instead.
  • A document listing whose request fails raises too, so that failure does not read as no (more) documents, but not as a GetPatientInfoError. download_documents given no infos lists the documents itself, downloading each batch as it is listed. On FHIR R4, document_infos, and download_documents given no infos, raise the client's errors as they are, so a server error is raised as FHIRR4ServerError, an EHRFetchUnavailableError; an answer that is not a Bundle (such as an OperationOutcome sent with a 200) is raised as FHIRR4APIError, with fhirpy's InvalidResponse as its __cause__. On NextGen, download_documents raises NextGenEnterpriseAPIError for a page whose request fails with an HTTP error, with that error as its __cause__; a next-page link of an unexpected form ends the listing with only a warning, so a listing cut short that way reads as complete. On both, a listing that fails part way raises after the documents of the batches before it were saved to save_path; they are not returned.

Variables​

  • demographics : RetrievedPatientDetailsJSON | None - The patient's names, date of birth, contacts and practitioners.
  • patient_id : str - The backend's key for the patient: opaque, passed back, not read.
  • raw_patient : Mapping[str, Any] | None - The backend's own patient resource as fetched, if one was.

Methods​


acuity_in_documents_only​

def acuity_in_documents_only(self) ‑> bool:

Whether the server is marked as serving acuity only in documents.

While it is, the acuity code searches can be skipped and the patient's documents read instead. Always False where acuity is not read from documents.

document_infos​

def document_infos(self) ‑> Iterable[list[EHRDocumentInfo]]:

The patient's documents, in batches, without their content.

download_documents​

def download_documents(    self, save_path: Path, infos: Sequence[EHRDocumentInfo] | None = None,) ‑> tuple[list[DownloadedEHRDocumentInfo], list[FailedEHRDocumentInfo]]:

Download the patient's documents to save_path.

Arguments

  • save_path: Where to save the documents.
  • infos: The documents to download, from document_infos; every document when None.

Returns The documents downloaded, and those that could not be.

get_document_acuity​

def get_document_acuity(    self,    codes: Sequence[tuple[str | None, str]],    *,    observed: Mapping[Eye, date] | None = None,) ‑> DocumentAcuityResult:

The visual acuity observations recorded in the patient's documents.

Arguments

  • codes: The (system, code) pairs of the acuity observations to read.
  • observed: The date of each eye's newest best-corrected reading in the patient's Observations. With both eyes given, the documents are listed but their CCDs downloaded only if one may be newer than the older of the two readings. None, or one eye, reads the CCDs as usual.

Returns The observations found, and whether the search was complete.

Raises

  • EHRFetchUnsupportedError: Only where the backend or provider does not read acuity from documents. Where it does, a server that will not list documents gives an incomplete result instead.
  • Exception: The listing's errors, as document_infos raises them.

get_next_appointment​

def get_next_appointment(self) ‑> datetime.date | None:

The date of the patient's next appointment, if any.

get_patient_allergies​

def get_patient_allergies(self) ‑> list[Allergy]:

The patient's allergies and intolerances.

get_patient_associated_medical_practitioner​

def get_patient_associated_medical_practitioner(self) ‑> str | None:

The name of the practitioner associated with the patient, if any.

get_patient_code_states​

def get_patient_code_states(    self, *, include_medications: bool = False,) ‑> PatientCodeDetails:

The patient's conditions, procedures and, optionally, medications.

Each is fetched on its own, so one failing costs only its own field, which is None; unsupported_fields names those the backend cannot serve at all.

Arguments

  • include_medications: Whether to fetch medications too.

get_patient_conditions​

def get_patient_conditions(    self,    statuses_filter: list[ClinicalStatus] | None = None,    code_types_filter: list[CodeSystems] | None = None,) ‑> list[Condition]:

The patient's conditions.

Arguments

  • statuses_filter: Only conditions with one of these clinical statuses, or all when None.
  • code_types_filter: Only codings in these code systems, or all when None.

get_patient_devices​

def get_patient_devices(self) ‑> list[Device]:

The devices recorded for the patient.

get_patient_medications​

def get_patient_medications(self) ‑> list[Medication]:

The patient's medications, from every medication source served.

get_patient_observations​

def get_patient_observations(    self, codes: Sequence[tuple[str | None, str]],) ‑> list[Observation]:

The patient's observations with any of these codes.

Arguments

  • codes: (system, code) pairs; a None system matches the code in any system.

get_patient_observations_by_category​

def get_patient_observations_by_category(    self, categories: Sequence[str],) ‑> list[Observation]:

The patient's observations in any of these categories.

Arguments

  • categories: Observation category codes, such as laboratory.

get_patient_procedures​

def get_patient_procedures(    self,    statuses_filter: list[ProcedureStatus] | None = None,    code_types_filter: list[CodeSystems] | None = None,) ‑> list[Procedure]:

The patient's procedures.

Arguments

  • statuses_filter: Only procedures with one of these statuses, or all when None.
  • code_types_filter: Only codings in these code systems, or all when None.

get_previous_appointment_details​

def get_previous_appointment_details(    self, include_maybe_attended: bool = True,) ‑> list[EHRAppointmentEncounter]:

The patient's past appointments, oldest first.

Arguments

  • include_maybe_attended: Whether to include appointments whose attendance is not recorded.

get_previous_encounter_details​

def get_previous_encounter_details(    self, include_maybe_attended: bool = True,) ‑> list[EHRAppointmentEncounter]:

The patient's past encounters, oldest first.

Arguments

  • include_maybe_attended: Whether to include encounters whose attendance is not recorded.

get_visual_acuity​

def get_visual_acuity(self) ‑> Observation | None:

The patient's most recent visual acuity reading, if any.

json_dump​

def json_dump(    self,    save_path: Path,    elements: Container[str] = frozenset({'procedures', 'patientInfo', 'encounters', 'medications', 'chart', 'appointments', 'conditions'}),) ‑> collections.abc.Mapping[str, typing.Any] | None:

Save a JSON dump of the patient's record to save_path.

Its content is backend-specific: FHIR R4 dumps by resource type, NextGen by endpoint.

On FHIR R4, a search that fails reads as no data for its part of the dump, except for these, which raise: a rejection, as EHRAuthenticationError; a 200 that is not a Bundle (an empty body included), as fhirpy's InvalidResponse; a 200 that is not JSON, as json.JSONDecodeError; and a connection error left after the client's retries, as it is.

Arguments

  • save_path: Where to save the dump.
  • elements: The parts of the record to dump.

Returns The dump, or None if there was nothing to dump.

reads_acuity_from_documents​

def reads_acuity_from_documents(self) ‑> bool:

Whether get_document_acuity reads acuity for this backend and provider.

record_acuity_sources​

def record_acuity_sources(self, *, in_observations: bool, in_documents: bool) ‑> None:

Record where this patient's visual acuity was found.

Evidence for acuity_in_documents_only, kept with what is known about the server. Does nothing where acuity is not read from documents.

Arguments

  • in_observations: Whether the patient's Observations held a reading for either eye.
  • in_documents: Whether the patient's documents held a reading for either eye.

with_name​

def with_name(    self, *, given_name: str | None = None, family_name: str | None = None,) ‑> PatientRecord:

The same patient's record, with these names in its demographics.

A name left as None keeps the record's own. A record with no demographics gets demographics holding just its key and the names given (none, given no names). This record is not changed.

Arguments

  • given_name: The given names to carry, joined by spaces.
  • family_name: The family name to carry.