Skip to content

feat(sources): a free-text contact on the source, and the default rule only at creation - #35

Merged
angela-helios merged 47 commits into
HeliosSoftware:mainfrom
Gordex2014:feat/source-contact
Nov 24, 2026
Merged

angela-helios merged 47 commits into
HeliosSoftware:mainfrom
Gordex2014:feat/source-contact

Conversation

@Gordex2014

Copy link
Copy Markdown
Contributor

Stacked on #34. This branch has #34 (which contains #33 and the PRs below it) merged into it, so until those land the diff against main also shows their work. This PR's own change is git diff 5405713 (#34's head): contact in src/config.rs, src/api.rs and src/main.rs; the default rule's birth in src/db.rs and src/manager.rs; src/manager/reference_tests.rs, tests/api.rs, tests/alerts.rs, tests/check.rs and the matching parts of docs/.

What changes

A source can say whom to call about it, and its default silence rule is given only when the source is created.

  • contact on a source definition.
    • It is optional free text: one line, at most 500 characters, never interpreted. The engine sends nothing to it.
    • It may not hold control characters, the line and paragraph separators, or the bidirectional marks and controls (U+061C, U+200E, U+200F, U+202A to U+202E, U+2066 to U+2069). It must be text: in YAML, a bare number or true is refused, so such a contact is quoted.
    • Absent, null and blank all mean no contact, and a blank one is not written.
    • It is returned as contact by every source read and write, by each source of GET /api/monitoring/status and by each of its needs_you entries. hie check prints it.
    • It is checked wherever a definition is: at start, by hie check, and on POST and PUT. An invalid one stops hie run and hie check, naming the file.
  • PUT /api/sources/{id} stays a whole replace. A body without contact leaves the source with none, so a client that changes one member sends back the definition it read. The top-level contact is what runs, normalised; definition.contact is the file as saved. docs/api.md says when the two can differ.
  • The default silence rule only at creation (an owner decision; amends decision 22).
    • Up to 0.2.0, every start and every replace gave the rule to a source that had none. A whole PUT (a contact or transform save) or a restart brought back a rule someone had deleted.
    • The store now records each source's birth in a new table, source_births, one row per id, shared by every instance on the store.
    • A source the store has never seen gets the rule when it first appears at a start. POST /api/sources always counts as a creation: it adds the rule unless the id still has a silence rule (rules outlive a deleted source), so there is never more than one.
    • PUT, pause, resume and restarts add none.
    • A deleted source keeps its birth. Created again with POST, it gets the rule as above; put back as a file, it is the source the store knew and gets none.
    • On POST, the rule is added before the file is written, and it stays if the write or the start then fails. A store too busy to record the birth answers 503 store_busy with nothing written.
    • Upgrade. The first time this version meets a source with no birth row, it looks for anything the store holds of it: a rule, an alert, a file, a pause, a cursor, a check, an event or a count of purged alerts. If it finds any, the source is marked born without a rule. A source the store holds nothing of is new and gets the rule.
    • Recording the birth and adding the rule happen in one transaction, at read committed on PostgreSQL, so two instances starting the same new source add one rule.
  • Docs:
    • docs/sources.md: contact, and when the rule is given.
    • docs/api.md: the POST, PUT, DELETE and monitoring rows, and the two views of contact.
    • docs/running.md: shared stores.
    • docs/development.md: the tests.
    • docs/decisions.md: decision 45, and decision 22 amended in place.

In plain words

Each source can carry a line saying whom to call when it goes quiet or starts failing, and the monitoring page shows it next to the problem. Saving that line, or any other change to a source, no longer brings back a silence alert someone had switched off on purpose.

Side effects checked

  • Sources without contact read as before, apart from contact: null. A definition saved by an older engine keeps working.
  • Older engines drop the member when they rewrite a definition. On a shared PostgreSQL store, instances still on an earlier version keep adding the rule back on their starts and replaces until every instance runs this one.
  • A deleted rule stays deleted through PUT, restarts and file re-reads. A source from before the upgrade that left nothing at all in the store (started, its rules all deleted, nothing received, never alerted, checked, paused or given a cursor) gets the rule once more on the first start of this version.
  • Alerts (feat(monitoring): report the FHIR server's reachability, with an idle probe #33's "an open alert ends with its rule"). Giving the default rule only inserts a row, so it clears nothing and queues no webhook. A source deleted while its silence alert is open keeps that alert and its rule, as before, since no runner watches it. Created again with POST, it gets no second rule. Its new runner judges the alert as after any restart. Deleting, turning off or changing the rule clears the alert.
  • Store. One new table, source_births, created on start. Rule ids still come from the same insert, so feat(events): event log of record attempts and outcomes, with retention #28's guarantee that a rule id is never given again holds.
  • Library types. FeedConfig gains contact. Db::has_rule is removed, and Db::give_default_rule is new.

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 (542 tests, 0 failures; Python transform tests OK)

The changed suites ran again on SQLite with no failure. Against a throwaway PostgreSQL 16 (HIE_TEST_DATABASE_URL=postgres://...), every suite:

$ cargo test --no-fail-fast
386 passed, 3 failed:
  secrets::key::tests::a_key_file_removed_after_start_asks_for_a_restart and
  a_socket_at_the_key_path_is_refused, the same two that fail on PostgreSQL before this change;
  hfs_credentials::the_engine_fetches_caches_refreshes_and_drops_its_token, which edits the SQLite file
  directly (tests/hfs_credentials.rs:116) and so cannot run with a PostgreSQL store; this PR does not touch it.
  • Contact (src/config.rs, tests/api.rs, tests/check.rs):
    • read from a file and from the API, kept by a replace that sends back what it read, and cleared by one without it;
    • refused when too long, when it is more than one line, when it holds a control or direction character, and when it is not text;
    • printed by hie check, and refused there naming the file, in both builds.
  • Birth, store (src/db.rs, on SQLite and PostgreSQL):
    • the rule is given once and not again after its deletion, and a forced create gives it again but never twice;
    • each kind of earlier evidence marks a source born without a rule;
    • a failed birth records nothing;
    • two handles on one store, one held inside its transaction while the other waits, give one rule in every forced and unforced pairing.
  • Birth, engine (src/manager/reference_tests.rs, tests/alerts.rs):
    • a create gives the rule;
    • a replace, a failed-start replace, a restart and a file put back give none;
    • a delete followed by POST gives one, or keeps the old one;
    • a source first seen in a file gets its rule once;
    • a failed birth, write or start leaves what the docs say;
    • over HTTP, a PUT of the read-back definition with a contact does not bring back a deleted rule.

Links

Closes #26

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.
`GET /api/sources/{id}/stats` takes `tz` and counts its days from local
midnight to the next, echoing the zone it used (`UTC` without one). A
`missing_by` rule takes an optional `tz` for its time of day and its
"today"; rules without one stay in UTC.

A local time skipped by a DST change stands for the change itself, a
repeated one for its first occurrence, and 23- and 25-hour days keep
their length. Zone rules come from the IANA database built into the
engine (jiff-tzdb), never the host's. An unknown zone answers 400 with
a fixed sentence (`invalid_query`, `field: tz`, on the stats query).

"Received today" for a rule and the `today` figures are bounded on both
sides, and a deadline pushed onto the next midnight by a DST gap is
checked as that day begins. Amends decision 22; adds decision 44.

Closes HeliosSoftware#25
…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.
…y, once

A file of the next day no longer hides that the day before's never came, and an alert of the rule open at that deadline covers it. A date a zone skipped misses no deadline. An unknown tz is refused before the source is looked up. Tests tie the echoed zone to the dates the route returns; the docs give day lengths as the clock's.
An optional one-line contact (at most 500 characters, text only, never
interpreted) on a source definition, from its file or the API. Returned by
every source read, each source and needs_you entry of the monitoring status,
and printed by hie check. PUT stays a whole replace: a body without it clears
it, and sending back the definition read keeps it. Decision 45.
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.
… send before clearing

The deadline pushed onto midnight is computed apart from today's, so a pass after today's deadline still checks the day before; an alert raised for it is cleared on the next pass, never in the one that sent it. Stats echo today's day beside the zone. Wording: a change of offset, such as daylight saving time; day lengths as on the clock.
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.
…se nothing

Rows a transform filters out on purpose are rejected as filtered and are not failures. Stats (per local day and today) and the monitoring status (last_24h and each source's failing_last_24h) gain failing beside rejected, which keeps its meaning, and needs_you lists a source for its failing rows only, with the same sentence.
…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.
A start or a replace used to add the default silence rule to any source
without one, so a whole-definition PUT (a contact or transform save) or a
restart brought back a rule someone had deleted. The store now records each
source's birth: a source the store has never seen gets the rule at the start
that finds it, a POST is always a creation (one silence rule at most), and a
replace, a restart or a file put back adds none. Sources an earlier version
left in the store are marked born without a rule. Decision 45, amending 22.
A failed write no longer deletes the rule its create was born with: another
create may already count on it, and a rule id can be reused on SQLite. A
store too busy to record a birth answers store_busy with nothing published.
The birth runs read committed on PostgreSQL, checks the rule's own condition
and shares the rule insert. The race test now holds one handle inside its
transaction while the other waits, in each forced/not-forced order, and a
failed birth is shown to publish nothing and keep no registration.
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.
Brings the event log, the alert webhook, loads across sources and the
destination's reachability under the time zone work:

- /api/sources/{id}/failures takes tz: its days are local days of the
  zone, each named, and the answer echoes the zone. An unknown zone is
  refused as on /stats, before the source is looked up.
- A change of a rule's tz ends its open alert, and an alert is written
  only while the rule still has the zone the pass read.
- tz is in the rules table's schema, so the SQLite rebuild that stops
  rule ids being reused keeps it.
…failing with rejected

- An alert that a change, turning off or deletion of its rule ended no
  longer stands for the day it was raised for: the rule as changed judges
  that day itself. A rule made after a pushed deadline does not judge the
  day before it.
- The monitoring status counts rejected and failing rows in one statement,
  so failing never exceeds rejected.
- The failures test keeps clear of a midnight; the failures example and
  decisions 43 and 44 say what the code does.
…contact

# Conflicts:
#	docs/api.md
#	docs/decisions.md
#	docs/development.md
#	docs/running.md
#	src/db.rs
…; refuse direction marks in a contact

The upgrade now treats a source with only a check, an event or a count of
purged alerts as one that existed, so a deleted default rule is not given
back. A contact also refuses U+061C, U+200E and U+200F. The docs list
503 store_busy on POST, say how a re-created source's open silence alert
is judged, and drop a start-order step the schema lock makes unneeded.
@Gordex2014
Gordex2014 marked this pull request as ready for review November 23, 2026 20:12
@angela-helios
angela-helios merged commit c3a27ca into HeliosSoftware:main Nov 24, 2026
2 checks passed
@Gordex2014
Gordex2014 deleted the feat/source-contact branch November 25, 2026 14:20
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.

Add a free-text contact to a source

2 participants