Skip to main content

rustorb_core/
policy.rs

1//! `CORBA::ORB::create_policy` and the client side policy overrides of
2//! the Messaging specification: `Object::set_policy_overrides`, the ORB's
3//! `PolicyManager` and the thread's `PolicyCurrent`.
4//!
5//! The one client side policy rustorb has is
6//! `Messaging::RelativeRoundtripTimeoutPolicy`, the standard form of the
7//! call timeouts: overriding it on an object reference, on the calling
8//! thread or on the ORB sets the same timeout as
9//! [`ObjectRef::set_call_timeout`], [`set_thread_call_timeout`] and
10//! [`Orb::set_call_timeout`] (see `docs/orb-operations.md`).
11
12use std::fmt;
13use std::time::Duration;
14
15use crate::poa::{
16    Bidirectional, IdAssignment, IdUniqueness, ImplicitActivation, Lifespan, Policy,
17    RequestProcessing, ServantRetention, ThreadPolicy,
18};
19use crate::timeout::{duration_to_time_t, time_t_to_duration};
20use crate::typecode::TCKind;
21use crate::{
22    Any, CompletionStatus, ObjectRef, Orb, SystemException, SystemExceptionKind, Value, minor,
23    set_thread_call_timeout, thread_call_timeout,
24};
25
26/// `CORBA::PolicyType`.
27pub type PolicyType = u32;
28
29/// `PortableServer::THREAD_POLICY_ID`; the other POA policies follow it,
30/// up to `REQUEST_PROCESSING_POLICY_ID` (22).
31pub const THREAD_POLICY_ID: PolicyType = 16;
32/// `PortableServer::LIFESPAN_POLICY_ID`.
33pub const LIFESPAN_POLICY_ID: PolicyType = 17;
34/// `PortableServer::ID_UNIQUENESS_POLICY_ID`.
35pub const ID_UNIQUENESS_POLICY_ID: PolicyType = 18;
36/// `PortableServer::ID_ASSIGNMENT_POLICY_ID`.
37pub const ID_ASSIGNMENT_POLICY_ID: PolicyType = 19;
38/// `PortableServer::IMPLICIT_ACTIVATION_POLICY_ID`.
39pub const IMPLICIT_ACTIVATION_POLICY_ID: PolicyType = 20;
40/// `PortableServer::SERVANT_RETENTION_POLICY_ID`.
41pub const SERVANT_RETENTION_POLICY_ID: PolicyType = 21;
42/// `PortableServer::REQUEST_PROCESSING_POLICY_ID`.
43pub const REQUEST_PROCESSING_POLICY_ID: PolicyType = 22;
44/// `Messaging::RELATIVE_RT_TIMEOUT_POLICY_TYPE`.
45pub const RELATIVE_RT_TIMEOUT_POLICY_TYPE: PolicyType = 32;
46/// `BiDirPolicy::BIDIRECTIONAL_POLICY_TYPE`.
47pub const BIDIRECTIONAL_POLICY_TYPE: PolicyType = 37;
48
49/// A policy that [`Orb::create_policy`] makes: a POA policy, or a client
50/// side policy that can override the defaults of a reference, a thread or
51/// the ORB.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub enum PolicyValue {
54    /// One of the seven POA policies, for `create_POA`.
55    Poa(Policy),
56    /// `Messaging::RelativeRoundtripTimeoutPolicy`: how long a call may
57    /// take, as a `TimeBase::TimeT` (units of 100 nanoseconds).
58    RelativeRoundtripTimeout(u64),
59}
60
61impl PolicyValue {
62    /// The policy type (`policy_type`).
63    pub fn policy_type(&self) -> PolicyType {
64        match self {
65            PolicyValue::Poa(p) => match p {
66                Policy::Thread(_) => THREAD_POLICY_ID,
67                Policy::Lifespan(_) => LIFESPAN_POLICY_ID,
68                Policy::IdUniqueness(_) => ID_UNIQUENESS_POLICY_ID,
69                Policy::IdAssignment(_) => ID_ASSIGNMENT_POLICY_ID,
70                Policy::ImplicitActivation(_) => IMPLICIT_ACTIVATION_POLICY_ID,
71                Policy::ServantRetention(_) => SERVANT_RETENTION_POLICY_ID,
72                Policy::RequestProcessing(_) => REQUEST_PROCESSING_POLICY_ID,
73                Policy::Bidirectional(_) => BIDIRECTIONAL_POLICY_TYPE,
74            },
75            PolicyValue::RelativeRoundtripTimeout(_) => RELATIVE_RT_TIMEOUT_POLICY_TYPE,
76        }
77    }
78
79    /// The value as a number: the enumerator of a POA policy, the
80    /// `relative_expiry` of a timeout. The bindings pass policies as this
81    /// pair; [`from_raw`](PolicyValue::from_raw) is the inverse.
82    pub fn raw_value(&self) -> u64 {
83        match *self {
84            PolicyValue::Poa(p) => u64::from(match p {
85                Policy::Thread(v) => v as u32,
86                Policy::Lifespan(v) => v as u32,
87                Policy::IdUniqueness(v) => v as u32,
88                Policy::IdAssignment(v) => v as u32,
89                Policy::ImplicitActivation(v) => v as u32,
90                Policy::ServantRetention(v) => v as u32,
91                Policy::RequestProcessing(v) => v as u32,
92                Policy::Bidirectional(v) => v as u32,
93            }),
94            PolicyValue::RelativeRoundtripTimeout(t) => t,
95        }
96    }
97
98    /// The policy of type `policy_type` with the value `value` (see
99    /// [`raw_value`](PolicyValue::raw_value)), or `None` if rustorb does
100    /// not know the type or the value.
101    pub fn from_raw(policy_type: PolicyType, value: u64) -> Option<PolicyValue> {
102        if policy_type == RELATIVE_RT_TIMEOUT_POLICY_TYPE {
103            return Some(PolicyValue::RelativeRoundtripTimeout(value));
104        }
105        let v = u32::try_from(value).ok()?;
106        let p = match policy_type {
107            THREAD_POLICY_ID => Policy::Thread(match v {
108                0 => ThreadPolicy::OrbCtrl,
109                1 => ThreadPolicy::SingleThread,
110                2 => ThreadPolicy::MainThread,
111                _ => return None,
112            }),
113            LIFESPAN_POLICY_ID => Policy::Lifespan(match v {
114                0 => Lifespan::Transient,
115                1 => Lifespan::Persistent,
116                _ => return None,
117            }),
118            ID_UNIQUENESS_POLICY_ID => Policy::IdUniqueness(match v {
119                0 => IdUniqueness::Unique,
120                1 => IdUniqueness::Multiple,
121                _ => return None,
122            }),
123            ID_ASSIGNMENT_POLICY_ID => Policy::IdAssignment(match v {
124                0 => IdAssignment::User,
125                1 => IdAssignment::System,
126                _ => return None,
127            }),
128            IMPLICIT_ACTIVATION_POLICY_ID => Policy::ImplicitActivation(match v {
129                0 => ImplicitActivation::Implicit,
130                1 => ImplicitActivation::NoImplicit,
131                _ => return None,
132            }),
133            SERVANT_RETENTION_POLICY_ID => Policy::ServantRetention(match v {
134                0 => ServantRetention::Retain,
135                1 => ServantRetention::NonRetain,
136                _ => return None,
137            }),
138            REQUEST_PROCESSING_POLICY_ID => Policy::RequestProcessing(match v {
139                0 => RequestProcessing::ActiveObjectMapOnly,
140                1 => RequestProcessing::UseDefaultServant,
141                2 => RequestProcessing::UseServantManager,
142                _ => return None,
143            }),
144            BIDIRECTIONAL_POLICY_TYPE => Policy::Bidirectional(match v {
145                0 => Bidirectional::Normal,
146                1 => Bidirectional::Both,
147                _ => return None,
148            }),
149            _ => return None,
150        };
151        Some(PolicyValue::Poa(p))
152    }
153
154    /// The timeout of a `RelativeRoundtripTimeoutPolicy`.
155    pub fn relative_expiry(&self) -> Option<Duration> {
156        match *self {
157            PolicyValue::RelativeRoundtripTimeout(t) => Some(time_t_to_duration(t)),
158            PolicyValue::Poa(_) => None,
159        }
160    }
161
162    /// The repository id of the policy's interface.
163    pub fn repository_id(&self) -> &'static str {
164        match self.policy_type() {
165            THREAD_POLICY_ID => "IDL:omg.org/PortableServer/ThreadPolicy:2.3",
166            LIFESPAN_POLICY_ID => "IDL:omg.org/PortableServer/LifespanPolicy:2.3",
167            ID_UNIQUENESS_POLICY_ID => "IDL:omg.org/PortableServer/IdUniquenessPolicy:2.3",
168            ID_ASSIGNMENT_POLICY_ID => "IDL:omg.org/PortableServer/IdAssignmentPolicy:2.3",
169            IMPLICIT_ACTIVATION_POLICY_ID => {
170                "IDL:omg.org/PortableServer/ImplicitActivationPolicy:2.3"
171            }
172            SERVANT_RETENTION_POLICY_ID => "IDL:omg.org/PortableServer/ServantRetentionPolicy:2.3",
173            REQUEST_PROCESSING_POLICY_ID => {
174                "IDL:omg.org/PortableServer/RequestProcessingPolicy:2.3"
175            }
176            BIDIRECTIONAL_POLICY_TYPE => "IDL:omg.org/BiDirPolicy/BidirectionalPolicy:1.0",
177            _ => "IDL:omg.org/Messaging/RelativeRoundtripTimeoutPolicy:1.0",
178        }
179    }
180}
181
182/// `CORBA::PolicyError`, raised by [`Orb::create_policy`]: the
183/// `PolicyErrorCode` in `reason`.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub struct PolicyError {
186    /// One of the `*_POLICY*` constants of this type.
187    pub reason: i16,
188}
189
190impl PolicyError {
191    /// `BAD_POLICY`: the ORB does not know the policy type.
192    pub const BAD_POLICY: i16 = 0;
193    /// `UNSUPPORTED_POLICY`: the ORB knows the type but does not support
194    /// it.
195    pub const UNSUPPORTED_POLICY: i16 = 1;
196    /// `BAD_POLICY_TYPE`: the any has the wrong type for the policy.
197    pub const BAD_POLICY_TYPE: i16 = 2;
198    /// `BAD_POLICY_VALUE`: the value is not one of the policy's values.
199    pub const BAD_POLICY_VALUE: i16 = 3;
200    /// `UNSUPPORTED_POLICY_VALUE`: the ORB does not support the value.
201    pub const UNSUPPORTED_POLICY_VALUE: i16 = 4;
202}
203
204impl fmt::Display for PolicyError {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        write!(f, "CORBA::PolicyError (reason {})", self.reason)
207    }
208}
209
210impl std::error::Error for PolicyError {}
211
212/// `CORBA::SetOverrideType`.
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
214pub enum SetOverrideType {
215    /// `SET_OVERRIDE`: the policies replace every override.
216    Set,
217    /// `ADD_OVERRIDE`: the policies replace the overrides of their types
218    /// and keep the others.
219    Add,
220}
221
222/// The repository id of the enum a POA policy's value has.
223fn poa_value_id(policy_type: PolicyType) -> Option<&'static str> {
224    Some(match policy_type {
225        THREAD_POLICY_ID => "IDL:omg.org/PortableServer/ThreadPolicyValue:2.3",
226        LIFESPAN_POLICY_ID => "IDL:omg.org/PortableServer/LifespanPolicyValue:2.3",
227        ID_UNIQUENESS_POLICY_ID => "IDL:omg.org/PortableServer/IdUniquenessPolicyValue:2.3",
228        ID_ASSIGNMENT_POLICY_ID => "IDL:omg.org/PortableServer/IdAssignmentPolicyValue:2.3",
229        IMPLICIT_ACTIVATION_POLICY_ID => {
230            "IDL:omg.org/PortableServer/ImplicitActivationPolicyValue:2.3"
231        }
232        SERVANT_RETENTION_POLICY_ID => "IDL:omg.org/PortableServer/ServantRetentionPolicyValue:2.3",
233        REQUEST_PROCESSING_POLICY_ID => {
234            "IDL:omg.org/PortableServer/RequestProcessingPolicyValue:2.3"
235        }
236        _ => return None,
237    })
238}
239
240/// `create_policy` without the ORB: see [`Orb::create_policy`].
241pub fn create_policy(policy_type: PolicyType, value: &Any) -> Result<PolicyValue, PolicyError> {
242    let tc = value.typecode().unaliased();
243    let raw = if policy_type == RELATIVE_RT_TIMEOUT_POLICY_TYPE {
244        // TimeBase::TimeT, an alias of unsigned long long.
245        match (tc.kind(), value.value()) {
246            (TCKind::ULongLong, Value::ULongLong(t)) => *t,
247            _ => {
248                return Err(PolicyError {
249                    reason: PolicyError::BAD_POLICY_TYPE,
250                });
251            }
252        }
253    } else if policy_type == BIDIRECTIONAL_POLICY_TYPE {
254        // BiDirPolicy::BidirectionalPolicyValue, an alias of unsigned
255        // short.
256        match (tc.kind(), value.value()) {
257            (TCKind::UShort, Value::UShort(v)) => u64::from(*v),
258            _ => {
259                return Err(PolicyError {
260                    reason: PolicyError::BAD_POLICY_TYPE,
261                });
262            }
263        }
264    } else if let Some(id) = poa_value_id(policy_type) {
265        // The enum of the policy; its version differs between the IDL
266        // of CORBA 2.3 and later (and between ORBs), so it is compared
267        // without the version.
268        let base = |s: &str| {
269            s.rsplit_once(':')
270                .map_or(s.to_owned(), |(b, _)| b.to_owned())
271        };
272        match (tc.kind(), value.value()) {
273            (TCKind::Enum, Value::Enum(v)) if tc.id().is_ok_and(|i| base(i) == base(id)) => {
274                u64::from(*v)
275            }
276            _ => {
277                return Err(PolicyError {
278                    reason: PolicyError::BAD_POLICY_TYPE,
279                });
280            }
281        }
282    } else {
283        return Err(PolicyError {
284            reason: PolicyError::BAD_POLICY,
285        });
286    };
287    PolicyValue::from_raw(policy_type, raw).ok_or(PolicyError {
288        reason: PolicyError::BAD_POLICY_VALUE,
289    })
290}
291
292/// `NO_PERMISSION`, for a policy that cannot override at the scope (CORBA
293/// 3.0, 4.9.3.1).
294fn no_permission() -> SystemException {
295    SystemException::new(SystemExceptionKind::NO_PERMISSION, 0, CompletionStatus::No)
296}
297
298/// The timeout the overrides `policies` set on top of `current` (the
299/// timeout of the scope; `None` when it has none).
300fn apply_overrides(
301    current: Option<u64>,
302    policies: &[PolicyValue],
303    set_add: SetOverrideType,
304) -> Result<Option<u64>, SystemException> {
305    check_duplicates(policies)?;
306    let mut timeout = match set_add {
307        SetOverrideType::Set => None,
308        SetOverrideType::Add => current,
309    };
310    for p in policies {
311        match p {
312            PolicyValue::RelativeRoundtripTimeout(t) => timeout = Some(*t),
313            PolicyValue::Poa(_) => return Err(no_permission()),
314        }
315    }
316    Ok(timeout)
317}
318
319/// `BAD_PARAM` when two policies of `policies` have the same type.
320fn check_duplicates(policies: &[PolicyValue]) -> Result<(), SystemException> {
321    for (i, p) in policies.iter().enumerate() {
322        if policies[..i]
323            .iter()
324            .any(|q| q.policy_type() == p.policy_type())
325        {
326            return Err(SystemException::new(
327                SystemExceptionKind::BAD_PARAM,
328                minor::DUPLICATE_POLICY,
329                CompletionStatus::No,
330            ));
331        }
332    }
333    Ok(())
334}
335
336/// The value of a `BidirectionalPolicy`.
337fn bidirectional(p: &PolicyValue) -> Option<Bidirectional> {
338    match p {
339        PolicyValue::Poa(Policy::Bidirectional(v)) => Some(*v),
340        _ => None,
341    }
342}
343
344/// The overrides of the types `types` (every type when empty) at a scope
345/// whose timeout is `timeout`.
346fn overrides(timeout: Option<u64>, types: &[PolicyType]) -> Vec<PolicyValue> {
347    let wanted = types.is_empty() || types.contains(&RELATIVE_RT_TIMEOUT_POLICY_TYPE);
348    timeout
349        .filter(|_| wanted)
350        .map(PolicyValue::RelativeRoundtripTimeout)
351        .into_iter()
352        .collect()
353}
354
355/// A stored timeout (`Some(None)` is "no limit") as a `relative_expiry`,
356/// if it is one a policy can say.
357fn as_time_t(timeout: Option<Option<Duration>>) -> Option<u64> {
358    timeout.flatten().map(duration_to_time_t)
359}
360
361/// `PolicyCurrent::set_policy_overrides`: the overrides of the calling
362/// thread, for every ORB. A `RelativeRoundtripTimeoutPolicy` sets the
363/// thread's call timeout ([`set_thread_call_timeout`]); without one (after
364/// `SET_OVERRIDE`) the thread has none. `NO_PERMISSION` for a POA policy.
365pub fn set_thread_policy_overrides(
366    policies: &[PolicyValue],
367    set_add: SetOverrideType,
368) -> Result<(), SystemException> {
369    let t = apply_overrides(as_time_t(thread_call_timeout()), policies, set_add)?;
370    set_thread_call_timeout(t.map(|t| Some(time_t_to_duration(t))));
371    Ok(())
372}
373
374/// `PolicyCurrent::get_policy_overrides`: the overrides of the calling
375/// thread of the types `types`, or all of them when `types` is empty.
376pub fn thread_policy_overrides(types: &[PolicyType]) -> Vec<PolicyValue> {
377    overrides(as_time_t(thread_call_timeout()), types)
378}
379
380impl Orb {
381    /// `CORBA::ORB::create_policy`: a POA policy from its enumerator, or a
382    /// `RelativeRoundtripTimeoutPolicy` from a `TimeBase::TimeT` (an
383    /// `unsigned long long`, in units of 100 nanoseconds).
384    ///
385    /// `PolicyError` with `BAD_POLICY` for a type rustorb does not know,
386    /// `BAD_POLICY_TYPE` when the any does not hold the policy's type, and
387    /// `BAD_POLICY_VALUE` for an enumerator out of range.
388    pub fn create_policy(
389        &self,
390        policy_type: PolicyType,
391        value: &Any,
392    ) -> Result<PolicyValue, PolicyError> {
393        create_policy(policy_type, value)
394    }
395
396    /// `PolicyManager::set_policy_overrides` of the ORB (the initial
397    /// reference `ORBPolicyManager`): a `RelativeRoundtripTimeoutPolicy`
398    /// sets [`call_timeout`](Orb::call_timeout); without one (after
399    /// `SET_OVERRIDE`) calls have no limit. A `BidirectionalPolicy` of
400    /// `BOTH` makes the ORB offer and accept bidirectional GIOP, like
401    /// `-ORBofferBiDirectionalGIOP 1 -ORBacceptBiDirectionalGIOP 1`, for
402    /// the connections opened or accepted from then on
403    /// (docs/bidir-giop.md). `NO_PERMISSION` for the other POA policies.
404    pub fn set_policy_overrides(
405        &self,
406        policies: &[PolicyValue],
407        set_add: SetOverrideType,
408    ) -> Result<(), SystemException> {
409        check_duplicates(policies)?;
410        let others: Vec<PolicyValue> = policies
411            .iter()
412            .filter(|p| bidirectional(p).is_none())
413            .copied()
414            .collect();
415        let current = self.call_timeout().map(duration_to_time_t);
416        let t = apply_overrides(current, &others, set_add)?;
417        self.set_call_timeout(t.map(time_t_to_duration));
418        let bidir = policies.iter().find_map(bidirectional);
419        let mut stored = self.inner.bidir_override.lock().unwrap();
420        match (bidir, set_add) {
421            (Some(v), _) => *stored = Some(v),
422            (None, SetOverrideType::Set) => *stored = None,
423            (None, SetOverrideType::Add) => {}
424        }
425        Ok(())
426    }
427
428    /// `PolicyManager::get_policy_overrides` of the ORB.
429    pub fn policy_overrides(&self, types: &[PolicyType]) -> Vec<PolicyValue> {
430        let mut out = overrides(self.call_timeout().map(duration_to_time_t), types);
431        if types.is_empty() || types.contains(&BIDIRECTIONAL_POLICY_TYPE) {
432            if let Some(v) = *self.inner.bidir_override.lock().unwrap() {
433                out.push(PolicyValue::Poa(Policy::Bidirectional(v)));
434            }
435        }
436        out
437    }
438}
439
440impl ObjectRef {
441    /// `CORBA::Object::set_policy_overrides`: a new reference to the same
442    /// object with these overrides, whose call timeout is its own (this
443    /// reference is unchanged). A `RelativeRoundtripTimeoutPolicy` sets
444    /// the new reference's [`call_timeout`](ObjectRef::set_call_timeout).
445    /// `NO_PERMISSION` for a POA policy.
446    pub fn set_policy_overrides(
447        &self,
448        policies: &[PolicyValue],
449        set_add: SetOverrideType,
450    ) -> Result<ObjectRef, SystemException> {
451        let t = apply_overrides(as_time_t(self.call_timeout()), policies, set_add)?;
452        let obj = self.with_own_settings();
453        obj.set_call_timeout(t.map(|t| Some(time_t_to_duration(t))));
454        Ok(obj)
455    }
456
457    /// `CORBA::Object::get_policy_overrides`: the overrides of this
458    /// reference of the types `types`, or all of them when `types` is
459    /// empty.
460    pub fn policy_overrides(&self, types: &[PolicyType]) -> Vec<PolicyValue> {
461        overrides(as_time_t(self.call_timeout()), types)
462    }
463
464    /// `CORBA::Object::get_client_policy`, and `get_policy` (rustorb reads
465    /// no policies from IORs): the policy of type `policy_type` that
466    /// applies to calls from this thread, from the reference's overrides,
467    /// else the thread's, else the ORB's. `None` when no scope has one,
468    /// which for the timeout means calls have no limit.
469    pub fn client_policy(&self, policy_type: PolicyType) -> Option<PolicyValue> {
470        if policy_type != RELATIVE_RT_TIMEOUT_POLICY_TYPE {
471            return None;
472        }
473        self.call_timeout()
474            .or_else(thread_call_timeout)
475            .unwrap_or_else(|| self.orb().call_timeout())
476            .map(|t| PolicyValue::RelativeRoundtripTimeout(duration_to_time_t(t)))
477    }
478}