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};
37#[cfg(all(feature = "sql", feature = "diagnostics"))]
38pub use query::{
39    DirectDataRowAttribution, GroupedCountAttribution, GroupedExecutionAttribution,
40    KernelRowAttribution, ScalarAggregateAttribution,
41};
42#[doc(hidden)]
43pub use query::{
44    MAX_TYPED_EXACT_KEY_BATCH_INPUT_BYTES, MAX_TYPED_EXACT_KEY_BATCH_ITEMS,
45    MAX_TYPED_EXACT_KEY_BATCH_RESULT_BYTES, MAX_TYPED_EXACT_KEY_BATCH_STORED_BYTES,
46};
47pub use request::RequestExecutionRoot;
48pub(in crate::db) use request::RequestExecutionScope;
49pub(in crate::db) use response::finalize_structural_grouped_projection_result;
50pub(in crate::db) use response::grouped_cursor_from_bytes;
51#[cfg(all(feature = "sql", feature = "diagnostics"))]
52pub use sql::{
53    SqlCompileAttribution, SqlDistinctProjectionAttribution, SqlExecutionAttribution,
54    SqlHybridCoveringAttribution, SqlOutputBlobAttribution, SqlPureCoveringAttribution,
55    SqlQueryCacheAttribution, SqlQueryExecutionAttribution,
56};
57#[cfg(feature = "sql")]
58pub use sql::{
59    SqlConstraintValidationPage, SqlConstraintValidationRevisionStatus,
60    SqlConstraintValidationState, SqlDdlExecutionStatus, SqlDdlMutationKind,
61    SqlDdlPreparationReport, SqlIntegrityError, SqlStatementDispatch, SqlStatementResult,
62    SqlStatementShellSurface, SqlStatementSurface, sql_statement_dispatch,
63    sql_statement_entity_name, sql_statement_shell_surface, sql_statement_surface,
64};
65#[cfg(feature = "sql")]
66pub(in crate::db::session) use write::{
67    AcceptedStructuralMutation, AcceptedStructuralMutationTarget,
68    structural_data_key_from_runtime_values,
69};
70
71///
72/// DbSession
73///
74/// Session-scoped database handle with policy (debug, metrics) and execution routing.
75///
76
77pub struct DbSession<C: CanisterKind> {
78    db: Db<C>,
79    debug: bool,
80    metrics: Option<&'static dyn MetricsSink>,
81}
82
83impl<C: CanisterKind> DbSession<C> {
84    /// Construct one session facade over a sealed runtime store registry.
85    #[must_use]
86    pub fn new(
87        store: &'static LocalKey<StoreRegistry>,
88        request_root: &RequestExecutionRoot,
89    ) -> Self {
90        Self {
91            db: Db::new(store, request_root.scope()),
92            debug: false,
93            metrics: None,
94        }
95    }
96
97    /// Drive one bounded startup page while retaining its persisted failure owner.
98    pub(in crate::db) fn drive_startup_recovery_page_with_failure_authority(
99        &self,
100    ) -> Result<bool, crate::db::commit::StartupRecoveryFailure> {
101        self.db.drive_startup_recovery_page_with_failure_authority()
102    }
103
104    /// Construct a session from the active synchronous request scope.
105    ///
106    /// Generated zero-argument `db!()` wiring uses this entry. `None` means
107    /// that the caller did not establish a request execution boundary.
108    #[doc(hidden)]
109    #[must_use]
110    pub fn __new_from_current_request(store: &'static LocalKey<StoreRegistry>) -> Option<Self> {
111        request::current_request_scope().map(|scope| Self {
112            db: Db::new(store, scope),
113            debug: false,
114            metrics: None,
115        })
116    }
117
118    /// Enable bounded request-wide query diagnostics without resetting prior counters.
119    ///
120    /// Returns `true` only when this call enabled collection. Every session
121    /// derived from the same request root observes the same diagnostic state.
122    #[cfg(feature = "diagnostics")]
123    #[must_use]
124    pub fn enable_request_diagnostics(&self) -> bool {
125        self.db.request_execution_scope().enable_diagnostics()
126    }
127
128    /// Snapshot bounded request-wide query diagnostics when collection is enabled.
129    #[cfg(feature = "diagnostics")]
130    #[must_use]
131    pub fn request_diagnostics(&self) -> Option<crate::db::RequestDiagnostics> {
132        self.db.request_execution_scope().diagnostics_snapshot()
133    }
134
135    /// Enable debug execution behavior where supported by executors.
136    #[must_use]
137    pub const fn debug(mut self) -> Self {
138        self.debug = true;
139        self
140    }
141
142    /// Attach one metrics sink for all session-executed operations.
143    #[must_use]
144    pub const fn metrics_sink(mut self, sink: &'static dyn MetricsSink) -> Self {
145        self.metrics = Some(sink);
146        self
147    }
148
149    fn with_metrics<T>(&self, f: impl FnOnce() -> T) -> T {
150        if let Some(sink) = self.metrics {
151            with_metrics_sink(sink, f)
152        } else {
153            f()
154        }
155    }
156}