Skip to main content

rpi_cli/host/
extension_custody.rs

1//! Concrete DLL custody for an owned ordinary binding. No discovery or CLI bridge.
2//!
3//! This is a trusted Rust assembly boundary, not a resource/permission grant.
4//! Profiles must not expose DLLs until artifact freezing and capability checks
5//! also exist. Callback scopes belong in the actual FFI worker, not its waiter.
6
7use super::ordinary::{BackendError, BackendResult};
8use rpi_extensions::{
9    ExtensionSession, PluginCleanupReceipt, PluginCleanupStatus, PluginDiagnostics,
10    PluginLoadCustody,
11};
12use rpi_harness::session::jsonl::JsonlSessionStorage;
13use std::{
14    path::PathBuf,
15    sync::{Arc, Mutex, MutexGuard},
16};
17use tokio::sync::{watch, Mutex as AsyncMutex};
18
19struct State {
20    claimed: bool,
21    attempted: bool,
22    loading: bool,
23    unknown: bool,
24    closing: bool,
25    calls: usize,
26    session: Option<ExtensionSession>,
27    failed: Option<PluginLoadCustody>,
28    receipts: Vec<PluginCleanupReceipt>,
29    storage: Option<JsonlSessionStorage>,
30    catalog: Option<super::HostCatalog>,
31}
32
33/// Host ownership of one explicit DLL batch, including failed registration.
34/// Debug never reveals artifact paths, plugin state or Session data.
35/// Harness hooks must retain only a Weak reference; each actual worker takes
36/// a call scope, and shutdown drops the session before waiting on its receipts.
37pub struct NativeExtensionCustody {
38    state: Mutex<State>,
39    changed: watch::Sender<()>,
40    close_gate: AsyncMutex<()>,
41}
42impl std::fmt::Debug for NativeExtensionCustody {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.write_str("NativeExtensionCustody { .. }")
45    }
46}
47
48impl NativeExtensionCustody {
49    pub fn new() -> Arc<Self> {
50        let (changed, _) = watch::channel(());
51        Arc::new(Self {
52            state: Mutex::new(State {
53                claimed: false,
54                attempted: false,
55                loading: false,
56                unknown: false,
57                closing: false,
58                calls: 0,
59                session: None,
60                failed: None,
61                receipts: Vec::new(),
62                storage: None,
63                catalog: None,
64            }),
65            changed,
66            close_gate: AsyncMutex::new(()),
67        })
68    }
69    fn state(&self) -> MutexGuard<'_, State> {
70        self.state.lock().unwrap_or_else(|error| error.into_inner())
71    }
72    /// Invoke only from owned assembly, never readonly validation. The caller
73    /// supplies trusted frozen/staged files and must validate capabilities before
74    /// publishing hooks. No ActionBridge, scanner or ambient registry is used.
75    /// Losing this waiter does not discard a partially loaded batch.
76    pub async fn load_owned(
77        self: &Arc<Self>,
78        files: Vec<PathBuf>,
79        diagnostics: Arc<dyn PluginDiagnostics>,
80        artifact_guard: Option<Arc<dyn Send + Sync>>,
81    ) -> BackendResult<()> {
82        self.load_owned_checked(files, diagnostics, artifact_guard, |_, _| true)
83            .await
84    }
85
86    /// Exact per-plugin data-only check, before SDK batch merge/publication.
87    /// Rejection and validator panic retain the current and all preceding
88    /// plugins in the same supervised cleanup path, never partial success.
89    pub async fn load_owned_checked(
90        self: &Arc<Self>,
91        files: Vec<PathBuf>,
92        diagnostics: Arc<dyn PluginDiagnostics>,
93        artifact_guard: Option<Arc<dyn Send + Sync>>,
94        validate: impl FnMut(usize, &rpi_extensions::RegistrationInventory) -> bool + Send + 'static,
95    ) -> BackendResult<()> {
96        {
97            let mut state = self.state();
98            if !state.claimed || state.attempted || state.closing {
99                return Err(BackendError::Binding("DLL custody is not reusable"));
100            }
101            state.attempted = true;
102            state.loading = true;
103        }
104        let owner = self.clone();
105        let loading = LoadingLease(owner.clone());
106        tokio::task::spawn_blocking(move || {
107            let _loading = loading;
108            let loaded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
109                rpi_extensions::load_explicit_session_owned_checked(
110                    &files,
111                    diagnostics,
112                    artifact_guard,
113                    validate,
114                )
115            }));
116            let result = {
117                let mut state = owner.state();
118                state.loading = false;
119                match loaded {
120                    Ok(Ok(session)) => {
121                        state.receipts = session.cleanup_receipts();
122                        state.session = Some(session);
123                        Ok(())
124                    }
125                    Ok(Err(failure)) => {
126                        state.receipts = failure.custody.cleanup_receipts();
127                        state.failed = Some(failure.custody);
128                        Err(BackendError::Binding("explicit DLL assembly failed"))
129                    }
130                    Err(_) => {
131                        // A panic may have dropped a loaded handle into async
132                        // cleanup without handing us its receipt. Never guess.
133                        state.unknown = true;
134                        Err(BackendError::TaskStopped)
135                    }
136                }
137            };
138            owner.changed.send_replace(());
139            result
140        })
141        .await
142        .map_err(|_| BackendError::TaskStopped)?
143    }
144
145    /// This value MUST move into the actual callback worker. It holds a session
146    /// keepalive until the callback and all plugin-owned frees have returned.
147    pub fn call(self: &Arc<Self>) -> BackendResult<NativeExtensionCall> {
148        let mut state = self.state();
149        if state.closing || state.loading || state.unknown {
150            return Err(BackendError::Closed);
151        }
152        let session = state.session.clone().ok_or(BackendError::Closed)?;
153        state.calls = state.calls.checked_add(1).ok_or(BackendError::Faulted)?;
154        Ok(NativeExtensionCall {
155            session,
156            _lease: CallLease(self.clone()),
157        })
158    }
159
160    pub(super) fn claim(&self, catalog: super::HostCatalog) -> BackendResult<()> {
161        let mut state = self.state();
162        if state.claimed || state.attempted || state.closing {
163            return Err(BackendError::Binding("DLL custody is not reusable"));
164        }
165        state.claimed = true;
166        state.catalog = Some(catalog);
167        Ok(())
168    }
169
170    pub(super) fn retain_storage(&self, storage: JsonlSessionStorage) {
171        self.state().storage = Some(storage);
172    }
173
174    /// Seal callbacks, wait for physical FFI scopes/loading, then relinquish all
175    /// session/custody keepalives and await final SDK/OS/context cleanup. This
176    /// operation is called by the supervised owner, never an unowned IPC waiter.
177    pub(super) async fn close(self: &Arc<Self>) -> BackendResult<()> {
178        let _close = self.close_gate.lock().await;
179        let mut changed = self.changed.subscribe();
180        let (session, failed, receipts, unknown) = loop {
181            let ready = {
182                let mut state = self.state();
183                state.closing = true;
184                if state.loading || state.calls != 0 {
185                    None
186                } else {
187                    Some((
188                        state.session.take(),
189                        state.failed.take(),
190                        state.receipts.clone(),
191                        state.unknown,
192                    ))
193                }
194            };
195            if let Some(ready) = ready {
196                break ready;
197            }
198            let _ = changed.changed().await;
199        };
200        // Last keepalive Drop queues cleanup. Receipts own no code/context and
201        // therefore cannot themselves keep the DLL loaded indefinitely.
202        drop(session);
203        drop(failed);
204        let mut retained = unknown;
205        for receipt in receipts {
206            retained |= receipt.wait().await != PluginCleanupStatus::Released;
207        }
208        if retained {
209            Err(BackendError::ExtensionUnsettled(self.clone()))
210        } else {
211            Ok(())
212        }
213    }
214
215    /// Failed-start rollback uses this only AFTER close proved DLL settlement.
216    /// The clone keeps the real writer alive across errors/panics in assembly.
217    pub(super) async fn release_storage(&self) {
218        let storage = self.state().storage.take();
219        if let Some(storage) = storage {
220            storage.drain().await;
221            storage.release_writer_lease();
222        }
223    }
224}
225
226impl Drop for NativeExtensionCustody {
227    fn drop(&mut self) {
228        let state = self
229            .state
230            .get_mut()
231            .unwrap_or_else(|error| error.into_inner());
232        let unproven = state.unknown
233            || state.loading
234            || state.calls != 0
235            || state
236                .receipts
237                .iter()
238                .any(|receipt| receipt.status() != PluginCleanupStatus::Released);
239        if unproven {
240            // Last-owner Drop is not a settlement operation. If explicit
241            // shutdown failed/was omitted, keep both the singleton exclusion
242            // and any real writer for process lifetime rather than let a new
243            // Host owner race code which may still be alive. Normal supervised
244            // close reaches Released first and never takes this fail-closed path.
245            if let Some(storage) = state.storage.take() {
246                std::mem::forget(storage);
247            }
248            if let Some(catalog) = state.catalog.take() {
249                std::mem::forget(catalog);
250            }
251        }
252    }
253}
254
255/// A scoped session view. Field order drops the session BEFORE publishing that
256/// the callback finished; close must not observe zero with a keepalive in flight.
257pub struct NativeExtensionCall {
258    session: ExtensionSession,
259    _lease: CallLease,
260}
261impl NativeExtensionCall {
262    pub fn session(&self) -> &ExtensionSession {
263        &self.session
264    }
265}
266struct LoadingLease(Arc<NativeExtensionCustody>);
267impl Drop for LoadingLease {
268    fn drop(&mut self) {
269        let mut state = self.0.state();
270        if state.loading {
271            // A queued worker can be destroyed without running during runtime
272            // shutdown. Do not leave close waiting for a nonexistent reporter.
273            state.loading = false;
274            state.unknown = true;
275            self.0.changed.send_replace(());
276        }
277    }
278}
279struct CallLease(Arc<NativeExtensionCustody>);
280impl Drop for CallLease {
281    fn drop(&mut self) {
282        let mut state = self.0.state();
283        state.calls -= 1;
284        self.0.changed.send_replace(());
285    }
286}