buttplug_core 11.0.0

Buttplug Intimate Hardware Control Library - Core Library
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
// Buttplug Rust Source Code File - See https://buttplug.io for more info.
//
// Copyright 2016-2026 Nonpolynomial Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.

use crate::util::async_manager::{self, TaskCompletion, TaskCompletionResult};
use futures::{
  channel::oneshot,
  future::{AbortHandle, Abortable, BoxFuture, FutureExt, Shared},
};
use std::{
  future::Future,
  sync::{Arc, Mutex},
};
use tracing::Span;

/// Build the [`Span`] identifying a task passed to [`TaskGroup::spawn`].
///
/// The name must be a literal: a span's name is baked into its `'static` callsite
/// metadata, so it cannot come from a runtime value.
#[macro_export]
macro_rules! task_span {
  ($name:expr) => {
    tracing::span!(tracing::Level::INFO, $name)
  };
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TaskGroupClosed;

struct OwnedTask {
  abort_handle: AbortHandle,
  completion: TaskCompletion,
}

type ShutdownCompletion = Shared<BoxFuture<'static, Vec<TaskCompletionResult>>>;

#[derive(Default)]
struct TaskGroupState {
  closed: bool,
  tasks: Vec<OwnedTask>,
  shutdown: Option<ShutdownCompletion>,
}

#[derive(Default)]
struct TaskGroupInner {
  state: Mutex<TaskGroupState>,
}

impl Drop for TaskGroupInner {
  fn drop(&mut self) {
    let state = self
      .state
      .get_mut()
      .unwrap_or_else(|poisoned| poisoned.into_inner());
    state.closed = true;
    for task in &state.tasks {
      task.abort_handle.abort();
    }
  }
}

#[derive(Clone, Default)]
pub struct TaskGroup {
  inner: Arc<TaskGroupInner>,
}

impl TaskGroup {
  pub fn new() -> Self {
    Self::default()
  }

  fn reserve(
    &self,
  ) -> Result<
    (
      futures::future::AbortRegistration,
      oneshot::Sender<TaskCompletion>,
    ),
    TaskGroupClosed,
  > {
    let mut state = self
      .inner
      .state
      .lock()
      .unwrap_or_else(|poisoned| poisoned.into_inner());
    if state.closed {
      return Err(TaskGroupClosed);
    }

    let (abort_handle, abort_registration) = AbortHandle::new_pair();
    let (completion_sender, completion_receiver) = oneshot::channel::<TaskCompletion>();
    let completion = async move {
      match completion_receiver.await {
        Ok(completion) => completion.await,
        Err(_) => TaskCompletionResult::RuntimeAborted,
      }
    }
    .boxed();
    state.tasks.push(OwnedTask {
      abort_handle,
      completion,
    });
    Ok((abort_registration, completion_sender))
  }

  /// Spawn a task into this group, identified by `span`.
  ///
  /// Build `span` at the call site with a literal name, via the [`task_span!`] macro or
  /// `tracing::span!` directly. A span's name lives in its callsite metadata, which
  /// [`AsyncManager`][async_manager::AsyncManager] implementations can read; a name passed
  /// as a span *field* is only visible to tracing subscribers, so runtimes that allocate
  /// per-task resources by name could not see it.
  ///
  /// Note that `Span::metadata()` returns `Some` only while the span is *enabled*: the
  /// active subscriber's filter must accept the INFO-level callsite. Runtimes that read
  /// task names from span metadata must install a subscriber that enables these spans
  /// before spawning, or every task arrives with `metadata() == None`.
  #[cfg(not(feature = "wasm"))]
  pub fn spawn<F, Fut>(&self, span: Span, task: F) -> Result<(), TaskGroupClosed>
  where
    F: FnOnce() -> Fut + Send + 'static,
    Fut: Future<Output = ()> + Send + 'static,
  {
    let (abort_registration, completion_sender) = self.reserve()?;
    let future = async move {
      match Abortable::new(task(), abort_registration).await {
        Ok(()) => TaskCompletionResult::Completed,
        Err(_) => TaskCompletionResult::Cancelled,
      }
    };
    let completion = async_manager::spawn_with_result(future, span);
    let _ = completion_sender.send(completion);
    Ok(())
  }

  /// Spawn a task into this group, identified by `span`.
  ///
  /// See the non-WASM variant for why this takes a [`Span`] rather than a name.
  #[cfg(feature = "wasm")]
  pub fn spawn<F, Fut>(&self, span: Span, task: F) -> Result<(), TaskGroupClosed>
  where
    F: FnOnce() -> Fut + 'static,
    Fut: Future<Output = ()> + 'static,
  {
    let (abort_registration, completion_sender) = self.reserve()?;
    let future = async move {
      match Abortable::new(task(), abort_registration).await {
        Ok(()) => TaskCompletionResult::Completed,
        Err(_) => TaskCompletionResult::Cancelled,
      }
    };
    let completion = async_manager::spawn_with_result(future, span);
    let _ = completion_sender.send(completion);
    Ok(())
  }

  pub fn cancel(&self) {
    let mut state = self
      .inner
      .state
      .lock()
      .unwrap_or_else(|poisoned| poisoned.into_inner());
    state.closed = true;
    for task in &state.tasks {
      task.abort_handle.abort();
    }
  }

  pub async fn shutdown(&self) -> Vec<TaskCompletionResult> {
    let shutdown = {
      let mut state = self
        .inner
        .state
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
      if let Some(shutdown) = &state.shutdown {
        shutdown.clone()
      } else {
        state.closed = true;
        let tasks = std::mem::take(&mut state.tasks);
        for task in &tasks {
          task.abort_handle.abort();
        }
        let shutdown = async move {
          futures::future::join_all(tasks.into_iter().map(|task| task.completion)).await
        }
        .boxed()
        .shared();
        state.shutdown = Some(shutdown.clone());
        shutdown
      }
    };

    shutdown.await
  }
}

#[cfg(all(test, not(feature = "wasm")))]
mod tests {
  use super::*;
  use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
  use tokio::sync::oneshot;

  /// `AsyncManager` implementations for runtimes that allocate per-task resources (stack
  /// size on FreeRTOS, for instance) can only identify a task by its callsite metadata
  /// name. A name passed as a span *field* is invisible to them, so every task would
  /// arrive indistinguishable and get the same fallback allocation.
  #[test]
  fn task_span_carries_name_in_callsite_metadata() {
    tracing::subscriber::with_default(tracing_subscriber::registry(), || {
      let span = crate::task_span!("DeviceTask");
      assert_eq!(
        span.metadata().map(|metadata| metadata.name()),
        Some("DeviceTask")
      );
    });
  }

  #[tokio::test]
  async fn spawned_task_is_joined_by_shutdown() {
    let group = TaskGroup::new();
    let (started_sender, started_receiver) = oneshot::channel();
    let (dropped_sender, dropped_receiver) = oneshot::channel();
    group
      .spawn(crate::task_span!("joined"), || async move {
        let _guard = DropSignal(Some(dropped_sender));
        let _ = started_sender.send(());
        futures::future::pending::<()>().await;
      })
      .unwrap();
    started_receiver.await.unwrap();

    assert_eq!(
      group.shutdown().await,
      vec![TaskCompletionResult::Cancelled]
    );
    dropped_receiver.await.unwrap();
  }

  #[tokio::test]
  async fn spawn_rejected_after_shutdown_begins() {
    let group = TaskGroup::new();
    group.cancel();
    let invoked = Arc::new(AtomicBool::new(false));
    let invoked_for_task = invoked.clone();

    assert_eq!(
      group.spawn(crate::task_span!("rejected"), move || {
        invoked_for_task.store(true, Ordering::SeqCst);
        async {}
      }),
      Err(TaskGroupClosed)
    );
    assert!(!invoked.load(Ordering::SeqCst));
  }

  #[test]
  fn concurrent_spawn_is_rejected_or_joined() {
    let group = TaskGroup::new();
    let invoked = Arc::new(AtomicBool::new(false));
    let mut state = group.inner.state.lock().unwrap();

    let spawn_group = group.clone();
    let invoked_for_task = invoked.clone();
    let spawn = std::thread::spawn(move || {
      spawn_group.spawn(crate::task_span!("racing spawn"), move || {
        invoked_for_task.store(true, Ordering::SeqCst);
        async {}
      })
    });
    state.closed = true;
    drop(state);

    assert_eq!(spawn.join().unwrap(), Err(TaskGroupClosed));
    assert!(!invoked.load(Ordering::SeqCst));
  }

  #[tokio::test]
  async fn task_panic_does_not_hang_shutdown() {
    let group = TaskGroup::new();
    let (started_sender, started_receiver) = oneshot::channel();
    group
      .spawn(crate::task_span!("panic"), || async move {
        let _ = started_sender.send(());
        panic!("expected panic");
      })
      .unwrap();
    started_receiver.await.unwrap();

    assert_eq!(group.shutdown().await, vec![TaskCompletionResult::Panicked]);
  }

  #[tokio::test]
  async fn concurrent_shutdown_callers_share_completion() {
    let group = TaskGroup::new();
    let (started_sender, started_receiver) = oneshot::channel();
    group
      .spawn(crate::task_span!("concurrent shutdown"), || async move {
        let _ = started_sender.send(());
        futures::future::pending::<()>().await;
      })
      .unwrap();
    started_receiver.await.unwrap();

    let first = group.shutdown();
    let second = group.shutdown();
    let (first, second) = futures::future::join(first, second).await;
    assert_eq!(first, vec![TaskCompletionResult::Cancelled]);
    assert_eq!(second, first);
  }

  #[tokio::test]
  async fn sequential_shutdown_is_idempotent() {
    let group = TaskGroup::new();
    let (started_sender, started_receiver) = oneshot::channel();
    group
      .spawn(crate::task_span!("sequential shutdown"), || async move {
        let _ = started_sender.send(());
        futures::future::pending::<()>().await;
      })
      .unwrap();
    started_receiver.await.unwrap();

    let first = group.shutdown().await;
    let second = group.shutdown().await;
    assert_eq!(first, vec![TaskCompletionResult::Cancelled]);
    assert_eq!(second, first);
  }

  #[tokio::test]
  async fn drop_requests_cancellation() {
    let (started_sender, started_receiver) = oneshot::channel();
    let (dropped_sender, dropped_receiver) = oneshot::channel();
    {
      let group = TaskGroup::new();
      group
        .spawn(crate::task_span!("drop"), || async move {
          let _guard = DropSignal(Some(dropped_sender));
          let _ = started_sender.send(());
          futures::future::pending::<()>().await;
        })
        .unwrap();
      started_receiver.await.unwrap();
    }

    dropped_receiver.await.unwrap();
  }

  #[tokio::test]
  async fn concurrent_final_clone_drops_request_cancellation() {
    let (started_sender, started_receiver) = oneshot::channel();
    let (dropped_sender, dropped_receiver) = oneshot::channel();
    let group = TaskGroup::new();
    group
      .spawn(crate::task_span!("concurrent drops"), || async move {
        let _guard = DropSignal(Some(dropped_sender));
        let _ = started_sender.send(());
        futures::future::pending::<()>().await;
      })
      .unwrap();
    started_receiver.await.unwrap();

    let other = group.clone();
    let barrier = Arc::new(std::sync::Barrier::new(3));
    let first_barrier = barrier.clone();
    let first = std::thread::spawn(move || {
      first_barrier.wait();
      drop(group);
    });
    let second_barrier = barrier.clone();
    let second = std::thread::spawn(move || {
      second_barrier.wait();
      drop(other);
    });
    barrier.wait();
    first.join().unwrap();
    second.join().unwrap();

    dropped_receiver.await.unwrap();
  }

  #[tokio::test]
  async fn duplicate_names_remain_independent() {
    let group = TaskGroup::new();
    let completed = Arc::new(AtomicUsize::new(0));
    let mut started = Vec::new();
    for _ in 0..2 {
      let completed = completed.clone();
      let (started_sender, started_receiver) = oneshot::channel();
      started.push(started_receiver);
      group
        .spawn(crate::task_span!("duplicate"), move || async move {
          completed.fetch_add(1, Ordering::SeqCst);
          let _ = started_sender.send(());
        })
        .unwrap();
    }
    for receiver in started {
      receiver.await.unwrap();
    }

    let results = group.shutdown().await;
    assert_eq!(results.len(), 2);
    assert_eq!(completed.load(Ordering::SeqCst), 2);
  }

  #[test]
  fn runtime_drop_with_live_tasks_does_not_poison_next_runtime() {
    let first_runtime = tokio::runtime::Builder::new_current_thread()
      .enable_all()
      .build()
      .unwrap();
    let completion = {
      let _guard = first_runtime.enter();
      async_manager::spawn(
        futures::future::pending::<()>(),
        tracing::span!(tracing::Level::INFO, "runtime drop test"),
      )
    };
    drop(first_runtime);

    let second_runtime = tokio::runtime::Builder::new_current_thread()
      .enable_all()
      .build()
      .unwrap();
    assert_eq!(
      second_runtime.block_on(completion),
      TaskCompletionResult::RuntimeAborted
    );
    let next_completion = {
      let _guard = second_runtime.enter();
      async_manager::spawn(
        async {},
        tracing::span!(tracing::Level::INFO, "replacement runtime test"),
      )
    };
    assert_eq!(
      second_runtime.block_on(next_completion),
      TaskCompletionResult::Completed
    );
  }

  #[test]
  fn repeated_runtime_shutdown_completes_owned_tasks() {
    for _ in 0..3 {
      let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();
      let group = TaskGroup::new();
      let _guard = runtime.enter();
      group
        .spawn(crate::task_span!("runtime cycle"), || async {
          futures::future::pending::<()>().await;
        })
        .unwrap();
      assert_eq!(
        runtime.block_on(group.shutdown()),
        vec![TaskCompletionResult::Cancelled]
      );
    }
  }

  struct DropSignal(Option<oneshot::Sender<()>>);

  impl Drop for DropSignal {
    fn drop(&mut self) {
      if let Some(sender) = self.0.take() {
        let _ = sender.send(());
      }
    }
  }
}