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
386
387
388
389
390
391
#![allow(clippy::declare_interior_mutable_const)] // see tokio#4872

use std::{
    cell::Cell,
    future::Future,
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
};

use crate::{
    actor::ActorMeta,
    addr::Addr,
    config::SystemConfig,
    dumping::DumpingControl,
    logging::_priv::LoggingControl,
    permissions::{AtomicPermissions, Permissions},
    telemetry::TelemetryConfig,
    tracing::TraceId,
};

tokio::task_local! {
    static SCOPE: Scope;
}

#[derive(Clone)]
pub struct Scope {
    trace_id: Cell<TraceId>,
    actor: Arc<ScopeActorShared>,
    group: Arc<ScopeGroupShared>,
}

assert_impl_all!(Scope: Send);
assert_not_impl_all!(Scope: Sync);

impl Scope {
    /// Private API for now.
    #[doc(hidden)]
    pub fn test(actor: Addr, meta: Arc<ActorMeta>) -> Self {
        Self::new(
            TraceId::generate(),
            actor,
            meta,
            Arc::new(ScopeGroupShared::new(Addr::NULL)),
        )
    }

    pub(crate) fn new(
        trace_id: TraceId,
        addr: Addr,
        meta: Arc<ActorMeta>,
        group: Arc<ScopeGroupShared>,
    ) -> Self {
        Self {
            trace_id: Cell::new(trace_id),
            actor: Arc::new(ScopeActorShared::new(addr, meta)),
            group,
        }
    }

    pub(crate) fn with_telemetry(mut self, config: &TelemetryConfig) -> Self {
        self.actor = Arc::new(self.actor.with_telemetry(config));
        self
    }

    #[inline]
    #[deprecated(note = "use `actor()` instead")]
    pub fn addr(&self) -> Addr {
        self.actor()
    }

    #[inline]
    pub fn actor(&self) -> Addr {
        self.actor.addr
    }

    #[inline]
    pub fn group(&self) -> Addr {
        self.group.addr
    }

    /// Returns the current object's meta.
    #[inline]
    pub fn meta(&self) -> &Arc<ActorMeta> {
        &self.actor.meta
    }

    /// Private API for now.
    #[inline]
    #[stability::unstable]
    #[doc(hidden)]
    pub fn telemetry_meta(&self) -> &Arc<ActorMeta> {
        &self.actor.telemetry_meta
    }

    /// Returns the current trace id.
    #[inline]
    pub fn trace_id(&self) -> TraceId {
        self.trace_id.get()
    }

    /// Replaces the current trace id with the provided one.
    #[inline]
    pub fn set_trace_id(&self, trace_id: TraceId) {
        self.trace_id.set(trace_id);
    }

    /// Returns the current permissions (for logging, telemetry and so on).
    #[inline]
    pub fn permissions(&self) -> Permissions {
        self.group.permissions.load()
    }

    /// Private API for now.
    #[inline]
    #[stability::unstable]
    #[doc(hidden)]
    pub fn logging(&self) -> &LoggingControl {
        &self.group.logging
    }

    /// Private API for now.
    #[inline]
    #[stability::unstable]
    #[doc(hidden)]
    pub fn dumping(&self) -> &DumpingControl {
        &self.group.dumping
    }

    #[doc(hidden)]
    #[stability::unstable]
    pub fn increment_allocated_bytes(&self, by: usize) {
        self.actor.allocated_bytes.fetch_add(by, Ordering::Relaxed);
    }

    #[doc(hidden)]
    #[stability::unstable]
    pub fn increment_deallocated_bytes(&self, by: usize) {
        self.actor
            .deallocated_bytes
            .fetch_add(by, Ordering::Relaxed);
    }

    pub(crate) fn take_allocated_bytes(&self) -> usize {
        self.actor.allocated_bytes.swap(0, Ordering::Relaxed)
    }

    pub(crate) fn take_deallocated_bytes(&self) -> usize {
        self.actor.deallocated_bytes.swap(0, Ordering::Relaxed)
    }

    /// Wraps the provided future with the current scope.
    pub async fn within<F: Future>(self, f: F) -> F::Output {
        SCOPE.scope(self, f).await
    }

    /// Runs the provided function with the current scope.
    pub fn sync_within<R>(self, f: impl FnOnce() -> R) -> R {
        SCOPE.sync_scope(self, f)
    }
}

struct ScopeActorShared {
    addr: Addr,
    meta: Arc<ActorMeta>,
    telemetry_meta: Arc<ActorMeta>,
    allocated_bytes: AtomicUsize,
    deallocated_bytes: AtomicUsize,
}

impl ScopeActorShared {
    fn new(addr: Addr, meta: Arc<ActorMeta>) -> Self {
        Self {
            addr,
            meta: meta.clone(),
            telemetry_meta: meta,
            allocated_bytes: AtomicUsize::new(0),
            deallocated_bytes: AtomicUsize::new(0),
        }
    }

    fn with_telemetry(&self, config: &TelemetryConfig) -> Self {
        Self {
            addr: self.addr,
            meta: self.meta.clone(),
            telemetry_meta: config
                .per_actor_key
                .key(&self.meta.key)
                .map(|key| {
                    Arc::new(ActorMeta {
                        group: self.meta.group.clone(),
                        key,
                    })
                })
                .unwrap_or_else(|| self.meta.clone()),
            allocated_bytes: AtomicUsize::new(0),
            deallocated_bytes: AtomicUsize::new(0),
        }
    }
}

assert_impl_all!(ScopeGroupShared: Send, Sync);

pub(crate) struct ScopeGroupShared {
    addr: Addr,
    permissions: AtomicPermissions,
    logging: LoggingControl,
    dumping: DumpingControl,
}

assert_impl_all!(ScopeGroupShared: Send, Sync);

impl ScopeGroupShared {
    pub(crate) fn new(addr: Addr) -> Self {
        Self {
            addr,
            permissions: Default::default(), // everything is disabled
            logging: Default::default(),
            dumping: Default::default(),
        }
    }

    pub(crate) fn configure(&self, config: &SystemConfig) {
        // Update the logging subsystem.
        self.logging.configure(&config.logging);
        let max_level = self.logging.max_level_hint().into_level();

        // Update the dumping subsystem.
        self.dumping.configure(&config.dumping);

        // Update permissions.
        let mut perm = self.permissions.load();
        perm.set_logging_enabled(max_level);
        perm.set_dumping_enabled(!config.dumping.disabled);
        perm.set_telemetry_per_actor_group_enabled(config.telemetry.per_actor_group);
        perm.set_telemetry_per_actor_key_enabled(config.telemetry.per_actor_key.is_enabled());
        self.permissions.store(perm);
    }
}

/// Exposes the current scope in order to send to other tasks.
///
/// # Panics
/// This function will panic if called outside actors.
pub fn expose() -> Scope {
    SCOPE.with(Clone::clone)
}

/// Exposes the current scope if inside the actor system.
pub fn try_expose() -> Option<Scope> {
    SCOPE.try_with(Clone::clone).ok()
}

/// Accesses the current scope and runs the provided closure.
///
/// # Panics
/// This function will panic if called ouside the actor system.
#[inline]
pub fn with<R>(f: impl FnOnce(&Scope) -> R) -> R {
    try_with(f).expect("cannot access a scope outside the actor system")
}

/// Accesses the current scope and runs the provided closure.
///
/// Returns `None` if called outside the actor system.
/// For a panicking variant, see `with`.
#[inline]
pub fn try_with<R>(f: impl FnOnce(&Scope) -> R) -> Option<R> {
    SCOPE.try_with(|scope| f(scope)).ok()
}

/// Returns the current trace id.
///
/// # Panics
/// This function will panic if called ouside the actor system.
#[inline]
pub fn trace_id() -> TraceId {
    with(Scope::trace_id)
}

/// Returns the current trace id if inside the actor system.
#[inline]
pub fn try_trace_id() -> Option<TraceId> {
    try_with(Scope::trace_id)
}

/// Replaces the current trace id with the provided one.
///
/// # Panics
/// This function will panic if called ouside the actor system.
#[inline]
pub fn set_trace_id(trace_id: TraceId) {
    with(|scope| scope.set_trace_id(trace_id));
}

/// Replaces the current trace id with the provided one
/// if inside the actor system.
///
/// Returns `true` if the trace id has been replaced.
#[inline]
pub fn try_set_trace_id(trace_id: TraceId) -> bool {
    try_with(|scope| scope.set_trace_id(trace_id)).is_some()
}

/// Returns the current object's meta.
///
/// # Panics
/// This function will panic if called ouside the actor system.
#[inline]
pub fn meta() -> Arc<ActorMeta> {
    with(|scope| scope.meta().clone())
}

/// Returns the current object's meta if inside the actor system.
#[inline]
pub fn try_meta() -> Option<Arc<ActorMeta>> {
    try_with(|scope| scope.meta().clone())
}

thread_local! {
    static SERDE_MODE: Cell<SerdeMode> = Cell::new(SerdeMode::Normal);
}

/// A mode of (de)serialization.
/// Useful to alternate a behavior depending on a context.
#[stability::unstable]
#[derive(Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SerdeMode {
    /// A default mode, regular ser/de calls.
    Normal,
    /// Serialzation for dumping purposes.
    Dumping,
    // Network
}

/// Sets the specified serde mode and runs the function.
///
/// # Panics
/// If the provided function panics.
#[stability::unstable]
#[inline]
pub fn with_serde_mode<R>(mode: SerdeMode, f: impl FnOnce() -> R) -> R {
    // We use a guard here to restore the current serde mode even on panics.
    struct Guard(SerdeMode);
    impl Drop for Guard {
        fn drop(&mut self) {
            SERDE_MODE.with(|cell| cell.set(self.0));
        }
    }

    let mode = SERDE_MODE.with(|cell| cell.replace(mode));
    let _guard = Guard(mode);
    f()
}

/// Returns the current serde mode.
#[stability::unstable]
#[inline]
pub fn serde_mode() -> SerdeMode {
    SERDE_MODE.with(Cell::get)
}

#[test]
fn serde_mode_works() {
    #[derive(serde::Serialize)]
    struct S {
        #[serde(serialize_with = "crate::dumping::hide")]
        f: u32,
    }

    let value = S { f: 42 };

    // `Normal` mode
    assert_eq!(serde_json::to_string(&value).unwrap(), r#"{"f":42}"#);

    // `Dumping` mode
    let json = with_serde_mode(SerdeMode::Dumping, || {
        serde_json::to_string(&value).unwrap()
    });
    assert_eq!(json, r#"{"f":"<hidden>"}"#);

    // Restored `Normal` mode
    assert_eq!(serde_json::to_string(&value).unwrap(), r#"{"f":42}"#);

    // `Normal` mode must be restored after panic
    let res = std::panic::catch_unwind(|| with_serde_mode(SerdeMode::Dumping, || panic!("oops")));
    assert!(res.is_err());
    assert_eq!(serde_json::to_string(&value).unwrap(), r#"{"f":42}"#);
}