repe 3.2.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
#![cfg(not(target_arch = "wasm32"))]
#![allow(unreachable_code)]

use repe::constants::{ErrorCode, QueryFormat};
use repe::{Message, Router};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::sync::{Arc, Mutex, RwLock};
use tokio::sync::{Mutex as TokioMutex, RwLock as TokioRwLock};

#[cfg(feature = "parking-lot")]
use parking_lot::RwLock as ParkingRwLock;

#[derive(Default, Serialize, Deserialize, repe::RepeStruct)]
#[repe(methods(
    hello(&self) -> String,
    world(&self) -> String,
    get_number(&self) -> i32,
    void_func(&mut self) -> (),
    max(&self, vec: Vec<f64>) -> f64
))]
struct MyFunctions {
    i: i32,
}

impl MyFunctions {
    fn hello(&self) -> String {
        "Hello".into()
    }

    fn world(&self) -> String {
        "World".into()
    }

    fn get_number(&self) -> i32 {
        42
    }

    fn void_func(&mut self) {}

    fn max(&self, vec: Vec<f64>) -> f64 {
        vec.into_iter().fold(f64::NEG_INFINITY, f64::max)
    }
}

#[derive(Default, Serialize, Deserialize, repe::RepeStruct)]
#[repe(methods(
    hello(&self) -> String,
    world(&self) -> String,
    get_number(&self) -> i32
))]
struct MetaFunctions {}

impl MetaFunctions {
    fn hello(&self) -> String {
        "Hello".into()
    }

    fn world(&self) -> String {
        "World".into()
    }

    fn get_number(&self) -> i32 {
        42
    }
}

#[derive(Default, Serialize, Deserialize, repe::RepeStruct)]
#[repe(methods(
    append_awesome(&self, input: String) -> String
))]
struct MyNestedFunctions {
    #[repe(nested)]
    my_functions: MyFunctions,
    #[repe(nested)]
    meta_functions: MetaFunctions,
    my_string: String,
}

impl MyNestedFunctions {
    fn append_awesome(&self, input: String) -> String {
        format!("{input} awesome!")
    }
}

#[derive(Default, Serialize, Deserialize, repe::RepeStruct)]
#[repe(methods(
    get_name(&self) -> String,
    set_name(&mut self, new_name: String) -> (),
    custom_name = set_name(&mut self, new_name: String) -> ()
))]
struct ExampleFunctions {
    name: String,
}

impl ExampleFunctions {
    fn get_name(&self) -> String {
        self.name.clone()
    }

    fn set_name(&mut self, new_name: String) {
        self.name = new_name;
    }
}

#[allow(unreachable_code)]
#[derive(Default, Serialize, Deserialize, repe::RepeStruct)]
#[repe(methods(
    alias = describe(&self) -> String
))]
struct AttributeStruct {
    #[repe(rename = "renamed_value")]
    value: i32,
    #[repe(skip)]
    hidden: bool,
    #[repe(readonly)]
    name: String,
}

impl AttributeStruct {
    fn describe(&self) -> String {
        format!("{}:{}", self.name, self.value)
    }
}

#[derive(Default, Serialize, Deserialize, repe::RepeStruct)]
struct RootStruct {
    foo: i32,
    bar: String,
}

fn request_empty(path: &str) -> Message {
    Message::builder()
        .query_str(path)
        .query_format(QueryFormat::JsonPointer)
        .build()
}

fn request_json(path: &str, body: &Value) -> Message {
    Message::builder()
        .query_str(path)
        .query_format(QueryFormat::JsonPointer)
        .body_json(body)
        .unwrap()
        .build()
}

fn parse_body(resp: &Message) -> Value {
    serde_json::from_slice(&resp.body).expect("response body should be JSON")
}

fn request_raw(path: &str, bytes: &[u8]) -> Message {
    Message::builder()
        .query_str(path)
        .query_format(QueryFormat::JsonPointer)
        .body_bytes(bytes.to_vec())
        .build()
}

#[test]
fn structs_of_functions() {
    let shared = Arc::new(Mutex::new(MyFunctions::default()));
    {
        let mut guard = shared.lock().unwrap();
        guard.i = 55;
    }

    let router = Router::new().with_struct_shared("", shared.clone());

    // read integer field
    let handler = router.get("/i").expect("handler for /i");
    let resp = handler.handle(&request_empty("/i")).unwrap();
    assert_eq!(parse_body(&resp), Value::from(55));

    // writing integer resets to requested value
    let handler = router.get("/i").unwrap();
    let resp = handler
        .handle(&request_json("/i", &json!(42)))
        .expect("write integer");
    assert_eq!(parse_body(&resp), Value::Null);
    assert_eq!(shared.lock().unwrap().i, 42);

    // zero-argument functions
    let hello = router
        .get("/hello")
        .unwrap()
        .handle(&request_empty("/hello"))
        .unwrap();
    assert_eq!(parse_body(&hello), Value::String("Hello".into()));
    let world = router
        .get("/world")
        .unwrap()
        .handle(&request_empty("/world"))
        .unwrap();
    assert_eq!(parse_body(&world), Value::String("World".into()));

    // zero-arg with body should still work
    let get_number = router
        .get("/get_number")
        .unwrap()
        .handle(&request_json("/get_number", &json!("ignored")))
        .unwrap();
    assert_eq!(parse_body(&get_number), Value::from(42));

    // void function returns null
    let void_resp = router
        .get("/void_func")
        .unwrap()
        .handle(&request_empty("/void_func"))
        .unwrap();
    assert_eq!(parse_body(&void_resp), Value::Null);

    // max with parameters
    let max_resp = router
        .get("/max")
        .unwrap()
        .handle(&request_json("/max", &json!([1.1, 3.3, 2.25])))
        .unwrap();
    assert_eq!(parse_body(&max_resp), Value::from(3.3));

    // root snapshot
    let snapshot = router.get("").unwrap().handle(&request_empty("")).unwrap();
    let body = parse_body(&snapshot);
    assert_eq!(body["i"], Value::from(42));
    assert_eq!(body["hello"], Value::String("fn(&self) -> String".into()));
    assert_eq!(
        body["max"],
        Value::String("fn(&self, vec: Vec<f64>) -> f64".into())
    );
}

#[test]
fn nested_structs_of_functions() {
    let shared = Arc::new(Mutex::new(MyNestedFunctions::default()));

    let router = Router::new().with_struct_shared("", shared.clone());

    // void function reflected in nested struct
    let resp = router
        .get("/my_functions/void_func")
        .unwrap()
        .handle(&request_empty("/my_functions/void_func"))
        .unwrap();
    assert_eq!(parse_body(&resp), Value::Null);

    let hello = router
        .get("/my_functions/hello")
        .unwrap()
        .handle(&request_empty("/my_functions/hello"))
        .unwrap();
    assert_eq!(parse_body(&hello), Value::String("Hello".into()));

    let meta = router
        .get("/meta_functions/hello")
        .unwrap()
        .handle(&request_empty("/meta_functions/hello"))
        .unwrap();
    assert_eq!(parse_body(&meta), Value::String("Hello".into()));

    let append = router
        .get("/append_awesome")
        .unwrap()
        .handle(&request_json("/append_awesome", &json!("you are")))
        .unwrap();
    assert_eq!(
        parse_body(&append),
        Value::String("you are awesome!".into())
    );

    let write_string = router
        .get("/my_string")
        .unwrap()
        .handle(&request_json("/my_string", &json!("Howdy!")))
        .unwrap();
    assert_eq!(parse_body(&write_string), Value::Null);

    let read_string = router
        .get("/my_string")
        .unwrap()
        .handle(&request_empty("/my_string"))
        .unwrap();
    assert_eq!(parse_body(&read_string), Value::String("Howdy!".into()));

    shared.lock().unwrap().my_string.clear();
    let empty_read = router
        .get("/my_string")
        .unwrap()
        .handle(&request_empty("/my_string"))
        .unwrap();
    assert_eq!(parse_body(&empty_read), Value::String("".into()));

    let max_resp = router
        .get("/my_functions/max")
        .unwrap()
        .handle(&request_json("/my_functions/max", &json!([1.1, 3.3, 2.25])))
        .unwrap();
    assert_eq!(parse_body(&max_resp), Value::from(3.3));

    let my_functions_snapshot = router
        .get("/my_functions")
        .unwrap()
        .handle(&request_empty("/my_functions"))
        .unwrap();
    let snapshot_body = parse_body(&my_functions_snapshot);
    assert_eq!(snapshot_body["i"], Value::from(0));
    assert_eq!(
        snapshot_body["hello"],
        Value::String("fn(&self) -> String".into())
    );

    let full_snapshot = router.get("").unwrap().handle(&request_empty("")).unwrap();
    let body = parse_body(&full_snapshot);
    assert_eq!(body["my_string"], Value::String("".into()));
    assert!(body["my_functions"].is_object());
    assert!(body["meta_functions"].is_object());
}

#[test]
fn example_functions() {
    let shared = Arc::new(Mutex::new(ExampleFunctions::default()));
    let router = Router::new().with_struct_shared("", shared.clone());

    let write_name = router
        .get("/name")
        .unwrap()
        .handle(&request_json("/name", &json!("Susan")))
        .unwrap();
    assert_eq!(parse_body(&write_name), Value::Null);

    let read_name = router
        .get("/get_name")
        .unwrap()
        .handle(&request_empty("/get_name"))
        .unwrap();
    assert_eq!(parse_body(&read_name), Value::String("Susan".into()));

    let read_with_body = router
        .get("/get_name")
        .unwrap()
        .handle(&request_json("/get_name", &json!("Bob")))
        .unwrap();
    assert_eq!(parse_body(&read_with_body), Value::String("Susan".into()));

    assert_eq!(shared.lock().unwrap().name, "Susan");

    let set_name = router
        .get("/set_name")
        .unwrap()
        .handle(&request_json("/set_name", &json!("Bob")))
        .unwrap();
    assert_eq!(parse_body(&set_name), Value::Null);
    assert_eq!(shared.lock().unwrap().name, "Bob");

    let custom_name = router
        .get("/custom_name")
        .unwrap()
        .handle(&request_json("/custom_name", &json!("Alice")))
        .unwrap();
    assert_eq!(parse_body(&custom_name), Value::Null);
    assert_eq!(shared.lock().unwrap().name, "Alice");
}

#[test]
fn struct_shared_accepts_rwlock() {
    let shared = Arc::new(RwLock::new(ExampleFunctions::default()));
    {
        let mut guard = shared.write().unwrap();
        guard.set_name("Initial".into());
    }

    let router = Router::new().with_struct_shared("", shared.clone());

    let get_name = router
        .get("/get_name")
        .unwrap()
        .handle(&request_empty("/get_name"))
        .unwrap();
    assert_eq!(parse_body(&get_name), Value::String("Initial".into()));

    let set_name = router
        .get("/set_name")
        .unwrap()
        .handle(&request_json("/set_name", &json!("Updated")))
        .unwrap();
    assert_eq!(parse_body(&set_name), Value::Null);

    assert_eq!(shared.read().unwrap().name.as_str(), "Updated");
}

#[test]
fn struct_shared_accepts_tokio_mutex() {
    let shared = Arc::new(TokioMutex::new(ExampleFunctions::default()));
    {
        let mut guard = shared.blocking_lock();
        guard.set_name("Initial".into());
    }

    let router = Router::new().with_struct_shared("", shared.clone());

    let get_name = router
        .get("/get_name")
        .unwrap()
        .handle(&request_empty("/get_name"))
        .unwrap();
    assert_eq!(parse_body(&get_name), Value::String("Initial".into()));

    let set_name = router
        .get("/set_name")
        .unwrap()
        .handle(&request_json("/set_name", &json!("Updated")))
        .unwrap();
    assert_eq!(parse_body(&set_name), Value::Null);

    assert_eq!(shared.blocking_lock().name.as_str(), "Updated");
}

#[test]
fn struct_shared_accepts_tokio_rwlock() {
    let shared = Arc::new(TokioRwLock::new(ExampleFunctions::default()));
    {
        let mut guard = shared.blocking_write();
        guard.set_name("Initial".into());
    }

    let router = Router::new().with_struct_shared("", shared.clone());

    let get_name = router
        .get("/get_name")
        .unwrap()
        .handle(&request_empty("/get_name"))
        .unwrap();
    assert_eq!(parse_body(&get_name), Value::String("Initial".into()));

    let set_name = router
        .get("/set_name")
        .unwrap()
        .handle(&request_json("/set_name", &json!("Updated")))
        .unwrap();
    assert_eq!(parse_body(&set_name), Value::Null);

    let guard = shared.blocking_read();
    assert_eq!(guard.name.as_str(), "Updated");
}

#[cfg(feature = "parking-lot")]
#[test]
fn struct_shared_accepts_parking_lot_rwlock() {
    let shared = Arc::new(ParkingRwLock::new(ExampleFunctions::default()));
    {
        let mut guard = shared.write();
        guard.set_name("Initial".into());
    }

    let router = Router::new().with_struct_shared("", shared.clone());

    let get_name = router
        .get("/get_name")
        .unwrap()
        .handle(&request_empty("/get_name"))
        .unwrap();
    assert_eq!(parse_body(&get_name), Value::String("Initial".into()));

    let set_name = router
        .get("/set_name")
        .unwrap()
        .handle(&request_json("/set_name", &json!("Updated")))
        .unwrap();
    assert_eq!(parse_body(&set_name), Value::Null);

    let guard = shared.read();
    assert_eq!(guard.name.as_str(), "Updated");
}

#[test]
fn struct_attributes_control_behavior() {
    let mut router = Router::new();
    let shared = router.register_struct(
        "",
        AttributeStruct {
            value: 7,
            hidden: true,
            name: "alpha".into(),
        },
    );

    // renamed field is accessible and writable
    let read_value = router
        .get("/renamed_value")
        .unwrap()
        .handle(&request_empty("/renamed_value"))
        .unwrap();
    assert_eq!(parse_body(&read_value), Value::from(7));

    let write_value = router
        .get("/renamed_value")
        .unwrap()
        .handle(&request_json("/renamed_value", &json!(11)))
        .unwrap();
    assert_eq!(parse_body(&write_value), Value::Null);
    assert_eq!(shared.lock().unwrap().value, 11);

    // readonly field rejects writes but stays readable
    let readonly_err = router
        .get("/name")
        .unwrap()
        .handle(&request_json("/name", &json!("beta")))
        .unwrap();
    assert!(readonly_err.is_error());
    assert_eq!(readonly_err.header.ec, ErrorCode::InvalidBody as u32);
    assert!(readonly_err.body_utf8().contains("body not allowed"));
    assert_eq!(shared.lock().unwrap().name, "alpha");

    let readonly_value = router
        .get("/name")
        .unwrap()
        .handle(&request_empty("/name"))
        .unwrap();
    assert_eq!(parse_body(&readonly_value), Value::String("alpha".into()));

    // root snapshot omits skipped field and reflects methods
    let snapshot = router.get("").unwrap().handle(&request_empty("")).unwrap();
    let body = parse_body(&snapshot);
    assert_eq!(body["renamed_value"], Value::from(11));
    assert_eq!(body["name"], Value::String("alpha".into()));
    assert!(
        body.get("hidden").is_none(),
        "skip attribute should hide field"
    );
    assert_eq!(body["alias"], Value::String("fn(&self) -> String".into()));

    // calling alias method reflects updated state
    let alias_value = router
        .get("/alias")
        .unwrap()
        .handle(&request_empty("/alias"))
        .unwrap();
    assert_eq!(parse_body(&alias_value), Value::String("alpha:11".into()));

    // raw binary payloads are rejected
    let raw_error = router
        .get("/renamed_value")
        .unwrap()
        .handle(&request_raw("/renamed_value", b"\x01\x02"))
        .unwrap();
    assert!(raw_error.is_error());
    assert_eq!(raw_error.header.ec, ErrorCode::InvalidBody as u32);
    assert_eq!(shared.lock().unwrap().value, 11);
}

#[test]
fn root_write_replaces_struct() {
    let mut router = Router::new();
    let shared = router.register_struct(
        "",
        RootStruct {
            foo: 1,
            bar: "one".into(),
        },
    );

    let replace = Message::builder()
        .query_str("")
        .query_format(QueryFormat::JsonPointer)
        .body_json(&json!({"foo": 5, "bar": "five"}))
        .unwrap()
        .build();
    let resp = router.get("").unwrap().handle(&replace).unwrap();
    assert_eq!(parse_body(&resp), Value::Null);

    let data = shared.lock().unwrap();
    assert_eq!(data.foo, 5);
    assert_eq!(data.bar, "five");
}

#[test]
fn struct_with_root_prefix_routes() {
    let shared = Arc::new(Mutex::new(MyFunctions::default()));
    let router = Router::new().with_struct_shared("sub", shared.clone());

    let number = router
        .get("/sub/get_number")
        .unwrap()
        .handle(&request_empty("/sub/get_number"))
        .unwrap();
    assert_eq!(parse_body(&number), Value::from(42));

    let write = router
        .get("/sub/i")
        .unwrap()
        .handle(&request_json("/sub/i", &json!(9)))
        .unwrap();
    assert_eq!(parse_body(&write), Value::Null);
    assert_eq!(shared.lock().unwrap().i, 9);

    let invalid = router
        .get("/sub/unknown")
        .unwrap()
        .handle(&request_empty("/sub/unknown"))
        .unwrap();
    assert!(invalid.is_error());
    assert_eq!(invalid.header.ec, ErrorCode::MethodNotFound as u32);
    assert!(invalid.body_utf8().contains("invalid path"));

    assert!(router.get("/i").is_none(), "prefix should scope visibility");
}

/// Pins down the RFC 6901 split between `""` and `"/"` at the dispatch
/// boundary so the routing fast path does not silently collapse them.
///
/// * `""` → empty pointer → no reference tokens → serialize the whole struct.
/// * `"/"` → pointer with a single empty reference token → field named `""`,
///   which the derive-macro emits as `InvalidPath` because no such field
///   exists.
///
/// Holds for both a root-mounted struct (`""`) and a prefix-mounted struct
/// (`"/svc"`), where the trailing-slash form is `"/svc/"`.
#[test]
fn struct_dispatch_distinguishes_root_from_trailing_slash() {
    // Root-mounted struct: "" → whole struct, "/" → InvalidPath.
    let root_shared = Arc::new(Mutex::new(RootStruct {
        foo: 7,
        bar: "ok".into(),
    }));
    let root_router = Router::new().with_struct_shared("", root_shared);

    let whole = root_router
        .get("")
        .unwrap()
        .handle(&request_empty(""))
        .unwrap();
    assert!(!whole.is_error(), "empty query should return the struct");
    assert_eq!(parse_body(&whole), json!({"foo": 7, "bar": "ok"}));

    let trailing_root = root_router
        .get("/")
        .unwrap()
        .handle(&request_empty("/"))
        .unwrap();
    assert!(
        trailing_root.is_error(),
        "lone `/` should resolve to the empty-named field and miss"
    );
    assert_eq!(trailing_root.header.ec, ErrorCode::MethodNotFound as u32);

    // Prefix-mounted struct: "/svc" → whole struct, "/svc/" → InvalidPath.
    let svc_shared = Arc::new(Mutex::new(RootStruct {
        foo: 1,
        bar: "x".into(),
    }));
    let svc_router = Router::new().with_struct_shared("/svc", svc_shared);

    let svc_whole = svc_router
        .get("/svc")
        .unwrap()
        .handle(&request_empty("/svc"))
        .unwrap();
    assert!(!svc_whole.is_error(), "/svc should return the struct");
    assert_eq!(parse_body(&svc_whole), json!({"foo": 1, "bar": "x"}));

    let svc_trailing = svc_router
        .get("/svc/")
        .unwrap()
        .handle(&request_empty("/svc/"))
        .unwrap();
    assert!(
        svc_trailing.is_error(),
        "/svc/ should resolve to the empty-named field and miss"
    );
    assert_eq!(svc_trailing.header.ec, ErrorCode::MethodNotFound as u32);
}