-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathshared_runtime.rs
More file actions
346 lines (318 loc) · 11.7 KB
/
shared_runtime.rs
File metadata and controls
346 lines (318 loc) · 11.7 KB
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
// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0
use crate::catch_panic;
use libdd_shared_runtime::{SharedRuntime, SharedRuntimeError};
use std::ffi::{c_char, CString};
use std::ptr::NonNull;
use std::sync::Arc;
/// Error codes for SharedRuntime FFI operations.
///
/// # ABI stability
/// Discriminants are pinned explicitly. The numeric values are part of the
/// C ABI: existing variants must never be renumbered or reused, and new
/// variants must be appended with a fresh value. Inserting a variant in
/// the middle of the list silently misclassifies errors on any caller
/// compiled against an older header.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum SharedRuntimeErrorCode {
/// Invalid argument provided (e.g. null handle).
InvalidArgument = 0,
/// The runtime is not available or in an invalid state.
RuntimeUnavailable = 1,
/// Failed to acquire a lock on internal state.
LockFailed = 2,
/// A worker operation failed.
WorkerError = 3,
/// Failed to create the tokio runtime.
RuntimeCreation = 4,
/// Shutdown timed out.
ShutdownTimedOut = 5,
/// An unexpected panic occurred inside the FFI call.
#[cfg(feature = "catch_panic")]
Panic = 6,
/// Operation rejected because the runtime has already been shut down.
AlreadyShutdown = 7,
}
/// Error returned by SharedRuntime FFI functions.
#[repr(C)]
pub struct SharedRuntimeFFIError {
pub code: SharedRuntimeErrorCode,
/// The error message is always defined when the error is returned by a ddog_shared_runtime
/// ffi.
pub msg: *mut c_char,
}
impl SharedRuntimeFFIError {
fn new(code: SharedRuntimeErrorCode, msg: &str) -> Self {
Self {
code,
msg: CString::new(msg).unwrap_or_default().into_raw(),
}
}
}
impl From<SharedRuntimeError> for SharedRuntimeFFIError {
fn from(err: SharedRuntimeError) -> Self {
let code = match &err {
SharedRuntimeError::RuntimeUnavailable => SharedRuntimeErrorCode::RuntimeUnavailable,
SharedRuntimeError::AlreadyShutdown => SharedRuntimeErrorCode::AlreadyShutdown,
SharedRuntimeError::LockFailed(_) => SharedRuntimeErrorCode::LockFailed,
SharedRuntimeError::WorkerError(_) => SharedRuntimeErrorCode::WorkerError,
SharedRuntimeError::RuntimeCreation(_) => SharedRuntimeErrorCode::RuntimeCreation,
SharedRuntimeError::ShutdownTimedOut(_) => SharedRuntimeErrorCode::ShutdownTimedOut,
};
SharedRuntimeFFIError::new(code, &err.to_string())
}
}
impl Drop for SharedRuntimeFFIError {
fn drop(&mut self) {
if !self.msg.is_null() {
// SAFETY: `msg` is always produced by `CString::into_raw` in `new`.
unsafe {
drop(CString::from_raw(self.msg));
self.msg = std::ptr::null_mut();
}
}
}
}
macro_rules! panic_error {
() => {
Some(Box::new(SharedRuntimeFFIError::new(
SharedRuntimeErrorCode::Panic,
"panic",
)))
};
}
/// Frees a `SharedRuntimeFFIError`. After this call the pointer is invalid.
#[no_mangle]
pub unsafe extern "C" fn ddog_shared_runtime_error_free(error: Option<Box<SharedRuntimeFFIError>>) {
catch_panic!(drop(error), ())
}
/// Create a new `SharedRuntime`.
///
/// On success writes a raw handle into `*out_handle` and returns `None`.
/// On failure leaves `*out_handle` unchanged and returns an error.
///
/// The caller owns the handle and must eventually pass it to
/// [`ddog_shared_runtime_free`] (or another consumer that takes ownership).
#[no_mangle]
pub unsafe extern "C" fn ddog_shared_runtime_new(
out_handle: NonNull<*const SharedRuntime>,
) -> Option<Box<SharedRuntimeFFIError>> {
catch_panic!(
match SharedRuntime::new() {
Ok(runtime) => {
out_handle.as_ptr().write(Arc::into_raw(Arc::new(runtime)));
None
}
Err(err) => Some(Box::new(SharedRuntimeFFIError::from(err))),
},
panic_error!()
)
}
/// Free a handle, decrementing the `Arc` strong count.
///
/// The underlying runtime may not be dropped if other components are still using it.
/// Use [`ddog_shared_runtime_shutdown`] to cleanly stop workers.
#[no_mangle]
pub unsafe extern "C" fn ddog_shared_runtime_free(handle: *const SharedRuntime) {
catch_panic!(
{
if !handle.is_null() {
// SAFETY: handle was produced by Arc::into_raw; this call takes ownership.
drop(Arc::from_raw(handle));
}
},
()
)
}
/// Must be called in the parent process before `fork()`.
///
/// Pauses all workers so that no background threads are running during the
/// fork, preventing deadlocks in the child process.
///
/// Returns an error if `handle` is null.
/// The handle must have been initialized with `ddog_shared_runtime_new`.
#[no_mangle]
pub unsafe extern "C" fn ddog_shared_runtime_before_fork(
handle: Option<&SharedRuntime>,
) -> Option<Box<SharedRuntimeFFIError>> {
catch_panic!(
{
match handle {
Some(runtime) => {
// SAFETY: handle was produced by Arc::into_raw and the Arc is still alive.
runtime.before_fork();
None
}
None => Some(Box::new(SharedRuntimeFFIError::new(
SharedRuntimeErrorCode::InvalidArgument,
"handle is null",
))),
}
},
panic_error!()
)
}
/// Must be called in the parent process after `fork()`.
///
/// Restarts all workers that were paused by [`ddog_shared_runtime_before_fork`].
///
/// Returns `None` on success, or an error if workers could not be restarted.
/// The handle must have been initialized with `ddog_shared_runtime_new`.
#[no_mangle]
pub unsafe extern "C" fn ddog_shared_runtime_after_fork_parent(
handle: Option<&SharedRuntime>,
) -> Option<Box<SharedRuntimeFFIError>> {
catch_panic!(
{
match handle {
Some(runtime) => {
// SAFETY: handle was produced by Arc::into_raw and the Arc is still alive.
match runtime.after_fork_parent() {
Ok(()) => None,
Err(err) => Some(Box::new(SharedRuntimeFFIError::from(err))),
}
}
None => Some(Box::new(SharedRuntimeFFIError::new(
SharedRuntimeErrorCode::InvalidArgument,
"handle is null",
))),
}
},
panic_error!()
)
}
/// Must be called in the child process after `fork()`.
///
/// Creates a fresh tokio runtime and restarts all workers. The original
/// runtime cannot be safely reused after a fork.
///
/// Returns `None` on success, or an error if the runtime could not be
/// reinitialized.
/// The handle must have been initialized with `ddog_shared_runtime_new`.
#[no_mangle]
pub unsafe extern "C" fn ddog_shared_runtime_after_fork_child(
handle: Option<&SharedRuntime>,
) -> Option<Box<SharedRuntimeFFIError>> {
catch_panic!(
{
match handle {
Some(runtime) => {
// SAFETY: handle was produced by Arc::into_raw and the Arc is still alive.
match runtime.after_fork_child() {
Ok(()) => None,
Err(err) => Some(Box::new(SharedRuntimeFFIError::from(err))),
}
}
None => Some(Box::new(SharedRuntimeFFIError::new(
SharedRuntimeErrorCode::InvalidArgument,
"handle is null",
))),
}
},
panic_error!()
)
}
/// Shut down the `SharedRuntime`, stopping all workers.
///
/// `timeout_ms` is the maximum time to wait for workers to stop, in
/// milliseconds. Pass `0` for no timeout.
///
/// Returns `None` on success, or `SharedRuntimeErrorCode::ShutdownTimedOut`
/// if the timeout was reached.
/// The handle must have been initialized with `ddog_shared_runtime_new`.
#[no_mangle]
pub unsafe extern "C" fn ddog_shared_runtime_shutdown(
handle: Option<&SharedRuntime>,
timeout_ms: u64,
) -> Option<Box<SharedRuntimeFFIError>> {
catch_panic!(
{
match handle {
Some(runtime) => {
let timeout = if timeout_ms > 0 {
Some(std::time::Duration::from_millis(timeout_ms))
} else {
None
};
// SAFETY: handle was produced by Arc::into_raw and the Arc is still alive.
match runtime.shutdown(timeout) {
Ok(()) => None,
Err(err) => Some(Box::new(SharedRuntimeFFIError::from(err))),
}
}
None => Some(Box::new(SharedRuntimeFFIError::new(
SharedRuntimeErrorCode::InvalidArgument,
"handle is null",
))),
}
},
panic_error!()
)
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem::MaybeUninit;
#[test]
fn test_new_and_free() {
unsafe {
let mut handle: MaybeUninit<*const SharedRuntime> = MaybeUninit::uninit();
let err = ddog_shared_runtime_new(NonNull::new_unchecked(handle.as_mut_ptr()));
assert!(err.is_none());
ddog_shared_runtime_free(handle.assume_init());
}
}
#[test]
fn test_before_after_fork_null() {
unsafe {
let err = ddog_shared_runtime_before_fork(None);
assert_eq!(err.unwrap().code, SharedRuntimeErrorCode::InvalidArgument);
let err = ddog_shared_runtime_after_fork_parent(None);
assert_eq!(err.unwrap().code, SharedRuntimeErrorCode::InvalidArgument);
let err = ddog_shared_runtime_after_fork_child(None);
assert_eq!(err.unwrap().code, SharedRuntimeErrorCode::InvalidArgument);
}
}
#[test]
fn test_fork_lifecycle() {
unsafe {
let mut handle: MaybeUninit<*const SharedRuntime> = MaybeUninit::uninit();
ddog_shared_runtime_new(NonNull::new_unchecked(handle.as_mut_ptr()));
let handle = handle.assume_init();
let err = ddog_shared_runtime_before_fork(std::mem::transmute::<
*const SharedRuntime,
Option<&SharedRuntime>,
>(handle));
assert!(err.is_none(), "{:?}", err.map(|e| e.code));
let err = ddog_shared_runtime_after_fork_parent(std::mem::transmute::<
*const SharedRuntime,
Option<&SharedRuntime>,
>(handle));
assert!(err.is_none(), "{:?}", err.map(|e| e.code));
ddog_shared_runtime_free(handle);
}
}
#[test]
fn test_shutdown() {
unsafe {
let mut handle: MaybeUninit<*const SharedRuntime> = MaybeUninit::uninit();
ddog_shared_runtime_new(NonNull::new_unchecked(handle.as_mut_ptr()));
let handle = handle.assume_init();
let err = ddog_shared_runtime_shutdown(
std::mem::transmute::<*const SharedRuntime, Option<&SharedRuntime>>(handle),
0,
);
assert!(err.is_none());
ddog_shared_runtime_free(handle);
}
}
#[test]
fn test_error_free() {
let error = Box::new(SharedRuntimeFFIError::new(
SharedRuntimeErrorCode::InvalidArgument,
"test error",
));
unsafe { ddog_shared_runtime_error_free(Some(error)) };
}
}