Watch
0
0
Fork
You've already forked hyperhive
0

matrix daemon: stay up when the primary account is down and say why in the tools

This commit is contained in:
damocles 2026-11-28 02:37:21 +01:00 • committed by mara
commit 73ef63a5e5

View file

@ -135,14 +135,15 @@ async fn main() -> Result<ExitCode> {
let registry = Registry::new(primary);
let restore =
|cfg: AccountCfg, is_primary| async move { restore_account(&cfg, is_primary).await };
let Some(Boot { sync_loops, down }) = bring_up_all(cfgs, &registry, restore).await? else {
return Ok(ExitCode::SUCCESS);
};
if registry.is_empty() {
tracing::warn!("no matrix accounts restored; exiting cleanly");
return Ok(ExitCode::SUCCESS);
}
// The daemon stays up whether or not an account came up: a primary with no
// token yet, or a homeserver that does not answer, leaves it down and
// retried, while the tools answer with why (see `Registry::resolve`) instead
// of the agent finding the MCP server refusing connections.
let Boot {
sync_loops,
mut down,
} = bring_up_all(cfgs, &registry, restore).await;
down.steady = Some(registry.primary().to_owned());
// Startup cancel-and-recreate (loose-ends v2): wipe this agent's
// matrix todos so stale ones (rooms read / invites resolved while the
@ -316,23 +317,18 @@ async fn wait_for_linked_change(
}
/// What [`bring_up_all`] brought up: the sync loops of the accounts that came
/// up, and the secondaries left to [`retry_down`].
/// up, and the accounts left to [`retry_down`].
struct Boot {
sync_loops: Vec<NamedSyncLoop>,
down: DownAccounts<Retry>,
}
/// Try each account of `cfgs` once with `restore`, the first as the primary,
/// and insert each that comes up into `registry`. `Ok(None)` when the primary
/// has no token. Each `restore` is bounded by [`within_restore_timeout`].
///
/// # Errors
/// The primary failing to restore, a timeout included.
async fn bring_up_all<F, Fut>(
cfgs: Vec<AccountCfg>,
registry: &Registry,
mut restore: F,
) -> Result<Option<Boot>>
/// and insert each that comes up into `registry`. One that does not (no token,
/// a homeserver that fails, a restore that outlasts [`RESTORE_TIMEOUT`]) is
/// left in the returned [`Boot::down`] and noted in `registry` with its reason.
/// Each `restore` is bounded by [`within_restore_timeout`].
async fn bring_up_all<F, Fut>(cfgs: Vec<AccountCfg>, registry: &Registry, mut restore: F) -> Boot
where
F: FnMut(AccountCfg, bool) -> Fut,
Fut: std::future::Future<Output = Restore>,
@ -351,32 +347,42 @@ where
sync_loops.push(named(cfg.name.clone(), account_sync_loop(&client, tag)));
registry.insert(cfg.name, client);
}
// No token yet: for the primary that means the daemon isn't
// useful — exit 0, and systemd restarts us once a token exists
// (the path-watcher for a file, the re-check timer for the store).
// No token yet. For the primary that is the account the swarm has
// not created yet, or a homeserver that does not answer: the tools
// say so, and the retry loop tries again.
Ok(None) if is_primary => {
tracing::warn!(
account = %cfg.name,
"primary matrix account has no token yet; exiting cleanly \
(systemd restarts us once one exists)"
"primary matrix account has no token yet; the tools say so and the daemon keeps retrying"
);
return Ok(None);
registry.note_down(&cfg.name, NO_TOKEN);
down.failed(cfg.name.clone(), (cfg, tag), Instant::now(), NO_TOKEN);
}
Ok(None) => {
tracing::warn!(account = %cfg.name, "secondary matrix account has no token; will retry");
registry.note_down(&cfg.name, NO_TOKEN);
down.failed(cfg.name.clone(), (cfg, tag), Instant::now(), NO_TOKEN);
}
// The primary failing to restore is fatal (propagate so
// systemd retries on a transient blip — matches legacy
// behaviour); a secondary failing is retried with backoff
// The primary failing to restore is retried by `retry_down` like a
// secondary, at once and at a steady pace, and its tools say why
// in the meantime. A secondary failing is retried with backoff
// here, then left to `retry_down`.
Err(e) if is_primary => return Err(e.context("bring up primary matrix account")),
Err(e) => match bring_up_secondary_with_retry(&cfg, e, &mut restore).await {
Some(client) => {
Err(e) if is_primary => {
let reason = format!("{e:#}");
tracing::warn!(
account = %cfg.name,
error = %reason,
"primary matrix account failed to come up; the tools say so and the daemon keeps retrying"
);
registry.note_down(&cfg.name, &reason);
down.failed(cfg.name.clone(), (cfg, tag), Instant::now(), &reason);
}
Err(e) => {
if let Some(client) = bring_up_secondary_with_retry(&cfg, e, &mut restore).await {
sync_loops.push(named(cfg.name.clone(), account_sync_loop(&client, tag)));
registry.insert(cfg.name, client);
}
None => {
} else {
registry.note_down(&cfg.name, FAILED_AT_START);
down.failed(
cfg.name.clone(),
(cfg, tag),
@ -384,10 +390,10 @@ where
FAILED_AT_START,
);
}
},
}
}
}
Ok(Some(Boot { sync_loops, down }))
Boot { sync_loops, down }
}
/// `restore` of `account`, failing once it has run for [`RESTORE_TIMEOUT`].
@ -497,6 +503,9 @@ fn retry_delay(failures: u32) -> std::time::Duration {
/// again (`T`) and the earliest time to.
struct DownAccounts<T> {
by_name: BTreeMap<String, Down<T>>,
/// The account that is retried at the base pace however often it fails,
/// not at a doubling one: the primary, whose tools are all down with it.
steady: Option<String>,
}
struct Down<T> {
@ -511,6 +520,7 @@ impl<T> Default for DownAccounts<T> {
fn default() -> Self {
Self {
by_name: BTreeMap::new(),
steady: None,
}
}
}
@ -521,6 +531,7 @@ impl<T> DownAccounts<T> {
/// account's first, or for a different reason than the last — and so
/// worth a warning.
fn failed(&mut self, name: String, retry: T, at: Instant, reason: &str) -> bool {
let steady = self.steady.as_deref() == Some(name.as_str());
let down = self.by_name.entry(name).or_insert(Down {
retry,
failures: 0,
@ -530,7 +541,12 @@ impl<T> DownAccounts<T> {
let news = down.failures == 0 || down.reason != reason;
reason.clone_into(&mut down.reason);
down.failures += 1;
down.not_before = at + retry_delay(down.failures);
down.not_before = at
+ if steady {
LINKED_REFRESH
} else {
retry_delay(down.failures)
};
news
}
@ -616,7 +632,7 @@ async fn retry_once<F, Fut>(
let restored = within_restore_timeout(&name, restore(cfg.clone())).await;
match restored {
Ok(Some(client)) => {
tracing::info!(account = %name, "secondary matrix account came up");
tracing::info!(account = %name, "matrix account came up");
let sync_loop = account_sync_loop(&client, tag);
down.came_up(&name);
registry.insert(name.clone(), client);
@ -627,16 +643,18 @@ async fn retry_once<F, Fut>(
let _ = up.send(named(name, sync_loop));
}
Ok(None) => {
registry.note_down(&name, NO_TOKEN);
if down.failed(name.clone(), (cfg, tag), now, NO_TOKEN) {
tracing::warn!(account = %name, "secondary matrix account has no token; will keep retrying");
tracing::warn!(account = %name, "matrix account has no token; will keep retrying");
} else {
tracing::debug!(account = %name, "secondary matrix account still has no token");
}
}
Err(e) => {
let reason = format!("{e:#}");
registry.note_down(&name, &reason);
if down.failed(name.clone(), (cfg, tag), now, &reason) {
tracing::warn!(account = %name, error = %reason, "secondary matrix account failing; will keep retrying");
tracing::warn!(account = %name, error = %reason, "matrix account failing; will keep retrying");
} else {
tracing::debug!(account = %name, error = %reason, "secondary matrix account still failing");
}
@ -1478,7 +1496,7 @@ mod tests {
}
#[tokio::test(start_paused = true)]
async fn a_primary_whose_restore_hangs_at_boot_fails_the_boot() {
async fn a_primary_whose_restore_hangs_at_boot_goes_down_and_says_why() {
let reg = Registry::new("hung".to_owned());
let boot = tokio::time::timeout(
Duration::from_hours(1),
@ -1487,9 +1505,44 @@ mod tests {
.await
.expect("boot never finished");
let err = boot.err().expect("a hung primary fails the boot");
assert!(format!("{err:#}").contains("hung"), "{err:#}");
// the daemon carries on without it, and the tools say why it's missing
assert_eq!(names(&reg), ["fine"]);
assert_eq!(boot.sync_loops.len(), 1);
let err = reg.resolve(Some("hung")).expect_err("the primary is down");
assert!(err.contains("not up"), "{err}");
assert!(err.contains("try the call again later"), "{err}");
}
#[tokio::test(start_paused = true)]
async fn a_primary_without_a_token_goes_down_instead_of_ending_the_boot() {
let reg = Registry::new("main".to_owned());
let boot = bring_up_all(vec![cfg("main")], &reg, |_, _| async {
Ok(None) as Restore
})
.await;
assert!(reg.is_empty());
assert!(boot.sync_loops.is_empty());
let err = reg.resolve(None).expect_err("the primary is down");
assert!(err.contains("not up"), "{err}");
}
#[test]
fn the_primary_is_retried_at_a_steady_pace_and_a_secondary_backs_off() {
let t0 = Instant::now();
let mut down = DownAccounts::<()> {
steady: Some("main".to_owned()),
..DownAccounts::default()
};
// three failures each: the secondary's wait doubles, the primary's doesn't
for _ in 0..3 {
down.failed("main".to_owned(), (), t0, "again");
down.failed("other".to_owned(), (), t0, "again");
}
let due = down.due(t0 + LINKED_REFRESH).map(|(name, ())| name);
assert_eq!(due, Some("main"));
down.came_up("main");
assert!(down.due(t0 + LINKED_REFRESH).is_none());
}
#[tokio::test(start_paused = true)]
@ -1504,9 +1557,7 @@ mod tests {
),
)
.await
.expect("boot never finished")
.expect("the primary came up")
.expect("the primary had a token");
.expect("boot never finished");
assert_eq!(names(&reg), ["main", "fine"]);
assert_eq!(boot.sync_loops.len(), 2);