Skip to main content

icydb_core/db/session/
mod.rs

1//! Module: session
2//! Responsibility: user-facing query/write execution facade over db executors.
3//! Does not own: planning semantics, cursor validation rules, or storage mutation protocol.
4//! Boundary: converts fluent/query intent calls into executor operations and response DTOs.
5
6mod accepted_schema;
7mod bounded_cache;
8mod catalog;
9mod integrity;
10mod mutation_job;
11mod query;
12mod read_set;
13mod request;
14mod response;
15mod resumable_job;
16#[cfg(feature = "sql")]
17mod sql;
18mod write;
19
20#[cfg(all(test, feature = "sql", feature = "diagnostics"))]
21mod tests;
22
23use crate::metrics::sink::with_metrics_sink;
24use crate::{
25    db::{Db, StoreRegistry},
26    metrics::sink::MetricsSink,
27    traits::CanisterKind,
28};
29use std::thread::LocalKey;
30
31pub(in crate::db) use accepted_schema::AcceptedSchemaCatalogContext;
32#[cfg(all(test, feature = "sql", feature = "diagnostics"))]
33pub(in crate::db) use accepted_schema::{
34    AcceptedSchemaRuntimeBuildCounts, accepted_schema_runtime_build_counts_for_tests,
35    reset_accepted_schema_runtime_build_counts_for_tests,
36};
37pub use query::{
38    AttributedRead, OperationReadAttribution, ReadAccessRoute, ReadExecutionRoute,
39    ReadPlanCacheOutcome,
40};
41#[cfg(all(feature = "sql", feature = "diagnostics"))]
42pub use query::{
43    DirectDataRowAttribution, GroupedCountAttribution, GroupedExecutionAttribution,
44    KernelRowAttribution, ScalarAggregateAttribution,
45};
46#[doc(hidden)]
47pub use query::{
48    MAX_TYPED_EXACT_KEY_BATCH_INPUT_BYTES, MAX_TYPED_EXACT_KEY_BATCH_ITEMS,
49    MAX_TYPED_EXACT_KEY_BATCH_RESULT_BYTES, MAX_TYPED_EXACT_KEY_BATCH_STORED_BYTES,
50};
51pub use request::RequestExecutionRoot;
52pub(in crate::db) use request::RequestExecutionScope;
53pub(in crate::db) use response::finalize_structural_grouped_projection_result;
54pub(in crate::db) use response::grouped_cursor_from_bytes;
55#[cfg(all(feature = "sql", feature = "diagnostics"))]
56pub use sql::{
57    SqlCompileAttribution, SqlDistinctProjectionAttribution, SqlExecutionAttribution,
58    SqlHybridCoveringAttribution, SqlOutputBlobAttribution, SqlPureCoveringAttribution,
59    SqlQueryCacheAttribution, SqlQueryExecutionAttribution,
60};
61#[cfg(feature = "sql")]
62pub use sql::{
63    SqlConstraintValidationPage, SqlConstraintValidationRevisionStatus,
64    SqlConstraintValidationState, SqlDdlExecutionStatus, SqlDdlMutationKind,
65    SqlDdlPreparationReport, SqlIntegrityError, SqlStatementDispatch, SqlStatementResult,
66    SqlStatementShellSurface, SqlStatementSurface, sql_statement_dispatch,
67    sql_statement_entity_name, sql_statement_shell_surface, sql_statement_surface,
68};
69#[cfg(feature = "sql")]
70pub(in crate::db::session) use write::{
71    AcceptedStructuralMutation, AcceptedStructuralMutationTarget,
72    structural_data_key_from_runtime_values,
73};
74
75///
76/// DbSession
77///
78/// Session-scoped database handle with policy (debug, metrics) and execution routing.
79///
80
81pub struct DbSession<C: CanisterKind> {
82    db: Db<C>,
83    debug: bool,
84    metrics: Option<&'static dyn MetricsSink>,
85}
86
87impl<C: CanisterKind> DbSession<C> {
88    /// Construct one session facade over a sealed runtime store registry.
89    #[must_use]
90    pub fn new(
91        store: &'static LocalKey<StoreRegistry>,
92        request_root: &RequestExecutionRoot,
93    ) -> Self {
94        Self {
95            db: Db::new(store, request_root.scope()),
96            debug: false,
97            metrics: None,
98        }
99    }
100
101    /// Drive one bounded startup page while retaining its persisted failure owner.
102    pub(in crate::db) fn drive_startup_recovery_page_with_failure_authority(
103        &self,
104    ) -> Result<bool, crate::db::commit::StartupRecoveryFailure> {
105        self.db.drive_startup_recovery_page_with_failure_authority()
106    }
107
108    /// Construct a session from the active synchronous request scope.
109    ///
110    /// Generated zero-argument `db!()` wiring uses this entry. `None` means
111    /// that the caller did not establish a request execution boundary.
112    #[doc(hidden)]
113    #[must_use]
114    pub fn __new_from_current_request(store: &'static LocalKey<StoreRegistry>) -> Option<Self> {
115        request::current_request_scope().map(|scope| Self {
116            db: Db::new(store, scope),
117            debug: false,
118            metrics: None,
119        })
120    }
121
122    /// Enable bounded request-wide query diagnostics without resetting prior counters.
123    ///
124    /// Returns `true` only when this call enabled collection. Every session
125    /// derived from the same request root observes the same diagnostic state.
126    #[cfg(feature = "diagnostics")]
127    #[must_use]
128    pub fn enable_request_diagnostics(&self) -> bool {
129        self.db.request_execution_scope().enable_diagnostics()
130    }
131
132    /// Snapshot bounded request-wide query diagnostics when collection is enabled.
133    #[cfg(feature = "diagnostics")]
134    #[must_use]
135    pub fn request_diagnostics(&self) -> Option<crate::db::RequestDiagnostics> {
136        self.db.request_execution_scope().diagnostics_snapshot()
137    }
138
139    /// Enable debug execution behavior where supported by executors.
140    #[must_use]
141    pub const fn debug(mut self) -> Self {
142        self.debug = true;
143        self
144    }
145
146    /// Attach one metrics sink for all session-executed operations.
147    #[must_use]
148    pub const fn metrics_sink(mut self, sink: &'static dyn MetricsSink) -> Self {
149        self.metrics = Some(sink);
150        self
151    }
152
153    fn with_metrics<T>(&self, f: impl FnOnce() -> T) -> T {
154        if let Some(sink) = self.metrics {
155            with_metrics_sink(sink, f)
156        } else {
157            f()
158        }
159    }
160}