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
use std::{borrow::Cow, cell::RefCell, mem, sync::Arc};
use arc_swap::ArcSwapOption;
use im::Vector;
use crate::util::PhantomNotSend;
type GroupTags = &'static [(&'static str, &'static str)];
type TokenRegistry = Vector<Option<GroupTags>>;
static TOKEN_REGISTRY: ArcSwapOption<TokenRegistry> = ArcSwapOption::const_empty();
thread_local! {
static CURRENT_ALLOCATION_TOKEN: RefCell<Option<usize>> = RefCell::new(None);
}
pub struct AllocationGroupToken(usize);
impl AllocationGroupToken {
pub fn acquire() -> AllocationGroupToken {
let mut id = 0;
TOKEN_REGISTRY.rcu(|registry| {
let mut registry = registry
.as_ref()
.map(|inner| inner.as_ref().clone())
.unwrap_or_default();
id = registry.len();
registry.push_back(None);
Some(Arc::new(registry))
});
AllocationGroupToken(id)
}
pub fn acquire_with_tags<K, V>(tags: &[(K, V)]) -> AllocationGroupToken
where
K: Into<Cow<'static, str>> + Clone,
V: Into<Cow<'static, str>> + Clone,
{
let tags = tags
.iter()
.map(|tag| {
let (k, v) = tag;
let sk = match k.clone().into() {
Cow::Borrowed(rs) => rs,
Cow::Owned(os) => Box::leak(os.into_boxed_str()),
};
let sv = match v.clone().into() {
Cow::Borrowed(rs) => rs,
Cow::Owned(os) => Box::leak(os.into_boxed_str()),
};
(sk, sv)
})
.collect::<Vec<_>>();
let tags = &*Box::leak(tags.into_boxed_slice());
let mut id = 0;
TOKEN_REGISTRY.rcu(|registry| {
let mut registry = registry
.as_ref()
.map(|inner| inner.as_ref().clone())
.unwrap_or_default();
id = registry.len();
registry.push_back(Some(tags));
Some(Arc::new(registry))
});
AllocationGroupToken(id)
}
pub(crate) fn into_unsafe(self) -> UnsafeAllocationGroupToken {
UnsafeAllocationGroupToken::new(self.0)
}
pub fn enter(self) -> AllocationGuard {
AllocationGuard::enter(self)
}
}
#[cfg(feature = "tracing-compat")]
impl AllocationGroupToken {
pub fn attach_to_span(self, span: &tracing::Span) {
use crate::tracing::WithAllocationGroup;
let mut unsafe_token = Some(self.into_unsafe());
tracing::dispatcher::get_default(move |dispatch| {
if let Some(id) = span.id() {
if let Some(ctx) = dispatch.downcast_ref::<WithAllocationGroup>() {
let unsafe_token = unsafe_token.take().expect("token already consumed");
return ctx.with_allocation_group(dispatch, &id, unsafe_token);
}
}
});
}
}
enum GuardState {
Idle(usize),
Active(Option<usize>),
}
impl GuardState {
fn idle(id: usize) -> Self {
Self::Idle(id)
}
fn transition_to_active(&mut self) {
let new_state = match self {
Self::Idle(id) => {
let previous = CURRENT_ALLOCATION_TOKEN.with(|current| current.replace(Some(*id)));
Self::Active(previous)
}
Self::Active(_) => panic!("transitioning active->active is invalid"),
};
*self = new_state;
}
fn transition_to_idle(&mut self) -> usize {
let (id, new_state) = match self {
Self::Idle(_) => panic!("transitioning idle->idle is invalid"),
Self::Active(previous) => {
let current = CURRENT_ALLOCATION_TOKEN.with(|current| {
let old = mem::replace(&mut *current.borrow_mut(), previous.take());
old.expect("transitioned to idle state with empty CURRENT_ALLOCATION_TOKEN")
});
(current, Self::Idle(current))
}
};
*self = new_state;
id
}
}
pub struct AllocationGuard {
state: GuardState,
_ns: PhantomNotSend,
}
impl AllocationGuard {
pub(crate) fn enter(token: AllocationGroupToken) -> AllocationGuard {
let mut state = GuardState::idle(token.0);
state.transition_to_active();
AllocationGuard {
state,
_ns: PhantomNotSend::default(),
}
}
pub fn exit(mut self) -> AllocationGroupToken {
self.exit_inner()
}
fn exit_inner(&mut self) -> AllocationGroupToken {
let current = self.state.transition_to_idle();
AllocationGroupToken(current)
}
}
impl Drop for AllocationGuard {
fn drop(&mut self) {
let _ = self.exit_inner();
}
}
pub(crate) struct UnsafeAllocationGroupToken {
state: GuardState,
}
impl UnsafeAllocationGroupToken {
pub fn new(id: usize) -> Self {
Self {
state: GuardState::idle(id),
}
}
pub fn enter(&mut self) {
self.state.transition_to_active();
}
pub fn exit(&mut self) {
let _ = self.state.transition_to_idle();
}
}
pub(crate) struct AllocationGroupMetadata {
id: usize,
tags: Option<GroupTags>,
}
impl AllocationGroupMetadata {
pub fn id(&self) -> usize {
self.id
}
pub fn tags(&self) -> Option<GroupTags> {
self.tags
}
}
#[inline(always)]
pub(crate) fn get_active_allocation_group() -> Option<AllocationGroupMetadata> {
CURRENT_ALLOCATION_TOKEN
.with(|current| *current.borrow())
.map(|id| {
let registry_guard = TOKEN_REGISTRY.load();
let registry = registry_guard
.as_ref()
.expect("allocation token cannot be set unless registry has been created");
let tags = registry.get(id).copied().flatten();
AllocationGroupMetadata { id, tags }
})
}