Skip to main content

systemprompt_database/repository/service/
presence.rs

1//! Per-replica role presence: every replica records its `server.role` with
2//! each registry heartbeat, so the live replica count per role is readable
3//! cluster-wide, including for roles that register no process, and the live
4//! members of one role are listable for spreading work across them. A replica
5//! that stops gracefully withdraws its own row, so it leaves the listings at
6//! once rather than when its heartbeat goes stale, and the withdrawal and each
7//! process lease it then releases are announced on
8//! [`PROCESS_OWNERSHIP_CHANNEL`](super::PROCESS_OWNERSHIP_CHANNEL) so its
9//! peers re-evaluate without waiting for their next tick.
10//!
11//! Copyright (c) systemprompt.io — Business Source License 1.1.
12//! See <https://systemprompt.io> for licensing details.
13
14use systemprompt_identifiers::{InstanceId, LeaseKey};
15use systemprompt_manifest::profile::NodeRole;
16
17use super::liveness::INSTANCE_DEAD_AFTER_SECS;
18use super::ownership_wake::PROCESS_OWNERSHIP_CHANNEL;
19use super::repo::ServiceRepository;
20use crate::error::DatabaseResult;
21
22/// The number of live replicas currently heartbeating one role.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct RoleCount {
25    pub role: String,
26    pub instances: i64,
27}
28
29impl ServiceRepository {
30    pub async fn touch_presence(&self, role: NodeRole) -> DatabaseResult<()> {
31        sqlx::query!(
32            r#"
33            INSERT INTO instance_presence (instance_id, role, heartbeat_at)
34            VALUES ($1, $2, CURRENT_TIMESTAMP)
35            ON CONFLICT (instance_id) DO UPDATE SET
36                role = EXCLUDED.role,
37                heartbeat_at = EXCLUDED.heartbeat_at
38            "#,
39            self.instance_id.as_str(),
40            role.as_str()
41        )
42        .execute(&*self.write_pool)
43        .await?;
44        Ok(())
45    }
46
47    pub async fn count_live_instances_by_role(&self) -> DatabaseResult<Vec<RoleCount>> {
48        let rows = sqlx::query_as!(
49            RoleCount,
50            r#"
51            SELECT role, COUNT(*) AS "instances!"
52            FROM instance_presence
53            WHERE heartbeat_at
54                  >= CURRENT_TIMESTAMP - make_interval(secs => $1::double precision)
55            GROUP BY role
56            ORDER BY role
57            "#,
58            INSTANCE_DEAD_AFTER_SECS as f64
59        )
60        .fetch_all(&*self.pool)
61        .await?;
62        Ok(rows)
63    }
64
65    pub async fn list_reachable_instances(
66        &self,
67        role: NodeRole,
68        fresh_within_secs: i64,
69    ) -> DatabaseResult<Vec<InstanceId>> {
70        let rows = sqlx::query_scalar!(
71            r#"
72            SELECT p.instance_id AS "instance_id!: InstanceId"
73            FROM instance_presence p
74            JOIN instance_endpoints e ON e.instance_id = p.instance_id
75            WHERE p.role = $1
76              AND p.heartbeat_at
77                  >= CURRENT_TIMESTAMP - make_interval(secs => $2::double precision)
78              AND e.heartbeat_at
79                  >= CURRENT_TIMESTAMP - make_interval(secs => $2::double precision)
80            ORDER BY p.instance_id
81            "#,
82            role.as_str(),
83            fresh_within_secs as f64
84        )
85        .fetch_all(&*self.write_pool)
86        .await?;
87        Ok(rows)
88    }
89
90    pub async fn delete_stale_presence(&self, older_than_secs: i64) -> DatabaseResult<u64> {
91        let result = sqlx::query!(
92            r#"
93            DELETE FROM instance_presence
94            WHERE heartbeat_at < CURRENT_TIMESTAMP - make_interval(secs => $1::double precision)
95            "#,
96            older_than_secs as f64
97        )
98        .execute(&*self.write_pool)
99        .await?;
100        Ok(result.rows_affected())
101    }
102
103    pub async fn delete_presence(&self) -> DatabaseResult<u64> {
104        let result = sqlx::query!(
105            "DELETE FROM instance_presence WHERE instance_id = $1",
106            self.instance_id.as_str()
107        )
108        .execute(&*self.write_pool)
109        .await?;
110        sqlx::query!(
111            "SELECT pg_notify($1, $2)",
112            PROCESS_OWNERSHIP_CHANNEL,
113            self.instance_id.as_str()
114        )
115        .execute(&*self.write_pool)
116        .await?;
117        Ok(result.rows_affected())
118    }
119
120    pub async fn announce_process_released(&self, lease: &LeaseKey) -> DatabaseResult<()> {
121        sqlx::query!(
122            "SELECT pg_notify($1, $2)",
123            PROCESS_OWNERSHIP_CHANNEL,
124            lease.as_str()
125        )
126        .execute(&*self.write_pool)
127        .await?;
128        Ok(())
129    }
130}