rapace-registry 0.5.0

Service registry with schema support for rapace RPC
Documentation
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
# Service Discovery Design

## Problem Statement

rapace-registry exists but is **half-baked** for actual service discovery. Current issues:

1. **No runtime registry** - `ServiceRegistry` is built at codegen time but not exposed globally
2. **No introspection** - Can't query "what services does this cell provide?"
3. **No announcement** - Cells don't advertise their capabilities when connecting
4. **Poor dispatching** - `DispatcherBuilder` just tries services linearly until one doesn't return `Unimplemented`
5. **No capability negotiation** - Host doesn't know what a cell can do until it tries to call it
6. **No versioning** - Can't handle version mismatches between host and cell

This makes debugging hard ("why isn't my RPC working?") and prevents useful features like:
- Runtime service browser/explorer
- Dynamic routing based on available services
- Health checks ("is service X available?")
- Hindsight integration (method name → ID mapping for traces)

---

## Current State

### What We Have

**`rapace-registry`**:
- `ServiceRegistry` with method_id → method name lookup
- `MethodEntry` with schemas (facet shapes), docs, arg info
- Sequential `MethodId` allocation (unique across services)
- Already captures all the metadata we need!

**`rapace-macros`**:
- `#[rapace::service]` generates client/server code
- Method IDs are computed at codegen time (FNV-1a hash)
- No automatic registration happens

**`rapace-cell`**:
- `DispatcherBuilder` for multi-service cells
- Linear search through services (inefficient + poor error messages)

### What's Missing

1. **Global registry access** - No way to get the registry at runtime
2. **Auto-registration** - Generated code doesn't register itself
3. **Introspection service** - Can't query available services via RPC
4. **Host-side discovery** - Host can't enumerate what services a cell provides

---

## MVP Proposal

### Goals

1. **Auto-registration** - Services register themselves when the server is created
2.**Global registry** - Thread-local or process-level registry accessible at runtime
3.**Introspection RPC** - Standard service for querying available services
4.**Better dispatching** - Use registry for fast method_id → service routing
5.**Hindsight integration** - Method name lookup for distributed tracing

### Non-Goals (Post-MVP)

- ❌ Capability negotiation protocol
- ❌ Service versioning
- ❌ Dynamic service addition/removal
- ❌ Cross-cell service discovery (service mesh)

---

## Design

### 1. Global Registry

Add a **process-level registry** that all services register into:

```rust
// In rapace-registry/src/lib.rs

use std::sync::LazyLock;
use parking_lot::RwLock;

/// Global process-level service registry.
///
/// All services automatically register here when their server is created.
static GLOBAL_REGISTRY: LazyLock<RwLock<ServiceRegistry>> =
    LazyLock::new(|| RwLock::new(ServiceRegistry::new()));

impl ServiceRegistry {
    /// Get a reference to the global registry.
    pub fn global() -> &'static RwLock<ServiceRegistry> {
        &GLOBAL_REGISTRY
    }

    /// Get the global registry (convenience for read access).
    pub fn with_global<F, R>(f: F) -> R
    where
        F: FnOnce(&ServiceRegistry) -> R,
    {
        f(&GLOBAL_REGISTRY.read())
    }

    /// Modify the global registry (convenience for write access).
    pub fn with_global_mut<F, R>(f: F) -> R
    where
        F: FnOnce(&mut ServiceRegistry) -> R,
    {
        f(&mut GLOBAL_REGISTRY.write())
    }
}
```

**Why process-level?**
- Simple - no Arc/lifetime complexity
- Works for both host and cell processes
- Thread-safe via RwLock
- LazyLock ensures single initialization

**Alternative considered**: Thread-local storage
- Rejected: Doesn't work across threads (RPC handlers often run on tokio thread pool)

### 2. Auto-Registration

Modify the `#[rapace::service]` macro to generate registration code:

```rust
// Generated by #[rapace::service] for trait MyService
impl MyServiceServer {
    /// Auto-register this service in the global registry.
    ///
    /// Called automatically when the server is created.
    fn __register() {
        use rapace_registry::ServiceRegistry;
        use once_cell::sync::OnceCell;

        static REGISTERED: OnceCell<()> = OnceCell::new();

        REGISTERED.get_or_init(|| {
            ServiceRegistry::with_global_mut(|registry| {
                let mut builder = registry.register_service(
                    "MyService",
                    "Service documentation from /// comments",
                );

                builder.add_method(
                    "my_method",
                    "Method documentation",
                    vec![
                        ArgInfo { name: "arg1", type_name: "String" },
                        ArgInfo { name: "arg2", type_name: "i32" },
                    ],
                    <MyMethodRequest as Facet>::SHAPE,
                    <MyMethodResponse as Facet>::SHAPE,
                );

                builder.finish();
            });
        });
    }

    pub fn new(service: impl MyService + 'static) -> Self {
        Self::__register(); // Auto-register on construction

        Self {
            service: Arc::new(service),
        }
    }
}
```

**Key insight**: Use `OnceCell` to ensure registration happens exactly once per service type, even if multiple instances are created.

### 3. Introspection Service

Define a **standard service** that all cells can optionally implement:

```rust
// In rapace-registry/src/introspection.rs

use facet::Facet;

/// Information about a registered service.
#[derive(Clone, Debug, Facet)]
pub struct ServiceInfo {
    /// Service name (e.g., "Calculator").
    pub name: String,
    /// Service documentation.
    pub doc: String,
    /// Methods provided by this service.
    pub methods: Vec<MethodInfo>,
}

/// Information about a method.
#[derive(Clone, Debug, Facet)]
pub struct MethodInfo {
    /// Method ID (for debugging/logging).
    pub id: u32,
    /// Method name (e.g., "add").
    pub name: String,
    /// Full qualified name (e.g., "Calculator.add").
    pub full_name: String,
    /// Method documentation.
    pub doc: String,
    /// Argument names and types.
    pub args: Vec<ArgInfo>,
    /// Whether this is a streaming method.
    pub is_streaming: bool,
}

/// Argument metadata.
#[derive(Clone, Debug, Facet)]
pub struct ArgInfo {
    pub name: String,
    pub type_name: String,
}

/// Standard introspection service.
///
/// Implement this service to expose runtime service information.
#[rapace::service]
pub trait ServiceIntrospection {
    /// List all services registered in this process.
    async fn list_services(&self) -> Vec<ServiceInfo>;

    /// Describe a specific service by name.
    async fn describe_service(&self, name: String) -> Option<ServiceInfo>;

    /// Check if a method ID is supported.
    async fn has_method(&self, method_id: u32) -> bool;
}
```

**Default implementation**:

```rust
// In rapace-registry/src/introspection.rs

/// Default implementation that reads from the global registry.
#[derive(Clone)]
pub struct DefaultServiceIntrospection;

impl ServiceIntrospection for DefaultServiceIntrospection {
    async fn list_services(&self) -> Vec<ServiceInfo> {
        ServiceRegistry::with_global(|registry| {
            registry
                .iter_services()
                .map(|service| ServiceInfo {
                    name: service.name.to_string(),
                    doc: service.doc.clone(),
                    methods: service
                        .iter_methods()
                        .map(|method| MethodInfo {
                            id: method.id.0,
                            name: method.name.to_string(),
                            full_name: method.full_name.clone(),
                            doc: method.doc.clone(),
                            args: method
                                .args
                                .iter()
                                .map(|arg| ArgInfo {
                                    name: arg.name.to_string(),
                                    type_name: arg.type_name.to_string(),
                                })
                                .collect(),
                            is_streaming: method.is_streaming,
                        })
                        .collect(),
                })
                .collect()
        })
    }

    async fn describe_service(&self, name: String) -> Option<ServiceInfo> {
        self.list_services()
            .await
            .into_iter()
            .find(|s| s.name == name)
    }

    async fn has_method(&self, method_id: u32) -> bool {
        ServiceRegistry::with_global(|registry| {
            registry.method_by_id(MethodId(method_id)).is_some()
        })
    }
}
```

### 4. Better Dispatching

Improve `DispatcherBuilder` to use the registry for routing:

```rust
// In rapace-cell/src/lib.rs

impl DispatcherBuilder {
    pub fn build(self) -> impl Fn(...) -> ... {
        let services = Arc::new(self.services);

        move |_channel_id, method_id, payload| {
            let services = services.clone();
            Box::pin(async move {
                // NEW: Use registry to find which service handles this method
                if let Some(method) = ServiceRegistry::with_global(|reg| {
                    reg.method_by_id(MethodId(method_id)).map(|m| m.full_name.clone())
                }) {
                    tracing::debug!(
                        method_id,
                        method_name = %method,
                        "Dispatching to registered method"
                    );
                }

                // Try each service until one handles it
                for service in services.iter() {
                    let result = service.dispatch(method_id, &payload).await;

                    if !matches!(
                        &result,
                        Err(RpcError::Status {
                            code: ErrorCode::Unimplemented,
                            ..
                        })
                    ) {
                        return result;
                    }
                }

                // No service handled this method - use registry for better error
                let error_msg = ServiceRegistry::with_global(|reg| {
                    if let Some(method) = reg.method_by_id(MethodId(method_id)) {
                        format!(
                            "Method '{}' (id={}) exists but is not implemented by any registered service",
                            method.full_name, method_id
                        )
                    } else {
                        format!(
                            "Unknown method_id: {} (not registered in global registry)",
                            method_id
                        )
                    }
                });

                Err(RpcError::Status {
                    code: ErrorCode::Unimplemented,
                    message: error_msg,
                })
            })
        }
    }
}
```

**Improvement**: Error messages now include method names instead of just IDs!

### 5. Cell Integration

Make it easy for cells to expose introspection:

```rust
// In rapace-cell/src/lib.rs

impl DispatcherBuilder {
    /// Add introspection service to this cell.
    ///
    /// This exposes the `ServiceIntrospection` service, allowing callers to
    /// query what services and methods this cell provides.
    pub fn with_introspection(self) -> Self {
        use rapace_registry::introspection::{
            DefaultServiceIntrospection, ServiceIntrospectionServer,
        };

        let introspection = DefaultServiceIntrospection;
        let server = ServiceIntrospectionServer::new(introspection);
        self.add_service(server)
    }
}
```

**Usage**:

```rust
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    rapace_cell::run_multi(|builder| {
        builder
            .add_service(MyServiceServer::new(my_impl))
            .add_service(AnotherServiceServer::new(another_impl))
            .with_introspection() // ← Add introspection!
    })
    .await?;
    Ok(())
}
```

---

## Implementation Plan

### Phase 1: Global Registry (1-2 hours)

**Files**:
- `rapace-registry/src/lib.rs`

**Changes**:
1. Add `GLOBAL_REGISTRY` static
2. Add `ServiceRegistry::global()`, `with_global()`, `with_global_mut()`
3. Add tests

**Test**:
```rust
#[test]
fn test_global_registry() {
    ServiceRegistry::with_global_mut(|reg| {
        let mut builder = reg.register_service("TestService", "Test");
        builder.add_method("test", "", vec![], &DUMMY_SHAPE, &DUMMY_SHAPE);
        builder.finish();
    });

    ServiceRegistry::with_global(|reg| {
        assert_eq!(reg.service_count(), 1);
        assert!(reg.service("TestService").is_some());
    });
}
```

### Phase 2: Auto-Registration (2-3 hours)

**Files**:
- `rapace-macros/src/lib.rs`

**Changes**:
1. Modify `#[rapace::service]` codegen to generate `__register()` method
2. Call `__register()` in generated `new()` constructors
3. Use `OnceCell` to prevent duplicate registration
4. Add dependency on `rapace-registry`

**Test**: Manually verify generated code

### Phase 3: Introspection Service (1-2 hours)

**Files**:
- `rapace-registry/src/introspection.rs` (new)
- `rapace-registry/src/lib.rs` (export module)

**Changes**:
1. Define `ServiceInfo`, `MethodInfo`, `ArgInfo` types
2. Define `ServiceIntrospection` trait (use `#[rapace::service]`)
3. Implement `DefaultServiceIntrospection`
4. Add tests

**Test**:
```rust
#[tokio::test]
async fn test_introspection() {
    let intro = DefaultServiceIntrospection;
    let services = intro.list_services().await;
    assert!(services.len() > 0);
}
```

### Phase 4: Better Dispatching (1 hour)

**Files**:
- `rapace-cell/src/lib.rs`

**Changes**:
1. Update `DispatcherBuilder::build()` to use registry for error messages
2. Add `with_introspection()` helper
3. Add optional tracing for method dispatch

### Phase 5: Integration & Testing (1-2 hours)

**Files**:
- `demos/*/` - Update demos to use introspection
- `rapace-explorer/` - Use introspection to list available services

**Tasks**:
1. Update at least one demo to expose introspection
2. Test end-to-end: connect to cell, call `list_services()`, verify results
3. Update docs with examples

---

## Example: Full Flow

### Cell Code

```rust
use rapace_cell::run_multi;

// Service implementation
struct CalculatorImpl;

#[rapace::async_trait]
impl Calculator for CalculatorImpl {
    async fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    run_multi(|builder| {
        builder
            .add_service(CalculatorServer::new(CalculatorImpl))
            .with_introspection() // ← Auto-exposes ServiceIntrospection
    })
    .await?;
    Ok(())
}
```

### Host Code (Debugging/Exploration)

```rust
use rapace_registry::introspection::{ServiceIntrospectionClient};

// Connect to cell
let session = connect_to_cell("/tmp/cell.shm").await?;
let intro_client = ServiceIntrospectionClient::new(session.clone());

// Query available services
let services = intro_client.list_services().await?;
for service in services {
    println!("Service: {}", service.name);
    for method in service.methods {
        println!("  - {}: {}", method.name, method.doc);
        for arg in method.args {
            println!("      {}: {}", arg.name, arg.type_name);
        }
    }
}
```

**Output**:
```
Service: Calculator
  - add: Add two numbers together
      a: i32
      b: i32
Service: ServiceIntrospection
  - list_services: List all services in this process
  - describe_service: Get details about a specific service
      name: String
```

### Hindsight Integration

```rust
// In hindsight-server, when receiving a span:
if let Some(method_name) = ServiceRegistry::with_global(|reg| {
    reg.method_by_id(MethodId(span.method_id))
        .map(|m| m.full_name.clone())
}) {
    span.set_attribute("rpc.method", method_name);
}
```

---

## Benefits

### For Developers

- **Better errors**: "Unknown method `Calculator.add`" instead of "Unknown method_id: 12345"
- **Runtime inspection**: Query what a cell can do without reading code
- **Easier debugging**: Hindsight traces show method names, not IDs

### For Hindsight

- Method name → ID mapping without manual configuration
- Service-level filtering ("only trace Calculator service")
- Human-readable trace views

### For Future Features

- Service mesh (discover services across multiple cells)
- Load balancing (route to cells that have service X)
- Health checks (is service X registered and healthy?)
- Version negotiation (ensure host and cell are compatible)

---

## Open Questions

1. **Should introspection be mandatory or optional?**
   - **Proposal**: Optional but enabled by default in `rapace-cell`
   - Cells can opt-out if they want minimal overhead

2. **Should we support service removal?**
   - **Proposal**: Not in MVP (static registration only)
   - Future: Add `ServiceRegistry::unregister_service()`

3. **How to handle method ID collisions?**
   - **Current**: FNV-1a hash of full method name
   - **Risk**: Collisions are theoretically possible
   - **Mitigation**: Registry can detect and panic on collision

4. **Thread safety of global registry?**
   - **Proposal**: RwLock for read-heavy workload
   - Most operations are reads (method lookups during dispatch)
   - Writes only happen at server creation time (rare)

---

## Alternatives Considered

### 1. Thread-Local Registry

**Rejected**: Doesn't work for multi-threaded RPC handlers.

### 2. Explicit Registry Passing

```rust
let registry = ServiceRegistry::new();
MyServiceServer::new_with_registry(impl, &registry);
```

**Rejected**: Too much boilerplate, easy to forget.

### 3. Discovery via Separate RPC

Instead of a service, use a separate RPC endpoint for discovery.

**Rejected**: Less idiomatic - services are the primitive in rapace.

### 4. Code Generation Only (No Runtime Registry)

Just generate service metadata at build time, no runtime component.

**Rejected**: Can't support Hindsight integration or runtime introspection.

---

## Success Criteria

MVP is successful when:

1. ✅ All generated services auto-register in global registry
2.`ServiceIntrospection` works end-to-end (cell advertises, host queries)
3. ✅ Error messages show method names instead of IDs
4. ✅ Hindsight can map method_id → method name without configuration
5. ✅ At least one demo uses introspection
6. ✅ Documentation is updated with examples

---

**Estimated Total Time**: 8-12 hours

**Priority**: Medium (useful but not blocking Hindsight MVP)

**Dependencies**: None (purely additive changes)