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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//! Warm-index daemon.
//!
//! Holds the index mmapped in memory with the filesystem watcher running, so
//! query latency drops to the cost of the query itself (no per-invocation open +
//! mmap + table load). Clients talk to it over a Unix domain socket.
#[cfg(unix)]
pub use unix_impl::serve;
#[cfg(not(unix))]
pub use stub_impl::serve;
// The daemon relies on Unix domain sockets and is unavailable on other
// platforms. The stub keeps the CLI compiling everywhere and reports a clear
// error if `greplm serve` is invoked.
#[cfg(not(unix))]
mod stub_impl {
use std::path::Path;
use std::sync::Arc;
use crate::error::{Error, Result};
use crate::Greplm;
/// Unsupported on this platform: the daemon requires Unix domain sockets.
pub fn serve(_greplm: Arc<Greplm>, _socket: &Path) -> Result<()> {
Err(Error::other(
"greplm daemon is not supported on this platform",
))
}
}
#[cfg(unix)]
mod unix_impl {
use std::io::{BufRead, BufReader, Read, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
use std::time::Duration;
use crate::error::{Error, Result};
use crate::proto::{Request, Response};
use crate::search::Searcher;
use crate::Greplm;
type Shared = Arc<RwLock<Searcher>>;
/// Maximum size of a single request line; protects against unbounded memory
/// growth from a malformed or hostile client.
const MAX_REQUEST_BYTES: u64 = 1 << 20; // 1 MiB
/// Maximum number of clients served concurrently. Excess connections are
/// rejected rather than spawning unbounded threads.
const MAX_CONNECTIONS: usize = 256;
static ACTIVE_CONNECTIONS: AtomicUsize = AtomicUsize::new(0);
/// RAII guard that tracks the live connection count.
struct ConnGuard;
impl Drop for ConnGuard {
fn drop(&mut self) {
ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::SeqCst);
}
}
/// Recover the inner value from a poisoned lock instead of propagating the
/// poison; a panicked query must not permanently disable the daemon.
fn read_searcher(s: &Shared) -> std::sync::RwLockReadGuard<'_, Searcher> {
s.read().unwrap_or_else(|e| e.into_inner())
}
fn swap_searcher(s: &Shared, new: Searcher) {
let mut guard = s.write().unwrap_or_else(|e| e.into_inner());
*guard = new;
}
/// Run the daemon: build/refresh the index, start the watcher, and serve
/// clients on `socket` until the process is terminated.
pub fn serve(greplm: Arc<Greplm>, socket: &Path) -> Result<()> {
greplm.ensure_initialized()?;
greplm.index(false)?;
let searcher: Shared = Arc::new(RwLock::new(greplm.searcher()?));
// Background watcher: reindex incrementally and hot-swap the searcher.
// If the watcher dies, log and restart it after a short backoff so the
// index doesn't silently stop updating.
{
let g_watch = greplm.clone();
let s = searcher.clone();
std::thread::Builder::new()
.name("greplm-watch".into())
.spawn(move || loop {
let g_cb = g_watch.clone();
let s_cb = s.clone();
let result = g_watch.watch(Duration::from_millis(300), move |_stats| {
if let Ok(ns) = g_cb.searcher() {
swap_searcher(&s_cb, ns);
}
});
match result {
Ok(()) => break,
Err(e) => {
tracing::warn!("watcher stopped ({e}); restarting in 1s");
std::thread::sleep(Duration::from_secs(1));
}
}
})
.ok();
}
// Fresh socket each run.
if socket.exists() {
let _ = std::fs::remove_file(socket);
}
let listener = UnixListener::bind(socket).map_err(|e| Error::io(socket, e))?;
// Restrict the socket to the owner so other local users can't connect
// and issue queries (which can read indexed file contents) as us.
{
use std::os::unix::fs::PermissionsExt;
let perms = std::fs::Permissions::from_mode(0o600);
if let Err(e) = std::fs::set_permissions(socket, perms) {
tracing::warn!("could not restrict socket permissions: {e}");
}
}
tracing::info!("greplm daemon listening on {}", socket.display());
for conn in listener.incoming() {
match conn {
Ok(mut stream) => {
// Reject excess connections instead of spawning unbounded
// threads; the guard decrements the count when the handler
// finishes.
let prev = ACTIVE_CONNECTIONS.fetch_add(1, Ordering::SeqCst);
if prev >= MAX_CONNECTIONS {
ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::SeqCst);
let resp = Response::err("server busy: too many connections");
if let Ok(mut bytes) = serde_json::to_vec(&resp) {
bytes.push(b'\n');
let _ = stream.write_all(&bytes);
}
continue;
}
let s = searcher.clone();
let g = greplm.clone();
std::thread::spawn(move || {
let _guard = ConnGuard;
if let Err(e) = handle(stream, s, g) {
tracing::debug!("client error: {e}");
}
});
}
Err(e) => tracing::debug!("accept error: {e}"),
}
}
Ok(())
}
fn handle(stream: UnixStream, searcher: Shared, greplm: Arc<Greplm>) -> Result<()> {
let mut reader = BufReader::new(stream.try_clone().map_err(Error::PlainIo)?);
let mut writer = stream;
let mut line = String::new();
loop {
line.clear();
// Bound the request size so a client can't make us buffer unbounded
// memory on a single line.
let n = (&mut reader)
.take(MAX_REQUEST_BYTES)
.read_line(&mut line)
.map_err(Error::PlainIo)?;
if n == 0 {
break; // client disconnected
}
if n as u64 >= MAX_REQUEST_BYTES && !line.ends_with('\n') {
let resp = Response::err("request too large");
let mut bytes = serde_json::to_vec(&resp)?;
bytes.push(b'\n');
writer.write_all(&bytes).map_err(Error::PlainIo)?;
writer.flush().map_err(Error::PlainIo)?;
break;
}
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let resp = match serde_json::from_str::<Request>(trimmed) {
Ok(req) => {
// Isolate each query: a panic while handling one request
// (a bug, an arithmetic overflow, a corrupt segment) must
// not poison the shared searcher beyond recovery or drop
// the connection — return an error to this client instead.
let s = &searcher;
let g = &greplm;
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| dispatch(req, s, g)))
.unwrap_or_else(|_| Response::err("internal error: query panicked"))
}
Err(e) => Response::err(format!("bad request: {e}")),
};
let mut bytes = serde_json::to_vec(&resp)?;
bytes.push(b'\n');
writer.write_all(&bytes).map_err(Error::PlainIo)?;
writer.flush().map_err(Error::PlainIo)?;
}
Ok(())
}
fn dispatch(req: Request, searcher: &Shared, greplm: &Arc<Greplm>) -> Response {
let json = |v| Response::ok(v);
match req {
Request::Ping => Response::ok(serde_json::json!({"pong": true})),
Request::Status => match greplm.status() {
Ok(s) => to_resp(serde_json::to_value(s)),
Err(e) => Response::err(e.to_string()),
},
Request::Reindex { force } => match greplm.index(force) {
Ok(stats) => {
if let Ok(ns) = greplm.searcher() {
swap_searcher(searcher, ns);
}
json(serde_json::json!({
"files_indexed": stats.files_indexed,
"files_removed": stats.files_removed,
"symbols": stats.symbols,
"segments": stats.segments,
}))
}
Err(e) => Response::err(e.to_string()),
},
other => {
let guard = read_searcher(searcher);
match other {
Request::Summary => to_resp(serde_json::to_value(guard.summary())),
Request::Search(q) => match guard.search(&q) {
Ok(h) => to_resp(serde_json::to_value(h)),
Err(e) => Response::err(e.to_string()),
},
Request::Symbols(q) => match guard.symbols(&q) {
Ok(h) => to_resp(serde_json::to_value(h)),
Err(e) => Response::err(e.to_string()),
},
Request::Refs {
name,
limit,
offset,
} => match guard.references(&name, limit, offset) {
Ok(h) => to_resp(serde_json::to_value(h)),
Err(e) => Response::err(e.to_string()),
},
Request::RefsResolved {
name,
limit,
offset,
} => to_resp(serde_json::to_value(
guard.references_resolved(&name, limit, offset),
)),
Request::Callers {
name,
limit,
offset,
} => to_resp(serde_json::to_value(guard.callers(&name, limit, offset))),
Request::Callees {
name,
limit,
offset,
} => to_resp(serde_json::to_value(guard.callees(&name, limit, offset))),
Request::BlastRadius { name, depth, limit } => to_resp(serde_json::to_value(
guard.blast_radius(&name, depth, limit),
)),
Request::Definition { file, line, col } => {
match guard.definition(&file, line, col) {
Ok(h) => to_resp(serde_json::to_value(h)),
Err(e) => Response::err(e.to_string()),
}
}
Request::ReferencesAt { file, line, col } => {
match guard.references_of(&file, line, col) {
Ok(h) => to_resp(serde_json::to_value(h)),
Err(e) => Response::err(e.to_string()),
}
}
Request::Structural {
pattern,
lang,
limit,
offset,
} => match guard.structural_search(&pattern, &lang, limit, offset) {
Ok(h) => to_resp(serde_json::to_value(h)),
Err(e) => Response::err(e.to_string()),
},
Request::ContextPack { task, budget } => {
to_resp(serde_json::to_value(guard.context_pack(&task, budget)))
}
Request::Blame { file, line } => match guard.blame(&file, line) {
Ok(b) => to_resp(serde_json::to_value(b)),
Err(e) => Response::err(e.to_string()),
},
Request::History { name, limit } => match guard.symbol_history(&name, limit) {
Ok(h) => to_resp(serde_json::to_value(h)),
Err(e) => Response::err(e.to_string()),
},
Request::ChangedSince { rev } => match guard.changed_since(&rev) {
Ok(c) => to_resp(serde_json::to_value(c)),
Err(e) => Response::err(e.to_string()),
},
Request::Outline { file } => match guard.outline(&file) {
Ok(h) => to_resp(serde_json::to_value(h)),
Err(e) => Response::err(e.to_string()),
},
Request::Snippet {
file,
start,
end,
context,
} => match guard.read_snippet(&file, start, end, context) {
Ok(h) => to_resp(serde_json::to_value(h)),
Err(e) => Response::err(e.to_string()),
},
// Handled above.
Request::Ping | Request::Status | Request::Reindex { .. } => {
Response::err("unreachable")
}
}
}
}
}
fn to_resp(v: serde_json::Result<serde_json::Value>) -> Response {
match v {
Ok(value) => Response::ok(value),
Err(e) => Response::err(e.to_string()),
}
}
}