Skip to main content

systemprompt_api/routes/admin/services/
refresh.rs

1//! `POST /admin/services/refresh`.
2//!
3//! Re-resolves the configured sources, recomposes the tree and — when the
4//! composition changed — projects the new composition into the authz tables
5//! and refreshes the skill inventory, all in-process. The routes that hand
6//! marketplaces, plugins and skills to clients reload the services tree per
7//! request through the `current` link the recompose just swapped, so a
8//! marketplace-only kit is live the moment this returns. `restart=true`
9//! remains an explicit opt-in for the one thing a running process cannot
10//! re-read: the static services config behind governance hooks.
11//!
12//! The pipeline is [`ServicesRefresh`], an in-process handle an extension
13//! router receives as an axum extension (see `extension_mount`), so a console
14//! that has authorised a caller by its own rule — a marketplace participant
15//! syncing their own kit, say — runs the same refresh the admin route runs
16//! without minting an admin token. One process-wide lock guards both. The
17//! handle never restarts the process: an extension router is authorised by
18//! `AuthzPolicy::user()`, so the restart stays on the admin route alone.
19//!
20//! Copyright (c) systemprompt.io — Business Source License 1.1.
21//! See <https://systemprompt.io> for licensing details.
22
23use 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
50// Why: one lock for the process, not one per router. The admin route and every
51// extension handle share it, so two callers on different routes cannot fetch
52// at once. `RefreshLock` clones share the mutex, so the router's extension is
53// a clone of this same lock.
54static 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/// In-process handle to the fetch-verify-compose-reconcile pipeline.
62#[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    // Why: the lock is injectable so a test can hold it and prove the second
75    // caller is refused; production always passes the process lock.
76    #[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    // Why: the boot-time root is a static; after an in-place import the cache
123    // state names the composition actually being served, so "changed" is
124    // measured against that and a repeat import is a no-op.
125    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    // Why: a composition that was swapped in but never projected (a failed
145    // earlier reconcile) is finished by the next import even though nothing
146    // else changed.
147    let unreconciled = new_hash.is_some() && previous.last_reconciled_hash != new_hash;
148    let mut reconciled = false;
149    if changed || unreconciled {
150        // Why: the boot-time root is a static that still names the previous
151        // tree; the recomposed tree is the one whose config is projected.
152        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
201// Why: governance hooks are read once at boot into the static services config;
202// a bundle that ships hooks is the one case an in-process import cannot fully
203// serve, so the caller is told a restart would complete it. A manifest that
204// cannot be read may own hooks, so it recommends the restart too.
205fn 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}