-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapping.rs
More file actions
1986 lines (1859 loc) · 71.7 KB
/
Copy pathmapping.rs
File metadata and controls
1986 lines (1859 loc) · 71.7 KB
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Messaging Mapper: the boundary between messaging and WIT-typed components.
//!
//! `MessageMapper` translates an inbound [`Message`] into an [`Invocation`] of
//! a specific WIT function, and translates the function's return value back
//! into a reply [`Message`]. The component knows nothing about messages, and
//! the messaging layer knows nothing about WIT.
//!
//! ## Mapping pipeline
//!
//! The mapper applies up to four user-declared blocks in pipeline order,
//! bundled into a single [`MappingConfig`]:
//!
//! Inbound (Message => WIT call):
//! 1. [`ParamMapping`]: per-arg templates that build WIT args by reading
//! paths into the inbound Message. Without an entry for a given WIT
//! param, the arg is name-matched against the parsed Message body.
//! 2. [`ParamEncoding`]: per-arg content-type specs that encode the
//! assembled value as bytes (for any WIT param typed as `list<u8>`).
//!
//! Outbound (WIT result => reply Message):
//! 3. [`ResultDecoding`]: per-field content-type specs that decode any
//! `list<u8>` field on the WIT result. The decoded value replaces the
//! bytes in the WIT result before result-mapping runs.
//! 4. result_mapping: a structural `body` / `headers` table that produces
//! the reply Message. Each slot can be a single source-path string
//! (bulk-lift) or a sub-table of target-name => source-path entries
//! (cherry-pick).
//!
//! With none declared, name-match drives inbound and the WIT result becomes
//! the reply body verbatim.
//!
//! ## Templates
//!
//! Templates reference values via `{path}` syntax. Paths use a uniform
//! dotted grammar across every block:
//!
//! - `body.user.email` => dot-name segments for normal keys.
//! - `headers["foo.bar"]` => bracket-quoted-string for keys containing
//! characters that are not `[A-Za-z0-9_-]`.
//! - `body.items[3].name` => bracket-integer for array indices.
//!
//! The first segment names the source root:
//!
//! - `param-mapping`: source is the inbound Message; first segment must be
//! `body` or `headers`.
//! - `result-mapping` and `result-decoding` (path-form): source is the WIT
//! result; first segment is a top-level field.
//! - `param-encoding` (path-form): source is the assembled WIT args; first
//! segment is a WIT param name.
//!
//! Defaulting is supported via `{path | <literal>}`:
//!
//! - `{body.user.email | "anonymous"}` => use the literal value when the
//! path is missing.
//!
//! ## `result-mapping` shape
//!
//! When result-mapping is declared, it takes over building the reply Message.
//! The block has two structural sub-keys: `body` and `headers`.
//!
//! - `body` absent (or `null` or `""`) => empty body (zero bytes).
//! - `body = "<path>"` => bulk-lift that source path as the body.
//! - `body = { <target> = "<path>", ... }` => cherry-pick.
//! - `headers` follows the same shape; entries become reply Message headers.
//!
//! ## `result-decoding` and `param-encoding` shape
//!
//! Each entry's value is a content-type spec, in one of two forms:
//!
//! - A literal content-type: `payload = "application/json"`.
//! - A path that resolves at runtime to a content-type string:
//! `payload = "{headers.content-type}"`.
//!
//! Supported content-types: `application/json` and `text/plain`.
use std::collections::HashMap;
use serde_json::{Map, Value};
use crate::message::{Message, MessageBuilder, MessageHeaders};
use crate::types::{Component, FunctionParam};
/// User-declared per-arg template config: arg name -> template value.
///
/// A template value can be a literal, a string containing `{path}`
/// placeholders, or a structured value with embedded placeholders. A missing
/// entry for an arg means fall back to name-match against the Message body.
pub type ParamMapping = HashMap<String, Value>;
/// A resolved function call: function key and positional JSON arguments.
#[derive(Debug)]
pub struct Invocation {
pub function_key: String,
pub args: Vec<Value>,
}
// How to determine the content-type for one `result-decoding` or
// `param-encoding` entry.
#[derive(Debug, Clone)]
pub(crate) enum ContentTypeSpec {
// A hardcoded content-type value (e.g. `"application/json"`).
Literal(String),
// A path into the source whose value at runtime supplies the
// content-type string. The source is the WIT result for
// result-decoding, or the assembled WIT args for param-encoding.
Path(Vec<PathSegment>),
}
/// Per-field decoding config applied to a WIT result before result-mapping.
///
/// Each entry names a WIT-result field whose value is a byte array and a
/// content-type spec describing how to decode it. The decoded value replaces
/// the byte array in the WIT result.
#[derive(Debug, Clone)]
pub struct ResultDecoding(pub(crate) HashMap<String, ContentTypeSpec>);
impl ResultDecoding {
/// Parse a `result-decoding` config block into a [`ResultDecoding`].
///
/// If the value is path-based (`{...}`), it is treated as a reference into
/// the WIT result. Otherwise it is treated as a literal content-type.
pub fn parse(map: &Map<String, Value>) -> Result<Self, String> {
let inner = parse_content_type_specs(map, "result-decoding")?;
Ok(Self(inner))
}
}
/// The four mapping-related configs that bridge a component invocation
/// to/from the WIT boundary. Listed in pipeline order: inbound side first
/// (`param_mapping` followed by `param_encoding`), then outbound side
/// (`result_decoding` followed by `result_mapping`).
#[derive(Debug, Clone, Default)]
pub struct MappingConfig {
pub param_mapping: Option<ParamMapping>,
pub param_encoding: Option<ParamEncoding>,
pub result_decoding: Option<ResultDecoding>,
pub result_mapping: Option<Value>,
}
/// Per-param encoding config applied to assembled WIT args after param-mapping.
///
/// Each entry names a WIT param whose assembled value should be encoded as
/// bytes per a content-type spec. The encoded bytes replace the structured
/// value at that arg's position.
#[derive(Debug, Clone)]
pub struct ParamEncoding(pub(crate) HashMap<String, ContentTypeSpec>);
impl ParamEncoding {
/// Parse a `param-encoding` config block into a [`ParamEncoding`].
///
/// Same value grammar as `result-decoding`: `{...}` is a path into the
/// assembled WIT args; otherwise the value is a literal content-type.
pub fn parse(map: &Map<String, Value>) -> Result<Self, String> {
let inner = parse_content_type_specs(map, "param-encoding")?;
Ok(Self(inner))
}
}
// Shared parser for ResultDecoding and ParamEncoding entries.
fn parse_content_type_specs(
map: &Map<String, Value>,
block_name: &str,
) -> Result<HashMap<String, ContentTypeSpec>, String> {
let mut out = HashMap::new();
for (field, value) in map {
let s = value
.as_str()
.ok_or_else(|| format!("{block_name} entry '{field}' must be a string, got {value}"))?;
let spec = if let Some(inner) = path_only_inner(s) {
let segments =
parse_path(inner).map_err(|e| format!("{block_name} entry '{field}': {e}"))?;
ContentTypeSpec::Path(segments)
} else {
ContentTypeSpec::Literal(s.to_string())
};
out.insert(field.clone(), spec);
}
Ok(out)
}
// Returns the inner content of a path-only `{...}` template string, or None.
fn path_only_inner(s: &str) -> Option<&str> {
let inner = s.strip_prefix('{')?.strip_suffix('}')?;
if inner.contains('{') || inner.contains('}') {
return None;
}
Some(inner)
}
// Whether a content-type literal is one that result-decoding / param-encoding
// can apply.
fn is_supported_content_type(ct: &str) -> bool {
matches!(ct, "application/json" | "text/plain")
}
// Check whether a WIT param's JSON Schema represents a byte array (list<u8>).
// A byte array is `{ type: "array", items: { type: "number", minimum: 0, maximum: 255 } }`.
fn is_byte_array_param_schema(schema: &Value) -> bool {
let Some(obj) = schema.as_object() else {
return false;
};
if obj.get("type").and_then(|t| t.as_str()) != Some("array") {
return false;
}
let Some(items) = obj.get("items") else {
return false;
};
items.get("type").and_then(|t| t.as_str()) == Some("number")
&& items.get("minimum").and_then(|m| m.as_u64()) == Some(0)
&& items.get("maximum").and_then(|m| m.as_u64()) == Some(255)
}
// Validate that a param-encoding path exists in the assembled-args view:
// first segment is a WIT param name; subsequent segments traverse that
// param's schema.
fn validate_param_encoding_path(
function: &crate::types::Function,
segments: &[PathSegment],
) -> Result<(), String> {
let first = segments.first().ok_or_else(|| "empty path".to_string())?;
let param_name = match first {
PathSegment::Key(k) => k.as_str(),
PathSegment::Index(i) => {
return Err(format!(
"first path segment must be a WIT param name, got index [{i}]"
));
}
};
let param = function
.params()
.iter()
.find(|p| p.name == param_name)
.ok_or_else(|| format!("no such WIT param '{param_name}'"))?;
crate::schema::validate_path_exists(¶m.json_schema, &segments[1..])
}
// Apply result-decoding to a WIT result. First resolves every content-type
// spec against the original wit_result, then decodes each named field and
// replaces its byte-array value with the decoded value.
//
// Returns a new `Value` with the decoded fields in place. Runtime errors:
// - content-type path is missing or null at runtime
// - content-type value is not a string
// - content-type value is not supported
// - field's value is not a byte array
// - byte payload is malformed for the declared content-type
fn apply_result_decoding(wit_result: &Value, decoding: &ResultDecoding) -> Result<Value, String> {
// Phase 1: resolve all content-types against the original wit_result.
let mut resolved: HashMap<&str, String> = HashMap::with_capacity(decoding.0.len());
for (field_name, spec) in &decoding.0 {
let ct = match spec {
ContentTypeSpec::Literal(s) => s.clone(),
ContentTypeSpec::Path(segments) => {
let mut current = wit_result;
for seg in segments {
let next = match seg {
PathSegment::Key(k) => current.get(k),
PathSegment::Index(i) => current.get(*i),
};
current = next.ok_or_else(|| {
format!("result-decoding '{field_name}': content-type path did not resolve")
})?;
}
match current {
Value::String(s) => s.clone(),
Value::Null => {
return Err(format!(
"result-decoding '{field_name}': content-type path resolved to null"
));
}
other => {
return Err(format!(
"result-decoding '{field_name}': content-type path must resolve to a string, got {other}"
));
}
}
}
};
if !is_supported_content_type(&ct) {
return Err(format!(
"result-decoding '{field_name}': content-type '{ct}' is not supported"
));
}
resolved.insert(field_name.as_str(), ct);
}
// Phase 2: decode each field and swap in the decoded value.
let mut out = wit_result.clone();
let out_obj = out
.as_object_mut()
.ok_or_else(|| "result-decoding requires the WIT result to be an object".to_string())?;
for (field_name, ct) in resolved {
let bytes = value_to_bytes(out_obj.get(field_name).ok_or_else(|| {
format!("result-decoding '{field_name}': field not present at runtime")
})?)
.ok_or_else(|| {
format!("result-decoding '{field_name}': field value is not a byte array")
})?;
let decoded = match ct.as_str() {
"application/json" => serde_json::from_slice::<Value>(&bytes).map_err(|e| {
format!("result-decoding '{field_name}': malformed application/json bytes: {e}")
})?,
"text/plain" => {
let s = std::str::from_utf8(&bytes).map_err(|e| {
format!("result-decoding '{field_name}': malformed text/plain bytes (not UTF-8): {e}")
})?;
Value::String(s.to_string())
}
_ => unreachable!("content-type already validated above"),
};
out_obj.insert(field_name.to_string(), decoded);
}
Ok(out)
}
// Convert a JSON array of integers into a Vec<u8> if all are in 0..=255.
fn value_to_bytes(v: &Value) -> Option<Vec<u8>> {
let arr = v.as_array()?;
let mut out = Vec::with_capacity(arr.len());
for item in arr {
let n = item.as_u64()?;
if n > 255 {
return None;
}
out.push(n as u8);
}
Some(out)
}
// Apply param-encoding to assembled WIT args. First resolves every
// content-type spec against the original assembled args, then encodes each
// named arg and replaces its value with the byte array.
//
// The `args` parameter is the positional args list (one per WIT param);
// `param_names` is the WIT param names in the same order, used to resolve
// path segments whose first segment names a param.
fn apply_param_encoding(
args: &mut [Value],
param_names: &[String],
encoding: &ParamEncoding,
) -> Result<(), String> {
// Phase 1: resolve all content-types against the original args view.
let mut resolved: HashMap<&str, String> = HashMap::with_capacity(encoding.0.len());
for (param_name, spec) in &encoding.0 {
let ct = match spec {
ContentTypeSpec::Literal(s) => s.clone(),
ContentTypeSpec::Path(segments) => resolve_param_path(args, param_names, segments)
.map_err(|e| format!("param-encoding '{param_name}': {e}"))?,
};
if !is_supported_content_type(&ct) {
return Err(format!(
"param-encoding '{param_name}': content-type '{ct}' is not supported"
));
}
resolved.insert(param_name.as_str(), ct);
}
// Phase 2: encode each named arg and replace its value.
for (param_name, ct) in resolved {
let idx = param_names
.iter()
.position(|n| n == param_name)
.ok_or_else(|| format!("param-encoding '{param_name}': no such param at runtime"))?;
let encoded = match ct.as_str() {
"application/json" => serde_json::to_vec(&args[idx]).map_err(|e| {
format!("param-encoding '{param_name}': failed to encode as application/json: {e}")
})?,
"text/plain" => match &args[idx] {
Value::String(s) => s.as_bytes().to_vec(),
Value::Null => {
return Err(format!(
"param-encoding '{param_name}': value is null; cannot encode as text/plain"
));
}
other => {
return Err(format!(
"param-encoding '{param_name}': cannot encode {other} as text/plain (expected string)"
));
}
},
_ => unreachable!("content-type already validated above"),
};
args[idx] = Value::Array(encoded.into_iter().map(|b| Value::from(b as u64)).collect());
}
Ok(())
}
// Resolve a param-encoding path against the assembled args. The first segment
// names a WIT param; subsequent segments traverse that arg's value.
fn resolve_param_path(
args: &[Value],
param_names: &[String],
segments: &[PathSegment],
) -> Result<String, String> {
let first = segments
.first()
.ok_or_else(|| "empty content-type path".to_string())?;
let param_name = match first {
PathSegment::Key(k) => k.as_str(),
PathSegment::Index(i) => {
return Err(format!(
"first path segment must be a WIT param name, got index [{i}]"
));
}
};
let idx = param_names
.iter()
.position(|n| n == param_name)
.ok_or_else(|| format!("content-type path references unknown param '{param_name}'"))?;
let mut current = &args[idx];
for seg in &segments[1..] {
let next = match seg {
PathSegment::Key(k) => current.get(k),
PathSegment::Index(i) => current.get(*i),
};
current = next.ok_or_else(|| "content-type path did not resolve".to_string())?;
}
match current {
Value::String(s) => Ok(s.clone()),
Value::Null => Err("content-type path resolved to null".to_string()),
other => Err(format!(
"content-type path must resolve to a string, got {other}"
)),
}
}
/// Messaging Mapper that mediates between the messaging layer and a
/// component's typed WIT function.
///
/// One mapper instance is bound to one WIT function. The component knows
/// nothing about messages, and the messaging layer knows nothing about WIT.
pub struct MessageMapper {
function_key: String,
params: Vec<FunctionParam>,
param_mapping: Option<ParamMapping>,
param_encoding: Option<ParamEncoding>,
result_decoding: Option<ResultDecoding>,
result_mapping: Option<Value>,
}
impl MessageMapper {
/// Create a mapper for a specific function on a component.
///
/// If `function_key` is `None`, the component must export exactly one
/// function. `config` carries the four optional mapping-related blocks.
/// See [`MappingConfig`].
pub fn from_component(
component: &Component,
function_key: Option<String>,
config: MappingConfig,
) -> Result<Self, String> {
let MappingConfig {
param_mapping,
param_encoding,
result_decoding,
result_mapping,
} = config;
let function_key = match function_key {
Some(key) => key,
None => {
let functions = &component.functions;
if functions.len() != 1 {
return Err(format!(
"mapper must specify a 'function' when component exports more than one: \
'{}' has {}",
component.metadata.name,
functions.len()
));
}
functions.keys().next().unwrap().clone()
}
};
let function = component.functions.get(&function_key).ok_or_else(|| {
format!(
"function '{}' not found in '{}'",
function_key, component.metadata.name
)
})?;
// Resolution-time validation for result-decoding:
// - Each key must reference a `list<u8>` field on the WIT result.
// - Each Path spec must reference an existing path on the WIT result.
// - Each Literal spec must be a supported content-type.
if let Some(decoding) = &result_decoding {
let result_schema = function.result().ok_or_else(|| {
format!(
"function '{}' has no return type; result-decoding requires one",
function.function_name()
)
})?;
for (field_name, spec) in &decoding.0 {
crate::schema::validate_byte_array_field(result_schema, field_name)?;
match spec {
ContentTypeSpec::Path(segments) => {
crate::schema::validate_path_exists(result_schema, segments).map_err(
|e| {
format!(
"result-decoding entry '{field_name}': content-type path invalid: {e}"
)
},
)?;
}
ContentTypeSpec::Literal(ct) => {
if !is_supported_content_type(ct) {
return Err(format!(
"result-decoding entry '{field_name}': content-type '{ct}' is not supported (supported: application/json, text/plain)"
));
}
}
}
}
}
// Resolution-time validation for param-encoding:
// - Each key must reference a WIT param whose type is `list<u8>`.
// - Each Path spec must reference an existing path in the WIT args.
// - Each Literal spec must be a supported content-type.
if let Some(encoding) = ¶m_encoding {
for (param_name, spec) in &encoding.0 {
let param = function
.params()
.iter()
.find(|p| p.name == *param_name)
.ok_or_else(|| {
format!(
"param-encoding entry '{param_name}': no such WIT param on function '{}'",
function.function_name()
)
})?;
if !is_byte_array_param_schema(¶m.json_schema) {
return Err(format!(
"param-encoding entry '{param_name}': WIT param must be a byte array (list<u8>)"
));
}
match spec {
ContentTypeSpec::Path(segments) => {
validate_param_encoding_path(function, segments).map_err(|e| {
format!(
"param-encoding entry '{param_name}': content-type path invalid: {e}"
)
})?;
}
ContentTypeSpec::Literal(ct) => {
if !is_supported_content_type(ct) {
return Err(format!(
"param-encoding entry '{param_name}': content-type '{ct}' is not supported (supported: application/json, text/plain)"
));
}
}
}
}
}
Ok(Self {
function_key,
params: function.params().to_vec(),
param_mapping,
param_encoding,
result_decoding,
result_mapping,
})
}
/// The function key this mapper is bound to.
pub fn function_key(&self) -> &str {
&self.function_key
}
/// Translate an inbound [`Message`] into an [`Invocation`].
///
/// The Message body is parsed per its content-type and is reachable from
/// templates via paths starting with `body`. Message headers are reachable
/// via paths starting with `headers`. Without templates, each WIT param
/// resolves by name-match against the parsed body.
pub fn to_invocation(&self, msg: &Message) -> Result<Invocation, String> {
if self.params.is_empty() {
return Ok(Invocation {
function_key: self.function_key.clone(),
args: vec![],
});
}
let parsed_body = parse_body(msg)?;
let headers = headers_as_value(msg);
// Build a source object with `body` and `headers` for template paths.
let template_source = Value::Object(
[
("body".to_string(), parsed_body.clone()),
("headers".to_string(), headers),
]
.into_iter()
.collect(),
);
// Name-match uses the (possibly wrapped) body directly.
let name_match_body = self.normalize_body(parsed_body)?;
let mut args = Vec::with_capacity(self.params.len());
for param in &self.params {
let value = match self.param_mapping.as_ref().and_then(|m| m.get(¶m.name)) {
Some(template) => substitute_value(template, &template_source)?,
None => name_match(param, &name_match_body)?,
};
args.push(value);
}
if let Some(encoding) = &self.param_encoding {
let param_names: Vec<String> = self.params.iter().map(|p| p.name.clone()).collect();
apply_param_encoding(&mut args, ¶m_names, encoding)?;
}
for (param, arg) in self.params.iter().zip(args.iter_mut()) {
let expects_string =
param.json_schema.get("type").and_then(|t| t.as_str()) == Some("string");
// Null represents an absent optional arg and must not be stringified.
if expects_string && !matches!(arg, Value::String(_) | Value::Null) {
*arg = Value::String(serde_json::to_string(arg).map_err(|e| {
format!(
"failed to stringify value for string arg '{}': {e}",
param.name
)
})?);
}
}
Ok(Invocation {
function_key: self.function_key.clone(),
args,
})
}
/// Translate a WIT-result [`Value`] into a reply [`Message`].
///
/// When `result_mapping` is absent, the WIT result becomes the reply body
/// as-is (serialized per content-type).
///
/// When `result_mapping` is present, it takes over: the `body` and
/// `headers` slots define the reply Message:
/// - `body` slot absent, `null`, or `""` => empty body (zero bytes).
/// - `body` slot containing a template => substitute against the WIT
/// result and serialize.
/// - `headers` slot containing a template => substitute against the WIT
/// result; the resulting object's key-value pairs become Message
/// headers.
///
/// Mapped headers are applied first, then `propagated` headers. A
/// `propagated` header with the same name as a mapped header overwrites
/// the mapped value.
pub fn from_invocation_result(
&self,
wit_result: &Value,
propagated: HashMap<String, String>,
) -> Result<Message, String> {
let content_type = propagated
.get(MessageHeaders::CONTENT_TYPE)
.map(String::as_str)
.unwrap_or("application/json");
// Apply result-decoding (if any) before mapping. Each declared field
// gets its byte-array value replaced with the decoded value, so
// downstream result-mapping templates traverse the decoded shape.
let decoded = match &self.result_decoding {
None => None,
Some(decoding) => Some(apply_result_decoding(wit_result, decoding)?),
};
let source = decoded.as_ref().unwrap_or(wit_result);
let (body_bytes, mapped_headers) = match &self.result_mapping {
None => (serialize_body(source, content_type)?, Map::new()),
Some(mapping) => {
let body_bytes = match mapping.get("body") {
None | Some(Value::Null) => Vec::new(),
Some(Value::String(s)) if s.is_empty() => Vec::new(),
Some(template) => {
let body_value = substitute_value(template, source)?;
serialize_body(&body_value, content_type)?
}
};
let mapped_headers = match mapping.get("headers") {
None | Some(Value::Null) => Map::new(),
Some(template) => {
let headers_value = substitute_value(template, source)?;
headers_value.as_object().cloned().ok_or_else(|| {
format!(
"result-mapping 'headers' must produce an object, got {headers_value}"
)
})?
}
};
(body_bytes, mapped_headers)
}
};
let mut builder = MessageBuilder::new(body_bytes);
for (key, value) in mapped_headers {
let value_str = match value {
Value::String(s) => s,
other => other.to_string(),
};
builder = builder.header(key, value_str);
}
for (key, value) in propagated {
builder = builder.header(key, value);
}
Ok(builder.build())
}
// Without a mapping, normalize the body to support name-match semantics:
// - Single-param function with a non-object body, OR an object body that
// does NOT contain the param's name: wrap as `{ <param.name>: body }`.
// This lets name-match still pick up the body as the single arg.
// - Multi-param function: body must be an object (so per-param
// name-match can find each field). A non-object body for a multi-param
// function will return an error.
// - With a mapping configured: pass body through unchanged.
fn normalize_body(&self, body: Value) -> Result<Value, String> {
if self.param_mapping.is_some() {
return Ok(body);
}
if self.params.len() == 1 {
let first = &self.params[0];
return Ok(match &body {
Value::Object(obj) if obj.contains_key(&first.name) => body,
_ => Value::Object([(first.name.clone(), body)].into_iter().collect()),
});
}
if !body.is_object() {
return Err(format!(
"non-object body cannot be mapped to {} parameters",
self.params.len()
));
}
Ok(body)
}
}
// Serialize a JSON Value into reply-body bytes per content-type. Used by
// `from_invocation_result`.
fn serialize_body(value: &Value, content_type: &str) -> Result<Vec<u8>, String> {
match content_type {
"text/plain" => match value {
Value::String(s) => Ok(s.as_bytes().to_vec()),
other => Ok(other.to_string().into_bytes()),
},
_ => serde_json::to_vec(value).map_err(|e| format!("failed to serialize result body: {e}")),
}
}
fn parse_body(msg: &Message) -> Result<Value, String> {
let content_type = msg.headers().content_type().unwrap_or("application/json");
match content_type {
"application/json" => {
if msg.body().is_empty() {
Ok(Value::Null)
} else {
serde_json::from_slice(msg.body())
.map_err(|e| format!("failed to parse body as JSON: {e}"))
}
}
"text/plain" => {
let text = std::str::from_utf8(msg.body())
.map_err(|e| format!("body is not valid UTF-8: {e}"))?;
Ok(Value::String(text.to_string()))
}
other => Err(format!("unsupported content-type: {other}")),
}
}
fn headers_as_value(msg: &Message) -> Value {
let mut map = Map::new();
for (key, val) in msg.headers().iter() {
map.insert(key.to_string(), Value::String(val.to_string()));
}
Value::Object(map)
}
fn name_match(param: &FunctionParam, body: &Value) -> Result<Value, String> {
match body.get(¶m.name) {
Some(v) => Ok(v.clone()),
None if param.is_optional => Ok(Value::Null),
None => Err(format!(
"missing required arg '{}' (no template and no name match in body)",
param.name
)),
}
}
// Substitute placeholders in a template Value against a single source.
// Path-only templates like `{path}` preserve the looked-up value's native
// JSON type. Interpolating string templates render as strings. Objects and
// arrays recurse.
fn substitute_value(template: &Value, source: &Value) -> Result<Value, String> {
match template {
Value::String(s) => {
if let Some(spec) = parse_path_only_template(s) {
resolve(&spec, source)
} else {
Ok(Value::String(substitute_string(s, source)?))
}
}
Value::Array(items) => items
.iter()
.map(|v| substitute_value(v, source))
.collect::<Result<Vec<_>, _>>()
.map(Value::Array),
Value::Object(map) => {
let mut out = Map::with_capacity(map.len());
for (k, v) in map {
out.insert(k.clone(), substitute_value(v, source)?);
}
Ok(Value::Object(out))
}
other => Ok(other.clone()),
}
}
// Parse a `{...}` token into a template spec. Returns None unless the entire
// string is a single `{...}` token (path-only template). Returns the inner
// spec parsed.
fn parse_path_only_template(s: &str) -> Option<TemplateSpec> {
let bytes = s.as_bytes();
if bytes.len() < 3 || bytes[0] != b'{' || bytes[bytes.len() - 1] != b'}' {
return None;
}
let inner = &s[1..s.len() - 1];
if inner.contains('{') || inner.contains('}') {
return None;
}
parse_spec(inner).ok()
}
// A path segment for traversing a JSON value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PathSegment {
Key(String),
Index(usize),
}
// A parsed `{path | "default"}` spec.
struct TemplateSpec {
path: Vec<PathSegment>,
raw_path: String,
default: Option<Value>,
}
fn parse_spec(inner: &str) -> Result<TemplateSpec, String> {
let trimmed = inner.trim();
if trimmed.is_empty() {
return Err("empty template reference '{}'".to_string());
}
// Split off `| "default"` first.
let (head, default) = match trimmed.split_once('|') {
Some((h, d)) => (h.trim(), Some(parse_default(d.trim())?)),
None => (trimmed, None),
};
if head.is_empty() {
return Err(format!("empty path in template reference '{{{inner}}}'"));
}
let path = parse_path(head)?;
Ok(TemplateSpec {
path,
raw_path: head.to_string(),
default,
})
}
// Parse a path string into segments. Grammar:
// - First segment: bare name (matches `[A-Za-z0-9_-]+`).
// - Subsequent segments: `.name`, `["string"]`, or `[integer]`.
pub(crate) fn parse_path(s: &str) -> Result<Vec<PathSegment>, String> {
let mut segments = Vec::new();
let bytes = s.as_bytes();
let mut i = 0;
// First segment: bare name.
let start = i;
while i < bytes.len() && is_name_char(bytes[i]) {
i += 1;
}
if i == start {
return Err(format!("path '{s}' must start with a name segment"));
}
segments.push(PathSegment::Key(s[start..i].to_string()));
// Subsequent segments.
while i < bytes.len() {
match bytes[i] {
b'.' => {
i += 1;
let start = i;
while i < bytes.len() && is_name_char(bytes[i]) {
i += 1;
}
if i == start {
return Err(format!("path '{s}' has empty segment after '.'"));
}
segments.push(PathSegment::Key(s[start..i].to_string()));
}
b'[' => {
i += 1;
if i >= bytes.len() {
return Err(format!("path '{s}' has unclosed '['"));
}
if bytes[i] == b'"' {
i += 1;
let start = i;
while i < bytes.len() && bytes[i] != b'"' {
i += 1;
}
if i >= bytes.len() {
return Err(format!("path '{s}' has unterminated quoted segment"));
}
let key = s[start..i].to_string();
i += 1; // closing quote
if i >= bytes.len() || bytes[i] != b']' {
return Err(format!("path '{s}' missing ']' after quoted segment"));
}
i += 1; // closing bracket
segments.push(PathSegment::Key(key));
} else {
let start = i;
while i < bytes.len() && bytes[i].is_ascii_digit() {
i += 1;
}
if i == start {
return Err(format!(
"path '{s}' has invalid bracket segment (expected integer or quoted string)"
));
}
let idx: usize = s[start..i].parse().map_err(|_| {
format!("path '{s}' has bracket-integer that is too large or invalid")
})?;
if i >= bytes.len() || bytes[i] != b']' {
return Err(format!("path '{s}' missing ']' after index"));
}
i += 1; // closing bracket
segments.push(PathSegment::Index(idx));
}
}
other => {
return Err(format!(
"path '{s}' has unexpected character '{}' at position {i}",
other as char
));
}
}
}
Ok(segments)
}
fn is_name_char(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_' || b == b'-'
}
// Parse the default literal that follows `|`. Supports quoted strings,
// numeric literals, true/false, and null.
fn parse_default(s: &str) -> Result<Value, String> {
let s = s.trim();
if s.is_empty() {
return Err("empty default literal after '|'".to_string());
}
serde_json::from_str(s).map_err(|e| format!("invalid default literal '{s}' after '|': {e}"))
}
fn resolve(spec: &TemplateSpec, source: &Value) -> Result<Value, String> {
let mut current = source;
for segment in &spec.path {
match segment {
PathSegment::Key(k) => match current.get(k) {
Some(v) => current = v,
None => {
return match &spec.default {
Some(default) => Ok(default.clone()),
None => Err(format!(
"template references unknown path: '{}'",
spec.raw_path
)),
};
}
},
PathSegment::Index(idx) => match current.get(*idx) {
Some(v) => current = v,
None => {
return match &spec.default {
Some(default) => Ok(default.clone()),
None => Err(format!(
"template references unknown path: '{}'",
spec.raw_path
)),
};
}
},
}