Skip to main content

hyperlight_common/flatbuffer_wrappers/
function_call.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025 The Hyperlight Authors.
3
4use alloc::string::{String, ToString};
5use alloc::vec::Vec;
6
7use anyhow::{Result, bail};
8use flatbuffers::{FlatBufferBuilder, WIPOffset, size_prefixed_root};
9#[cfg(feature = "tracing")]
10use tracing::{Span, instrument};
11
12use super::codec::{ExternalValueSink, ExternalValueSource};
13use super::function_types::{ParameterValue, ReturnType, decode_parameter_value};
14use super::util::try_byte_chunks_len;
15use crate::flatbuffers::hyperlight::generated::{
16    FunctionCall as FbFunctionCall, FunctionCallArgs as FbFunctionCallArgs,
17    FunctionCallType as FbFunctionCallType, Parameter, ParameterArgs,
18    ParameterValue as FbParameterValue, hlbool, hlboolArgs, hldouble, hldoubleArgs,
19    hlexternalbytes, hlexternalbytesArgs, hlfloat, hlfloatArgs, hlint, hlintArgs, hllong,
20    hllongArgs, hlstring, hlstringArgs, hluint, hluintArgs, hlulong, hlulongArgs,
21};
22
23/// The type of function call.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub enum FunctionCallType {
26    /// The function call is to a guest function.
27    Guest,
28    /// The function call is to a host function.
29    Host,
30}
31
32/// `Functioncall` represents a call to a function in the guest or host.
33#[derive(Clone)]
34pub struct FunctionCall {
35    /// The function name
36    pub function_name: String,
37    /// The parameters for the function call.
38    pub parameters: Option<Vec<ParameterValue>>,
39    function_call_type: FunctionCallType,
40    /// The return type of the function call
41    pub expected_return_type: ReturnType,
42}
43
44impl FunctionCall {
45    #[cfg_attr(feature = "tracing", instrument(skip_all, parent = Span::current(), level= "Trace"))]
46    pub fn new(
47        function_name: String,
48        parameters: Option<Vec<ParameterValue>>,
49        function_call_type: FunctionCallType,
50        expected_return_type: ReturnType,
51    ) -> Self {
52        Self {
53            function_name,
54            parameters,
55            function_call_type,
56            expected_return_type,
57        }
58    }
59
60    /// The type of the function call.
61    pub fn function_call_type(&self) -> FunctionCallType {
62        self.function_call_type.clone()
63    }
64
65    /// Encode control data and collect byte parameters as external values.
66    pub fn encode<'a, 'b, S>(
67        &'a self,
68        builder: &'b mut FlatBufferBuilder,
69        external_values: &mut S,
70    ) -> Result<&'b [u8]>
71    where
72        S: ExternalValueSink<'a> + ?Sized,
73    {
74        let function_name = builder.create_string(&self.function_name);
75
76        let function_call_type = match self.function_call_type {
77            FunctionCallType::Guest => FbFunctionCallType::guest,
78            FunctionCallType::Host => FbFunctionCallType::host,
79        };
80
81        let expected_return_type = self.expected_return_type.into();
82
83        let parameters = match &self.parameters {
84            Some(parameters) if !parameters.is_empty() => {
85                let parameter_offsets: Vec<WIPOffset<Parameter>> = parameters
86                    .iter()
87                    .map(|parameter| -> Result<WIPOffset<Parameter>> {
88                        let parameter = match parameter {
89                            ParameterValue::Int(value) => {
90                                let value = hlint::create(builder, &hlintArgs { value: *value });
91                                Parameter::create(
92                                    builder,
93                                    &ParameterArgs {
94                                        value_type: FbParameterValue::hlint,
95                                        value: Some(value.as_union_value()),
96                                    },
97                                )
98                            }
99                            ParameterValue::UInt(value) => {
100                                let value = hluint::create(builder, &hluintArgs { value: *value });
101                                Parameter::create(
102                                    builder,
103                                    &ParameterArgs {
104                                        value_type: FbParameterValue::hluint,
105                                        value: Some(value.as_union_value()),
106                                    },
107                                )
108                            }
109                            ParameterValue::Long(value) => {
110                                let value = hllong::create(builder, &hllongArgs { value: *value });
111                                Parameter::create(
112                                    builder,
113                                    &ParameterArgs {
114                                        value_type: FbParameterValue::hllong,
115                                        value: Some(value.as_union_value()),
116                                    },
117                                )
118                            }
119                            ParameterValue::ULong(value) => {
120                                let value =
121                                    hlulong::create(builder, &hlulongArgs { value: *value });
122                                Parameter::create(
123                                    builder,
124                                    &ParameterArgs {
125                                        value_type: FbParameterValue::hlulong,
126                                        value: Some(value.as_union_value()),
127                                    },
128                                )
129                            }
130                            ParameterValue::Float(value) => {
131                                let value =
132                                    hlfloat::create(builder, &hlfloatArgs { value: *value });
133                                Parameter::create(
134                                    builder,
135                                    &ParameterArgs {
136                                        value_type: FbParameterValue::hlfloat,
137                                        value: Some(value.as_union_value()),
138                                    },
139                                )
140                            }
141                            ParameterValue::Double(value) => {
142                                let value =
143                                    hldouble::create(builder, &hldoubleArgs { value: *value });
144                                Parameter::create(
145                                    builder,
146                                    &ParameterArgs {
147                                        value_type: FbParameterValue::hldouble,
148                                        value: Some(value.as_union_value()),
149                                    },
150                                )
151                            }
152                            ParameterValue::Bool(value) => {
153                                let value = hlbool::create(builder, &hlboolArgs { value: *value });
154                                Parameter::create(
155                                    builder,
156                                    &ParameterArgs {
157                                        value_type: FbParameterValue::hlbool,
158                                        value: Some(value.as_union_value()),
159                                    },
160                                )
161                            }
162                            ParameterValue::String(value) => {
163                                let value = builder.create_string(value.as_str());
164                                let value =
165                                    hlstring::create(builder, &hlstringArgs { value: Some(value) });
166                                Parameter::create(
167                                    builder,
168                                    &ParameterArgs {
169                                        value_type: FbParameterValue::hlstring,
170                                        value: Some(value.as_union_value()),
171                                    },
172                                )
173                            }
174                            ParameterValue::VecBytes(value) => {
175                                let length = u64::try_from(value.len()).map_err(|_| {
176                                    anyhow::anyhow!(
177                                        "External VecBytes parameter length does not fit in u64"
178                                    )
179                                })?;
180                                external_values.push_bytes(value)?;
181                                let value = hlexternalbytes::create(
182                                    builder,
183                                    &hlexternalbytesArgs {
184                                        length,
185                                        chunked: false,
186                                    },
187                                );
188                                Parameter::create(
189                                    builder,
190                                    &ParameterArgs {
191                                        value_type: FbParameterValue::hlexternalbytes,
192                                        value: Some(value.as_union_value()),
193                                    },
194                                )
195                            }
196                            ParameterValue::ByteChunks(value) => {
197                                let length = try_byte_chunks_len(value).ok_or_else(|| {
198                                    anyhow::anyhow!("External ByteChunks parameter length overflow")
199                                })?;
200                                let length = u64::try_from(length).map_err(|_| {
201                                    anyhow::anyhow!(
202                                        "External ByteChunks parameter length does not fit in u64"
203                                    )
204                                })?;
205                                external_values.push_chunks(value)?;
206                                let value = hlexternalbytes::create(
207                                    builder,
208                                    &hlexternalbytesArgs {
209                                        length,
210                                        chunked: true,
211                                    },
212                                );
213                                Parameter::create(
214                                    builder,
215                                    &ParameterArgs {
216                                        value_type: FbParameterValue::hlexternalbytes,
217                                        value: Some(value.as_union_value()),
218                                    },
219                                )
220                            }
221                        };
222                        Ok(parameter)
223                    })
224                    .collect::<Result<Vec<_>>>()?;
225                Some(builder.create_vector(&parameter_offsets))
226            }
227            _ => None,
228        };
229
230        let function_call = FbFunctionCall::create(
231            builder,
232            &FbFunctionCallArgs {
233                function_name: Some(function_name),
234                parameters,
235                function_call_type,
236                expected_return_type,
237            },
238        );
239        builder.finish_size_prefixed(function_call, None);
240        Ok(builder.finished_data())
241    }
242
243    /// Decode control data and consume external byte parameters.
244    pub fn decode<S>(value: &[u8], external_values: &mut S) -> Result<Self>
245    where
246        S: ExternalValueSource + ?Sized,
247    {
248        let function_call_fb = size_prefixed_root::<FbFunctionCall>(value)
249            .map_err(|e| anyhow::anyhow!("Error reading function call buffer: {:?}", e))?;
250        let function_name = function_call_fb.function_name();
251        let function_call_type = match function_call_fb.function_call_type() {
252            FbFunctionCallType::guest => FunctionCallType::Guest,
253            FbFunctionCallType::host => FunctionCallType::Host,
254            other => {
255                bail!("Invalid function call type: {:?}", other);
256            }
257        };
258        let expected_return_type = function_call_fb.expected_return_type().try_into()?;
259
260        let parameters = function_call_fb
261            .parameters()
262            .map(|parameters| {
263                parameters
264                    .iter()
265                    .map(|parameter| decode_parameter_value(parameter, external_values))
266                    .collect::<Result<Vec<ParameterValue>>>()
267            })
268            .transpose()?;
269
270        external_values.finish()?;
271        Ok(Self {
272            function_name: function_name.to_string(),
273            parameters,
274            function_call_type,
275            expected_return_type,
276        })
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use alloc::collections::VecDeque;
283    use alloc::vec;
284
285    use super::*;
286    use crate::flatbuffer_wrappers::function_types::{Bytes, ReturnType};
287
288    #[derive(Debug, Clone, PartialEq)]
289    enum TestExternalValue {
290        VecBytes(Vec<u8>),
291        ByteChunks(Vec<Bytes>),
292    }
293
294    #[derive(Default)]
295    struct TestExternalValues {
296        values: VecDeque<TestExternalValue>,
297    }
298
299    impl TestExternalValues {
300        fn from_values(values: impl IntoIterator<Item = TestExternalValue>) -> Self {
301            Self {
302                values: values.into_iter().collect(),
303            }
304        }
305    }
306
307    impl<'a> ExternalValueSink<'a> for TestExternalValues {
308        fn push_bytes(&mut self, value: &'a [u8]) -> Result<()> {
309            self.values
310                .push_back(TestExternalValue::VecBytes(value.to_vec()));
311            Ok(())
312        }
313
314        fn push_chunks(&mut self, value: &'a [Bytes]) -> Result<()> {
315            self.values
316                .push_back(TestExternalValue::ByteChunks(value.to_vec()));
317            Ok(())
318        }
319    }
320
321    impl ExternalValueSource for TestExternalValues {
322        fn take_bytes(&mut self, _length: usize) -> Result<Vec<u8>> {
323            match self.values.pop_front() {
324                Some(TestExternalValue::VecBytes(value)) => Ok(value),
325                Some(TestExternalValue::ByteChunks(_)) => {
326                    anyhow::bail!("Expected external VecBytes value")
327                }
328                None => anyhow::bail!("Missing external VecBytes value"),
329            }
330        }
331
332        fn take_chunks(&mut self, _length: usize) -> Result<Vec<Bytes>> {
333            match self.values.pop_front() {
334                Some(TestExternalValue::ByteChunks(value)) => Ok(value),
335                Some(TestExternalValue::VecBytes(_)) => {
336                    anyhow::bail!("Expected external ByteChunks value")
337                }
338                None => anyhow::bail!("Missing external ByteChunks value"),
339            }
340        }
341
342        fn finish(&mut self) -> Result<()> {
343            if self.values.is_empty() {
344                Ok(())
345            } else {
346                anyhow::bail!("Unused external values")
347            }
348        }
349    }
350
351    #[test]
352    fn read_from_flatbuffer() -> Result<()> {
353        let mut builder = FlatBufferBuilder::new();
354        let mut external_values = TestExternalValues::default();
355        let test_data = FunctionCall::new(
356            "PrintTwelveArgs".to_string(),
357            Some(vec![
358                ParameterValue::String("1".to_string()),
359                ParameterValue::Int(2),
360                ParameterValue::Long(3),
361                ParameterValue::String("4".to_string()),
362                ParameterValue::String("5".to_string()),
363                ParameterValue::Bool(true),
364                ParameterValue::Bool(false),
365                ParameterValue::UInt(8),
366                ParameterValue::ULong(9),
367                ParameterValue::Int(10),
368                ParameterValue::Float(3.123),
369                ParameterValue::Double(0.01),
370            ]),
371            FunctionCallType::Guest,
372            ReturnType::Int,
373        )
374        .encode(&mut builder, &mut external_values)?;
375
376        let function_call = FunctionCall::decode(test_data, &mut external_values)?;
377        assert_eq!(function_call.function_name, "PrintTwelveArgs");
378        assert!(function_call.parameters.is_some());
379        let parameters = function_call.parameters.unwrap();
380        assert_eq!(parameters.len(), 12);
381        let expected_parameters = vec![
382            ParameterValue::String("1".to_string()),
383            ParameterValue::Int(2),
384            ParameterValue::Long(3),
385            ParameterValue::String("4".to_string()),
386            ParameterValue::String("5".to_string()),
387            ParameterValue::Bool(true),
388            ParameterValue::Bool(false),
389            ParameterValue::UInt(8),
390            ParameterValue::ULong(9),
391            ParameterValue::Int(10),
392            ParameterValue::Float(3.123),
393            ParameterValue::Double(0.01),
394        ];
395        assert!(expected_parameters == parameters);
396        assert_eq!(function_call.function_call_type, FunctionCallType::Guest);
397
398        Ok(())
399    }
400
401    #[test]
402    fn byte_parameters_round_trip_in_external_value_order() {
403        let mut builder = FlatBufferBuilder::new();
404        let expected_parameters = vec![
405            ParameterValue::Int(7),
406            ParameterValue::UInt(8),
407            ParameterValue::Long(-9),
408            ParameterValue::ULong(10),
409            ParameterValue::Float(1.25),
410            ParameterValue::Double(2.5),
411            ParameterValue::Bool(true),
412            ParameterValue::VecBytes(vec![0xa5; 4096]),
413            ParameterValue::String("middle".to_string()),
414            ParameterValue::ByteChunks(vec![
415                Bytes::from_static(b"chunk one"),
416                Bytes::from_static(b" and two"),
417            ]),
418            ParameterValue::VecBytes(Vec::new()),
419            ParameterValue::ByteChunks(Vec::new()),
420        ];
421        let call = FunctionCall::new(
422            "external_bytes".to_string(),
423            Some(expected_parameters.clone()),
424            FunctionCallType::Host,
425            ReturnType::ByteChunks,
426        );
427        let mut external_values = TestExternalValues::default();
428        let encoded = call.encode(&mut builder, &mut external_values).unwrap();
429
430        assert!(encoded.len() < 4096);
431        assert_eq!(
432            external_values.values,
433            VecDeque::from([
434                TestExternalValue::VecBytes(vec![0xa5; 4096]),
435                TestExternalValue::ByteChunks(vec![
436                    Bytes::from_static(b"chunk one"),
437                    Bytes::from_static(b" and two"),
438                ]),
439                TestExternalValue::VecBytes(Vec::new()),
440                TestExternalValue::ByteChunks(Vec::new()),
441            ])
442        );
443
444        let encoded_call = size_prefixed_root::<FbFunctionCall>(encoded).unwrap();
445        let encoded_parameters = encoded_call.parameters().unwrap();
446        for (index, length, chunked) in [
447            (7, 4096, false),
448            (9, 17, true),
449            (10, 0, false),
450            (11, 0, true),
451        ] {
452            let parameter = encoded_parameters.get(index);
453            assert_eq!(parameter.value_type(), FbParameterValue::hlexternalbytes);
454            let metadata = parameter.value_as_hlexternalbytes().unwrap();
455            assert_eq!(metadata.length(), length);
456            assert_eq!(metadata.chunked(), chunked);
457        }
458
459        let decoded = FunctionCall::decode(encoded, &mut external_values).unwrap();
460        assert_eq!(decoded.function_name, "external_bytes");
461        assert_eq!(decoded.parameters, Some(expected_parameters));
462        assert_eq!(decoded.function_call_type(), FunctionCallType::Host);
463        assert_eq!(decoded.expected_return_type, ReturnType::ByteChunks);
464        assert!(external_values.values.is_empty());
465    }
466
467    #[test]
468    fn scalar_call_uses_no_external_values() {
469        let call = FunctionCall::new(
470            "scalars".to_string(),
471            Some(vec![
472                ParameterValue::Int(42),
473                ParameterValue::String("value".to_string()),
474            ]),
475            FunctionCallType::Guest,
476            ReturnType::Bool,
477        );
478        let mut builder = FlatBufferBuilder::new();
479        let mut external_values = TestExternalValues::default();
480        let encoded = call.encode(&mut builder, &mut external_values).unwrap();
481
482        assert!(external_values.values.is_empty());
483        let decoded = FunctionCall::decode(encoded, &mut external_values).unwrap();
484        assert_eq!(decoded.function_name, "scalars");
485    }
486
487    #[test]
488    fn external_parameter_decoder_rejects_invalid_value_sequences() {
489        let mut builder = FlatBufferBuilder::new();
490        let call = FunctionCall::new(
491            "external_bytes".to_string(),
492            Some(vec![ParameterValue::VecBytes(vec![1, 2, 3])]),
493            FunctionCallType::Guest,
494            ReturnType::Void,
495        );
496        let mut encoded_values = TestExternalValues::default();
497        let encoded = call.encode(&mut builder, &mut encoded_values).unwrap();
498
499        let mut missing = TestExternalValues::default();
500        assert!(FunctionCall::decode(encoded, &mut missing).is_err());
501
502        let mut wrong_type =
503            TestExternalValues::from_values([TestExternalValue::ByteChunks(vec![
504                Bytes::from_static(b"123"),
505            ])]);
506        assert!(FunctionCall::decode(encoded, &mut wrong_type).is_err());
507
508        let mut wrong_length =
509            TestExternalValues::from_values([TestExternalValue::VecBytes(vec![1, 2])]);
510        assert!(FunctionCall::decode(encoded, &mut wrong_length).is_err());
511
512        let mut extra = TestExternalValues::from_values([
513            TestExternalValue::VecBytes(vec![1, 2, 3]),
514            TestExternalValue::VecBytes(Vec::new()),
515        ]);
516        assert!(FunctionCall::decode(encoded, &mut extra).is_err());
517    }
518}