Skip to main content

tembra_runtime/host/
acquisition.rs

1//! Reference acquisition and policy checks share the kernel's ownership graph.
2use super::*;
3
4/// Requirements applied when acquiring a service reference.
5#[derive(Clone, Debug, Default)]
6pub struct AcquisitionOptions {
7    pub api_version: core::Version,
8    pub methods: BTreeSet<String>,
9}
10
11impl Host {
12    /// Acquire a reference with an explicit API version and allowed method requirement.
13    pub fn get_with_options(
14        &self,
15        service: &str,
16        key: Vec<String>,
17        principal: &str,
18        options: AcquisitionOptions,
19    ) -> Result<Reference> {
20        self.acquire(service, key, principal, options, None)
21    }
22
23    /// Acquire after the exact previous instance has physically closed, repeating admission.
24    /// Other refusals return immediately. Dropping this future never cancels the old cleanup.
25    /// This waits for address availability; use [`Reference::ready`] to await activation.
26    pub async fn get_wait(
27        &self,
28        service: &str,
29        key: Vec<String>,
30        principal: &str,
31        options: AcquisitionOptions,
32    ) -> Result<Reference> {
33        loop {
34            match self.get_with_options(service, key.clone(), principal, options.clone()) {
35                Ok(reference) => return Ok(reference),
36                Err(error) => self.closing(service, &key, principal, error)?.await,
37            }
38        }
39    }
40
41    pub(super) fn closing(
42        &self,
43        service: &str,
44        key: &[String],
45        principal: &str,
46        error: Error,
47    ) -> Result<core::Disposal> {
48        if error.code == core::Code::Unavailable && error.reason == Reason::Disposing.as_str() {
49            let address = core::Address {
50                service: service.into(),
51                key: key.to_vec(),
52                principal: principal.into(),
53            };
54            if let Some(wait) = self.kernel().wait_for_disposal(&address) {
55                return Ok(wait);
56            }
57        }
58        Err(error)
59    }
60
61    pub(super) fn acquire(
62        &self,
63        service: &str,
64        key: Vec<String>,
65        principal: &str,
66        options: AcquisitionOptions,
67        owner: Option<core::Owner>,
68    ) -> Result<Reference> {
69        if !self.0.external_actions.get() {
70            self.tick();
71        }
72        let acquired = self.kernel().acquire(
73            core::Address {
74                service: service.into(),
75                key,
76                principal: principal.into(),
77            },
78            options.api_version,
79            options.methods.clone(),
80        )?;
81        let mut foreign_ready = None;
82        let result = (|| {
83            if let Some(core::Owner::Object(object)) = owner {
84                self.kernel().dependency(object, acquired.reference)?;
85            }
86            #[cfg(feature = "views")]
87            {
88                let access = self
89                    .0
90                    .orbs
91                    .borrow()
92                    .get(&acquired.orb)
93                    .and_then(|services| services.get(service))
94                    .and_then(|implementation| implementation.access.clone());
95                if let Some(access) = access {
96                    self.kernel()
97                        .restrict(acquired.reference, access(principal))?;
98                }
99            }
100            if !self.has_orb(acquired.orb) {
101                let host = self.clone();
102                let object = acquired.object;
103                let address = self.kernel().object_address(object)?;
104                let request = serde_json::json!({
105                    "kind":"activate", "acquired":{
106                        "reference":acquired.reference,"object":object,"orb":acquired.orb,
107                        "codeVersion":acquired.code_version,"activate":acquired.activate,
108                    },
109                    "methods":options.methods,
110                    "address":{"service":address.service,"key":address.key,"principal":address.principal},
111                });
112                let receive = self.spawn(async move {
113                    let result = host.foreign(request).await.map(|_| ());
114                    host.flush();
115                    result
116                })?;
117                foreign_ready = Some(
118                    async move {
119                        receive.await.map_err(|_| {
120                            Error::invalid(Reason::Executor, "foreign activation stopped")
121                        })?
122                    }
123                    .boxed_local()
124                    .shared(),
125                );
126            } else if acquired.activate {
127                self.ensure_orb(acquired.orb)?;
128                let before = self
129                    .0
130                    .orbs
131                    .borrow()
132                    .get(&acquired.orb)
133                    .and_then(|services| services.get(service))
134                    .and_then(|implementation| implementation.before_create.clone());
135                if let Some(before) = before {
136                    self.activate_deferred(&acquired, service.to_owned(), before)?;
137                    return Ok(());
138                }
139                let scope = self.activate(acquired.object, acquired.orb, service)?;
140                let program = self.kernel().activate_scope(scope)?;
141                let activation = self.run(program)?;
142                self.0
143                    .objects
144                    .borrow_mut()
145                    .get_mut(&acquired.object)
146                    .expect("activated object")
147                    .activation = Some(activation);
148            }
149            Ok(())
150        })();
151        if let Err(error) = result {
152            if acquired.activate {
153                self.kernel().fail(acquired.object)?;
154            }
155            if let Some(core::Owner::Object(object)) = owner {
156                self.kernel()
157                    .detach_dependency(object, acquired.reference)?;
158            }
159            self.kernel().release(acquired.reference)?;
160            self.kernel().forget_reference(acquired.reference)?;
161            self.flush();
162            return Err(error);
163        }
164        Ok(Reference {
165            host: self.clone(),
166            id: acquired.reference,
167            object: acquired.object,
168            foreign_ready,
169            released: Rc::new(crate::readable::ReadLifetime::default()),
170        })
171    }
172}
173
174impl Host {
175    /// Resolve an optional native service access policy for a shared adapter's acquisition.
176    pub fn access(
177        &self,
178        orb: core::Id,
179        service: &str,
180        principal: &str,
181    ) -> Option<BTreeSet<String>> {
182        #[cfg(feature = "views")]
183        let access = self
184            .0
185            .orbs
186            .borrow()
187            .get(&orb)
188            .and_then(|services| services.get(service))
189            .and_then(|implementation| implementation.access.clone());
190        #[cfg(feature = "views")]
191        {
192            access.map(|access| access(principal))
193        }
194        #[cfg(not(feature = "views"))]
195        {
196            let _ = (orb, service, principal);
197            None
198        }
199    }
200}