Skip to main content

speedyspec_container/
port_cell.rs

1//! [`PortCell`]: the core of a generated port proxy.
2//!
3//! A seam reaches another seam's port through a proxy that forwards to whatever the container binds under the
4//! port's key now. The cell caches the resolved port against the container's [`Container::epoch`], so a call with
5//! nothing rebound costs one compare. Any binding change, and every request start and end, moves the epoch. The
6//! next call then resolves through the container again, which serves a shared or scoped value from its own cache
7//! and records the key as resolved in this request (so ADR-017's refusal to rebind a used stateful port holds). A
8//! transient binding is never cached: it builds on every call, as its meaning requires. Nor is a foreign binding (a PHP
9//! object), which lives only as long as its request.
10
11use std::cell::{Cell, RefCell};
12use std::rc::{Rc, Weak};
13
14use crate::{Container, ContainerError, Sharing};
15
16struct Cached<P: ?Sized> {
17    epoch: u64,
18    port: Rc<P>,
19}
20
21/// A handle on the port `P` bound under a key. Holds the container weakly, so a container that owns, through an
22/// area or a handler, a value holding this cell is not kept alive by it.
23pub struct PortCell<P: ?Sized + 'static> {
24    container: Weak<Container>,
25    epoch: Rc<Cell<u64>>,
26    key: &'static str,
27    cache: RefCell<Option<Cached<P>>>,
28}
29
30impl<P: ?Sized + 'static> PortCell<P> {
31    pub fn new(container: &Rc<Container>, key: &'static str) -> PortCell<P> {
32        PortCell {
33            container: Rc::downgrade(container),
34            epoch: container.epoch_cell(),
35            key,
36            cache: RefCell::new(None),
37        }
38    }
39
40    /// The port's key.
41    pub fn key(&self) -> &'static str {
42        self.key
43    }
44
45    /// What the container binds under the key now. Panics, naming the key, when the container is gone or the key
46    /// cannot be resolved: a provider binds every port its seam owns, so either is a configuration error.
47    pub fn get(&self) -> Rc<P> {
48        if self.container.strong_count() == 0 {
49            panic!("port {}: the container was dropped", self.key);
50        }
51        match self.try_get() {
52            Ok(port) => port,
53            Err(err) => panic!("port {}: {err}", self.key),
54        }
55    }
56
57    /// Calls `f` with what the container binds under the key now; the hot path of a generated proxy. With nothing
58    /// rebound since the last call it reads one counter and borrows the cache: no reference counting. Panics as
59    /// [`PortCell::get`] does.
60    pub fn with<R>(&self, f: impl FnOnce(&P) -> R) -> R {
61        {
62            let cache = self.cache.borrow();
63            if let Some(hit) = cache.as_ref()
64                && hit.epoch == self.epoch.get()
65            {
66                return f(&hit.port);
67            }
68        }
69        let port = self.get();
70        f(&port)
71    }
72
73    /// As [`PortCell::get`], with the failure returned instead.
74    pub fn try_get(&self) -> Result<Rc<P>, ContainerError> {
75        let Some(container) = self.container.upgrade() else {
76            return Err(ContainerError::Unresolvable(
77                self.key.to_string(),
78                "the container was dropped".to_string(),
79            ));
80        };
81        let epoch = self.epoch.get();
82        if let Some(hit) = self.cache.borrow().as_ref()
83            && hit.epoch == epoch
84        {
85            return Ok(hit.port.clone());
86        }
87        let port = container.make_port::<P>(self.key)?;
88        // A foreign value (a PHP object) is valid only for the request that made it, and the request's end frees it.
89        // The container drops its own copy at `end_request`; a copy kept here would be released after PHP freed the
90        // object. So a foreign binding is resolved through the container on every call, never held.
91        let cached = if container.is_foreign(self.key) {
92            None
93        } else {
94            match container.sharing(self.key) {
95                Some(Sharing::Transient) | None => None,
96                Some(_) => Some(Cached {
97                    // The epoch read before resolving: if resolving registered anything, this entry is merely stale.
98                    epoch,
99                    port: port.clone(),
100                }),
101            }
102        };
103        // A re-entrant call (a port method that calls back into the same port while a binding changed) finds the
104        // cache borrowed by the outer call: it answers without caching, and the outer call's next use refreshes it.
105        if let Ok(mut cache) = self.cache.try_borrow_mut() {
106            *cache = cached;
107        }
108        Ok(port)
109    }
110}