1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//! Object type for our RPC system.

pub(crate) mod cast;

use derive_deftly::define_derive_deftly;
use downcast_rs::DowncastSync;
use serde::{Deserialize, Serialize};

use self::cast::CastTable;

/// An object in our RPC system to which methods can be addressed.
///
/// You shouldn't implement this trait yourself; instead, use the
/// [`derive_deftly(Object)`].
///
/// See the documentation for [`derive_deftly(Object)`]
/// for examples of how to declare and
/// downcast `Object`s.
///
/// [`derive_deftly(Object)`]: crate::templates::derive_deftly_template_Object
pub trait Object: DowncastSync + Send + Sync + 'static {
    /// Return true if this object should be given an identifier that allows it
    /// to be used outside of the session that generated it.
    ///
    /// Currently, the only use for such IDs in arti is identifying stream
    /// contexts in when opening a SOCKS connection: When an application opens a
    /// stream, it needs to declare what RPC context (like a `TorClient`) it's
    /// using, which requires that some identifier for that context exist
    /// outside of the RPC session that owns it.
    //
    // TODO RPC: It would be neat if this were automatically set to true if and
    // only if there were any "out-of-session psuedomethods" defined on the
    // object.
    fn expose_outside_of_session(&self) -> bool {
        false
    }

    /// Return a [`CastTable`] that can be used to downcast a `dyn Object` of
    /// this type into various kinds of `dyn Trait` references.
    ///
    /// The default implementation of this method declares that the `Object`
    /// can't be downcast into any traits.
    ///
    /// You should not implement this method yourself; instead use
    /// [`derive_deftly(Object)`](crate::templates::derive_deftly_template_Object).
    fn get_cast_table(&self) -> &CastTable {
        &cast::EMPTY_CAST_TABLE
    }
}
downcast_rs::impl_downcast!(sync Object);

/// An identifier for an Object within the context of a Session.
///
/// These are opaque from the client's perspective.
#[derive(Debug, Eq, PartialEq, Hash, Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ObjectId(
    // (We use Box<str> to save a word here, since these don't have to be
    // mutable ever.)
    Box<str>,
);

impl AsRef<str> for ObjectId {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

impl<T> From<T> for ObjectId
where
    T: Into<Box<str>>,
{
    fn from(value: T) -> Self {
        Self(value.into())
    }
}

/// Extension trait for `dyn Object` and similar to support convenient
/// downcasting to `dyn Trait`.
///
/// You don't need to use this for downcasting to an object's concrete
/// type; for that, use [`downcast_rs::DowncastSync`].
///
/// # Examples
///
/// ```
/// use tor_rpcbase::{Object, ObjectRefExt, templates::*};
/// use derive_deftly::Deftly;
/// use std::sync::Arc;
///
/// #[derive(Deftly)]
/// #[derive_deftly(Object)]
/// #[deftly(rpc(downcastable_to = "HasFeet"))]
/// pub struct Frog {}
/// pub trait HasFeet {
///     fn num_feet(&self) -> usize;
/// }
/// impl HasFeet for Frog {
///     fn num_feet(&self) -> usize { 4 }
/// }
///
/// /// If `obj` is a HasFeet, return how many feet it has.
/// /// Otherwise, return 0.
/// fn check_feet(obj: Arc<dyn Object>) -> usize {
///     let maybe_has_feet: Option<&dyn HasFeet> = obj.cast_to_trait();
///     match maybe_has_feet {
///         Some(foot_haver) => foot_haver.num_feet(),
///         None => 0,
///     }
/// }
///
/// assert_eq!(check_feet(Arc::new(Frog{})), 4);
/// ```
pub trait ObjectRefExt {
    /// Try to cast this `Object` to a `T`.  On success, return a reference to
    /// T; on failure, return None.
    fn cast_to_trait<T: ?Sized + 'static>(&self) -> Option<&T>;
}

impl ObjectRefExt for dyn Object {
    fn cast_to_trait<T: ?Sized + 'static>(&self) -> Option<&T> {
        let table = self.get_cast_table();
        table.cast_object_to(self)
    }
}

impl ObjectRefExt for std::sync::Arc<dyn Object> {
    fn cast_to_trait<T: ?Sized + 'static>(&self) -> Option<&T> {
        self.as_ref().cast_to_trait()
    }
}

define_derive_deftly! {
/// Allow a type to participate as an Object in the RPC system.
///
/// This template implements `Object` for the
/// target type, and can be used to cause objects to participate in the trait
/// downcasting system.
///
/// # Examples
///
/// ## Simple case, just implements `Object`.
///
/// ```
/// use tor_rpcbase::{self as rpc, templates::*};
/// use derive_deftly::Deftly;
///
/// #[derive(Default, Deftly)]
/// #[derive_deftly(Object)]
/// struct Houseplant {
///    oxygen_per_sec: f64,
///    benign_neglect: u8
/// }
///
/// // You can downcast an Object to a concrete type.
/// use downcast_rs::DowncastSync;
/// use std::sync::Arc;
/// let plant_obj: Arc<dyn rpc::Object> = Arc::new(Houseplant::default());
/// let as_plant: Arc<Houseplant> = plant_obj.downcast_arc().ok().unwrap();
/// ```
///
/// ## With trait downcasting
///
/// By default, you can use [`downcast_rs`] to downcast a `dyn Object` to its
/// concrete type.  If you also need to be able to downcast a `dyn Object` to a given
/// trait that it implements, you can use the `downcastable_to` attributes for `Object` to have
/// it participate in trait downcasting:
///
/// ```
/// use tor_rpcbase::{self as rpc, templates::*};
/// use derive_deftly::Deftly;
///
/// #[derive(Deftly)]
/// #[derive_deftly(Object)]
/// #[deftly(rpc(downcastable_to = "Gizmo, Doodad"))]
/// struct Frobnitz {}
///
/// trait Gizmo {}
/// trait Doodad {}
/// impl Gizmo for Frobnitz {}
/// impl Doodad for Frobnitz {}
///
/// use std::sync::Arc;
/// use rpc::ObjectRefExt; // for the cast_to method.
/// let frob_obj: Arc<dyn rpc::Object> = Arc::new(Frobnitz {});
/// let gizmo: &dyn Gizmo = frob_obj.cast_to_trait().unwrap();
/// let doodad: &dyn Doodad = frob_obj.cast_to_trait().unwrap();
/// ```
///
/// ## With generic objects
///
/// Right now, a generic object can't participate in our method lookup system,
/// but it _can_ participate in trait downcasting.  We'll try to remove this
/// limitation in the future.
///
/// ```
/// use tor_rpcbase::{self as rpc, templates::*};
/// use derive_deftly::Deftly;
///
/// #[derive(Deftly)]
/// #[derive_deftly(Object)]
/// #[deftly(rpc(downcastable_to = "ExampleTrait"))]
/// struct Generic<T,U> where T:Clone, U:PartialEq {
///     t: T,
///     u: U,
/// }
///
/// trait ExampleTrait {}
/// impl<T:Clone,U:PartialEq> ExampleTrait for Generic<T,U> {}
///
/// use std::sync::Arc;
/// use rpc::ObjectRefExt; // for the cast_to method.
/// let obj: Arc<dyn rpc::Object> = Arc::new(Generic { t: 42_u8, u: 42_u8 });
/// let tr: &dyn ExampleTrait = obj.cast_to_trait().unwrap();
/// ```
///
/// ## Making an object "exposed outside of the session"
///
/// You flag any kind of Object so that its identifiers will be exported
/// outside of the local RPC session.  (Arti uses this for Objects whose
/// ObjectId needs to be used as a SOCKS identifier.)  To do so,
/// use the `expose_outside_session` attribute:
///
/// ```
/// use tor_rpcbase::{self as rpc, templates::*};
/// use derive_deftly::Deftly;
///
/// #[derive(Deftly)]
/// #[derive_deftly(Object)]
/// #[deftly(rpc(expose_outside_of_session))]
/// struct Visible {}
/// ```
    pub Object expect items =

    impl<$tgens> $ttype where
        // We need this restriction in case there are generics
        // that might not impl these traits.
        $ttype: Send + Sync + 'static,
        $twheres
    {
        /// Construct a new `CastTable` for this type.
        ///
        /// This is a function so that we can call it multiple times as
        /// needed if the type is generic.
        ///
        /// Don't invoke this yourself; instead use `decl_object!`.
        #[doc(hidden)]
        fn make_cast_table() -> $crate::CastTable {
            ${if tmeta(rpc(downcastable_to)) {
                $crate::cast_table_deftness_helper!{ ${tmeta(rpc(downcastable_to)) } }
            } else {
                $crate::CastTable::default()
            }}
        }
    }

    impl<$tgens> $crate::Object for $ttype where
        // We need this restriction in case there are generics
        // that might not impl these traits.
        $ttype: Send + Sync + 'static,
        $twheres
    {
        ${if tmeta(rpc(expose_outside_of_session)) {
            fn expose_outside_of_session(&self) -> bool {
                true
            }
        }}

        fn get_cast_table(&self) -> &$crate::CastTable {
            // TODO RPC: Is there a better way to check "is this a generic type"?
            // See derive-deftly#37
            ${if not(approx_equal({$tgens}, {})) {
                // For generic types, we have a potentially unbounded number
                // of CastTables: one for each instantiation of the type.
                // Therefore we keep a mutable add-only HashMap of CastTables.

                use $crate::once_cell::sync::Lazy;
                use std::sync::RwLock;
                use std::collections::HashMap;
                use std::any::TypeId;
                // Map from concrete type to CastTable.
                //
                // Note that we use `&'static CastTable` here, not
                // `Box<CastTable>`: If we used Box<>, the borrow checker would
                // worry that our `CastTable`s might get freed after we returned
                // a reference to them.  Using `&'static` guarantees that the CastTable
                // references are safe to return.
                //
                // In order to get a `&'static`, we need to use Box::leak().
                // That's fine, since we only create one CastTable per
                // instantiation of the type.
                static TABLES: Lazy<RwLock<HashMap<TypeId, &'static $crate::CastTable>>> =
                Lazy::new(|| RwLock::new(HashMap::new()));
                {
                    let tables_r = TABLES.read().expect("poisoned lock");
                    if let Some(table) = tables_r.get(&TypeId::of::<Self>()) {
                        // Fast case: we already had a CastTable for this instantiation.
                        table
                    } else {
                        // We didn't find a CastTable.
                        drop(tables_r); // prevent deadlock.
                        TABLES
                         .write()
                         .expect("poisoned lock")
                         .entry(TypeId::of::<Self>())
                         // We use `or_insert_with` here to avoid a race
                         // condition: we only want to call make_cast_table if
                         // one didn't already exist.
                         .or_insert_with(|| Box::leak(Box::new(Self::make_cast_table())))
                    }
                }
            } else {
                // For non-generic types, we only ever have a single CastTable,
                // so we can just construct it once and return it.
                use $crate::once_cell::sync::Lazy;
                static TABLE: Lazy<$crate::CastTable> = Lazy::new(|| $ttype::make_cast_table());
                &TABLE
            }}
        }
    }
}
pub use derive_deftly_template_Object;

#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_duration_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->

    use super::*;
    use derive_deftly::Deftly;

    #[derive(Deftly)]
    #[derive_deftly(Object)]
    #[deftly(rpc(downcastable_to = "HasWheels"))]
    struct Bicycle {}
    trait HasWheels {
        fn num_wheels(&self) -> usize;
    }
    impl HasWheels for Bicycle {
        fn num_wheels(&self) -> usize {
            2
        }
    }

    #[test]
    fn standard_cast() {
        let bike = Bicycle {};
        let erased_bike: &dyn Object = &bike;
        let has_wheels: &dyn HasWheels = erased_bike.cast_to_trait().unwrap();
        assert_eq!(has_wheels.num_wheels(), 2);
    }

    #[derive(Deftly)]
    #[derive_deftly(Object)]
    #[deftly(rpc(downcastable_to = "HasWheels"))]
    struct Crowd<T: HasWheels + Send + Sync + 'static> {
        members: Vec<T>,
    }
    impl<T: HasWheels + Send + Sync> HasWheels for Crowd<T> {
        fn num_wheels(&self) -> usize {
            self.members.iter().map(T::num_wheels).sum()
        }
    }

    #[test]
    fn generic_cast() {
        let bikes = Crowd {
            members: vec![Bicycle {}, Bicycle {}],
        };
        let erased_bikes: &dyn Object = &bikes;
        let has_wheels: &dyn HasWheels = erased_bikes.cast_to_trait().unwrap();
        assert_eq!(has_wheels.num_wheels(), 4);
    }
}