1#![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#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct RegistryIdentity {
48 pub node_id: String,
50 pub listen: String,
52 pub data_dir: String,
54 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
69pub const DEFAULT_SHARD_COUNT: usize = 8;
71
72pub const MAX_REGISTERED_STRING_BYTES: usize = 1024 * 1024;
83
84const BLOB_FRAME_CHUNK_BYTES: usize = 1024 * 1024;
90
91pub const RESOLVE_FRAME_BUDGET_BYTES: usize = GRPC_MAX_MESSAGE_SIZE / 2;
97
98const RESOLVE_SUBBATCH: usize = 4096;
113
114const RESOLVED_ENTRY_OVERHEAD_BYTES: usize = 16;
117
118const SEND_BLOCKED_THRESHOLD: Duration = Duration::from_millis(1);
120
121#[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 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 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 fn done(&self) {
211 if !self.enabled {
212 return;
213 }
214 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#[derive(Debug, Clone)]
240pub struct RegistryService {
241 registry: Arc<RwLock<Registry>>,
245 trace: bool,
248 identity: RegistryIdentity,
249 blobs_reg: Option<Arc<BlobStore>>,
254 warm: Option<Arc<waratah_storage::WarmState>>,
258}
259
260impl RegistryService {
261 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 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 pub fn with_warm_state(mut self, warm: Arc<waratah_storage::WarmState>) -> Self {
290 self.warm = Some(warm);
291 self
292 }
293
294 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 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 pub fn blob_store(&self) -> Option<&BlobStore> {
313 self.blobs_reg.as_deref()
314 }
315
316 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 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 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 pub fn with_trace(mut self, enabled: bool) -> Self {
358 self.trace = enabled;
359 self
360 }
361
362 pub fn with_identity(mut self, identity: RegistryIdentity) -> Self {
364 self.identity = identity;
365 self
366 }
367
368 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 pub fn shard_count(&self) -> Result<usize, RegistryError> {
401 Ok(self.lock_read()?.shard_count())
402 }
403
404 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 pub fn resolve(&self, hashes: &[StrHash]) -> Result<Vec<Option<String>>, RegistryError> {
426 Ok(self.lock_read()?.lookup_many(hashes)?)
427 }
428
429 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 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 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 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 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 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 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 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 let mut frame: Vec<pb::BlobChunk> = Vec::new();
634 let mut frame_bytes = 0usize;
635 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 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 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 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 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 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 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; }
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 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
894pub fn bind(addr: SocketAddr) -> Result<(TcpIncoming, SocketAddr), RegistryError> {
896 let incoming = TcpIncoming::bind(addr)?.with_nodelay(Some(true));
902 let local = incoming.local_addr()?;
903 Ok((incoming, local))
904}
905
906pub async fn serve(service: RegistryService, incoming: TcpIncoming) -> Result<(), RegistryError> {
908 Server::builder()
909 .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 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 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 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 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}