systemprompt_api/routes/admin/services/
refresh.rs1use std::sync::LazyLock;
24use std::time::Duration;
25
26use axum::Json;
27use axum::extract::{Extension, Query, State};
28use serde::Deserialize;
29use systemprompt_config::{ProfileBootstrap, SecretsBootstrap};
30use systemprompt_identifiers::UserId;
31use systemprompt_loader::bundle::bootstrap::baked::BASE_SOURCE_NAME;
32use systemprompt_loader::bundle::{BundleCache, cache_root};
33use systemprompt_loader::services_root::ServicesRootBootstrap;
34use systemprompt_loader::{ConfigLoader, ServicesSourceBootstrap};
35use systemprompt_models::RequestContext;
36use systemprompt_models::api::ApiError;
37use systemprompt_models::services::bundle::ServicesBundleState;
38use systemprompt_runtime::AppContext;
39use systemprompt_runtime::managed::inventory::publish_latest;
40use systemprompt_runtime::services_reconcile::{ReconcileOutcome, reconcile_fetched_services};
41
42use super::{
43 RefreshLock, ServicesRefreshResponse, composed_hash_of, provenance_view, source_views,
44};
45use crate::error::ApiHttpError;
46
47const RESTART_DELAY: Duration = Duration::from_millis(250);
48const RESTART_REASON: &str = "admin services refresh";
49
50static REFRESH_LOCK: LazyLock<RefreshLock> = LazyLock::new(RefreshLock::default);
55
56#[must_use]
57pub fn process_refresh_lock() -> RefreshLock {
58 REFRESH_LOCK.clone()
59}
60
61#[derive(Debug, Clone)]
63pub struct ServicesRefresh {
64 ctx: AppContext,
65 lock: RefreshLock,
66}
67
68impl ServicesRefresh {
69 #[must_use]
70 pub fn new(ctx: &AppContext) -> Self {
71 Self::with_lock(ctx, process_refresh_lock())
72 }
73
74 #[must_use]
77 pub fn with_lock(ctx: &AppContext, lock: RefreshLock) -> Self {
78 Self {
79 ctx: ctx.clone(),
80 lock,
81 }
82 }
83
84 pub async fn run(&self, actor: &UserId) -> Result<ServicesRefreshResponse, ApiHttpError> {
85 let _guard = self.lock.try_acquire().ok_or_else(busy)?;
86 run_refresh(&self.ctx, actor, false).await
87 }
88}
89
90fn busy() -> ApiHttpError {
91 ApiError::conflict("a services refresh is already running").into()
92}
93
94#[derive(Debug, Clone, Copy, Default, Deserialize)]
95pub struct RefreshQuery {
96 #[serde(default)]
97 pub restart: bool,
98}
99
100pub async fn refresh(
101 State(ctx): State<AppContext>,
102 Extension(lock): Extension<RefreshLock>,
103 Extension(req_ctx): Extension<RequestContext>,
104 Query(query): Query<RefreshQuery>,
105) -> Result<Json<ServicesRefreshResponse>, ApiHttpError> {
106 let _guard = lock.try_acquire().ok_or_else(busy)?;
107 run_refresh(&ctx, req_ctx.user_id(), query.restart)
108 .await
109 .map(Json)
110}
111
112async fn run_refresh(
113 ctx: &AppContext,
114 actor: &UserId,
115 restart: bool,
116) -> Result<ServicesRefreshResponse, ApiHttpError> {
117 let profile = ProfileBootstrap::get()
118 .map_err(|e| ApiHttpError::internal_error(format!("profile not ready: {e}")))?;
119 let secrets = SecretsBootstrap::get()
120 .map_err(|e| ApiHttpError::internal_error(format!("secrets not ready: {e}")))?;
121
122 let cache = BundleCache::new(cache_root(profile));
126 let previous = cache.read_state();
127 let served_hash = (!previous.composed_hash.is_empty())
128 .then_some(previous.composed_hash.clone())
129 .or_else(|| {
130 ServicesRootBootstrap::get()
131 .and_then(composed_hash_of)
132 .map(str::to_owned)
133 });
134
135 let resolved = ServicesSourceBootstrap::resolve(
136 profile,
137 |name| secrets.get(name).cloned(),
138 env!("CARGO_PKG_VERSION"),
139 )
140 .await?;
141
142 let new_hash = composed_hash_of(&resolved).map(str::to_owned);
143 let changed = new_hash != served_hash;
144 let unreconciled = new_hash.is_some() && previous.last_reconciled_hash != new_hash;
148 let mut reconciled = false;
149 if changed || unreconciled {
150 let services =
153 ConfigLoader::reload_from_path(&resolved.path.join("config").join("config.yaml"))
154 .map_err(|e| {
155 ApiHttpError::internal_error(format!("recomposed services config: {e}"))
156 })?;
157 let outcome = reconcile_fetched_services(profile, &resolved, &services, ctx.db_pool())
158 .await
159 .map_err(|e| ApiHttpError::internal_error(format!("services reconcile: {e}")))?;
160 reconciled = outcome == ReconcileOutcome::Projected;
161
162 let system_admin = ctx.system_admin().id().clone();
163 if let Err(error) = publish_latest(ctx, &system_admin, actor).await {
164 tracing::warn!(%error, "Inventory refresh after services import failed; the scheduled pass will retry");
165 }
166 }
167
168 let state = cache.read_state();
169 let restart_recommended = changed && owns_static_config(&cache, &state);
170 let restarting = changed && restart;
171
172 tracing::info!(
173 user_id = %actor,
174 changed,
175 reconciled,
176 restart_recommended,
177 composed_hash = new_hash.as_deref().unwrap_or("none"),
178 provenance = %provenance_view(&resolved.provenance).kind,
179 restarting,
180 "Admin services refresh"
181 );
182
183 if restarting {
184 let ctx = ctx.clone();
185 tokio::spawn(async move {
186 tokio::time::sleep(RESTART_DELAY).await;
187 ctx.request_restart(RESTART_REASON);
188 });
189 }
190
191 Ok(ServicesRefreshResponse {
192 changed,
193 composed_hash: new_hash,
194 sources: source_views(&state),
195 reconciled,
196 restart_recommended,
197 restarting,
198 })
199}
200
201fn owns_static_config(cache: &BundleCache, state: &ServicesBundleState) -> bool {
206 state
207 .sources
208 .iter()
209 .filter(|(name, _)| name.as_str() != BASE_SOURCE_NAME)
210 .any(|(name, fetched)| match cache.read_manifest(name, &fetched.content_hash) {
211 Ok(signed) => !signed.manifest.owns.hooks.is_empty(),
212 Err(error) => {
213 tracing::warn!(source = %name, %error, "Cached bundle manifest unreadable; recommending a restart");
214 true
215 },
216 })
217}