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