Skip to content

feat: heartbeat endpoint with real-path Stalwart JMAP probe - #61

Merged
Urdemonlord merged 1 commit into
mainfrom
feat/heartbeat
Nov 26, 2026
Merged

Urdemonlord merged 1 commit into
mainfrom
feat/heartbeat

Conversation

@Urdemonlord

Copy link
Copy Markdown
Owner

Heartbeat endpoint with real-path Stalwart JMAP probe

GET /heartbeat answers 200 only when the database and the Stalwart JMAP path are both healthy, so an external monitor can alert on the status code alone. Per-component JSON (name, status, latency_ms), no sensitive info.

  • database: existing iris_database::health_check, 5s timeout.
  • stalwart_jmap: real login via JmapClient::login (plain GET /jmap/session, mints no app password) plus a real management read (x:Domain/get). Fails closed with 503 while the admin credential is unset, matching the alias endpoints.
  • mail_roundtrip (only with ?roundtrip=true): sends a test message from a dedicated heartbeat mailbox to itself, waits for delivery, then deletes it. Unconfigured it reports disabled and never fails the endpoint; configured but not requested it reports skipped. 60s budget, 2s poll interval.

Alerting v1 is the 503 status for an external monitor plus one structured tracing::warn per failed check. No push notification built in.

Verified locally: fmt, clippy -D warnings, cargo test --all-targets 327 passed, 0 failed, including failure-detection tests (admin unset / Stalwart 401 / unreachable / DB down / roundtrip failure all yield 503) and a roundtrip happy-path test.

Deploy note: needs a dedicated heartbeat mailbox plus IRIS_HEARTBEAT_MAILBOX_USER / IRIS_HEARTBEAT_MAILBOX_PASSWORD in the VPS .env before roundtrip is live; without them the endpoint still reports database + JMAP health.

GET /heartbeat answers 200 only when the database and the Stalwart
JMAP path are both healthy, so an external monitor can alert on the
status code alone. The JMAP check logs in with the admin credential
(a plain GET /jmap/session, which mints no app password) and then
performs a real management read (x:Domain/get); it fails closed with
503 while the admin credential is unset, matching the alias
endpoints. An optional ?roundtrip=true variant sends a test message
from a dedicated heartbeat mailbox to itself, waits for delivery,
then deletes it; unconfigured it reports disabled and never fails
the endpoint. Each check has its own 5s timeout (60s for the
roundtrip), and failures are logged as structured warnings without
error detail.
@coderabbitai

coderabbitai Bot commented Nov 26, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 33 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7753ccf1-9b8a-42bd-8117-8876bfb883f7
Commits

Reviewing files that changed from the base of the PR and between 1e00747 and 84b3919.

Files selected for processing: 14

  • apps/api/src/admin.rs
  • apps/api/src/aliases.rs
  • apps/api/src/audit.rs
  • apps/api/src/cleanup.rs
  • apps/api/src/contacts.rs
  • apps/api/src/heartbeat.rs
  • apps/api/src/linked_mailboxes.rs
  • apps/api/src/main.rs
  • apps/api/src/pending_sends.rs
  • apps/api/src/signatures.rs
  • apps/api/src/temp.rs
  • apps/api/src/transactional_email.rs
  • crates/config/src/lib.rs
  • docs/07-PRODUCTION-READINESS.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

6 issues found across 14 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="docs/07-PRODUCTION-READINESS.md">

<violation number="1" location="docs/07-PRODUCTION-READINESS.md:74">
P2: The `?roundtrip=true` check does not unconditionally prove end-to-end mail delivery: it is skipped when the mailbox is unconfigured, and the configured probe only verifies local Stalwart self-delivery. Qualify this checklist item with the mailbox prerequisite and state that it verifies local send/receive delivery.</violation>
</file>

<file name="apps/api/src/main.rs">

<violation number="1" location="apps/api/src/main.rs:445">
P1: The new endpoint is not exposed by the repository’s public proxy configurations, so an external monitor receives the frontend/404 rather than the heartbeat status. Add `/heartbeat` to every backend matcher/location, including the packaged and Docker nginx/Caddy templates.</violation>

<violation number="2" location="apps/api/src/main.rs:445">
P1: This unauthenticated route exposes a mail-sending, 60-second operation without rate or concurrency limiting. Anyone who can reach the API can parallelize `?roundtrip=true` requests and exhaust mailbox, Stalwart, or API resources; gate or strictly limit the roundtrip variant.</violation>
</file>

<file name="apps/api/src/heartbeat.rs">

<violation number="1" location="apps/api/src/heartbeat.rs:64">
P2: The roundtrip gives up after about 30 seconds despite the documented 60-second budget, so delivery completing between 30 and 60 seconds is reported failed. Increase the poll count to cover the configured budget or derive it from `ROUNDTRIP_TIMEOUT`.</violation>

<violation number="2" location="apps/api/src/heartbeat.rs:274">
P2: After the send succeeds, polling errors, delivery timeout, and cancellation exit without deleting the probe message. Transient failures therefore accumulate heartbeat messages; retain the created message identity and perform best-effort cleanup on every post-send failure.</violation>

<violation number="3" location="apps/api/src/heartbeat.rs:285">
P2: `list_folder` relies on asynchronous full-text indexing, so a delivered probe message can remain invisible for all 15 polls and produce a false 503. Query the inbox without full-text search and paginate/inspect summaries instead.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread apps/api/src/main.rs

let app = Router::new()
.route("/health", get(|| async { "OK" }))
.route("/heartbeat", get(heartbeat::heartbeat))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: The new endpoint is not exposed by the repository’s public proxy configurations, so an external monitor receives the frontend/404 rather than the heartbeat status. Add /heartbeat to every backend matcher/location, including the packaged and Docker nginx/Caddy templates.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At apps/api/src/main.rs, line 445:

<comment>The new endpoint is not exposed by the repository’s public proxy configurations, so an external monitor receives the frontend/404 rather than the heartbeat status. Add `/heartbeat` to every backend matcher/location, including the packaged and Docker nginx/Caddy templates.</comment>

<file context>
@@ -441,6 +442,7 @@ async fn main() {
 
     let app = Router::new()
         .route("/health", get(|| async { "OK" }))
+        .route("/heartbeat", get(heartbeat::heartbeat))
         .route("/ready", get(ready))
         .route("/auth/csrf", get(csrf))
</file context>

Comment thread apps/api/src/main.rs

let app = Router::new()
.route("/health", get(|| async { "OK" }))
.route("/heartbeat", get(heartbeat::heartbeat))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: This unauthenticated route exposes a mail-sending, 60-second operation without rate or concurrency limiting. Anyone who can reach the API can parallelize ?roundtrip=true requests and exhaust mailbox, Stalwart, or API resources; gate or strictly limit the roundtrip variant.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At apps/api/src/main.rs, line 445:

<comment>This unauthenticated route exposes a mail-sending, 60-second operation without rate or concurrency limiting. Anyone who can reach the API can parallelize `?roundtrip=true` requests and exhaust mailbox, Stalwart, or API resources; gate or strictly limit the roundtrip variant.</comment>

<file context>
@@ -441,6 +442,7 @@ async fn main() {
 
     let app = Router::new()
         .route("/health", get(|| async { "OK" }))
+        .route("/heartbeat", get(heartbeat::heartbeat))
         .route("/ready", get(ready))
         .route("/auth/csrf", get(csrf))
</file context>

## 7. Monitoring

- [ ] Uptime check on `/ready` (DB) and `/health`.
- [ ] Uptime check on `/heartbeat` (200 = database + Stalwart JMAP healthy, 503 = degraded; `?roundtrip=true` every 15-30 min proves mail delivery end to end). `/ready` (DB only) and `/health` (static) remain as lighter probes.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The ?roundtrip=true check does not unconditionally prove end-to-end mail delivery: it is skipped when the mailbox is unconfigured, and the configured probe only verifies local Stalwart self-delivery. Qualify this checklist item with the mailbox prerequisite and state that it verifies local send/receive delivery.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/07-PRODUCTION-READINESS.md, line 74:

<comment>The `?roundtrip=true` check does not unconditionally prove end-to-end mail delivery: it is skipped when the mailbox is unconfigured, and the configured probe only verifies local Stalwart self-delivery. Qualify this checklist item with the mailbox prerequisite and state that it verifies local send/receive delivery.</comment>

<file context>
@@ -71,7 +71,7 @@ Actions (DNS changes, owner: the deployment operator):
 ## 7. Monitoring
 
-- [ ] Uptime check on `/ready` (DB) and `/health`.
+- [ ] Uptime check on `/heartbeat` (200 = database + Stalwart JMAP healthy, 503 = degraded; `?roundtrip=true` every 15-30 min proves mail delivery end to end). `/ready` (DB only) and `/health` (static) remain as lighter probes.
 - [ ] Disk usage alert at 80 % (mail + SQLite volumes).
   Live note (2026-11-06): root disk is at 89% (6.5 GB free) — already
</file context>
Suggested change
- [ ] Uptime check on `/heartbeat` (200 = database + Stalwart JMAP healthy, 503 = degraded; `?roundtrip=true` every 15-30 min proves mail delivery end to end). `/ready` (DB only) and `/health` (static) remain as lighter probes.
- [ ] Uptime check on `/heartbeat` (200 = database + Stalwart JMAP healthy, 503 = degraded; with the heartbeat mailbox configured, `?roundtrip=true` every 15-30 min verifies local Stalwart send/receive delivery). `/ready` (DB only) and `/health` (static) remain as lighter probes.

Comment thread apps/api/src/heartbeat.rs
text: format!("IRIS heartbeat probe {token}.\nDelete after receipt; this message only proves delivery."),
..Compose::default()
};
client.send(user, pass, &account, &compose, None).await?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: After the send succeeds, polling errors, delivery timeout, and cancellation exit without deleting the probe message. Transient failures therefore accumulate heartbeat messages; retain the created message identity and perform best-effort cleanup on every post-send failure.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At apps/api/src/heartbeat.rs, line 274:

<comment>After the send succeeds, polling errors, delivery timeout, and cancellation exit without deleting the probe message. Transient failures therefore accumulate heartbeat messages; retain the created message identity and perform best-effort cleanup on every post-send failure.</comment>

<file context>
@@ -0,0 +1,760 @@
+        text: format!("IRIS heartbeat probe {token}.\nDelete after receipt; this message only proves delivery."),
+        ..Compose::default()
+    };
+    client.send(user, pass, &account, &compose, None).await?;
+    for _ in 0..ROUNDTRIP_MAX_POLLS {
+        let (found, _) = client
</file context>

Comment thread apps/api/src/heartbeat.rs
/// Gap between inbox polls while waiting for the test message.
const ROUNDTRIP_POLL_INTERVAL: Duration = Duration::from_secs(2);
/// Polls before the roundtrip gives up: ~30s of polling after the send.
const ROUNDTRIP_MAX_POLLS: usize = 15;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The roundtrip gives up after about 30 seconds despite the documented 60-second budget, so delivery completing between 30 and 60 seconds is reported failed. Increase the poll count to cover the configured budget or derive it from ROUNDTRIP_TIMEOUT.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At apps/api/src/heartbeat.rs, line 64:

<comment>The roundtrip gives up after about 30 seconds despite the documented 60-second budget, so delivery completing between 30 and 60 seconds is reported failed. Increase the poll count to cover the configured budget or derive it from `ROUNDTRIP_TIMEOUT`.</comment>

<file context>
@@ -0,0 +1,760 @@
+/// Gap between inbox polls while waiting for the test message.
+const ROUNDTRIP_POLL_INTERVAL: Duration = Duration::from_secs(2);
+/// Polls before the roundtrip gives up: ~30s of polling after the send.
+const ROUNDTRIP_MAX_POLLS: usize = 15;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
</file context>

Comment thread apps/api/src/heartbeat.rs
ListPage {
limit: 1,
position: 0,
query: Some(&token),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: list_folder relies on asynchronous full-text indexing, so a delivered probe message can remain invisible for all 15 polls and produce a false 503. Query the inbox without full-text search and paginate/inspect summaries instead.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At apps/api/src/heartbeat.rs, line 285:

<comment>`list_folder` relies on asynchronous full-text indexing, so a delivered probe message can remain invisible for all 15 polls and produce a false 503. Query the inbox without full-text search and paginate/inspect summaries instead.</comment>

<file context>
@@ -0,0 +1,760 @@
+                ListPage {
+                    limit: 1,
+                    position: 0,
+                    query: Some(&token),
+                },
+            )
</file context>

@Urdemonlord
Urdemonlord merged commit c6ee057 into main Nov 26, 2026
7 of 9 checks passed
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.

1 participant