Skip to main content

waratah_registry/
lib.rs

1//! String-registry process: the inverse `StrHash → raw` dictionary.
2//!
3//! This crate serves the `StringRegistry` service (`RegisterStrings`,
4//! `ResolveStrings`, `FlushMemtables`, `CompactRange`, `Health`, `Describe`) and nothing else — it
5//! never serves hexastore RPCs, and hexastore partitions never serve these.
6//! Compute writes hashed strings here on insert and reads them back only for
7//! final output bindings (late materialization).
8//!
9//! MVP runs one process holding either N in-process shards of
10//! [`waratah_storage::ShardedRegistry`] or a RocksDB dictionary at
11//! `{data-dir}/{repository}/registry`. Splitting those shards across several
12//! registry processes (`murmur3(StrHash) % N` at the caller) is a later change
13//! to routing, not to this RPC surface.
14
15#![deny(unused_must_use)]
16#![warn(missing_docs)]
17
18mod blobs;
19mod error;
20
21use std::net::SocketAddr;
22use std::path::Path;
23use std::sync::{Arc, RwLock};
24use std::time::{Duration, Instant};
25
26use tokio_stream::wrappers::ReceiverStream;
27use tonic::transport::Server;
28use tonic::transport::server::TcpIncoming;
29use tonic::{Request, Response, Status};
30use waratah_proto::pb;
31use waratah_proto::{
32    GRPC_MAX_MESSAGE_SIZE, StringRegistry, StringRegistryServer, blocking_join_error,
33    str_hash_from_bytes,
34};
35use waratah_storage::{
36    LsmMetrics, MAIN_REPOSITORY_ID, Registry, RocksDbTuning, StrHash, iterator_readahead_bytes,
37};
38
39pub use blobs::{
40    BlobStore, BlobVerifyReport, INLINE_THRESHOLD_BYTES, MAX_BLOB_BYTES, SEGMENT_HANDLE_CACHE,
41    SEGMENT_TARGET_BYTES, TuningOverride, set_segment_handle_cache, set_segment_target_bytes,
42};
43pub use error::RegistryError;
44
45/// Process identity echoed by `Describe`.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct RegistryIdentity {
48    /// Routing id (`registry-0` on the MVP).
49    pub node_id: String,
50    /// gRPC listen address as advertised, empty if unknown.
51    pub listen: String,
52    /// RocksDB directory, empty for the memory backend.
53    pub data_dir: String,
54    /// Repository this process opened (`main`).
55    pub repository_id: String,
56}
57
58impl Default for RegistryIdentity {
59    fn default() -> Self {
60        Self {
61            node_id: String::new(),
62            listen: String::new(),
63            data_dir: String::new(),
64            repository_id: MAIN_REPOSITORY_ID.to_owned(),
65        }
66    }
67}
68
69/// Number of in-process registry shards when none is configured.
70pub const DEFAULT_SHARD_COUNT: usize = 8;
71
72/// Maximum stored length of one registered string (IRI, literal lexical
73/// form, or big language tag), counted in UTF-8 bytes.
74///
75/// This is the invariant that keeps `ResolveStrings` frames inside one
76/// gRPC message: every entry fits a frame budget of
77/// [`RESOLVE_FRAME_BUDGET_BYTES`] by construction, so the streaming
78/// protocol never needs entry-level chunking. It is also a storage-health
79/// bound — multi-megabyte RocksDB values are bad for compaction. Blobs of
80/// this scale belong in object storage referenced by IRI, inlined as RDF
81/// literals they are a data-modeling error.
82pub const MAX_REGISTERED_STRING_BYTES: usize = 1024 * 1024;
83
84/// Payload bytes per transport chunk of a streamed `GetBlobs` frame.
85///
86/// Frames themselves pack under [`RESOLVE_FRAME_BUDGET_BYTES`]; this constant
87/// splits a single payload so one 64 MiB blob streams as many bounded frames
88/// instead of one oversized message.
89const BLOB_FRAME_CHUNK_BYTES: usize = 1024 * 1024;
90
91/// Byte budget for one streamed `ResolveStrings` frame (message).
92///
93/// Half the gRPC message ceiling: with strings bounded at
94/// [`MAX_REGISTERED_STRING_BYTES`], a frame can overshoot the budget by at
95/// most one max-size entry and still stay well under the hard limit.
96pub const RESOLVE_FRAME_BUDGET_BYTES: usize = GRPC_MAX_MESSAGE_SIZE / 2;
97
98/// Hashes per `spawn_blocking` lookup walk while streaming.
99///
100/// The streaming task pipelines with exactly one outstanding walk: the next
101/// sub-batch starts resolving after the current one returns and runs while
102/// its results pack into frames and stream out. Walks never overlap — two
103/// interleaved seek streams thrash disk locality (one look-ahead walk
104/// measured ~9x slower on a 400k-hash resolve) — and the resolved-ahead
105/// buffer is bounded to one sub-batch by hash *count*; its byte size
106/// follows the resolved strings, each ≤ [`MAX_REGISTERED_STRING_BYTES`].
107/// Compute sends request hashes pre-sorted and deduplicated, so consecutive
108/// sub-batches are disjoint ascending key ranges (seek locality) covering
109/// contiguous request positions (frame order falls out without
110/// reassembly). The resolver never requires that — it is positional for
111/// any arrival order — it only benefits from it.
112const RESOLVE_SUBBATCH: usize = 4096;
113
114/// Proto framing per `ResolvedString` entry (field tags + lengths plus the
115/// enclosing `repeated` element), added to `raw.len()` when packing frames.
116const RESOLVED_ENTRY_OVERHEAD_BYTES: usize = 16;
117
118/// A frame send is "blocked" (compute / network could not drain it) past this.
119const SEND_BLOCKED_THRESHOLD: Duration = Duration::from_millis(1);
120
121/// Stderr timing trace for one streamed `ResolveStrings` RPC (`--trace`).
122///
123/// Answers "was this resolve cache-hot or disk-bound?" from the registry's
124/// side: per-subbatch lookup latency is the disk signal — hot RocksDB walks
125/// are single-digit ms, cold walks stream blocks and cost hundreds of ms.
126/// A send that blocks past [`SEND_BLOCKED_THRESHOLD`] means compute or the
127/// network, not storage, was the bottleneck for that frame.
128#[derive(Debug)]
129struct ResolveTrace {
130    enabled: bool,
131    started: Instant,
132    hashes: usize,
133    readahead_kib: usize,
134    subbatch: usize,
135    subbatches: usize,
136    lookup_total: Duration,
137    lookup_max: Duration,
138    pack_wall_total: Duration,
139    send_total: Duration,
140    send_max: Duration,
141    sends_blocked: u64,
142    frames: u64,
143    found: u64,
144    missing: u64,
145}
146
147impl ResolveTrace {
148    fn new(enabled: bool, hashes: usize, readahead_kib: usize) -> Self {
149        Self {
150            enabled,
151            started: Instant::now(),
152            hashes,
153            readahead_kib,
154            subbatch: 0,
155            subbatches: hashes.div_ceil(RESOLVE_SUBBATCH),
156            lookup_total: Duration::ZERO,
157            lookup_max: Duration::ZERO,
158            pack_wall_total: Duration::ZERO,
159            send_total: Duration::ZERO,
160            send_max: Duration::ZERO,
161            sends_blocked: 0,
162            frames: 0,
163            found: 0,
164            missing: 0,
165        }
166    }
167
168    /// Record one sub-batch lookup result; logs when enabled.
169    fn subbatch_done(&mut self, lookup: Duration, resolved: &[Option<String>]) {
170        self.subbatch += 1;
171        self.lookup_total += lookup;
172        self.lookup_max = self.lookup_max.max(lookup);
173        for raw in resolved {
174            if raw.is_some() {
175                self.found += 1;
176            } else {
177                self.missing += 1;
178            }
179        }
180        if self.enabled {
181            eprintln!(
182                "registry-trace subbatch {}/{} hashes={} lookup={:.1}ms found={} missing={}",
183                self.subbatch,
184                self.subbatches,
185                resolved.len(),
186                lookup.as_secs_f64() * 1e3,
187                self.found,
188                self.missing,
189            );
190        }
191    }
192
193    /// Record one frame handed to the channel; logs when it blocked.
194    fn frame_sent(&mut self, entries: usize, waited: Duration) {
195        self.frames += 1;
196        self.send_total += waited;
197        self.send_max = self.send_max.max(waited);
198        if waited > SEND_BLOCKED_THRESHOLD {
199            self.sends_blocked += 1;
200        }
201        if self.enabled && waited > SEND_BLOCKED_THRESHOLD {
202            eprintln!(
203                "registry-trace send blocked entries={entries} waited={:.1}ms",
204                waited.as_secs_f64() * 1e3,
205            );
206        }
207    }
208
209    /// Emit the per-request summary line when enabled.
210    fn done(&self) {
211        if !self.enabled {
212            return;
213        }
214        // pack_wall includes the send awaits; report the difference.
215        let pack_total = self.pack_wall_total.saturating_sub(self.send_total);
216        eprintln!(
217            "registry-trace resolve done hashes={} subbatches={} frames={} found={} missing={} \
218             wall={:.3}s ra={}KiB lookup_total={:.3}s lookup_avg={:.1}ms lookup_max={:.1}ms \
219             pack_total={:.1}ms send_total={:.1}ms send_max={:.1}ms sends_blocked={}",
220            self.hashes,
221            self.subbatch,
222            self.frames,
223            self.found,
224            self.missing,
225            self.started.elapsed().as_secs_f64(),
226            self.readahead_kib,
227            self.lookup_total.as_secs_f64(),
228            (self.lookup_total / self.subbatches.max(1) as u32).as_secs_f64() * 1e3,
229            self.lookup_max.as_secs_f64() * 1e3,
230            pack_total.as_secs_f64() * 1e3,
231            self.send_total.as_secs_f64() * 1e3,
232            self.send_max.as_secs_f64() * 1e3,
233            self.sends_blocked,
234        );
235    }
236}
237
238/// `StringRegistry` service over an in-memory or RocksDB dictionary.
239#[derive(Debug, Clone)]
240pub struct RegistryService {
241    /// Read/write lock: `register_entries` is the only `&mut Registry` path
242    /// (write guard); resolves, shard counts, flush, and compact take the
243    /// read guard, so concurrent resolves never block each other.
244    registry: Arc<RwLock<Registry>>,
245    /// Emit per-subbatch resolve timings and a per-request summary to stderr
246    /// (`--trace` / [`Self::with_trace`]).
247    trace: bool,
248    identity: RegistryIdentity,
249    /// Content-addressed blob store (GeoSPARQL geometry payloads). `None`
250    /// means no store is attached (pure registry process); `PutBlobChunks`
251    /// / `PutBlobs` fail with `UNAVAILABLE` there so a mis-wired compute
252    /// learns at write time.
253    blobs_reg: Option<Arc<BlobStore>>,
254    /// Startup cache-warm lifecycle (`WARATAH_WARM_CACHE`). `Some` when the
255    /// launcher handed a tracker in; the `Health` RPC reports warm readiness
256    /// from it so the launcher can hold startup until walks finish.
257    warm: Option<Arc<waratah_storage::WarmState>>,
258}
259
260impl RegistryService {
261    /// In-memory registry with `shard_count` in-process logical shards.
262    pub fn new(shard_count: usize) -> Self {
263        Self {
264            registry: Arc::new(RwLock::new(Registry::memory(shard_count))),
265            trace: false,
266            identity: RegistryIdentity::default(),
267            blobs_reg: None,
268            warm: None,
269        }
270    }
271
272    /// RocksDB dictionary at `path` (created if missing).
273    pub fn open_rocksdb(
274        path: impl AsRef<Path>,
275        tuning: RocksDbTuning,
276    ) -> Result<Self, RegistryError> {
277        Ok(Self {
278            registry: Arc::new(RwLock::new(Registry::open_rocksdb(path, tuning)?)),
279            trace: false,
280            identity: RegistryIdentity::default(),
281            blobs_reg: None,
282            warm: None,
283        })
284    }
285
286    /// Hand in the startup cache-warm tracker. The `Health` RPC reports
287    /// `warm_ready = false` (plus the pending walk names) until every
288    /// tracked walk completes or outlives the tracker's max wait.
289    pub fn with_warm_state(mut self, warm: Arc<waratah_storage::WarmState>) -> Self {
290        self.warm = Some(warm);
291        self
292    }
293
294    /// Attach the content-addressed blob store rooted at `blobs_root`
295    /// (typically `{data_dir}/{repository}/blobs`).
296    pub fn with_blobs(mut self, blobs_root: &Path) -> Result<Self, RegistryError> {
297        self.blobs_reg = Some(Arc::new(BlobStore::open(blobs_root)?));
298        Ok(self)
299    }
300
301    /// Attach an in-memory content-addressed blob store.
302    ///
303    /// Used by the default in-memory registry mode (no data dir) so geo
304    /// writes work: payloads live until process shutdown, consistent with
305    /// in-memory storage semantics.
306    pub fn with_blobs_memory(mut self) -> Result<Self, RegistryError> {
307        self.blobs_reg = Some(Arc::new(BlobStore::memory()));
308        Ok(self)
309    }
310
311    /// Blob store when one is attached.
312    pub fn blob_store(&self) -> Option<&BlobStore> {
313        self.blobs_reg.as_deref()
314    }
315
316    /// Store one fully assembled blob (the attached [`BlobStore`] validates
317    /// the content hash against the payload before writing anything).
318    pub fn put_blob(&self, blob_id: StrHash, payload: &[u8]) -> Result<u64, RegistryError> {
319        let store = self
320            .blobs_reg
321            .as_deref()
322            .ok_or(RegistryError::BlobStoreMissing)?;
323        store.put(blob_id, payload)
324    }
325
326    /// Batched, all-or-nothing blob write — the shared unit behind the
327    /// unary `PutBlobs` RPC and its in-process twins (`waratah standalone`
328    /// local client, geo tests).
329    ///
330    /// Every payload must be non-empty, is size-checked, and is
331    /// content-hash-validated **before** any index write. Blobs already
332    /// present are skipped; new blobs are
333    /// committed in one atomic index batch, so a failure leaves no partial
334    /// entries. Content addressing makes a whole-batch retry idempotent.
335    ///
336    /// [`BlobStore`] enforces [`MAX_BLOB_BYTES`] as a backstop; the unary
337    /// `PutBlobs` request is already bounded by the gRPC message ceiling.
338    pub fn put_blobs(&self, blobs: &[(StrHash, Arc<[u8]>)]) -> Result<(), RegistryError> {
339        let store = self
340            .blobs_reg
341            .as_deref()
342            .ok_or(RegistryError::BlobStoreMissing)?;
343        store.put_blobs(blobs)
344    }
345
346    /// Batched blob get: payloads positionally aligned with `ids`
347    /// (`None` = miss).
348    pub fn get_blobs(&self, ids: &[StrHash]) -> Result<Vec<Option<Vec<u8>>>, RegistryError> {
349        let store = self
350            .blobs_reg
351            .as_deref()
352            .ok_or(RegistryError::BlobStoreMissing)?;
353        store.get(ids)
354    }
355
356    /// Enable (`--trace`) stderr timing lines for streamed resolves.
357    pub fn with_trace(mut self, enabled: bool) -> Self {
358        self.trace = enabled;
359        self
360    }
361
362    /// Set the identity `Describe` reports.
363    pub fn with_identity(mut self, identity: RegistryIdentity) -> Self {
364        self.identity = identity;
365        self
366    }
367
368    /// Identity + LSM snapshot for `Describe`.
369    pub fn describe(&self) -> Result<pb::RegistryDescribeResponse, RegistryError> {
370        let guard = self.lock_read()?;
371        let node_id = if self.identity.node_id.is_empty() {
372            "registry-0".to_owned()
373        } else {
374            self.identity.node_id.clone()
375        };
376        let backend = match &*guard {
377            Registry::Memory(_) => pb::StorageBackend::Memory,
378            Registry::RocksDb(_) => pb::StorageBackend::Rocksdb,
379        };
380        let metrics = proto_lsm(guard.lsm_metrics());
381        Ok(pb::RegistryDescribeResponse {
382            node_id,
383            listen: self.identity.listen.clone(),
384            data_dir: self.identity.data_dir.clone(),
385            backend: backend.into(),
386            version: waratah_buildinfo::version_string(),
387            repository_id: if self.identity.repository_id.is_empty() {
388                MAIN_REPOSITORY_ID.to_owned()
389            } else {
390                self.identity.repository_id.clone()
391            },
392            shard_count: guard.shard_count() as u64,
393            entry_count: guard.entry_count(),
394            metrics: Some(metrics),
395            serving: true,
396        })
397    }
398
399    /// Number of logical shards behind this process (always `1` for RocksDB).
400    pub fn shard_count(&self) -> Result<usize, RegistryError> {
401        Ok(self.lock_read()?.shard_count())
402    }
403
404    /// Register `(hash, raw)` pairs, returning how many entries were written.
405    ///
406    /// Rejects any string over [`MAX_REGISTERED_STRING_BYTES`] before
407    /// writing, so a batch either lands whole or nothing oversized is
408    /// stored.
409    pub fn register(
410        &self,
411        entries: impl IntoIterator<Item = (StrHash, String)>,
412    ) -> Result<u64, RegistryError> {
413        let entries: Vec<_> = entries.into_iter().collect();
414        if let Some(len) = entries
415            .iter()
416            .map(|(_, raw)| raw.len())
417            .find(|len| *len > MAX_REGISTERED_STRING_BYTES)
418        {
419            return Err(RegistryError::StringTooLarge { len });
420        }
421        Ok(self.lock_write()?.register_entries(&entries)?)
422    }
423
424    /// Resolve `hashes` positionally; `None` marks a hash this registry lacks.
425    pub fn resolve(&self, hashes: &[StrHash]) -> Result<Vec<Option<String>>, RegistryError> {
426        Ok(self.lock_read()?.lookup_many(hashes)?)
427    }
428
429    /// Flush MemTables: the string dictionary plus the blob index.
430    ///
431    /// The in-memory backend and the in-memory blob variant are no-ops.
432    pub fn flush_memtables(&self) -> Result<(), RegistryError> {
433        {
434            self.lock_read()?.flush_memtables()?;
435        }
436        if let Some(store) = self.blobs_reg.as_deref() {
437            store.flush()?;
438        }
439        Ok(())
440    }
441
442    /// Compact the string registry CF and the blob index (no-op on the
443    /// in-memory backends).
444    pub fn compact_range(&self) -> Result<(), RegistryError> {
445        {
446            self.lock_read()?.compact_range();
447        }
448        if let Some(store) = self.blobs_reg.as_deref() {
449            store.compact_range()?;
450        }
451        Ok(())
452    }
453
454    /// Warm the registry's block cache (see
455    /// [`waratah_storage::Registry::warm_block_cache`]); no-op on the
456    /// in-memory backend. Called from the registry process when
457    /// `WARATAH_WARM_CACHE` is set.
458    pub fn warm_block_cache(
459        &self,
460        fill_fraction: f64,
461    ) -> Result<waratah_storage::WarmBlockCacheStats, RegistryError> {
462        Ok(self.lock_read()?.warm_block_cache(fill_fraction)?)
463    }
464
465    fn lock_read(&self) -> Result<std::sync::RwLockReadGuard<'_, Registry>, RegistryError> {
466        self.registry
467            .read()
468            .map_err(|_| RegistryError::LockPoisoned)
469    }
470
471    fn lock_write(&self) -> Result<std::sync::RwLockWriteGuard<'_, Registry>, RegistryError> {
472        self.registry
473            .write()
474            .map_err(|_| RegistryError::LockPoisoned)
475    }
476}
477
478impl Default for RegistryService {
479    fn default() -> Self {
480        Self::new(DEFAULT_SHARD_COUNT)
481    }
482}
483
484#[tonic::async_trait]
485impl StringRegistry for RegistryService {
486    type ResolveStringsStream = ReceiverStream<Result<pb::ResolveStringsResponse, Status>>;
487    type GetBlobsStream = ReceiverStream<Result<pb::GetBlobsResponse, Status>>;
488
489    /// Client-streaming blob put (`PutBlobChunks`): assemble chunks and
490    /// store the payload through the attached blob store (two-tier
491    /// index/segments, or in-memory), which validates the content hash
492    /// against the assembled bytes before writing anything.
493    ///
494    /// One call carries ONE blob (chunks repeat under the frame budget); a
495    /// later `PutBlobChunks` of the same id is a no-op because the address
496    /// is the commitment. Assembly is bounded by [`MAX_BLOB_BYTES`].
497    /// Batched puts of whole (already message-sized) blobs use `PutBlobs`
498    /// instead.
499    async fn put_blob_chunks(
500        &self,
501        request: Request<tonic::Streaming<pb::PutBlobRequest>>,
502    ) -> Result<Response<pb::PutBlobResponse>, Status> {
503        use tokio_stream::StreamExt;
504        let mut stream = request.into_inner();
505        let mut blob_id: Option<[u8; 16]> = None;
506        let mut total_chunks: Option<u64> = None;
507        let mut next_seq: u64 = 0;
508        let mut parts: Vec<Vec<u8>> = Vec::new();
509        let mut assembled: usize = 0;
510        while let Some(frame) = stream.next().await {
511            let frame = frame?;
512            for chunk in frame.chunks {
513                // No per-chunk size check: every chunk rides a gRPC
514                // message far under the blob size limit, and the
515                // assembled-size check below subsumes any single
516                // oversized chunk anyway.
517                let id: [u8; 16] = chunk.blob_id.clone().try_into().map_err(|_| {
518                    Status::invalid_argument(format!(
519                        "blob id must be 16 bytes, got {}",
520                        chunk.blob_id.len()
521                    ))
522                })?;
523                match &blob_id {
524                    Some(existing) if *existing != id => {
525                        return Err(Status::invalid_argument(
526                            "one PutBlobChunks call must carry chunks of exactly one blob id",
527                        ));
528                    }
529                    None => blob_id = Some(id),
530                    _ => {}
531                }
532                if let Some(total) = total_chunks
533                    && chunk.total_chunks != total
534                {
535                    return Err(Status::invalid_argument(
536                        "inconsistent total_chunks across blob chunks",
537                    ));
538                }
539                total_chunks = Some(chunk.total_chunks);
540                if chunk.seq != next_seq {
541                    return Err(Status::invalid_argument(format!(
542                        "expected blob chunk seq {next_seq}, got {}",
543                        chunk.seq
544                    )));
545                }
546                next_seq += 1;
547                assembled = assembled.saturating_add(chunk.data.len());
548                if assembled > MAX_BLOB_BYTES {
549                    return Err(Status::invalid_argument(format!(
550                        "assembled blob of {assembled} bytes exceeds the {} byte limit",
551                        MAX_BLOB_BYTES
552                    )));
553                }
554                parts.push(chunk.data);
555            }
556        }
557        let Some(blob_id) = blob_id else {
558            return Err(Status::invalid_argument("PutBlobChunks sent no chunks"));
559        };
560        if let Some(total) = total_chunks
561            && next_seq != total
562        {
563            return Err(Status::invalid_argument(format!(
564                "PutBlobChunks declared {total} chunks but delivered {next_seq}"
565            )));
566        }
567        let payload: Vec<u8> = parts.concat();
568        let id = StrHash::from_be_bytes(blob_id);
569        let service = self.clone();
570        let written = tokio::task::spawn_blocking(move || service.put_blob(id, &payload))
571            .await
572            .map_err(|join| blocking_join_error("registry", join))??;
573        Ok(Response::new(pb::PutBlobResponse {
574            bytes_written: written,
575        }))
576    }
577
578    /// Unary batched blob put: whole blobs (each already under the message
579    /// ceiling by the caller's framing) in one round trip. All-or-nothing —
580    /// see the inherent [`RegistryService::put_blobs`] for the validation
581    /// and atomic-write contract.
582    async fn put_blobs(
583        &self,
584        request: Request<pb::PutBlobsRequest>,
585    ) -> Result<Response<pb::PutBlobsResponse>, Status> {
586        let blobs = request
587            .into_inner()
588            .blobs
589            .into_iter()
590            .map(|blob| Ok((str_hash_from_bytes(&blob.id)?, Arc::from(blob.data))))
591            .collect::<Result<Vec<_>, waratah_proto::ProtoError>>()
592            .map_err(RegistryError::from)?;
593        let service = self.clone();
594        tokio::task::spawn_blocking(move || service.put_blobs(&blobs))
595            .await
596            .map_err(|join| blocking_join_error("registry", join))??;
597        Ok(Response::new(pb::PutBlobsResponse {}))
598    }
599
600    /// Batched server-streaming blob get: chunks of every requested id that
601    /// hits, packed under the frame budget by the side that knows payload
602    /// sizes. Misses send nothing — the stream simply ends.
603    async fn get_blobs(
604        &self,
605        request: Request<pb::GetBlobsRequest>,
606    ) -> Result<Response<Self::GetBlobsStream>, Status> {
607        let ids = request
608            .into_inner()
609            .blob_ids
610            .iter()
611            .map(|bytes| str_hash_from_bytes(bytes))
612            .collect::<Result<Vec<_>, waratah_proto::ProtoError>>()
613            .map_err(RegistryError::from)?;
614        let service = self.clone();
615        // The blocking lookup takes its own copy; the packing loop below
616        // zips the requested ids back against the positional results.
617        let request_ids = ids.clone();
618        let (tx, rx) = tokio::sync::mpsc::channel(2);
619        tokio::spawn(async move {
620            let result = tokio::task::spawn_blocking(move || service.get_blobs(&request_ids))
621                .await
622                .map_err(|join| blocking_join_error("registry", join))
623                .and_then(|inner| inner.map_err(Status::from));
624            let blobs = match result {
625                Ok(blobs) => blobs,
626                Err(status) => {
627                    let _ = tx.send(Err(status)).await;
628                    return;
629                }
630            };
631            // Pack hit payloads into frames under half the message ceiling —
632            // the same budget logic as ResolveStrings frames.
633            let mut frame: Vec<pb::BlobChunk> = Vec::new();
634            let mut frame_bytes = 0usize;
635            // Async send into the bounded channel: the producer task runs on
636            // the tokio runtime, so backpressure must be an await, never a
637            // blocking wait (`blocking_send` panics on a runtime worker).
638            async fn flush(
639                frame: &mut Vec<pb::BlobChunk>,
640                tx: &tokio::sync::mpsc::Sender<Result<pb::GetBlobsResponse, Status>>,
641            ) -> Result<(), ()> {
642                if frame.is_empty() {
643                    return Ok(());
644                }
645                let response = pb::GetBlobsResponse {
646                    chunks: std::mem::take(frame),
647                };
648                if tx.send(Ok(response)).await.is_ok() {
649                    Ok(())
650                } else {
651                    Err(())
652                }
653            }
654            // The wire blob id is the REQUESTED id, not one re-derived from
655            // the payload: re-deriving would re-hash every payload (tens of
656            // milliseconds each for segment-tier sizes) just to echo a value
657            // the caller already has. The payload's identity is still
658            // checked end-to-end — the client re-hashes the reassembled
659            // payload against this id, and the registry verifies each
660            // segment record's CRC32 at read time.
661            for (requested_id, payload) in ids.iter().zip(blobs) {
662                let Some(payload) = payload else { continue };
663                let blob_id = requested_id.to_be_bytes();
664                for (seq, chunk_data) in payload.chunks(BLOB_FRAME_CHUNK_BYTES).enumerate() {
665                    let chunk_bytes = chunk_data.len() + 40;
666                    if !frame.is_empty() && frame_bytes + chunk_bytes > RESOLVE_FRAME_BUDGET_BYTES {
667                        if flush(&mut frame, &tx).await.is_err() {
668                            return;
669                        }
670                        frame_bytes = 0;
671                    }
672                    frame_bytes += chunk_bytes;
673                    frame.push(pb::BlobChunk {
674                        blob_id: blob_id.to_vec(),
675                        seq: seq as u64,
676                        // Chunks here are transport framing of an
677                        // already-validated payload; `total_chunks` is the
678                        // count of this payload's frames. GetBlobs clients
679                        // re-validate that declared total and re-hash the
680                        // reassembled payload against the requested id.
681                        total_chunks: payload.len().div_ceil(BLOB_FRAME_CHUNK_BYTES) as u64,
682                        data: chunk_data.to_vec(),
683                    });
684                }
685            }
686            let _ = flush(&mut frame, &tx).await;
687        });
688        Ok(Response::new(ReceiverStream::new(rx)))
689    }
690
691    async fn register_strings(
692        &self,
693        request: Request<pb::RegisterStringsRequest>,
694    ) -> Result<Response<pb::RegisterStringsResponse>, Status> {
695        let request = request.into_inner();
696        let entries = request
697            .entries
698            .into_iter()
699            .map(|entry| Ok((str_hash_from_bytes(&entry.hash)?, entry.raw)))
700            .collect::<Result<Vec<_>, waratah_proto::ProtoError>>()
701            .map_err(RegistryError::from)?;
702        let service = self.clone();
703        let registered = tokio::task::spawn_blocking(move || service.register(entries))
704            .await
705            .map_err(|join| blocking_join_error("registry", join))??;
706        Ok(Response::new(pb::RegisterStringsResponse { registered }))
707    }
708
709    /// Stream resolved entries as byte-budgeted frames.
710    ///
711    /// Compute cannot predict response sizes (requests carry only 16-byte
712    /// hashes), so the registry — the side that knows the string sizes —
713    /// packs each frame with as many entries as fit
714    /// [`RESOLVE_FRAME_BUDGET_BYTES`] before emitting it. Frames carry
715    /// consecutive runs in request order, so the concatenation of all
716    /// frames' `values` is positionally aligned exactly like the former
717    /// unary response. Resolution is pipelined per [`RESOLVE_SUBBATCH`]
718    /// chunk with exactly one outstanding walk: the task awaits the current
719    /// chunk's lookup, starts the next chunk's lookup, then packs the
720    /// current results — so the next lookup runs during frame packing and
721    /// channel sends, while two lookups never overlap (interleaved seek
722    /// streams thrash disk locality). The bounded channel backpressures
723    /// packing against a slow consumer.
724    async fn resolve_strings(
725        &self,
726        request: Request<pb::ResolveStringsRequest>,
727    ) -> Result<Response<Self::ResolveStringsStream>, Status> {
728        let hashes = request
729            .into_inner()
730            .hashes
731            .iter()
732            .map(|bytes| str_hash_from_bytes(bytes))
733            .collect::<Result<Vec<_>, _>>()
734            .map_err(RegistryError::from)?;
735        let service = self.clone();
736        // Two outstanding frames: backpressure without pinning much memory.
737        let (tx, rx) = tokio::sync::mpsc::channel(2);
738        let mut trace = ResolveTrace::new(
739            service.trace,
740            hashes.len(),
741            iterator_readahead_bytes() / 1024,
742        );
743        tokio::spawn(async move {
744            let mut frame: Vec<pb::ResolvedString> = Vec::new();
745            let mut frame_bytes = 0usize;
746            let mut batches = hashes.chunks(RESOLVE_SUBBATCH);
747            // Pipeline with exactly one outstanding walk. The order inside
748            // the iteration is load-bearing: await the current lookup
749            // FIRST, start the next lookup SECOND, pack THIRD. Spawning
750            // before the await would run two seek streams over the CF at
751            // once and thrash disk locality. Each chunk's results come
752            // back positionally aligned to its own slice, so packing in
753            // `batches` order keeps the stream in request order.
754            let spawn_resolve = |batch: &[StrHash]| {
755                let service = service.clone();
756                let batch = batch.to_vec();
757                tokio::task::spawn_blocking(move || service.resolve(&batch))
758            };
759            let mut pending = batches.next().map(spawn_resolve);
760            while let Some(handle) = pending {
761                let lookup_started = Instant::now();
762                let resolved = match handle
763                    .await
764                    .map_err(|join| blocking_join_error("registry", join))
765                    .and_then(|result| result.map_err(Status::from))
766                {
767                    Ok(resolved) => resolved,
768                    Err(status) => {
769                        let _ = tx.send(Err(status)).await;
770                        return;
771                    }
772                };
773                trace.subbatch_done(lookup_started.elapsed(), &resolved);
774                pending = batches.next().map(spawn_resolve);
775                let pack_started = Instant::now();
776                for raw in resolved {
777                    // `None` (unknown hash) still occupies its position; it
778                    // costs only the framing overhead.
779                    let entry_bytes = raw.as_ref().map_or(RESOLVED_ENTRY_OVERHEAD_BYTES, |raw| {
780                        RESOLVED_ENTRY_OVERHEAD_BYTES + raw.len()
781                    });
782                    if !frame.is_empty() && frame_bytes + entry_bytes > RESOLVE_FRAME_BUDGET_BYTES {
783                        let entries = frame.len();
784                        let response = pb::ResolveStringsResponse {
785                            values: std::mem::take(&mut frame),
786                        };
787                        let send_started = Instant::now();
788                        if tx.send(Ok(response)).await.is_err() {
789                            return; // consumer dropped the stream
790                        }
791                        trace.frame_sent(entries, send_started.elapsed());
792                        frame_bytes = 0;
793                    }
794                    frame.push(pb::ResolvedString { raw });
795                    frame_bytes += entry_bytes;
796                }
797                trace.pack_wall_total += pack_started.elapsed();
798            }
799            if !frame.is_empty() {
800                let entries = frame.len();
801                let response = pb::ResolveStringsResponse { values: frame };
802                let send_started = Instant::now();
803                let _ = tx.send(Ok(response)).await;
804                trace.frame_sent(entries, send_started.elapsed());
805            }
806            trace.done();
807        });
808        Ok(Response::new(ReceiverStream::new(rx)))
809    }
810
811    async fn flush_memtables(
812        &self,
813        _request: Request<pb::FlushMemtablesRequest>,
814    ) -> Result<Response<pb::FlushMemtablesResponse>, Status> {
815        let service = self.clone();
816        tokio::task::spawn_blocking(move || RegistryService::flush_memtables(&service))
817            .await
818            .map_err(|join| blocking_join_error("registry", join))??;
819        Ok(Response::new(pb::FlushMemtablesResponse {}))
820    }
821
822    async fn compact_range(
823        &self,
824        _request: Request<pb::CompactRangeRequest>,
825    ) -> Result<Response<pb::CompactRangeResponse>, Status> {
826        let service = self.clone();
827        tokio::task::spawn_blocking(move || RegistryService::compact_range(&service))
828            .await
829            .map_err(|join| blocking_join_error("registry", join))??;
830        Ok(Response::new(pb::CompactRangeResponse {}))
831    }
832
833    async fn health(
834        &self,
835        _request: Request<pb::HealthRequest>,
836    ) -> Result<Response<pb::HealthResponse>, Status> {
837        let (warm_ready, warm_pending) = match &self.warm {
838            Some(warm) => {
839                // Past the max wait a stuck walk warns (stderr, once) and
840                // stops gating readiness — serving cold beats serving never.
841                let stuck = warm.stuck_warning().is_some();
842                (warm.is_done() || stuck, warm.pending())
843            }
844            None => (true, Vec::new()),
845        };
846        let (cache_capacity_bytes, cache_usage_bytes) = {
847            let guard = self
848                .registry
849                .read()
850                .map_err(|_| Status::internal("registry lock poisoned"))?;
851            guard.block_cache_bytes().unwrap_or((0, 0))
852        };
853        Ok(Response::new(pb::HealthResponse {
854            serving: true,
855            detail: String::new(),
856            warm_ready,
857            warm_pending,
858            cache_capacity_bytes,
859            cache_usage_bytes,
860        }))
861    }
862
863    async fn describe(
864        &self,
865        _request: Request<pb::RegistryDescribeRequest>,
866    ) -> Result<Response<pb::RegistryDescribeResponse>, Status> {
867        let service = self.clone();
868        let response = tokio::task::spawn_blocking(move || service.describe())
869            .await
870            .map_err(|join| blocking_join_error("registry", join))??;
871        Ok(Response::new(response))
872    }
873}
874
875fn proto_lsm(metrics: Option<LsmMetrics>) -> pb::LsmMetrics {
876    match metrics {
877        None => pb::LsmMetrics::default(),
878        Some(m) => pb::LsmMetrics {
879            estimate_live_data_bytes: m.estimate_live_data_bytes,
880            estimate_num_keys: m.estimate_num_keys,
881            total_sst_bytes: m.total_sst_bytes,
882            memtable_bytes: m.memtable_bytes,
883            num_running_compactions: m.num_running_compactions,
884            num_running_flushes: m.num_running_flushes,
885            open_total_puts: None,
886            compaction_event_count: None,
887            named_graph_count: None,
888            block_cache_capacity_bytes: m.block_cache_capacity_bytes,
889            block_cache_usage_bytes: m.block_cache_usage_bytes,
890        },
891    }
892}
893
894/// Bind a listener for the registry process (port `0` picks an ephemeral port).
895pub fn bind(addr: SocketAddr) -> Result<(TcpIncoming, SocketAddr), RegistryError> {
896    // NODELAY on accepted connections: `Server::builder().tcp_nodelay(..)`
897    // is IGNORED when serving via `serve_with_incoming` (this crate), so the
898    // flag must ride on the incoming. Without it a large response written
899    // after the headers sits in the Nagle buffer for the client's ~40ms
900    // delayed-ACK window.
901    let incoming = TcpIncoming::bind(addr)?.with_nodelay(Some(true));
902    let local = incoming.local_addr()?;
903    Ok((incoming, local))
904}
905
906/// Serve the `StringRegistry` service on `incoming` until the future is dropped.
907pub async fn serve(service: RegistryService, incoming: TcpIncoming) -> Result<(), RegistryError> {
908    Server::builder()
909        // NOTE: `.tcp_nodelay(true)` here is ignored for `serve_with_incoming`
910        // — the operative flag is on the `TcpIncoming` (see [`bind`]).
911        .add_service(
912            StringRegistryServer::new(service)
913                .max_decoding_message_size(waratah_proto::GRPC_MAX_MESSAGE_SIZE)
914                .max_encoding_message_size(waratah_proto::GRPC_MAX_MESSAGE_SIZE),
915        )
916        .serve_with_incoming(incoming)
917        .await?;
918    Ok(())
919}
920
921#[cfg(test)]
922mod tests {
923    use super::*;
924    use pretty_assertions::assert_eq;
925
926    #[tokio::test]
927    async fn health_reports_warm_readiness() {
928        let warm = waratah_storage::WarmState::new(["registry"]);
929        let service = RegistryService::new(4).with_warm_state(warm.clone());
930
931        let response = service
932            .health(Request::new(pb::HealthRequest::default()))
933            .await
934            .unwrap()
935            .into_inner();
936        assert!(!response.warm_ready);
937        assert_eq!(response.warm_pending, vec!["registry".to_owned()]);
938
939        warm.complete("registry");
940        let response = service
941            .health(Request::new(pb::HealthRequest::default()))
942            .await
943            .unwrap()
944            .into_inner();
945        assert!(response.warm_ready);
946        assert!(response.warm_pending.is_empty());
947    }
948
949    #[test]
950    fn warm_block_cache_is_a_noop_on_memory() {
951        let service = RegistryService::new(4);
952        let stats = service.warm_block_cache(0.5).unwrap();
953        assert!(stats.is_noop());
954    }
955
956    #[test]
957    fn register_then_resolve_reports_hits_and_misses() {
958        let service = RegistryService::new(4);
959        let iri = StrHash::new("http://ex/hasWeather");
960        assert_eq!(
961            service
962                .register([(iri, "http://ex/hasWeather".to_owned())])
963                .unwrap(),
964            1
965        );
966
967        let missing = StrHash::new("http://ex/never-registered");
968        let resolved = service.resolve(&[iri, missing]).unwrap();
969        assert_eq!(resolved[0].as_deref(), Some("http://ex/hasWeather"));
970        assert_eq!(resolved[1], None);
971    }
972
973    #[test]
974    fn resolve_only_touches_requested_hashes() {
975        let service = RegistryService::new(2);
976        let a = StrHash::new("http://ex/alice");
977        let b = StrHash::new("http://ex/bob");
978        service
979            .register([
980                (a, "http://ex/alice".to_owned()),
981                (b, "http://ex/bob".to_owned()),
982            ])
983            .unwrap();
984
985        assert_eq!(service.resolve(&[b]).unwrap().len(), 1);
986        assert_eq!(service.resolve(&[]).unwrap(), Vec::<Option<String>>::new());
987    }
988
989    #[test]
990    fn memory_flush_and_compact_are_noops() {
991        let service = RegistryService::new(2).with_blobs_memory().unwrap();
992        service.flush_memtables().unwrap();
993        service.compact_range().unwrap();
994    }
995
996    #[test]
997    fn disk_blob_store_round_trip_flush_and_compact() {
998        let dir = tempfile::tempdir().unwrap();
999        let service = RegistryService::new(2)
1000            .with_blobs(&dir.path().join("blobs"))
1001            .unwrap();
1002        let payload = b"disk-backed geometry".to_vec();
1003        let id = StrHash::from_bytes(&payload);
1004        assert_eq!(
1005            service.put_blob(id, &payload).unwrap(),
1006            payload.len() as u64
1007        );
1008        assert_eq!(
1009            service
1010                .get_blobs(&[id, StrHash::new("http://ex/missing")])
1011                .unwrap(),
1012            vec![Some(payload), None]
1013        );
1014        service.flush_memtables().unwrap();
1015        service.compact_range().unwrap();
1016    }
1017
1018    #[test]
1019    fn memory_registry_blob_round_trip_and_miss() {
1020        // The default in-memory registry mode attaches a RAM-backed blob
1021        // store so geo writes work without a data dir.
1022        let service = RegistryService::new(2).with_blobs_memory().unwrap();
1023        let payload = b"geometry EWKB payload".to_vec();
1024        let id = StrHash::from_bytes(&payload);
1025        assert_eq!(
1026            service.put_blob(id, &payload).unwrap(),
1027            payload.len() as u64
1028        );
1029        let missing = StrHash::new("http://ex/not-a-blob");
1030        assert_eq!(
1031            service.get_blobs(&[id, missing]).unwrap(),
1032            vec![Some(payload), None]
1033        );
1034    }
1035
1036    fn blob(payload: &[u8]) -> (StrHash, Arc<[u8]>) {
1037        (StrHash::from_bytes(payload), Arc::from(payload.to_vec()))
1038    }
1039
1040    #[test]
1041    fn put_blobs_stores_every_blob() {
1042        let service = RegistryService::new(2).with_blobs_memory().unwrap();
1043        let (a_id, a) = blob(b"blob-alpha");
1044        let (b_id, b) = blob(b"blob-beta");
1045        service
1046            .put_blobs(&[(a_id, Arc::clone(&a)), (b_id, Arc::clone(&b))])
1047            .unwrap();
1048        let got = service.get_blobs(&[a_id, b_id]).unwrap();
1049        assert_eq!(got, vec![Some(a.to_vec()), Some(b.to_vec())]);
1050    }
1051
1052    #[test]
1053    fn put_blobs_rejects_an_empty_batch() {
1054        let service = RegistryService::new(2).with_blobs_memory().unwrap();
1055        let error = service.put_blobs(&[]).unwrap_err();
1056        assert!(matches!(error, RegistryError::EmptyBlobBatch));
1057    }
1058
1059    #[test]
1060    fn put_blobs_is_all_or_nothing_on_hash_mismatch() {
1061        let service = RegistryService::new(2).with_blobs_memory().unwrap();
1062        // `a` is pre-existing (committed by an earlier put); the batch also
1063        // carries `b`, then fails on `c`'s bad content hash.
1064        let (a_id, a) = blob(b"pre-existing");
1065        service.put_blob(a_id, &a).unwrap();
1066        let (b_id, b) = blob(b"newly-written");
1067        let (c_id, _) = blob(b"doomed");
1068        let bad = (c_id, Arc::from(b"mismatched bytes".to_vec()));
1069        let error = service
1070            .put_blobs(&[(a_id, Arc::clone(&a)), (b_id, Arc::clone(&b)), bad])
1071            .unwrap_err();
1072        assert!(matches!(error, RegistryError::BlobHashMismatch { id } if id == c_id));
1073
1074        let got = service.get_blobs(&[a_id, b_id, c_id]).unwrap();
1075        // Validation runs before any write: the pre-existing blob stays,
1076        // and neither the batched blob nor the rejected one was written.
1077        assert_eq!(got[0], Some(a.to_vec()));
1078        assert_eq!(got[1], None);
1079        assert_eq!(got[2], None);
1080    }
1081
1082    #[test]
1083    fn put_blobs_validates_content_hashes_before_writing() {
1084        let service = RegistryService::new(2).with_blobs_memory().unwrap();
1085        let (id, _payload) = blob(b"real payload");
1086        let impostor = (id, Arc::from(b"payload that does not hash to id".to_vec()));
1087        let error = service.put_blobs(&[impostor]).unwrap_err();
1088        assert!(matches!(
1089            error,
1090            RegistryError::BlobHashMismatch { id: rejected } if rejected == id
1091        ));
1092        assert_eq!(service.get_blobs(&[id]).unwrap(), vec![None]);
1093    }
1094
1095    #[tokio::test]
1096    async fn concurrent_register_and_resolve_succeed() {
1097        // Four concurrent writers serialize on the write guard while any
1098        // number of resolvers overlap under read guards; nothing deadlocks
1099        // and every registered hash resolves.
1100        let service = RegistryService::new(4);
1101        let mut writers = Vec::new();
1102        for writer in 0..4 {
1103            let service = service.clone();
1104            writers.push(tokio::task::spawn(async move {
1105                let entries: Vec<(StrHash, String)> = (0..16)
1106                    .map(|i| {
1107                        let raw = format!("http://ex/w{writer}/i{i}");
1108                        (StrHash::new(&raw), raw)
1109                    })
1110                    .collect();
1111                service.register(entries).unwrap()
1112            }));
1113        }
1114        for handle in writers {
1115            assert_eq!(handle.await.unwrap(), 16);
1116        }
1117        let hashes: Vec<StrHash> = (0..4)
1118            .flat_map(|writer| {
1119                (0..16).map(move |i| StrHash::new(&format!("http://ex/w{writer}/i{i}")))
1120            })
1121            .collect();
1122        let resolved = service.resolve(&hashes).unwrap();
1123        assert_eq!(resolved.len(), 64);
1124        assert!(resolved.iter().all(|value| value.is_some()));
1125    }
1126}