1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
//! Lazy initialization for expensive subsystems (#50).
//!
//! Uses `tokio::sync::OnceCell` to defer initialization of heavy subsystems
//! (LSP, MCP, embeddings) until first use rather than at startup.
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use tokio::sync::OnceCell;
use tracing::debug;
/// A lazily-initialized subsystem value.
///
/// The inner `T` is initialized on the first call to [`LazySubsystem::get`]
/// or [`LazySubsystem::get_or_try_init`]. Subsequent calls return the
/// cached value without re-running the initializer.
///
/// This is a thin, ergonomic wrapper around `tokio::sync::OnceCell` that
/// adds logging and a human-readable subsystem name.
pub struct LazySubsystem<T: Send + Sync + 'static> {
name: &'static str,
cell: Arc<OnceCell<T>>,
}
impl<T: Send + Sync + 'static> LazySubsystem<T> {
/// Create a new lazy subsystem with the given human-readable `name`.
pub fn new(name: &'static str) -> Self {
Self {
name,
cell: Arc::new(OnceCell::new()),
}
}
/// Get the value, initializing it with `init` if necessary.
///
/// The `init` future runs at most once, even under concurrent access.
pub async fn get<F, Fut>(&self, init: F) -> &T
where
F: FnOnce() -> Fut,
Fut: Future<Output = T>,
{
self.cell
.get_or_init(|| async {
debug!("Lazy-initializing subsystem: {}", self.name);
let value = init().await;
debug!("Subsystem {} initialized", self.name);
value
})
.await
}
/// Get the value, initializing with a fallible `init` if necessary.
///
/// If `init` returns an error, the cell remains uninitialized and future
/// calls will retry.
pub async fn get_or_try_init<F, Fut, E>(&self, init: F) -> Result<&T, E>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<T, E>>,
{
let name = self.name;
self.cell
.get_or_try_init(|| async {
debug!("Lazy-initializing subsystem (fallible): {name}");
let value = init().await?;
debug!("Subsystem {name} initialized");
Ok(value)
})
.await
}
/// Check whether the subsystem has been initialized.
pub fn is_initialized(&self) -> bool {
self.cell.initialized()
}
/// Return the value if already initialized, without triggering init.
pub fn try_get(&self) -> Option<&T> {
self.cell.get()
}
/// The human-readable name of this subsystem.
pub fn name(&self) -> &'static str {
self.name
}
}
impl<T: Send + Sync + 'static> Clone for LazySubsystem<T> {
fn clone(&self) -> Self {
Self {
name: self.name,
cell: Arc::clone(&self.cell),
}
}
}
impl<T: Send + Sync + fmt::Debug + 'static> fmt::Debug for LazySubsystem<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LazySubsystem")
.field("name", &self.name)
.field("initialized", &self.is_initialized())
.finish()
}
}
// ---------------------------------------------------------------------------
// Convenience type aliases for the three named subsystems
// ---------------------------------------------------------------------------
/// Lazy-init wrapper for the LSP subsystem.
pub type LazyLsp<T> = LazySubsystem<T>;
/// Lazy-init wrapper for the MCP subsystem.
pub type LazyMcp<T> = LazySubsystem<T>;
/// Lazy-init wrapper for the embeddings subsystem.
pub type LazyEmbeddings<T> = LazySubsystem<T>;
/// Create standard lazy wrappers for LSP, MCP, and embeddings.
pub fn create_lazy_subsystems<L, M, E>() -> (LazyLsp<L>, LazyMcp<M>, LazyEmbeddings<E>)
where
L: Send + Sync + 'static,
M: Send + Sync + 'static,
E: Send + Sync + 'static,
{
(
LazySubsystem::new("LSP"),
LazySubsystem::new("MCP"),
LazySubsystem::new("Embeddings"),
)
}
// ---------------------------------------------------------------------------
// SyncLazy — for non-async contexts using std::sync::OnceLock
// ---------------------------------------------------------------------------
/// A synchronous lazy-init wrapper using `std::sync::OnceLock`.
///
/// Useful for subsystems that can be initialized without async.
pub struct SyncLazy<T: Send + Sync + 'static> {
name: &'static str,
cell: std::sync::OnceLock<T>,
}
impl<T: Send + Sync + 'static> SyncLazy<T> {
/// Create a new synchronous lazy subsystem.
pub const fn new(name: &'static str) -> Self {
Self {
name,
cell: std::sync::OnceLock::new(),
}
}
/// Get the value, initializing with `init` if necessary.
pub fn get_or_init(&self, init: impl FnOnce() -> T) -> &T {
self.cell.get_or_init(|| {
debug!("Sync lazy-init: {}", self.name);
init()
})
}
/// Check whether initialized.
pub fn is_initialized(&self) -> bool {
self.cell.get().is_some()
}
/// Return the value if already initialized.
pub fn try_get(&self) -> Option<&T> {
self.cell.get()
}
/// The human-readable name.
pub fn name(&self) -> &'static str {
self.name
}
}
impl<T: Send + Sync + fmt::Debug + 'static> fmt::Debug for SyncLazy<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SyncLazy")
.field("name", &self.name)
.field("initialized", &self.is_initialized())
.finish()
}
}
#[cfg(test)]
#[path = "lazy_init_tests.rs"]
mod tests;