Skip to content

feat(monitoring): report the FHIR server's reachability, with an idle probe - #33

Merged
angela-helios merged 35 commits into
HeliosSoftware:mainfrom
Gordex2014:feat/destination-reachability
Nov 24, 2026
Merged

angela-helios merged 35 commits into
HeliosSoftware:mainfrom
Gordex2014:feat/destination-reachability

Conversation

@Gordex2014

Copy link
Copy Markdown
Contributor

Stacked on #32. This branch has #32 (which contains #31, #30, #29 and #28) merged into it, so until those land the diff against main also shows the event log, the alerts cursor, the alert webhook, the check outcome and the loads list. This PR's own change is git diff fb5830e (#32's head): src/destination.rs, the exchange observation in src/fhir.rs and src/bulk.rs, the destination: block in src/config.rs, destination in src/api.rs, the outage, recovery and rule-clear parts of src/pipeline.rs, src/alerts.rs and src/db.rs, the PostgreSQL index order in src/db.rs, tests/destination.rs, tests/rule_alerts.rs, and the matching parts of docs/.

What changes

GET /api/monitoring/status says whether the FHIR server answers. Delivery alerts end at recovery, and an alert ends with its rule. On PostgreSQL, a start no longer builds indexes in one batch, so a rolling start cannot deadlock with a running instance: this fixes a pattern introduced in #28 and #31.

  • destination in GET /api/monitoring/status: {reachable, since, last_error, consecutive_failures, observed_at} (src/destination.rs), kept in memory per engine process.
    • Every request a delivery sends under fhir_base_url is observed: REST batch Bundles, the $bulk-submit kick-off and $bulk-submit-status. Bulk status pages and file fetches are not.
    • A failure is no connection, a timeout, a connection lost before the answer, or 502, 503 or 504. Any other answer, a 401 or a 500 included, means the server answers.
    • last_error is one of a few fixed sentences ("could not connect to the FHIR server", "the FHIR server answered HTTP 503", ...): never a URL, host or library text. The detail (the error chain, without the URL) goes to the log when the state changes.
    • Order: a request that started before the latest counted one does not overwrite it. A probe gives way to any delivery started after it, and its success does not end an outage deliveries see as 502 to 504 until none has been seen for ten minutes.
  • Idle probe. Once nothing has reached the server for destination.probe_seconds (60 by default, at most 86400, 0 off), the engine sends GET {base}/metadata: no token, no user information from the URL, no redirects, a 10-second limit, a fresh connection each time.
  • REST delivery reasons for a server that cannot be reached are the same fixed sentences. A request that cannot be built is logged and no longer counted as an exchange.
  • Delivery alerts end at recovery. Before, a rule-less delivery alert stayed open after recovery, beside a delivery_recovered alert that never cleared either.
    • Recovery clears every open delivery alert of the source, with a rule or without, through the webhook's clear path: one cleared event per alert, to the channels recorded when it fired. delivery_recovered is no longer raised.
    • A rule-less outage alert is raised once per outage, checked in the store rather than in one process's memory.
    • REST recovery needs HFS to decide at least one entry of a batch: a batch whose every entry is to be retried is still an outage.
    • The first start of this version on a store closes, in the store only, the delivery_recovered alerts earlier versions left open, and the outage alerts a later recovery notice, or a record of the source delivered after them, shows to be over. A marker keeps later starts from doing it again.
    • Retention keeps an open rule-less outage alert whatever its age, since it is what stops a second alert for the same outage.
    • last_alert in a source's status gains cleared_at.
  • An alert ends with its rule.
    • Turning a rule off, deleting it, or changing its condition, threshold or source through PUT/DELETE /api/alert-rules/{id} clears its open alerts in the same transaction as the change. Each gets its cleared event, to the channels recorded when it fired.
    • A change of recipients or channels alone clears nothing.
    • If the changed rule still finds the condition, its next evaluation raises a new alert with its own id.
    • An alert of a rule is written only while the rule is on and still has the condition, threshold and source the pass read. On PostgreSQL the rule's row is locked until the alert commits, so a pass that read the rule just before a change raises nothing under it.
    • A start clears the open alerts whose rule an earlier version turned off, deleted, or moved to another condition or source.
  • PostgreSQL start order (src/db.rs). The tables and their added columns come first. Then every index (the schema's, the two from feat(events): event log of record attempts and outcomes, with retention #28, files(feed_id, id) and the checks indexes from feat(api): give Check now an id and an outcome #31, the loads ones, the PostgreSQL-only one) is checked or built in a transaction of its own, as feat(api): list loads across sources, filtered and in pages #32 already did for its four.
  • Docs: docs/api.md (the status row, "The destination", the alert-rules row, alerts and retention), docs/running.md (the destination probe, retention, the PostgreSQL start), docs/sources.md (alert clearing, legacy alerts), docs/decisions.md (decision 43; decisions 8, 12, 38 and 40 amended).

In plain words

When the FHIR server is down, the status endpoint now says so once, with when it started and a reason that is safe to show anyone, instead of every source failing on its own. When nothing is being sent, the engine checks the server once a minute, so the answer does not go stale. An outage alert now closes when delivery works again. An alert also closes when someone turns off, deletes or changes the rule that raised it, so the list of open alerts matches the rules in force. On PostgreSQL, starting a new instance while another one is running can no longer stall both of them.

Side effects checked

  • Alert kinds. delivery_recovered is no longer raised, so hie_alerts_total{kind="delivery_recovered"} stops growing. A receiver reads the cleared delivery alert, or its webhook cleared event, instead.
  • Webhook. Every clear goes through feat(alerts): sign, retry and record the alert webhook #30's clear path, so a cleared event goes only to the channels recorded when the alert fired. Start-up closes legacy delivery alerts without events, because they never had a fired event. The first start clears old alerts of rules turned off or deleted earlier, each with its cleared event, possibly several at once.
  • Rolling upgrade. An instance of an earlier version still running on the store keeps raising delivery_recovered. After the marker is set, those stay open. A rule changed by such an instance leaves its alerts to the next start.
  • Reasons and leaks. destination and REST delivery reasons carry no URL, host or library text. Bulk failure reasons keep the server's origin (scheme://host:port/…), as before. A token endpoint's answer in a delivery reason is unchanged and out of scope.
  • What reachable means. It is not "delivering": a server answering 500 to every batch, or a token that cannot be fetched, leaves it true. Records and alerts say that.
  • Store. There are no new tables or columns: one store_meta row (delivery_alerts_reconciled) and the PostgreSQL start order. Every start still runs ALTER TABLE … ADD COLUMN IF NOT EXISTS per added column, one table at a time, which can wait behind a running instance's longest transaction on that table. That is documented, and it cannot deadlock.
  • Configuration. A new optional destination: block with one key, probe_seconds. Unknown keys there are refused at start and by hie check.
  • Library types. Db::insert_alert_with_webhook returns Option<AlertRow> (None when the rule moved on). Alerter::update_rule and delete_rule are new, and FhirClient::destination and BulkSubmitter::with_destination are new. All are new or changed since 0.2.0.

How to verify

The CI commands, with CI=true and default parallelism, on this tree (Linux):

$ helios-ci-gate      # fmt, clippy (both feature sets), Python tests, cargo test, the no-backend tests
test: passed (451 tests, 0 failures; Python transform tests OK)

cargo test --all-targets ran twice more on SQLite, both times with no failure. Against a throwaway PostgreSQL 17 (HIE_TEST_DATABASE_URL=postgres://...), run twice:

$ cargo test --lib --test rule_alerts --test destination --test pipeline --test alerts --test alert_webhook --test events --test api --test loads
every listed integration suite passed
lib 142 passed, 2 failed: secrets::key::tests::a_socket_at_the_key_path_is_refused and
a_key_file_removed_after_start_asks_for_a_restart. They fail on PostgreSQL only and are not touched here:
on PostgreSQL the store does not create the data directory those tests use for the key file.
  • The deadlock. db::tests::a_start_on_postgres_waits_for_a_write_without_holding_what_it_needs holds each indexed table in an open write, starts a second handle, then takes every other table. Against the old single batch it fails with deadlock detected; now it passes.
  • Other tests.
    • tests/destination.rs uses a stand-in FHIR server and no transform. It covers an unreachable server, a 503 and recovery, a batch whose entries are all retried, the idle probe (no token, path /fhir/metadata), the probe off, the probe against a delivery 503, a token that cannot be fetched, bulk observation, a lost connection, legacy alerts, webhook clears and retention.
    • tests/rule_alerts.rs covers rules turned off, deleted and changed through the API, a change of recipients only, a new alert after a change, a stale rule raising nothing, and the start-up clear.

Links

Closes #24

GET /api/alerts takes since (alerts created at or after an RFC 3339
instant) and cursor (the previous page's next_cursor), keeping source,
open and limit. Pages are a keyset on the alert id, newest first, and
next_cursor is null exactly when nothing more matches. A malformed query
answers 400 invalid_query. Decision 39.
… query checked

limit=0 no longer reads the store; a row without an id is an error rather
than a silent end of the walk; /api/alert-rules checks limit and open as
before. The docs say a late or cleared alert is found by a new walk and
that a page after a cursor can be empty.
The cursor is a1.<id>, so a client cannot take an alert id for one and a
later form can be told apart. The docs state the limit=0 exception and
when an error names its field; tests cover an empty page after a cursor
and the rules list's type checks.
POST /api/sources/{id}/check-now now records a check and answers its
check_id; GET /api/checks/{id} answers pending, found (with the loads),
nothing_new or failed (with a fixed reason), with requested/finished
times. A check is answered by the first scan that starts after it, with
the source's loads since it was asked for. Decision 41.
Every change of an alert, fired and cleared, is now an event with a
random event_id, written with its exact body in the same transaction as
the alert (table alert_webhooks). A sender task per instance posts
waiting events oldest first, signs them with HMAC-SHA256 over the raw
body when alerts.webhook_secret (or HIE_ALERT_WEBHOOK_SECRET) is set,
and retries a failed attempt up to five times with exponential backoff
(alerts.webhook_backoff_ms, 10 s by default). Attempts are claimed with
one conditional update and their outcome is fenced by the attempt
number, so several instances on one store never send one attempt twice.
Redirects are not followed. An event belongs to the URL configured when
it was written and waits for it.

GET /api/alerts shows each alert's latest delivery (event, state,
attempts, last_error, last_status, delivered_at) and whether this
instance has a webhook configured and signed.

The webhook body changes: {event_id, event, alert, source, text}
replaces {text, feed, kind, alert_id, notify, cleared}. A clear is now
posted only when the alert's rule asked for the webhook. alerts: refuses
unknown keys, and its errors never quote the URL or the secret.

Decision 40.
The baseline is taken in the check's own INSERT; a delete fails the
source's waiting checks first, in one statement guarded by the lease,
and answers store_busy rather than strand them; a pause lifted while a
pass reads the checks leaves them to the next pass. Index files by
(feed_id, id) for the baseline and range reads.
- hie check no longer echoes values from a malformed alerts: block:
  YAML errors pointing into it are reported without the parser's words,
  and an unknown key is named only when it looks like a key.
- A blank webhook secret is refused on the library path too.
- A failed COMMIT of an alert and its event is rolled back.
- Tests: the PostgreSQL schema outlives the engines a test drops; the
  fence is tested while the newer attempt runs; timeout category; the
  API's pending and parked states; no URL, secret or fingerprint in the
  API answer; two more hie check canaries.
- Docs: ordering holds per URL; last_error, last_status, pending and
  failed spelled out; backoff bounds.
A runner stopped while it read the waiting checks drops them, so a
check asked for after a replace is answered with the new definition.
Docs: when a pass reads its checks, and the delete and index costs.
Tests wait for the live check's answer and release the delete case's
lease instead of letting it lapse.
An append-only events table, written in the same transaction as the change
it reports, through one insert path (on PostgreSQL under an advisory lock
keyed by schema, so ids commit in order). Every outcome is a guarded update
on the status it leaves and the record's revision, bumped when a person puts
a record back, so an outcome for a superseded revision changes nothing.
Admission, finishing a load, Retry and reprocess, REST batch outcomes, bulk
opening, settling and refusal each run in one transaction with their events.

GET /api/events lists the log oldest first by id, with source, kind, since,
cursor and limit; every unreadable parameter is a 400 invalid_query naming
its field.

retention.history (30d by default) purges events and stored alerts at start
and hourly; open alerts the engine tracks and the newest alert are kept, and
purged alerts still count in hie_alerts_total. safe_reason now keeps
brackets and parentheses inside a URL, and bulk texts replace the
submission token by value.
- hie.yaml parse errors leave out every quoted value while the file
  holds the webhook URL or secret: YAML can carry a value into an error
  from anywhere (quoted or explicit keys, aliases). The runtime check no
  longer reports a parse error of its own.
- HIE_ALERT_WEBHOOK_URL is refused under its own name.
- PostgreSQL schema set-up runs in one transaction under an advisory
  lock, so instances upgrading one store together all start.
- The webhook client speaks HTTP/1.1 only.
- A claimed attempt clears last_status until it is answered.
- Tests: concurrent claims on two connections, last_status while an
  attempt runs, five more hie check canaries.
- Docs: which clears are posted (the channels recorded when the alert
  fired; rules turned off or deleted leave their alert open).
- A hie.yaml that is not valid YAML is refused again (a repeated
  runtime: key no longer slips past the check), with quoted values left
  out of the error.
- Quoted values are left out of a typed parse error when the decoded
  file gives alerts: any value, rather than when the text names a key:
  escaped keys are caught, and a blank template keeps full errors.
- PostgreSQL: added columns are altered one at a time and only when
  missing, outside the locked schema transaction, so start-up cannot
  deadlock with a query joining those tables.
- The concurrent-claim test cannot hang when its set-up fails.
Failure reasons name a request target only by its origin, or <URL> for a
relative one, and cleanup errors replace the submission token by value.
Settling locks the open submission first, as a refusal does. A source-object
submission opens only if each file claims exactly what its manifest counted,
and REST outcomes are also guarded by the attempt count selected. Admission
takes a per-source lock on PostgreSQL and looks the content up again. The
alert purge checks its predicate again on the row it deletes. Large set
writes keep only ids and write their events a chunk at a time. A transform
that cannot finish now is logged once per record and reason per runner.
GET /api/events refuses unknown parameters and signed limits.
… probe

GET /api/monitoring/status gains destination: {reachable, since,
last_error, consecutive_failures, observed_at}, from every request a
delivery sends under the base URL and from an anonymous GET /metadata
once nothing has reached the server for destination.probe_seconds (60 by
default, 0 off). last_error is one of a few fixed sentences, never a URL.

Recovery now clears every open delivery alert of the source, with a rule
or without, instead of raising a delivery_recovered alert next to an
outage alert that never cleared; start-up closes the ones earlier
versions left open. REST delivery errors name the FHIR server instead of
its URL.

Closes HeliosSoftware#24
… cannot be reached

A request's start instant is taken while the destination's lock is held,
so a probe always gives way to a delivery that registered after it. Each
change of state logs the failure with its whole error chain, and REST
transient reasons carry that chain too. Every server-error status gets
its own sentence. Start-up also closes an old rule-less outage alert when
a record of its source was delivered after it. Tests cover a connection
closed before the answer, the status request and a status page on the
server's own origin, and the webhook around a recovery.
Set updates page by id and check their guard again on each row, so a record
changed meanwhile is left alone and each chunk is a seek, on two new indexes
made after the added columns. A relative target echoed with a query keeps
its path only. A transform-phase failure is remembered as logged only once
its event is stored. A since finer than a millisecond starts at the next
one. A zip entry found taken after it was staged does not reuse its name.
…nd logs

A REST delivery that cannot reach the server stores the destination's
fixed sentence as its reason; the log gets the errors under the request
error, never the request error's own text, which carries the URL. A
request is built before it counts as one sent to the server, so one that
cannot be built does not hold back the probe. Start-up compares an old
outage alert with the source's newest record only, found through the
index. Tests keep their seeding store open, so they also run on
PostgreSQL, and check the webhook's alert ids and the probe's query.
GET /api/loads lists the loads of every source, newest first, with the
fields of the per-source list, narrowed by source and by status or to the
loads failing now (unreadable, or with a rejected row, also while in
progress). A page of up to 200 loads, its counts and whether more follow
come from one statement, behind an opaque cursor on the load id.

Every load answer gains failed and source_name, the name the source had
when the load was recorded, so a deleted source's loads stay identifiable.
New indexes let each page be chosen through an index, with one seek per
failed load on a partial index of rejected rows.
A source name with a NUL, which a PostgreSQL text value cannot hold, is no
longer kept with its loads instead of failing every load of that source;
a source query with a control character is refused as invalid_query.
The docs now say what a source created again under a deleted id takes
over exactly (pending rows keep the earlier transform's resources, the
silence rule counts from the earlier loads, read-only sources skip by
name and size, zip entries), which empty parameters count as absent, and
what a failed scan raises. Tests walk failed pages one load at a time
across unreadable loads and loads with many rejected rows.
A new source on a deleted source's id sends waiting rows as they are by
REST or transformed bulk, but hands over the load's file on the
source-object path. The docs also list every alert a failed scan may be
followed by, qualify the read-only skip by name and size to non-empty
files, and require a UTF8 PostgreSQL store.
safe_reason cuts any word with a ? followed later by = (a query), and
leaves questions alone. A submission's progress and failure writes hold only
at the attempt count read before the request, and the outage alert follows
only a write that changed it. Each file is finished in its own transaction
and its alerts weighed right after. An open alert is kept by an enabled rule
only if the rule is older than it. A since is rounded up from the digits of
its text. PostgreSQL builds the schema under a session lock, and SQLite gets
no index that its rowid already gives.
A row its transform turns into no resources is rejected as filtered and
still counts in rejected, but a load whose only rejected rows are
filtered is not failed: failed now means unreadable, or a row rejected
for any other reason. The partial indexes hold only those failing rows.
GET /api/sources/{id}/failures counts the distinct records a source
rejected over the last 24 hours and each of the last days (UTC, from one
day_windows function), filtered rows apart, with each window's coverage:
from when this store began recording events (store_meta.events_since, set
once) and within the retention. An index on events(source_id, kind, at)
serves it.

A SQLite alert_rules made before is rebuilt once with AUTOINCREMENT, with the
same rows and ids and its sequence past every rule id in use, so no rule id
is given again; every rule answer carries created_at, never taken from a
request body.
reject_submission, settle_page and settle_submission take the attempt count
read before the poll and require it, with the open status, on the
submission row they lock first. An answer to an older poll (a newer one
failed meanwhile) changes nothing: no record, no event, no archive. A
settlement that finds the count moved stops after the pages it applied.
…ince-cursor

# Conflicts:
#	docs/api.md
#	docs/decisions.md
#	docs/development.md
#	src/api.rs
#	tests/alerts.rs
failing counts the rejected rows that make a load fail, every rejected
row but the filtered ones, beside rejected, so a list's failure count
agrees with failed: a load whose only rejections are filtered shows
failing 0.
…t/alert-webhook-delivery

# Conflicts:
#	docs/api.md
#	docs/decisions.md
#	docs/development.md
#	src/api.rs
#	src/config.rs
#	src/db.rs
#	src/lib.rs
#	tests/alerts.rs
Checks join the retention purge (retention.history) with events and
alerts, and GET /api/checks/{id} reads its parameters as /api/events
does: an opaque cursor, and 400 invalid_query naming the field.
…ate pause

purge_checks locks the rows it chooses, so on PostgreSQL a purge that
waited for another moves on to the next old checks instead of stopping
with some left. A pause that lands while a pass loads its credential
fails the checks it read and ends the pass. Docs name /api/checks among
the invalid_query routes and the duplicates a read-only source skips.
Loads record the source's name through the store calls that now take
files in (admit_file, insert_duplicate, insert_container), the paging
module is the landed one, /api/loads joins the routes that answer
invalid_query, and decision 42 follows 38 to 41.
The four indexes the loads list reads are built each in a transaction of
its own after the schema, so a long build over records never holds files
while another instance's Retry waits on both. The docs add the events,
failure figures and pending checks a reused id takes over, count the
four indexes in the upgrade note, and say how /api/loads refuses a
query. The test of a name a store cannot hold covers every way a file
is taken in.
Conflicts resolved: the alert clear keeps the webhook's `cleared` event
and clears by id, so recovery clears every open delivery alert of a
source through it; the bulk submitter keeps the origin-only base in its
reasons; the store keeps both sides' functions; the outage test checks
the cleared alert and the event log together; the docs keep both
sections. The destination tests follow the store's new signatures and
the webhook's new body.
A start ran the schema's indexes, and the two added with the event log,
each batch in one transaction. CREATE INDEX IF NOT EXISTS takes a SHARE
lock on its table even when the index exists, so a start that waited
for a running instance's write to one table held the others meanwhile,
and could deadlock with that write during a rolling start. The tables
and their added columns now come first, then every index on its own, as
the loads indexes already were. A PostgreSQL test holds each indexed
table in an open write, starts a second handle, then takes every other
table: it deadlocked before and passes now.
Turning a rule off, deleting it, or changing its condition, threshold
or source clears the rule's open alerts when the API makes the change,
through the same clear as every other, so each writes its cleared event
for the channels recorded when it fired. A changed rule that still
finds the condition raises a new alert with its own id. A change of
recipients or channels alone clears nothing. Each source's pass also
clears an open alert whose rule is gone, off, or watches another
condition or source, which catches one raised by a pass that read the
rule just before the change.
Review round 3. A rule turned off, deleted or changed through the API
clears its open alerts in the transaction that changes it, so a failed
clear cannot leave them behind a committed change, and an alert raised
under the changed rule is not cleared by it. An alert of a rule is
written only while the rule is on and has the condition, threshold and
source the pass read; on PostgreSQL the rule's row stays locked to the
alert's commit. The per-pass sweep goes: a start clears what earlier
versions left, a rule whose id was given again included.

The reconciliation of delivery alerts left by earlier versions runs
once per store, so a rolling start cannot close an outage alert this
version raised without its cleared event, and it counts any record of
the source delivered after the alert. Retention keeps an open outage
alert without a rule. The PostgreSQL start test checks which lock the
start waits for. Docs say when a changed rule raises again, what a
start still locks, and that bulk reasons keep the server's origin.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Report FHIR destination reachability in the monitoring status

2 participants