1use super::*;
4
5impl Host {
6 pub fn context(&self, root: core::Id, invocation: Option<core::Invocation>) -> Result<Context> {
8 self.kernel().check_root(root)?;
9 if invocation.as_ref().is_some_and(|call| call.root != root) {
10 return Err(Error::invalid(
11 Reason::Context,
12 "invocation belongs to another root",
13 ));
14 }
15 Ok(Context {
16 host: self.clone(),
17 root,
18 frame: invocation.as_ref().map_or(0, |call| call.context),
19 call: invocation,
20 signal: self.context_signal(root),
21 owner: None,
22 })
23 }
24
25 pub async fn root<T>(
27 &self,
28 principal: &str,
29 operation: impl FnOnce(Context) -> LocalBoxFuture<'static, Result<T>>,
30 ) -> Result<T> {
31 let root = self.kernel().begin_root(principal)?;
32 let context = self.context(root, None)?;
33 let _guard = RootGuard {
34 host: self.clone(),
35 root,
36 };
37 operation(context).await
38 }
39}
40
41impl Host {
42 pub fn spawn_root<T: 'static>(
50 &self,
51 principal: &str,
52 operation: impl FnOnce(Context) -> LocalBoxFuture<'static, Result<T>> + 'static,
53 ) -> Result<futures::channel::oneshot::Receiver<Result<T>>> {
54 let host = self.clone();
55 let principal = principal.to_owned();
56 self.spawn(async move { host.root(&principal, operation).await })
57 }
58}
59
60pub(super) struct RootGuard {
61 pub(super) host: Host,
62 pub(super) root: core::Id,
63}
64
65impl Drop for RootGuard {
66 fn drop(&mut self) {
68 if let Err(error) = self.host.kernel().end_root(self.root) {
69 self.host.0.errors.borrow_mut().push(error);
70 }
71 self.host.end_context(self.root);
72 self.host
73 .notify_foreign(super::signals::ForeignNotification::RootEnded(self.root));
74 self.host.flush();
75 }
76}
77
78#[derive(Clone)]
80pub struct Context {
81 frame: core::Id,
82 pub(crate) host: Host,
83 pub root: core::Id,
84 call: Option<core::Invocation>,
85 signal: Cancellation,
89 owner: Option<Owner>,
93}
94
95#[derive(Clone)]
100pub(super) struct Owner {
101 pub(super) orb: Option<String>,
102 pub(super) object: Option<core::Id>,
103}
104
105impl Context {
106 pub(super) fn owned(mut self, owner: Owner, signal: Option<Cancellation>) -> Self {
109 self.owner = Some(owner);
110 if let Some(signal) = signal {
111 self.signal = signal;
112 }
113 self
114 }
115}
116
117impl Context {
118 pub fn frame(&self) -> core::Id {
120 self.frame
121 }
122
123 pub fn with<T: core::ContextDatum>(&self, key: &core::ContextKey<T>, value: T) -> Result<Self> {
125 self.check()?;
126 let frame = self.host.kernel().derive_context(
127 self.root,
128 self.frame,
129 self.call.as_ref().map(|call| call.id),
130 key.contract(),
131 value.into_value(),
132 )?;
133 Ok(Self {
134 host: self.host.clone(),
135 root: self.root,
136 call: self.call.clone(),
137 frame,
138 signal: self.signal.clone(),
139 owner: self.owner.clone(),
140 })
141 }
142
143 pub fn enter_execution(&self) -> Result<Self> {
145 let call = self.invocation()?;
146 let frame = self.host.kernel().enter_execution(call.id, self.frame)?;
147 Ok(Self {
148 host: self.host.clone(),
149 root: self.root,
150 call: self.call.clone(),
151 frame,
152 signal: self.signal.clone(),
153 owner: self.owner.clone(),
154 })
155 }
156
157 pub fn value<T: core::ContextDatum>(&self, key: &core::ContextKey<T>) -> Result<Option<T>> {
159 self.check()?;
160 if self.frame == 0 {
161 return Ok(None);
162 }
163 self.host
164 .kernel()
165 .context_value(self.root, self.frame, &key.contract())?
166 .map(T::from_value)
167 .transpose()
168 }
169
170 pub fn check(&self) -> Result<()> {
172 self.host.kernel().check_root(self.root)?;
173 if let Some(call) = &self.call {
174 self.host.kernel().check_call(call.id)?;
175 }
176 Ok(())
177 }
178
179 pub fn cancel(&self) -> Result<()> {
181 self.host.kernel().cancel_root(self.root)?;
182 self.host.cancel_context(self.root);
183 self.host.flush();
184 Ok(())
185 }
186
187 pub fn principal(&self) -> Result<String> {
189 self.host.kernel().root_principal(self.root)
190 }
191
192 pub fn address(&self) -> Result<core::Address> {
196 let object = match (&self.call, &self.owner) {
197 (Some(call), _) => call.object,
198 (
199 None,
200 Some(Owner {
201 object: Some(object),
202 ..
203 }),
204 ) => *object,
205 (None, _) => self.invocation()?.object,
206 };
207 self.host.kernel().object_address(object)
208 }
209
210 pub(super) fn attributed(&self) -> Result<String> {
214 match (&self.call, &self.owner) {
215 (Some(call), _) => Ok(self.host.kernel().orb(call.orb)?.declaration.name),
216 (None, Some(Owner { orb: Some(orb), .. })) => Ok(orb.clone()),
217 (None, _) => {
218 let call = self.invocation()?;
219 Ok(self.host.kernel().orb(call.orb)?.declaration.name)
220 }
221 }
222 }
223
224 pub(crate) fn issuer(&self) -> Option<core::Id> {
226 self.call.as_ref().map(|call| call.id)
227 }
228
229 pub fn invocation(&self) -> Result<core::Invocation> {
231 self.call
232 .clone()
233 .ok_or_else(|| Error::invalid(Reason::Context, "an entered invocation is required"))
234 }
235}
236
237impl Context {
238 pub fn signal(&self) -> Cancellation {
242 match &self.call {
243 Some(call) => self.host.call_signal(self.root, &self.signal, call.id),
244 None => self.signal.clone(),
245 }
246 }
247}
248
249impl Host {
250 fn call_signal(
254 &self,
255 root: core::Id,
256 root_signal: &Cancellation,
257 call: core::Id,
258 ) -> Cancellation {
259 let mut signals = self.0.call_signals.borrow_mut();
260 signals.retain(|_, (_, signal)| signal.strong_count() != 0);
261 if let Some(signal) = signals.get(&call).and_then(|(_, signal)| signal.upgrade()) {
262 return Cancellation(signal);
263 }
264 let signal = Cancellation::new("root");
265 if root_signal.is_cancelled() {
266 signal.cancel();
267 } else if self.kernel().call_cancelled(call) {
268 signal.cancel_because("call");
269 }
270 signals.insert(call, (root, Rc::downgrade(&signal.0)));
271 signal
272 }
273
274 pub fn cancel_call_signal(&self, call: core::Id) {
276 let signal = self
277 .0
278 .call_signals
279 .borrow()
280 .get(&call)
281 .and_then(|(_, signal)| signal.upgrade());
282 if let Some(signal) = signal {
283 Cancellation(signal).cancel_because("call");
284 }
285 }
286
287 fn context_signal(&self, root: core::Id) -> Cancellation {
291 let mut signals = self.0.context_signals.borrow_mut();
292 if let Some(signal) = signals.get(&root).and_then(std::rc::Weak::upgrade) {
294 return Cancellation(signal);
295 }
296 signals.retain(|_, signal| signal.strong_count() != 0);
297 let signal = Cancellation::new("root");
298 signals.insert(root, Rc::downgrade(&signal.0));
299 signal
300 }
301
302 fn root_end_signal(&self, root: core::Id) -> Cancellation {
305 let mut signals = self.0.root_end_signals.borrow_mut();
306 signals.retain(|_, signal| signal.strong_count() != 0);
307 if let Some(signal) = signals.get(&root).and_then(std::rc::Weak::upgrade) {
308 return Cancellation(signal);
309 }
310 let signal = Cancellation::new("root_end");
311 if self.kernel().check_root(root).is_err() {
312 signal.cancel();
313 }
314 signals.insert(root, Rc::downgrade(&signal.0));
315 signal
316 }
317
318 pub fn cancel_context(&self, root: core::Id) {
321 if let Some(signal) = self
322 .0
323 .context_signals
324 .borrow()
325 .get(&root)
326 .and_then(std::rc::Weak::upgrade)
327 {
328 Cancellation(signal).cancel();
329 }
330 let calls: Vec<_> = self
332 .0
333 .call_signals
334 .borrow()
335 .values()
336 .filter(|(owner, _)| *owner == root)
337 .filter_map(|(_, signal)| signal.upgrade())
338 .collect();
339 for signal in calls {
340 Cancellation(signal).cancel_because("root");
341 }
342 for stream in self.root_streams(root, false) {
343 stream.cancel_root();
344 }
345 }
346
347 pub(crate) fn bind_root_stream(
349 &self,
350 root: core::Id,
351 stream: std::rc::Weak<dyn crate::portable::RootStream>,
352 ) -> Result<()> {
353 self.kernel().check_root(root)?;
354 let mut claims = self.0.root_references.borrow_mut();
355 let streams = &mut claims.entry(root).or_default().streams;
356 streams.retain(|stream| stream.strong_count() != 0);
357 streams.push(stream);
358 Ok(())
359 }
360
361 fn root_streams(&self, root: core::Id, take: bool) -> Vec<Rc<dyn crate::portable::RootStream>> {
364 let mut claims = self.0.root_references.borrow_mut();
365 let Some(claims) = claims.get_mut(&root) else {
366 return Vec::new();
367 };
368 let streams = if take {
369 std::mem::take(&mut claims.streams)
370 } else {
371 claims.streams.clone()
372 };
373 streams.iter().filter_map(std::rc::Weak::upgrade).collect()
374 }
375}
376
377impl Context {
378 pub fn get(
380 &self,
381 service: &str,
382 key: Vec<String>,
383 options: crate::AcquisitionOptions,
384 ) -> Result<Rc<Reference>> {
385 self.check()?;
386 let reference =
387 Rc::new(
388 self.host
389 .get_with_options(service, key, &self.principal()?, options)?,
390 );
391 self.host
392 .0
393 .root_references
394 .borrow_mut()
395 .entry(self.root)
396 .or_default()
397 .references
398 .push(reference.clone());
399 Ok(reference)
400 }
401}
402
403impl Context {
404 pub async fn get_wait(
409 &self,
410 service: &str,
411 key: Vec<String>,
412 options: crate::AcquisitionOptions,
413 ) -> Result<Rc<Reference>> {
414 let signal = self.signal();
415 loop {
416 match self.get(service, key.clone(), options.clone()) {
417 Ok(reference) => return Ok(reference),
418 Err(error) => {
419 let wait = self
420 .host
421 .closing(service, &key, &self.principal()?, error)?;
422 let root_signal = self.host.root_end_signal(self.root);
423 let cancelled = std::pin::pin!(async {
424 let call = std::pin::pin!(signal.cancelled());
425 let root = std::pin::pin!(root_signal.cancelled());
426 futures::future::select(call, root).await;
427 });
428 let wait = std::pin::pin!(wait);
429 if let futures::future::Either::Left(_) =
430 futures::future::select(cancelled, wait).await
431 {
432 self.check()?;
433 signal.check()?;
434 root_signal.check()?;
435 }
436 }
437 }
438 }
439 }
440
441 pub fn orb<T: 'static>(&self) -> Result<Rc<T>> {
443 self.check()?;
444 let call = self.invocation()?;
445 self.host
446 .0
447 .orb_values
448 .borrow()
449 .get(&call.orb)
450 .cloned()
451 .ok_or_else(|| Error::invalid(Reason::Orb, "orb environment unavailable"))?
452 .downcast::<T>()
453 .map_err(|_| type_error())
454 }
455
456 pub fn resource<T: 'static>(&self, name: &str) -> Result<Resource<T>> {
458 self.check()?;
459 self.host.resource(name)
460 }
461}
462
463impl Host {
464 pub fn end_context(&self, root: core::Id) {
469 let ended = self
470 .0
471 .root_end_signals
472 .borrow_mut()
473 .remove(&root)
474 .and_then(|signal| signal.upgrade());
475 if let Some(ended) = ended {
476 Cancellation(ended).cancel();
477 }
478 for stream in self.root_streams(root, true) {
479 stream.end_root();
480 }
481 let references = self
482 .0
483 .root_references
484 .borrow_mut()
485 .remove(&root)
486 .unwrap_or_default()
487 .references;
488 for reference in references {
489 if let Err(error) = reference.release() {
490 self.0.errors.borrow_mut().push(error);
491 }
492 }
493 }
494}