repe 3.8.0

Rust implementation of the REPE RPC protocol (JSON-focused)
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
use crate::constants::{BodyFormat, ErrorCode};
use crate::message::Message;
use crate::peer::CallContext;
use serde_json::{Map, Value, json};
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

type RegistryFunction = Arc<dyn RegistryCallable>;

#[derive(Debug, thiserror::Error)]
pub enum RegistryError {
    #[error("invalid JSON pointer `{pointer}`")]
    InvalidPointer { pointer: String },
    #[error("path not found `{path}`")]
    PathNotFound { path: String },
    #[error("array index `{segment}` is invalid at `{path}`")]
    InvalidArrayIndex { path: String, segment: String },
    #[error("array index `{segment}` out of bounds at `{path}`")]
    ArrayIndexOutOfBounds { path: String, segment: String },
    #[error("root write requires a JSON object body")]
    RootWriteRequiresObject,
    #[error("registry body format `{format}` is unsupported")]
    UnsupportedBodyFormat { format: u16 },
    #[error("registry body is not valid UTF-8")]
    InvalidUtf8(#[source] std::str::Utf8Error),
    #[error("registry JSON parse error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("registry BEVE parse error: {0}")]
    Beve(#[from] beve::Error),
    #[error("{message}")]
    Execution { code: ErrorCode, message: String },
}

impl RegistryError {
    pub fn code(&self) -> ErrorCode {
        match self {
            RegistryError::InvalidPointer { .. }
            | RegistryError::PathNotFound { .. }
            | RegistryError::InvalidArrayIndex { .. }
            | RegistryError::ArrayIndexOutOfBounds { .. } => ErrorCode::MethodNotFound,
            RegistryError::RootWriteRequiresObject => ErrorCode::InvalidBody,
            RegistryError::UnsupportedBodyFormat { .. }
            | RegistryError::InvalidUtf8(_)
            | RegistryError::Json(_)
            | RegistryError::Beve(_) => ErrorCode::InvalidBody,
            RegistryError::Execution { code, .. } => *code,
        }
    }
}

/// A function or object that the registry dispatches to.
///
/// Handlers receive a [`CallContext`] alongside the request body so that
/// peer-aware handlers can push notify messages back to the calling peer.
/// Handlers that don't care about the context can register a plain
/// `Fn(Option<Value>) -> Result<Value, ...>` closure: the blanket impl
/// below ignores the context for them.
///
/// To register a closure that *does* want the context, wrap it with
/// [`WithContext`]:
///
/// ```ignore
/// registry.register_function("/run", WithContext(|ctx, params| {
///     if let Some(peer) = ctx.peer() {
///         peer.send_notify("/progress", NotifyBody::Json(b"{}".to_vec())).ok();
///     }
///     Ok(serde_json::json!({"status": "ok"}))
/// }))?;
/// ```
pub trait RegistryCallable: Send + Sync {
    fn call(&self, ctx: &CallContext, params: Option<Value>) -> Result<Value, (ErrorCode, String)>;
}

impl<F> RegistryCallable for F
where
    F: Fn(Option<Value>) -> Result<Value, (ErrorCode, String)> + Send + Sync + 'static,
{
    fn call(
        &self,
        _ctx: &CallContext,
        params: Option<Value>,
    ) -> Result<Value, (ErrorCode, String)> {
        (self)(params)
    }
}

/// Newtype wrapper that adapts an `Fn(&CallContext, Option<Value>) -> ...`
/// closure into a [`RegistryCallable`].
///
/// Rust's coherence rules forbid two blanket impls on different `Fn`
/// signatures for the same trait, so context-aware closures need a marker.
/// `WithContext` is that marker; pass it to
/// [`Registry::register_function`] like any other handler.
pub struct WithContext<F>(pub F);

impl<F> RegistryCallable for WithContext<F>
where
    F: Fn(&CallContext, Option<Value>) -> Result<Value, (ErrorCode, String)>
        + Send
        + Sync
        + 'static,
{
    fn call(&self, ctx: &CallContext, params: Option<Value>) -> Result<Value, (ErrorCode, String)> {
        (self.0)(ctx, params)
    }
}

struct RegistryState {
    root: Value,
    /// Callable entries keyed by their canonical JSON Pointer string (the
    /// `canonical_pointer` form computed once at registration). Keying on the
    /// canonical `String` rather than the parsed `Vec<String>` segments lets
    /// dispatch probe the map with a borrowed `&str`: for the escape-free
    /// common case the wire pointer already *is* its own canonical key, so a
    /// function call resolves without allocating the per-segment `Vec<String>`
    /// + `String`s that routing previously required on every request.
    functions: HashMap<String, RegistryFunction>,
}

impl Default for RegistryState {
    fn default() -> Self {
        Self {
            root: Value::Object(Map::new()),
            functions: HashMap::new(),
        }
    }
}

/// Dynamic registry that serves values and callable entries by JSON pointer.
///
/// Request semantics:
/// - Empty body => READ value at pointer.
/// - Non-empty body + function target => CALL function.
/// - Non-empty body + non-function target => WRITE value.
#[derive(Default)]
pub struct Registry {
    state: RwLock<RegistryState>,
}

impl Registry {
    pub fn new() -> Self {
        Self::default()
    }

    /// Replace the root JSON value stored by the registry.
    pub fn set_root(&self, value: Value) {
        let mut state = self.write_state();
        state.root = value;
    }

    /// Register or replace a value at `path`, creating missing object parents.
    pub fn register_value(&self, path: &str, value: Value) -> Result<(), RegistryError> {
        let mut state = self.write_state();
        let segments = parse_registration_path(path)?;
        if segments.is_empty() {
            state.root = value;
            return Ok(());
        }

        let parent = ensure_object_parent(&mut state.root, &segments)?;
        parent.insert(segments.last().unwrap().clone(), value);
        Ok(())
    }

    /// Merge object fields into the root.
    pub fn merge_root(&self, object: Map<String, Value>) -> Result<(), RegistryError> {
        let mut state = self.write_state();
        let root = ensure_object_root(&mut state.root)?;
        for (key, value) in object {
            root.insert(key, value);
        }
        Ok(())
    }

    /// Merge object fields into an object at `path`.
    pub fn merge_at(&self, path: &str, object: Map<String, Value>) -> Result<(), RegistryError> {
        let mut state = self.write_state();
        let segments = parse_registration_path(path)?;
        if segments.is_empty() {
            let root = ensure_object_root(&mut state.root)?;
            for (key, value) in object {
                root.insert(key, value);
            }
            return Ok(());
        }

        let target = resolve_mut(&mut state.root, &segments)?;
        let map = target
            .as_object_mut()
            .ok_or_else(|| RegistryError::PathNotFound {
                path: canonical_pointer(&segments),
            })?;
        for (key, value) in object {
            map.insert(key, value);
        }
        Ok(())
    }

    /// Register a callable at `path`, creating missing object parents for discoverability.
    pub fn register_function(
        &self,
        path: &str,
        function: impl RegistryCallable + 'static,
    ) -> Result<(), RegistryError> {
        self.register_function_arc(path, Arc::new(function))
    }

    pub fn register_function_arc(
        &self,
        path: &str,
        function: Arc<dyn RegistryCallable>,
    ) -> Result<(), RegistryError> {
        let mut state = self.write_state();
        let segments = parse_registration_path(path)?;
        if segments.is_empty() {
            return Err(RegistryError::InvalidPointer {
                pointer: path.to_string(),
            });
        }
        let _ = ensure_object_parent(&mut state.root, &segments)?;
        state
            .functions
            .insert(canonical_pointer(&segments), function);
        Ok(())
    }

    pub fn read_value(&self, pointer: &str) -> Result<Value, RegistryError> {
        let state = self.read_state();
        let segments = parse_pointer(pointer)?;
        resolve_ref(&state.root, &segments).cloned()
    }

    /// Dispatch a request to a registered value or function.
    ///
    /// Equivalent to [`Registry::dispatch_with_ctx`] with a
    /// [`CallContext::detached`] context. Use this for direct in-process
    /// dispatches where there's no calling peer (tests, batch fixups,
    /// etc.). Servers that want to surface a [`PeerHandle`](crate::PeerHandle)
    /// to handlers should call `dispatch_with_ctx` instead.
    pub fn dispatch(&self, pointer: &str, body: Option<Value>) -> Result<Value, RegistryError> {
        let ctx = CallContext::detached(pointer);
        self.dispatch_with_ctx(pointer, body, &ctx)
    }

    /// Dispatch a request to a registered value or function, threading
    /// `ctx` through to any registered [`RegistryCallable`].
    ///
    /// Reads (`body == None`) and writes (`body == Some(...)` against a
    /// non-function target) ignore the context; only function calls use
    /// it. The pointer used for routing is the `pointer` argument; the
    /// context's `method()` is informational and may differ (e.g. a
    /// router that strips a path prefix before dispatching).
    pub fn dispatch_with_ctx(
        &self,
        pointer: &str,
        body: Option<Value>,
        ctx: &CallContext,
    ) -> Result<Value, RegistryError> {
        // Resolve the function-lookup key up front. For the escape-free common
        // case `key` borrows `pointer` directly (no allocation); only escaped
        // pointers fall back to an owned canonical string. Crucially, the
        // per-segment `Vec<String>` from `parse_pointer` is now allocated only
        // on the value-tree fallback paths below, never on a function call.
        let key = canonical_key(pointer)?;

        if body.is_none() {
            let state = self.read_state();
            if state.functions.contains_key(key.as_ref()) {
                return Ok(json!({
                    "type": "function",
                    "path": key.as_ref(),
                }));
            }
            let segments = parse_pointer(pointer)?;
            return resolve_ref(&state.root, &segments).cloned();
        }

        let payload = body.unwrap();

        let function = {
            let state = self.read_state();
            state.functions.get(key.as_ref()).cloned()
        };
        if let Some(f) = function {
            return f
                .call(ctx, Some(payload))
                .map_err(|(code, message)| RegistryError::Execution { code, message });
        }

        let segments = parse_pointer(pointer)?;
        let mut state = self.write_state();
        if segments.is_empty() {
            let Value::Object(object) = payload else {
                return Err(RegistryError::RootWriteRequiresObject);
            };
            let root = ensure_object_root(&mut state.root)?;
            for (key, value) in object {
                root.insert(key, value);
            }
            return Ok(json!({
                "status": "ok",
                "path": "/",
            }));
        }

        set_pointer(&mut state.root, &segments, payload)?;
        Ok(json!({
            "status": "ok",
            "path": canonical_pointer(&segments),
        }))
    }

    pub fn decode_body(req: &Message) -> Result<Option<Value>, RegistryError> {
        if req.body.is_empty() {
            return Ok(None);
        }

        match BodyFormat::try_from(req.header.body_format) {
            Ok(BodyFormat::Json) => Ok(Some(serde_json::from_slice::<Value>(&req.body)?)),
            Ok(BodyFormat::Beve) => Ok(Some(beve::from_slice::<Value>(&req.body)?)),
            Ok(BodyFormat::Utf8) => {
                let text = std::str::from_utf8(&req.body).map_err(RegistryError::InvalidUtf8)?;
                Ok(Some(Value::String(text.to_string())))
            }
            Ok(BodyFormat::RawBinary) => Ok(Some(Value::Array(
                req.body.iter().map(|byte| Value::from(*byte)).collect(),
            ))),
            Err(_) => Err(RegistryError::UnsupportedBodyFormat {
                format: req.header.body_format,
            }),
        }
    }

    fn read_state(&self) -> std::sync::RwLockReadGuard<'_, RegistryState> {
        match self.state.read() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }

    fn write_state(&self) -> std::sync::RwLockWriteGuard<'_, RegistryState> {
        match self.state.write() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }
}

fn parse_registration_path(path: &str) -> Result<Vec<String>, RegistryError> {
    if path.is_empty() {
        return Ok(Vec::new());
    }
    // Registration is not on the hot path; own the segments so they outlive the
    // (possibly synthesized) normalized pointer and slot into the value tree.
    let normalized: Cow<'_, str> = if path.starts_with('/') {
        Cow::Borrowed(path)
    } else {
        Cow::Owned(format!("/{path}"))
    };
    Ok(parse_pointer(&normalized)?
        .into_iter()
        .map(Cow::into_owned)
        .collect())
}

/// Compute the canonical JSON-Pointer key used to probe `RegistryState::functions`,
/// borrowing the input when possible.
///
/// The function map is keyed by `canonical_pointer(parse_pointer(p))`. For any
/// valid `/`-prefixed pointer, `escape ∘ unescape` round-trips each reference
/// token, so that canonical form is byte-identical to `p` itself — meaning an
/// escape-free pointer (the overwhelmingly common case) is *already* its own
/// canonical key and can be returned as a borrow with zero allocation. Only
/// pointers containing a `~` escape need the parse + re-escape round-trip, and
/// only those allocate.
///
/// Errors exactly where [`parse_pointer`] would: a non-empty pointer without a
/// leading `/`, or a malformed `~` escape.
fn canonical_key(pointer: &str) -> Result<Cow<'_, str>, RegistryError> {
    if pointer.is_empty() || pointer == "/" {
        // No function can register at the root, so this never matches a
        // callable; normalize to "/" to mirror `canonical_pointer(&[])`.
        return Ok(Cow::Borrowed("/"));
    }
    if !pointer.starts_with('/') {
        return Err(RegistryError::InvalidPointer {
            pointer: pointer.to_string(),
        });
    }
    if !pointer.contains('~') {
        // Already canonical: slash-prefixed and escape-free.
        return Ok(Cow::Borrowed(pointer));
    }
    // Escaped tokens need validation (rejecting malformed `~` sequences) and
    // re-canonicalization; this allocates, but escapes are rare in practice.
    Ok(Cow::Owned(canonical_pointer(&parse_pointer(pointer)?)))
}

/// Parse a JSON Pointer into its reference tokens, borrowing each token from
/// `pointer` when it needs no unescaping (the common case) and allocating only
/// for tokens that contain a `~` escape. The returned tokens borrow `pointer`,
/// so the value-tree walk in `resolve_ref`/`resolve_mut`/`set_pointer` resolves
/// without a per-segment `String` allocation.
fn parse_pointer(pointer: &str) -> Result<Vec<Cow<'_, str>>, RegistryError> {
    if pointer.is_empty() || pointer == "/" {
        return Ok(Vec::new());
    }
    if !pointer.starts_with('/') {
        return Err(RegistryError::InvalidPointer {
            pointer: pointer.to_string(),
        });
    }

    pointer[1..]
        .split('/')
        .map(unescape_token)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|_| RegistryError::InvalidPointer {
            pointer: pointer.to_string(),
        })
}

fn unescape_token(token: &str) -> Result<Cow<'_, str>, ()> {
    // Escape-free tokens are already their own unescaped form: borrow them
    // rather than allocating a fresh `String` per segment.
    if !token.contains('~') {
        return Ok(Cow::Borrowed(token));
    }
    let mut out = String::with_capacity(token.len());
    let mut chars = token.chars();
    while let Some(c) = chars.next() {
        if c != '~' {
            out.push(c);
            continue;
        }
        let Some(next) = chars.next() else {
            return Err(());
        };
        match next {
            '0' => out.push('~'),
            '1' => out.push('/'),
            _ => return Err(()),
        }
    }
    Ok(Cow::Owned(out))
}

fn escape_token(token: &str) -> String {
    token.replace('~', "~0").replace('/', "~1")
}

fn canonical_pointer<S: AsRef<str>>(segments: &[S]) -> String {
    if segments.is_empty() {
        "/".to_string()
    } else {
        let mut out = String::new();
        for segment in segments {
            out.push('/');
            out.push_str(&escape_token(segment.as_ref()));
        }
        out
    }
}

fn ensure_object_root(value: &mut Value) -> Result<&mut Map<String, Value>, RegistryError> {
    if !value.is_object() {
        *value = Value::Object(Map::new());
    }
    value
        .as_object_mut()
        .ok_or_else(|| RegistryError::PathNotFound {
            path: "/".to_string(),
        })
}

fn ensure_object_parent<'a>(
    root: &'a mut Value,
    segments: &[String],
) -> Result<&'a mut Map<String, Value>, RegistryError> {
    let mut current = ensure_object_root(root)?;
    if segments.len() <= 1 {
        return Ok(current);
    }
    for segment in &segments[..segments.len() - 1] {
        let entry = current
            .entry(segment.clone())
            .or_insert_with(|| Value::Object(Map::new()));
        if !entry.is_object() {
            *entry = Value::Object(Map::new());
        }
        current = entry
            .as_object_mut()
            .ok_or_else(|| RegistryError::PathNotFound {
                path: canonical_pointer(segments),
            })?;
    }
    Ok(current)
}

fn resolve_ref<'a, S: AsRef<str>>(
    root: &'a Value,
    segments: &[S],
) -> Result<&'a Value, RegistryError> {
    let mut current = root;
    for (i, segment) in segments.iter().enumerate() {
        // Error paths are computed lazily from `segments[..=i]`, so the success
        // path neither clones segments nor grows a `walked` vector.
        let segment = segment.as_ref();
        match current {
            Value::Object(map) => {
                current = map
                    .get(segment)
                    .ok_or_else(|| RegistryError::PathNotFound {
                        path: canonical_pointer(&segments[..=i]),
                    })?;
            }
            Value::Array(array) => {
                let index =
                    segment
                        .parse::<usize>()
                        .map_err(|_| RegistryError::InvalidArrayIndex {
                            path: canonical_pointer(&segments[..=i]),
                            segment: segment.to_string(),
                        })?;
                current = array
                    .get(index)
                    .ok_or_else(|| RegistryError::ArrayIndexOutOfBounds {
                        path: canonical_pointer(&segments[..=i]),
                        segment: segment.to_string(),
                    })?;
            }
            _ => {
                return Err(RegistryError::PathNotFound {
                    path: canonical_pointer(&segments[..=i]),
                });
            }
        }
    }
    Ok(current)
}

fn resolve_mut<'a, S: AsRef<str>>(
    root: &'a mut Value,
    segments: &[S],
) -> Result<&'a mut Value, RegistryError> {
    let mut current = root;
    for (i, segment) in segments.iter().enumerate() {
        let segment = segment.as_ref();
        match current {
            Value::Object(map) => {
                current = map
                    .get_mut(segment)
                    .ok_or_else(|| RegistryError::PathNotFound {
                        path: canonical_pointer(&segments[..=i]),
                    })?;
            }
            Value::Array(array) => {
                let index =
                    segment
                        .parse::<usize>()
                        .map_err(|_| RegistryError::InvalidArrayIndex {
                            path: canonical_pointer(&segments[..=i]),
                            segment: segment.to_string(),
                        })?;
                current =
                    array
                        .get_mut(index)
                        .ok_or_else(|| RegistryError::ArrayIndexOutOfBounds {
                            path: canonical_pointer(&segments[..=i]),
                            segment: segment.to_string(),
                        })?;
            }
            _ => {
                return Err(RegistryError::PathNotFound {
                    path: canonical_pointer(&segments[..=i]),
                });
            }
        }
    }
    Ok(current)
}

fn set_pointer<S: AsRef<str>>(
    root: &mut Value,
    segments: &[S],
    value: Value,
) -> Result<(), RegistryError> {
    if segments.is_empty() {
        *root = value;
        return Ok(());
    }

    let parent_len = segments.len() - 1;
    let mut current = root;
    for (i, segment) in segments[..parent_len].iter().enumerate() {
        let segment = segment.as_ref();
        match current {
            Value::Object(map) => {
                current = map
                    .get_mut(segment)
                    .ok_or_else(|| RegistryError::PathNotFound {
                        path: canonical_pointer(&segments[..=i]),
                    })?;
            }
            Value::Array(array) => {
                let index =
                    segment
                        .parse::<usize>()
                        .map_err(|_| RegistryError::InvalidArrayIndex {
                            path: canonical_pointer(&segments[..=i]),
                            segment: segment.to_string(),
                        })?;
                current =
                    array
                        .get_mut(index)
                        .ok_or_else(|| RegistryError::ArrayIndexOutOfBounds {
                            path: canonical_pointer(&segments[..=i]),
                            segment: segment.to_string(),
                        })?;
            }
            _ => {
                return Err(RegistryError::PathNotFound {
                    path: canonical_pointer(&segments[..=i]),
                });
            }
        }
    }

    let last = segments[parent_len].as_ref();
    match current {
        Value::Object(map) => {
            map.insert(last.to_string(), value);
            Ok(())
        }
        Value::Array(array) => {
            let index = last
                .parse::<usize>()
                .map_err(|_| RegistryError::InvalidArrayIndex {
                    path: canonical_pointer(segments),
                    segment: last.to_string(),
                })?;
            if let Some(slot) = array.get_mut(index) {
                *slot = value;
                Ok(())
            } else {
                Err(RegistryError::ArrayIndexOutOfBounds {
                    path: canonical_pointer(segments),
                    segment: last.to_string(),
                })
            }
        }
        _ => Err(RegistryError::PathNotFound {
            path: canonical_pointer(segments),
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_pointer_unescapes_tokens() {
        let segments = parse_pointer("/a~1b/m~0n").unwrap();
        assert_eq!(segments, vec!["a/b".to_string(), "m~n".to_string()]);
    }

    #[test]
    fn parse_pointer_rejects_invalid_tilde_escape() {
        let err = parse_pointer("/a~2b").unwrap_err();
        assert!(matches!(err, RegistryError::InvalidPointer { .. }));
    }

    #[test]
    fn registry_dispatch_read_write_call() {
        let registry = Registry::new();
        registry
            .register_value("/counter", Value::from(0))
            .expect("register counter");
        registry
            .register_function("/add", |params| {
                let Some(Value::Object(map)) = params else {
                    return Err((ErrorCode::InvalidBody, "expected object".into()));
                };
                let a = map.get("a").and_then(Value::as_i64).unwrap_or(0);
                let b = map.get("b").and_then(Value::as_i64).unwrap_or(0);
                Ok(Value::from(a + b))
            })
            .expect("register function");

        let read_counter = registry.dispatch("/counter", None).expect("read");
        assert_eq!(read_counter, Value::from(0));

        let write_result = registry
            .dispatch("/counter", Some(Value::from(42)))
            .expect("write");
        assert_eq!(write_result["status"], "ok");

        let read_counter = registry.dispatch("/counter", None).expect("read");
        assert_eq!(read_counter, Value::from(42));

        let function_info = registry.dispatch("/add", None).expect("function info");
        assert_eq!(function_info["type"], "function");
        assert_eq!(function_info["path"], "/add");

        let call_result = registry
            .dispatch("/add", Some(json!({"a": 2, "b": 3})))
            .expect("call");
        assert_eq!(call_result, Value::from(5));
    }

    #[test]
    fn dispatch_resolves_functions_at_escaped_pointers() {
        // The function map is keyed by the canonical pointer string. A pointer
        // whose reference token contains an escaped `/` (`~1`) or `~` (`~0`)
        // must still register and dispatch: registration stores the canonical
        // key, and dispatch rebuilds the byte-identical key via
        // `canonical_key`'s owned (escape) path. This is the branch the
        // borrow-the-wire-pointer fast path cannot cover.
        let registry = Registry::new();
        registry
            .register_function("/a~1b/run", |_params| Ok(Value::from("slash")))
            .expect("register escaped-slash function");
        registry
            .register_function("/m~0n", |_params| Ok(Value::from("tilde")))
            .expect("register escaped-tilde function");

        // Metadata read echoes the canonical (re-escaped) pointer.
        let info = registry.dispatch("/a~1b/run", None).expect("info");
        assert_eq!(info["type"], "function");
        assert_eq!(info["path"], "/a~1b/run");

        // Calls resolve to the correct handler through the owned canonical key.
        assert_eq!(
            registry
                .dispatch("/a~1b/run", Some(json!({})))
                .expect("call slash"),
            Value::from("slash")
        );
        assert_eq!(
            registry
                .dispatch("/m~0n", Some(json!({})))
                .expect("call tilde"),
            Value::from("tilde")
        );

        // Write fallback still works after the lookup reorder: an escaped
        // non-function pointer parses to segments and writes under the parent.
        let written = registry
            .dispatch("/a~1b/note", Some(json!("hi")))
            .expect("write");
        assert_eq!(written["status"], "ok");
        assert_eq!(written["path"], "/a~1b/note");
    }

    #[test]
    fn dispatch_with_ctx_threads_peer_to_callable() {
        use crate::peer::{NotifyBody, PeerHandle, PeerId, PeerSendError, PeerSink};
        use std::sync::Mutex;

        #[derive(Default)]
        struct CapturingSink {
            captured: Mutex<Vec<String>>,
        }
        impl PeerSink for CapturingSink {
            fn send_notify(&self, method: &str, _body: NotifyBody) -> Result<(), PeerSendError> {
                self.captured.lock().unwrap().push(method.to_string());
                Ok(())
            }
        }

        let sink = Arc::new(CapturingSink::default());
        let peer = PeerHandle::new(PeerId(7), sink.clone());

        let observed_peer = Arc::new(Mutex::new(None::<PeerId>));
        let observed_peer_clone = Arc::clone(&observed_peer);
        let registry = Registry::new();
        registry
            .register_function(
                "/run",
                WithContext(move |ctx: &CallContext, _params| {
                    if let Some(p) = ctx.peer() {
                        *observed_peer_clone.lock().unwrap() = Some(p.peer_id());
                        p.send_notify("/progress", NotifyBody::Json(b"{}".to_vec()))
                            .ok();
                    }
                    Ok(Value::from("ok"))
                }),
            )
            .expect("register WithContext function");

        let ctx = CallContext::new("/run", &peer);
        let result = registry
            .dispatch_with_ctx("/run", Some(json!({})), &ctx)
            .expect("dispatch");
        assert_eq!(result, Value::from("ok"));
        assert_eq!(*observed_peer.lock().unwrap(), Some(PeerId(7)));
        assert_eq!(sink.captured.lock().unwrap().as_slice(), &["/progress"]);
    }

    #[test]
    fn dispatch_default_context_is_detached() {
        let registry = Registry::new();
        let observed = Arc::new(std::sync::Mutex::new(false));
        let observed_clone = Arc::clone(&observed);
        registry
            .register_function(
                "/probe",
                WithContext(move |ctx: &CallContext, _params| {
                    *observed_clone.lock().unwrap() = ctx.peer().is_none();
                    Ok(Value::from("ok"))
                }),
            )
            .expect("register");

        registry
            .dispatch("/probe", Some(json!({})))
            .expect("dispatch");
        assert!(
            *observed.lock().unwrap(),
            "dispatch must use a detached context"
        );
    }

    #[test]
    fn decode_body_maps_utf8_to_string_value() {
        let req = Message::builder()
            .id(1)
            .query_str("/name")
            .query_format(crate::constants::QueryFormat::JsonPointer)
            .body_utf8("alice")
            .build();
        let decoded = Registry::decode_body(&req).expect("decode");
        assert_eq!(decoded, Some(Value::String("alice".into())));
    }
}