rib/
call_type.rs

1// Copyright 2024-2025 Golem Cloud
2//
3// Licensed under the Golem Source License v1.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://license.golem.cloud/LICENSE
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::{ComponentDependencyKey, DynamicParsedFunctionName, Expr};
16use crate::{FullyQualifiedResourceConstructor, VariableId};
17use std::fmt::Display;
18
19#[derive(Debug, Hash, PartialEq, Eq, Clone, Ord, PartialOrd)]
20pub enum CallType {
21    Function {
22        component_info: Option<ComponentDependencyKey>,
23        // as compilation progress the function call is expected to a instance_identifier
24        // and will be always `Some`.
25        instance_identifier: Option<Box<InstanceIdentifier>>,
26        // TODO; a dynamic-parsed-function-name can be replaced by ParsedFunctionName
27        // after the introduction of non-lazy resource constructor.
28        function_name: DynamicParsedFunctionName,
29    },
30    VariantConstructor(String),
31    EnumConstructor(String),
32    InstanceCreation(InstanceCreationType),
33}
34
35// InstanceIdentifier holds the variables that are used to identify a worker or resource instance.
36// Unlike InstanceCreationType, this type can be formed only after the instance is inferred
37#[derive(Debug, Hash, PartialEq, Eq, Clone, Ord, PartialOrd)]
38pub enum InstanceIdentifier {
39    WitWorker {
40        variable_id: Option<VariableId>,
41        worker_name: Option<Box<Expr>>,
42    },
43
44    WitResource {
45        variable_id: Option<VariableId>,
46        worker_name: Option<Box<Expr>>,
47        resource_name: String,
48    },
49}
50
51impl InstanceIdentifier {
52    pub fn worker_name_mut(&mut self) -> Option<&mut Box<Expr>> {
53        match self {
54            InstanceIdentifier::WitWorker { worker_name, .. } => worker_name.as_mut(),
55            InstanceIdentifier::WitResource { worker_name, .. } => worker_name.as_mut(),
56        }
57    }
58    pub fn worker_name(&self) -> Option<&Expr> {
59        match self {
60            InstanceIdentifier::WitWorker { worker_name, .. } => worker_name.as_deref(),
61            InstanceIdentifier::WitResource { worker_name, .. } => worker_name.as_deref(),
62        }
63    }
64}
65
66#[derive(Debug, Hash, PartialEq, Eq, Clone, Ord, PartialOrd)]
67pub enum InstanceCreationType {
68    // A wit worker instance can be created without another module
69    WitWorker {
70        component_info: Option<ComponentDependencyKey>,
71        worker_name: Option<Box<Expr>>,
72    },
73    // an instance type of the type wit-resource can only be part of
74    // another instance (we call it module), which can be theoretically only be
75    // a worker, but we don't restrict this in types, such that it will easily
76    // handle nested wit resources
77    WitResource {
78        component_info: Option<ComponentDependencyKey>,
79        // this module identifier during resource creation will be always a worker module, but we don't necessarily restrict
80        // i.e, we do allow nested resource construction
81        module: Option<InstanceIdentifier>,
82        resource_name: FullyQualifiedResourceConstructor,
83    },
84}
85
86impl InstanceCreationType {
87    pub fn worker_name(&self) -> Option<Expr> {
88        match self {
89            InstanceCreationType::WitWorker { worker_name, .. } => worker_name.as_deref().cloned(),
90            InstanceCreationType::WitResource { module, .. } => {
91                let r = module.as_ref().and_then(|m| m.worker_name());
92                r.cloned()
93            }
94        }
95    }
96}
97
98impl CallType {
99    pub fn function_name(&self) -> Option<DynamicParsedFunctionName> {
100        match self {
101            CallType::Function { function_name, .. } => Some(function_name.clone()),
102            _ => None,
103        }
104    }
105    pub fn worker_expr(&self) -> Option<&Expr> {
106        match self {
107            CallType::Function {
108                instance_identifier,
109                ..
110            } => {
111                let module = instance_identifier.as_ref()?;
112                module.worker_name()
113            }
114            _ => None,
115        }
116    }
117
118    pub fn function_call(
119        function: DynamicParsedFunctionName,
120        component_info: Option<ComponentDependencyKey>,
121    ) -> CallType {
122        CallType::Function {
123            instance_identifier: None,
124            function_name: function,
125            component_info,
126        }
127    }
128
129    pub fn function_call_with_worker(
130        module: InstanceIdentifier,
131        function: DynamicParsedFunctionName,
132        component_info: Option<ComponentDependencyKey>,
133    ) -> CallType {
134        CallType::Function {
135            instance_identifier: Some(Box::new(module)),
136            function_name: function,
137            component_info,
138        }
139    }
140
141    pub fn is_resource_method(&self) -> bool {
142        match self {
143            CallType::Function { function_name, .. } => function_name
144                .to_parsed_function_name()
145                .function
146                .resource_method_name()
147                .is_some(),
148            _ => false,
149        }
150    }
151}
152
153impl Display for CallType {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        match self {
156            CallType::Function { function_name, .. } => write!(f, "{function_name}"),
157            CallType::VariantConstructor(name) => write!(f, "{name}"),
158            CallType::EnumConstructor(name) => write!(f, "{name}"),
159            CallType::InstanceCreation(instance_creation_type) => match instance_creation_type {
160                InstanceCreationType::WitWorker { .. } => {
161                    write!(f, "instance")
162                }
163                InstanceCreationType::WitResource { resource_name, .. } => {
164                    write!(f, "{}", resource_name.resource_name)
165                }
166            },
167        }
168    }
169}
170
171#[cfg(feature = "protobuf")]
172mod protobuf {
173    use crate::call_type::{CallType, InstanceCreationType};
174    use crate::FullyQualifiedResourceConstructor;
175    use crate::{ComponentDependencyKey, DynamicParsedFunctionName, Expr, ParsedFunctionName};
176    use golem_api_grpc::proto::golem::rib::WorkerInstance;
177
178    impl TryFrom<golem_api_grpc::proto::golem::rib::ComponentDependencyKey> for ComponentDependencyKey {
179        type Error = String;
180
181        fn try_from(
182            value: golem_api_grpc::proto::golem::rib::ComponentDependencyKey,
183        ) -> Result<Self, Self::Error> {
184            let component_name = value.component_name;
185            let component_id = value.value.ok_or("Missing component id")?;
186
187            let root_package_name = value.root_package_name;
188
189            let root_package_version = value.root_package_version;
190
191            Ok(ComponentDependencyKey {
192                component_name,
193                component_id: component_id.into(),
194                root_package_name,
195                root_package_version,
196            })
197        }
198    }
199
200    impl From<ComponentDependencyKey> for golem_api_grpc::proto::golem::rib::ComponentDependencyKey {
201        fn from(value: ComponentDependencyKey) -> Self {
202            golem_api_grpc::proto::golem::rib::ComponentDependencyKey {
203                component_name: value.component_name,
204                value: Some(value.component_id.into()),
205                root_package_name: value.root_package_name,
206                root_package_version: value.root_package_version,
207            }
208        }
209    }
210
211    impl TryFrom<golem_api_grpc::proto::golem::rib::InstanceCreationType> for InstanceCreationType {
212        type Error = String;
213        fn try_from(
214            value: golem_api_grpc::proto::golem::rib::InstanceCreationType,
215        ) -> Result<Self, Self::Error> {
216            match value.kind.ok_or("Missing instance creation kind")? {
217                golem_api_grpc::proto::golem::rib::instance_creation_type::Kind::Worker(
218                    worker_instance,
219                ) => {
220                    let worker_name = worker_instance
221                        .worker_name
222                        .map(|w| Expr::try_from(*w))
223                        .transpose()?
224                        .map(Box::new);
225
226                    Ok(InstanceCreationType::WitWorker {
227                        component_info: None,
228                        worker_name,
229                    })
230                }
231                golem_api_grpc::proto::golem::rib::instance_creation_type::Kind::Resource(
232                    resource_instance,
233                ) => {
234                    let resource_constructor_proto = resource_instance
235                        .resource_name
236                        .ok_or("Missing resource name")?;
237                    let resource_name =
238                        FullyQualifiedResourceConstructor::try_from(resource_constructor_proto)?;
239
240                    let component_info = resource_instance
241                        .component
242                        .map(ComponentDependencyKey::try_from)
243                        .transpose()?;
244
245                    Ok(InstanceCreationType::WitResource {
246                        component_info,
247                        module: None,
248                        resource_name,
249                    })
250                }
251            }
252        }
253    }
254
255    impl From<InstanceCreationType> for golem_api_grpc::proto::golem::rib::InstanceCreationType {
256        fn from(value: InstanceCreationType) -> Self {
257            match value {
258                InstanceCreationType::WitWorker { component_info, .. } => {
259                    golem_api_grpc::proto::golem::rib::InstanceCreationType {
260                        kind: Some(golem_api_grpc::proto::golem::rib::instance_creation_type::Kind::Worker(Box::new(WorkerInstance {
261                            component: component_info.map(golem_api_grpc::proto::golem::rib::ComponentDependencyKey::from),
262                            worker_name: None
263                        }))),
264                    }
265                }
266                InstanceCreationType::WitResource { component_info, resource_name, .. } => {
267                    golem_api_grpc::proto::golem::rib::InstanceCreationType {
268                        kind: Some(golem_api_grpc::proto::golem::rib::instance_creation_type::Kind::Resource(Box::new(golem_api_grpc::proto::golem::rib::ResourceInstanceWithWorkerName {
269                            component: component_info.map(golem_api_grpc::proto::golem::rib::ComponentDependencyKey::from),
270                            worker_name: None,
271                            resource_name: Some(golem_api_grpc::proto::golem::rib::FullyQualifiedResourceConstructor::from(resource_name)),
272                        }))),
273                    }
274                }
275            }
276        }
277    }
278
279    impl TryFrom<golem_api_grpc::proto::golem::rib::CallType> for CallType {
280        type Error = String;
281        fn try_from(
282            value: golem_api_grpc::proto::golem::rib::CallType,
283        ) -> Result<Self, Self::Error> {
284            let invocation = value.name.ok_or("Missing name of invocation")?;
285            match invocation {
286                golem_api_grpc::proto::golem::rib::call_type::Name::Parsed(name) => {
287                    Ok(CallType::Function {
288                        component_info: None,
289                        function_name: DynamicParsedFunctionName::try_from(name)?,
290                        instance_identifier: None,
291                    })
292                }
293                golem_api_grpc::proto::golem::rib::call_type::Name::VariantConstructor(name) => {
294                    Ok(CallType::VariantConstructor(name))
295                }
296                golem_api_grpc::proto::golem::rib::call_type::Name::EnumConstructor(name) => {
297                    Ok(CallType::EnumConstructor(name))
298                }
299
300                golem_api_grpc::proto::golem::rib::call_type::Name::InstanceCreation(
301                    instance_creation,
302                ) => {
303                    let instance_creation = InstanceCreationType::try_from(*instance_creation)?;
304                    Ok(CallType::InstanceCreation(instance_creation))
305                }
306            }
307        }
308    }
309
310    impl From<CallType> for golem_api_grpc::proto::golem::rib::CallType {
311        fn from(value: CallType) -> Self {
312            match value {
313                CallType::Function {
314                    function_name,
315                    ..
316                } => golem_api_grpc::proto::golem::rib::CallType {
317                    name: Some(golem_api_grpc::proto::golem::rib::call_type::Name::Parsed(
318                        function_name.into(),
319                    )),
320                },
321                CallType::VariantConstructor(name) => golem_api_grpc::proto::golem::rib::CallType {
322                    name: Some(
323                        golem_api_grpc::proto::golem::rib::call_type::Name::VariantConstructor(
324                            name,
325                        ),
326                    ),
327                },
328                CallType::EnumConstructor(name) => golem_api_grpc::proto::golem::rib::CallType {
329                    name: Some(
330                        golem_api_grpc::proto::golem::rib::call_type::Name::EnumConstructor(name),
331                    ),
332                },
333                CallType::InstanceCreation(instance_creation) => {
334                    match instance_creation {
335                        InstanceCreationType::WitWorker { worker_name , component_info} => {
336                            golem_api_grpc::proto::golem::rib::CallType {
337                                name:  Some(golem_api_grpc::proto::golem::rib::call_type::Name::InstanceCreation(
338                                    Box::new(golem_api_grpc::proto::golem::rib::InstanceCreationType {
339                                        kind: Some(golem_api_grpc::proto::golem::rib::instance_creation_type::Kind::Worker(Box::new(WorkerInstance {
340                                            component: component_info.map(golem_api_grpc::proto::golem::rib::ComponentDependencyKey::from),
341                                            worker_name: worker_name.map(|w| Box::new(golem_api_grpc::proto::golem::rib::Expr::from(*w))),
342                                        }))),
343                                    })
344                                )),
345                            }
346                        }
347                        InstanceCreationType::WitResource { resource_name, component_info, .. } => {
348                            golem_api_grpc::proto::golem::rib::CallType {
349                                name:  Some(golem_api_grpc::proto::golem::rib::call_type::Name::InstanceCreation(
350                                    Box::new(golem_api_grpc::proto::golem::rib::InstanceCreationType {
351                                        kind: Some(golem_api_grpc::proto::golem::rib::instance_creation_type::Kind::Resource(Box::new(golem_api_grpc::proto::golem::rib::ResourceInstanceWithWorkerName {
352                                            component: component_info.map(golem_api_grpc::proto::golem::rib::ComponentDependencyKey::from),
353                                            worker_name: None,
354                                            resource_name: Some(golem_api_grpc::proto::golem::rib::FullyQualifiedResourceConstructor::from(resource_name)),
355                                        }))),
356                                    })
357                                )),
358                            }
359                        }
360                    }
361                }
362            }
363        }
364    }
365
366    // InvocationName is a legacy structure to keep the backward compatibility.
367    // InvocationName is corresponding to the new CallType and the difference here is,
368    // InvocationName::Function will always hold a static function name and not a dynamic one
369    // with Expr representing resource construction parameters
370    impl TryFrom<golem_api_grpc::proto::golem::rib::InvocationName> for CallType {
371        type Error = String;
372        fn try_from(
373            value: golem_api_grpc::proto::golem::rib::InvocationName,
374        ) -> Result<Self, Self::Error> {
375            let invocation = value.name.ok_or("Missing name of invocation")?;
376            match invocation {
377                golem_api_grpc::proto::golem::rib::invocation_name::Name::Parsed(name) => {
378                    Ok(CallType::Function {
379                        component_info: None,
380                        instance_identifier: None,
381                        function_name: DynamicParsedFunctionName::parse(
382                            ParsedFunctionName::try_from(name)?.to_string(),
383                        )?,
384                    })
385                }
386                golem_api_grpc::proto::golem::rib::invocation_name::Name::VariantConstructor(
387                    name,
388                ) => Ok(CallType::VariantConstructor(name)),
389                golem_api_grpc::proto::golem::rib::invocation_name::Name::EnumConstructor(name) => {
390                    Ok(CallType::EnumConstructor(name))
391                }
392            }
393        }
394    }
395}