Skip to main content

cartel_sqlite/engine/conn/
raw.rs

1use crate::{
2    api, catalogs,
3    conn::{
4        Installed,
5        phase::{Live, Phase},
6    },
7    runtime,
8};
9use api::stmt;
10use dope_core::driver::{schedule, settings};
11use dope_runtime::{executor, topology::lending};
12use std::{alloc::Layout, marker, pin, ptr};
13
14pub(crate) struct Vacant<'local, 'd: 'local, I: catalogs::Catalog> {
15    phase: ptr::NonNull<Phase<'local, 'd, I>>,
16    backing: marker::PhantomData<&'local mut Phase<'local, 'd, I>>,
17}
18
19impl<'local, 'd: 'local, I: catalogs::Catalog> Vacant<'local, 'd, I> {
20    pub(crate) const LAYOUT: Layout = Layout::new::<Phase<'local, 'd, I>>();
21
22    /// # Safety
23    /// Storage is an uninitialized, aligned LAYOUT partition retained for 'local.
24    /// The consumed database admission grants its only initialization authority.
25    pub(crate) unsafe fn new(storage: &'local runtime::raw::Span) -> Self {
26        Self {
27            phase: storage.base().cast(),
28            backing: marker::PhantomData,
29        }
30    }
31
32    pub(crate) fn insert(self, state: api::State<'local, 'd, I>) -> Installed<'local, 'd, I> {
33        // SAFETY: this affine vacancy owns the admitted storage's sole initialization.
34        unsafe { self.phase.as_ptr().write(Phase::Live(Live::new(state))) };
35        Installed {
36            phase: self.phase,
37            ownership: marker::PhantomData,
38        }
39    }
40}
41
42impl<I: catalogs::Catalog> Drop for Installed<'_, '_, I> {
43    fn drop(&mut self) {
44        // SAFETY: client loans ended before this unique owner is destroyed. Local
45        // retains the backing allocation, including when this owner is forgotten.
46        unsafe { self.phase.as_ptr().drop_in_place() };
47    }
48}
49
50// SAFETY: SQLite owns no driver routes or asynchronous native requests. Its SQL
51// and VFS calls finish synchronously. Retry alarms retain resident timer leases;
52// cleanup checks their absolute deadlines and clears them without native dispatch.
53// The pinned connection and allocator remain owned through release and finish.
54unsafe impl<'local, 'd: 'local, I: catalogs::Catalog> lending::raw::Resume<'d>
55    for Installed<'local, 'd, I>
56{
57}
58
59impl<'local, 'd: 'local, I: catalogs::Catalog> executor::raw::Layout<'d>
60    for Installed<'local, 'd, I>
61{
62    type ParkPlan = ();
63}
64
65unsafe impl<'local, 'd: 'local, I: catalogs::Catalog> executor::raw::App<'d>
66    for Installed<'local, 'd, I>
67{
68    const ROUTES: settings::Routes = settings::Routes::EMPTY;
69    const COORDS: usize = 1;
70
71    fn select_park() -> Option<Self::ParkPlan> {
72        Some(())
73    }
74
75    fn released(
76        mut released: executor::raw::Released<'_, Self>,
77    ) -> executor::raw::Released<'_, Self> {
78        let app = released.owner();
79        let conn = app.as_ref().get_ref();
80        // SAFETY: Released ends all client access to this exact pinned owner,
81        // including loans whose guards were forgotten without running Drop.
82        unsafe { &mut *conn.phase.as_ptr() }.released();
83        released
84    }
85
86    fn shutdown<'app, 'turn, 'driver>(
87        shutdown: executor::raw::Shutdown<'app, 'turn, 'driver, 'd, Self>,
88    ) -> executor::raw::Shutdown<'app, 'turn, 'driver, 'd, Self> {
89        let (app, turn, driver) = shutdown.into_parts();
90        let conn = app.as_ref().get_ref();
91        // SAFETY: shared phase access preserves any dependent client's state borrow.
92        unsafe { &*conn.phase.as_ptr() }.stop();
93        executor::raw::Shutdown::new(app, turn, driver)
94    }
95
96    fn finish<'app, 'finish, 'owner, 'epoch>(
97        finish: executor::raw::Finish<'app, 'finish, 'owner, 'epoch, 'd, Self>,
98    ) -> executor::raw::Finish<'app, 'finish, 'owner, 'epoch, 'd, Self> {
99        let (app, install, finish) = finish.into_parts();
100        if finish.is_forced() {
101            let conn = app.as_ref().get_ref();
102            // SAFETY: all client borrows ended before this final pinned application access.
103            unsafe { &mut *conn.phase.as_ptr() }.force();
104        }
105        executor::raw::Finish::new(app, install, finish)
106    }
107
108    fn progress(
109        app: pin::Pin<&Self>,
110        _: executor::raw::Progress<'_, '_, 'd>,
111    ) -> schedule::Progress<'d> {
112        // SAFETY: progress only reads the phase; Live excludes active client state borrows.
113        unsafe { &*app.get_ref().phase.as_ptr() }.progress::<false>()
114    }
115
116    fn stopping(
117        app: pin::Pin<&Self>,
118        _: executor::raw::Progress<'_, '_, 'd>,
119    ) -> schedule::Progress<'d> {
120        // SAFETY: stopping only reads the phase; Live excludes active client state borrows.
121        unsafe { &*app.get_ref().phase.as_ptr() }.progress::<true>()
122    }
123
124    /// # Safety
125    /// The root, prepared plan, and park authority belong to this installed owner.
126    unsafe fn park<'app, 'driver, 'turn>(
127        app: pin::Pin<&'app mut Self>,
128        (): &mut Self::ParkPlan,
129        mut park: executor::raw::Park<'driver, 'turn, 'd>,
130    ) where
131        'd: 'driver + 'turn,
132    {
133        let conn = app.as_ref().get_ref();
134        // SAFETY: the phase remains pinned, and shared access preserves client state borrows.
135        let phase = unsafe { &*conn.phase.as_ptr() };
136        if let Phase::Live(live) = phase
137            && live.borrow.get().is_borrowed()
138        {
139            return;
140        }
141        // SAFETY: phase admission excludes client borrows, and park excludes reentry.
142        let phase = unsafe { &mut *conn.phase.as_ptr() };
143        loop {
144            let (state, plan) = match phase {
145                Phase::Live(live) => {
146                    // SAFETY: the vacant live phase excludes all mutable client state borrows.
147                    let state = unsafe { &mut *live.state.get() };
148                    let plan = state.maintenance(park.now());
149                    (state, plan)
150                }
151                Phase::Closing(state) => {
152                    let plan = state.maintenance(park.now());
153                    if matches!(plan, api::Plan::Idle) {
154                        phase.retire();
155                        continue;
156                    }
157                    (state, plan)
158                }
159                Phase::Retiring(retiring) => {
160                    if matches!(retiring.inventory(), stmt::Inventory::Empty) {
161                        break;
162                    }
163                    if park.next_step().is_none() {
164                        break;
165                    }
166                    retiring.retire_one();
167                    continue;
168                }
169                Phase::Empty => break,
170            };
171            match plan {
172                api::Plan::Idle | api::Plan::Delayed => break,
173                api::Plan::Ready => {}
174            }
175            let Some(step) = park.next_step() else {
176                break;
177            };
178            if state.maintain(step.now()).is_pending() {
179                break;
180            }
181        }
182    }
183}