Skip to main content

ntex_server/
wrk.rs

1use std::sync::atomic::{AtomicU64, Ordering};
2use std::sync::{Arc, OnceLock};
3use std::task::{Context, Poll, ready};
4use std::{cmp, future::Future, future::poll_fn, hash, pin::Pin};
5
6use async_channel::{Receiver, Sender, TryRecvError, TrySendError, unbounded};
7use event_listener::Event;
8
9use ntex_rt::{Arbiter, spawn};
10use ntex_service::Pipeline;
11use ntex_util::future::{Either, Stream, select, stream_recv};
12use ntex_util::time::{Millis, sleep, timeout_checked};
13
14use crate::{ServerConfiguration, affinity::Placement, metrics::WorkerSlot};
15
16const STOP_TIMEOUT: Millis = Millis(3000);
17
18#[derive(Debug)]
19/// Shutdown worker command.
20struct Shutdown {
21    timeout: Millis,
22    result: oneshot::Sender<bool>,
23}
24
25#[derive(Copy, Clone, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
26/// Worker status.
27pub enum WorkerStatus {
28    /// The worker is ready to accept an item.
29    Available,
30    /// The worker is temporarily unable to accept an item.
31    #[default]
32    Unavailable,
33    /// The worker has stopped.
34    ///
35    /// Reported when the worker panics, its service cannot be created, or
36    /// it finishes a regular stop.
37    Failed,
38}
39
40#[derive(Debug)]
41/// Server worker.
42///
43/// A worker runs one service instance on its own arbiter thread. It receives
44/// items through an unbounded channel. Clones refer to the same worker.
45pub struct Worker<T> {
46    name: String,
47    reqs: Sender<T>,
48    /// Takes back items the worker has not received yet.
49    queue: Receiver<T>,
50    stop: Sender<Shutdown>,
51    avail: WorkerAvailability,
52    arbiter: Arbiter,
53    metrics: Option<Arc<WorkerSlot>>,
54    /// Set once the placement is applied.
55    cpus: Arc<OnceLock<Box<[usize]>>>,
56}
57
58#[derive(Debug)]
59/// Future returned when stopping a worker.
60///
61/// Resolves to `true` if the worker's service shut down within the timeout,
62/// or if the worker was already gone. Resolves to `false` if the timeout
63/// expired, or if the worker was stopped before its service was created.
64pub struct WorkerStop(oneshot::AsyncReceiver<bool>);
65
66impl<T> Worker<T> {
67    /// Starts a worker on a new arbiter thread.
68    ///
69    /// Returns immediately. The worker reports
70    /// [`Unavailable`](WorkerStatus::Unavailable) until its service is
71    /// created. If `cpu` is set, the worker thread is pinned to the logical
72    /// CPU with that index. On Windows, CPUs are numbered across processor
73    /// groups, the CPUs of group 1 follow the CPUs of group 0. Pinning is
74    /// supported on Windows, Linux and Android.
75    pub fn start<F>(name: String, cfg: F, cpu: Option<usize>) -> Worker<T>
76    where
77        T: Send + 'static,
78        F: ServerConfiguration<Item = T>,
79    {
80        Self::start_with(name, cfg, cpu.map(Placement::cpu), None)
81    }
82
83    pub(crate) fn start_with<F>(
84        name: String,
85        cfg: F,
86        placement: Option<Placement>,
87        metrics: Option<Arc<WorkerSlot>>,
88    ) -> Worker<T>
89    where
90        T: Send + 'static,
91        F: ServerConfiguration<Item = T>,
92    {
93        let (reqs, r_rx) = unbounded();
94        let (stop, s_rx) = unbounded();
95        let (avail, a_tx) = WorkerAvailability::create();
96        let n = name.clone();
97        let inner = avail.inner.clone();
98        let cpus = Arc::new(OnceLock::new());
99
100        let n2 = name.clone();
101        let cpus2 = cpus.clone();
102        let init = move || {
103            if let Some(placement) = placement {
104                if placement.apply() {
105                    log::info!("Set affinity to {placement} for worker {n2:?}");
106                    crate::affinity::set_current_cpu(placement.cpus().first().copied());
107                    // the worker is not available before init completes,
108                    // the balancer reads the CPUs once it is
109                    let _ = cpus2.set(placement.cpus().into());
110                } else {
111                    log::warn!("Cannot set affinity to {placement} for worker {n2:?}");
112                }
113            }
114        };
115
116        // placement is applied before the runtime is created, so its memory
117        // is allocated on the NUMA node of the worker's CPU
118        let arbiter =
119            Arbiter::with_init(name.clone(), init).on_stop(move || inner.set_failed(true));
120        if let Some(ref m) = metrics {
121            m.set_arbiter(arbiter.clone());
122        }
123        let worker = Worker {
124            reqs,
125            queue: r_rx.clone(),
126            avail,
127            stop,
128            name,
129            arbiter: arbiter.clone(),
130            metrics: metrics.clone(),
131            cpus,
132        };
133        let reqs = Queue(r_rx);
134
135        arbiter.handle().spawn_detached(async move {
136            log::info!("Starting worker {n:?}");
137
138            // the arbiter is stopped even if the service panics, runtimes
139            // that catch task panics keep the arbiter running otherwise
140            WorkerSlot::set_current(metrics.clone());
141            let task = spawn(async move {
142                match ServiceRunner::create(&n, cfg, reqs, s_rx, a_tx, metrics).await {
143                    Ok(wrk) => {
144                        log::debug!("Server instance has been created in {n:?}");
145                        wrk.run().await;
146                    }
147                    Err(()) => {
148                        log::error!("Cannot start worker {n:?}");
149                    }
150                }
151            });
152            ntex_rt::spawn_detached(async move {
153                let _ = task.await;
154                Arbiter::current().stop();
155            });
156        });
157
158        worker
159    }
160
161    /// Returns the worker name.
162    pub fn name(&self) -> &str {
163        &self.name
164    }
165
166    /// Returns the arbiter the worker runs on.
167    pub(crate) fn arbiter(&self) -> &Arbiter {
168        &self.arbiter
169    }
170
171    /// Returns the number of open connections plus queued items.
172    pub(crate) fn load(&self) -> usize {
173        self.metrics.as_ref().map_or(0, |m| m.active()) + self.reqs.len()
174    }
175
176    /// Returns the index of the worker's CPU followed by its SMT siblings,
177    /// empty if the worker is not placed on a CPU or the placement failed.
178    pub(crate) fn cpus(&self) -> &[usize] {
179        self.cpus.get().map_or(&[], |cpus| cpus)
180    }
181
182    #[cfg(test)]
183    pub(crate) fn set_cpus(&self, cpus: &[usize]) {
184        let _ = self.cpus.set(cpus.into());
185    }
186
187    #[inline]
188    /// Sends a message to the worker.
189    ///
190    /// Returns `Ok` if the message was queued. The message is queued even if
191    /// the worker is currently unavailable. Returns the message as `Err` if
192    /// the worker has stopped.
193    pub fn send(&self, msg: T) -> Result<(), T> {
194        self.reqs.try_send(msg).map_err(TrySendError::into_inner)
195    }
196
197    /// Takes the items queued for the worker that it has not received yet.
198    ///
199    /// Takes at most the items queued when called. If `close` is set, the
200    /// queue is closed first, so every queued item is taken and later sends
201    /// fail.
202    pub(crate) fn take_queued(&self, close: bool) -> Vec<T> {
203        if close {
204            self.queue.close();
205        }
206        (0..self.queue.len())
207            .map_while(|_| self.queue.try_recv().ok())
208            .collect()
209    }
210
211    /// Returns the current worker status.
212    pub fn status(&self) -> WorkerStatus {
213        self.avail.inner.status()
214    }
215
216    /// Waits for a status change not yet reported by this handle and
217    /// returns the current status.
218    ///
219    /// Each handle tracks the changes it has reported, so every clone
220    /// observes every change. A clone starts with the reported changes of
221    /// the handle it was cloned from. Several changes between calls are
222    /// reported once. Returns immediately if the worker has failed.
223    pub async fn wait_for_status(&mut self) -> WorkerStatus {
224        self.avail.wait_for_update().await
225    }
226
227    /// Stops the worker.
228    ///
229    /// The worker stops accepting items and shuts down its service, waiting
230    /// up to `timeout`. A zero timeout uses the default of 3 seconds.
231    pub fn stop(&self, timeout: Millis) -> WorkerStop {
232        let (result, rx) = oneshot::async_channel();
233        let _ = self.stop.try_send(Shutdown { timeout, result });
234        WorkerStop(rx)
235    }
236}
237
238impl<T> Eq for Worker<T> {}
239
240impl<T> PartialEq for Worker<T> {
241    fn eq(&self, other: &Worker<T>) -> bool {
242        self.name == other.name
243    }
244}
245
246impl<T> cmp::Ord for Worker<T> {
247    fn cmp(&self, other: &Self) -> cmp::Ordering {
248        self.name.cmp(&other.name)
249    }
250}
251
252impl<T> cmp::PartialOrd for Worker<T> {
253    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
254        Some(self.cmp(other))
255    }
256}
257
258impl<T> hash::Hash for Worker<T> {
259    fn hash<H: hash::Hasher>(&self, state: &mut H) {
260        self.name.hash(state);
261    }
262}
263
264impl<T> Clone for Worker<T> {
265    fn clone(&self) -> Self {
266        Worker {
267            name: self.name.clone(),
268            reqs: self.reqs.clone(),
269            queue: self.queue.clone(),
270            stop: self.stop.clone(),
271            avail: self.avail.clone(),
272            arbiter: self.arbiter.clone(),
273            metrics: self.metrics.clone(),
274            cpus: self.cpus.clone(),
275        }
276    }
277}
278
279impl Future for WorkerStop {
280    type Output = bool;
281
282    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
283        match ready!(Pin::new(&mut self.0).poll(cx)) {
284            Ok(res) => Poll::Ready(res),
285            Err(_) => Poll::Ready(true),
286        }
287    }
288}
289
290#[derive(Debug, Clone)]
291struct WorkerAvailability {
292    inner: Arc<Inner>,
293    /// The last state reported by this handle.
294    seen: u64,
295}
296
297#[derive(Debug, Clone)]
298struct WorkerAvailabilityTx {
299    inner: Arc<Inner>,
300}
301
302const UNAVAILABLE: u64 = 0;
303const AVAILABLE: u64 = 1;
304const FAILED: u64 = 2;
305const STATUS_BITS: u32 = 2;
306const STATUS_MASK: u64 = (1 << STATUS_BITS) - 1;
307
308#[derive(Debug)]
309struct Inner {
310    /// Change counter in the high bits, status in the low bits.
311    state: AtomicU64,
312    event: Event,
313}
314
315fn status(state: u64) -> WorkerStatus {
316    match state & STATUS_MASK {
317        AVAILABLE => WorkerStatus::Available,
318        FAILED => WorkerStatus::Failed,
319        _ => WorkerStatus::Unavailable,
320    }
321}
322
323impl Inner {
324    fn status(&self) -> WorkerStatus {
325        status(self.state.load(Ordering::Acquire))
326    }
327
328    /// Sets the status, returns `true` if it has changed.
329    ///
330    /// `Failed` is terminal.
331    fn update(&self, st: u64) -> bool {
332        let mut cur = self.state.load(Ordering::Acquire);
333        loop {
334            let old = cur & STATUS_MASK;
335            if old == st || old == FAILED {
336                return false;
337            }
338            let next = (((cur >> STATUS_BITS).wrapping_add(1)) << STATUS_BITS) | st;
339            match self
340                .state
341                .compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire)
342            {
343                Ok(_) => return true,
344                Err(val) => cur = val,
345            }
346        }
347    }
348
349    fn set_failed(&self, notify: bool) {
350        self.update(FAILED);
351        if notify {
352            self.event.notify(usize::MAX);
353        }
354    }
355}
356
357impl WorkerAvailability {
358    fn create() -> (Self, WorkerAvailabilityTx) {
359        let inner = Arc::new(Inner {
360            state: AtomicU64::new(UNAVAILABLE),
361            event: Event::new(),
362        });
363
364        let avail = WorkerAvailability {
365            inner: inner.clone(),
366            seen: UNAVAILABLE,
367        };
368        let avail_tx = WorkerAvailabilityTx { inner };
369        (avail, avail_tx)
370    }
371
372    fn changed(&mut self) -> Option<WorkerStatus> {
373        let cur = self.inner.state.load(Ordering::Acquire);
374        let st = status(cur);
375        if cur != self.seen || st == WorkerStatus::Failed {
376            self.seen = cur;
377            Some(st)
378        } else {
379            None
380        }
381    }
382
383    async fn wait_for_update(&mut self) -> WorkerStatus {
384        loop {
385            if let Some(st) = self.changed() {
386                return st;
387            }
388            let listener = self.inner.event.listen();
389            if let Some(st) = self.changed() {
390                return st;
391            }
392            listener.await;
393        }
394    }
395}
396
397impl WorkerAvailabilityTx {
398    fn set(&self, val: bool) {
399        if self.inner.update(if val { AVAILABLE } else { UNAVAILABLE }) {
400            self.inner.event.notify(usize::MAX);
401        }
402    }
403}
404
405impl Drop for WorkerAvailabilityTx {
406    fn drop(&mut self) {
407        // the arbiter `on_stop` callback wakes the waiters. compio aborts the
408        // process if a task on another thread is woken during unwinding
409        self.inner.set_failed(!std::thread::panicking());
410    }
411}
412
413/// The worker's end of its item queue.
414///
415/// [`Worker`] handles keep the queue open, it is closed when the worker drops
416/// its end, so sends to a stopped worker fail.
417struct Queue<T>(Receiver<T>);
418
419impl<T> Drop for Queue<T> {
420    fn drop(&mut self) {
421        self.0.close();
422    }
423}
424
425/// Service runner.
426///
427/// The runner receives messages through an unbounded channel and processes them.
428struct ServiceRunner<F: ServerConfiguration<Item = Req>, Req> {
429    name: String,
430    factory: F,
431    svc: Pipeline<Req, (), ()>,
432    reqs: Queue<Req>,
433    stop: Pin<Box<dyn Stream<Item = Shutdown>>>,
434    /// Items accepted by the worker itself, dropped before `availability`
435    local: Option<Pin<Box<dyn Stream<Item = Req>>>>,
436    availability: WorkerAvailabilityTx,
437    metrics: Option<Arc<WorkerSlot>>,
438}
439
440impl<F, Req> ServiceRunner<F, Req>
441where
442    Req: Send + 'static,
443    F: ServerConfiguration<Item = Req> + 'static,
444{
445    async fn create(
446        name: &str,
447        factory: F,
448        reqs: Queue<Req>,
449        stop: Receiver<Shutdown>,
450        availability: WorkerAvailabilityTx,
451        metrics: Option<Arc<WorkerSlot>>,
452    ) -> Result<Self, ()> {
453        availability.set(false);
454        let mut stop = Box::pin(stop);
455
456        let svc = match select(factory.create(), stream_recv(&mut stop)).await {
457            Either::Left(Ok(svc)) => Pipeline::new((), svc),
458            Either::Right(Some(Shutdown { result, .. })) => {
459                log::trace!("Shutdown uninitialized worker");
460                let _ = result.send(false);
461                return Err(());
462            }
463            Either::Left(Err(_)) | Either::Right(None) => return Err(()),
464        };
465        availability.set(true);
466        let local = factory.local_items();
467
468        Ok(ServiceRunner {
469            factory,
470            svc,
471            reqs,
472            stop,
473            local,
474            availability,
475            metrics,
476            name: name.to_string(),
477        })
478    }
479
480    async fn run(mut self) {
481        // kept across items, so its listener is not re-registered per item
482        let mut recv = std::pin::pin!(self.reqs.0.recv());
483        loop {
484            let fut = poll_fn(|cx| {
485                match self.svc.poll_ready(cx) {
486                    Poll::Ready(Ok(())) => {
487                        self.availability.set(true);
488                        if let Some(ref m) = self.metrics {
489                            m.ready(true);
490                        }
491                    }
492                    Poll::Ready(Err(err)) => {
493                        self.availability.set(false);
494                        return Poll::Ready(Err(err));
495                    }
496                    Poll::Pending => {
497                        self.availability.set(false);
498                        if let Some(ref m) = self.metrics {
499                            m.ready(false);
500                        }
501                        return Poll::Pending;
502                    }
503                }
504
505                // a cheap check of the server queue first, so local items
506                // cannot starve it
507                match self.reqs.0.try_recv() {
508                    Ok(item) => return Poll::Ready(Ok(Some(item))),
509                    Err(TryRecvError::Closed) => {
510                        log::error!("Server is gone");
511                        return Poll::Ready(Ok(None));
512                    }
513                    Err(TryRecvError::Empty) => {}
514                }
515                if let Some(ref mut local) = self.local {
516                    match local.as_mut().poll_next(cx) {
517                        Poll::Ready(Some(item)) => return Poll::Ready(Ok(Some(item))),
518                        Poll::Ready(None) => self.local = None,
519                        Poll::Pending => {}
520                    }
521                }
522                match recv.as_mut().poll(cx) {
523                    Poll::Ready(Ok(item)) => {
524                        recv.set(self.reqs.0.recv());
525                        Poll::Ready(Ok(Some(item)))
526                    }
527                    Poll::Ready(Err(_)) => {
528                        log::error!("Server is gone");
529                        Poll::Ready(Ok(None))
530                    }
531                    Poll::Pending => Poll::Pending,
532                }
533            });
534
535            match select(fut, stream_recv(&mut self.stop)).await {
536                Either::Left(Ok(Some(item))) => {
537                    // got item
538                    if let Some(ref m) = self.metrics {
539                        m.item();
540                    }
541                    let _ = self.svc.call(item).await;
542                    continue;
543                }
544                Either::Left(Err(())) => {
545                    // re-create service
546                    ntex_rt::spawn_detached(async move {
547                        self.svc.shutdown().await;
548                    });
549                }
550                Either::Right(Some(Shutdown { timeout, result })) => {
551                    log::info!("Shutting down {:?} worker gracefully", self.name);
552                    self.availability.set(false);
553                    // close the worker's listeners before waiting for the service
554                    self.local = None;
555
556                    let timeout = if timeout.is_zero() { STOP_TIMEOUT } else { timeout };
557                    self.stop(timeout, Some(result)).await;
558                    return;
559                }
560                Either::Left(Ok(None)) | Either::Right(None) => {
561                    log::info!("Shutting down {:?} worker", self.name);
562                    self.availability.set(false);
563                    self.local = None;
564                    self.stop(STOP_TIMEOUT, None).await;
565                    return;
566                }
567            }
568
569            // re-create service
570            loop {
571                match select(self.factory.create(), stream_recv(&mut self.stop)).await {
572                    Either::Left(Ok(service)) => {
573                        self.svc = Pipeline::new((), service);
574                        break;
575                    }
576                    Either::Left(Err(_)) => sleep(Millis::ONE_SEC).await,
577                    Either::Right(_) => return,
578                }
579            }
580        }
581    }
582
583    async fn stop(&self, timeout: Millis, result: Option<oneshot::Sender<bool>>) {
584        // a stopped worker is not counted as not ready
585        if let Some(ref m) = self.metrics {
586            m.ready(true);
587        }
588        let res = timeout_checked(timeout, self.svc.shutdown()).await;
589        if let Some(result) = result {
590            let _ = result.send(res.is_ok());
591        }
592
593        log::info!("Worker {:?} has been stopped", self.name);
594    }
595}
596
597#[cfg(test)]
598mod tests {
599    #![allow(clippy::unused_async_trait_impl)]
600    use std::sync::atomic::AtomicUsize;
601    use std::task::{Wake, Waker};
602
603    use ntex_service::{Ctx, Service};
604
605    use super::*;
606
607    #[derive(Default)]
608    struct WakeCount(AtomicUsize);
609
610    impl Wake for WakeCount {
611        fn wake(self: Arc<Self>) {
612            self.0.fetch_add(1, Ordering::SeqCst);
613        }
614    }
615
616    fn poll<F: Future>(fut: Pin<&mut F>, wake: &Arc<WakeCount>) -> Poll<F::Output> {
617        let waker = Waker::from(wake.clone());
618        fut.poll(&mut Context::from_waker(&waker))
619    }
620
621    /// STATEMENT: Every clone of `WorkerAvailability` observes status changes, and `Failed` is
622    /// terminal for all of them.
623    ///
624    /// HOW:
625    /// - Wait on two clones; on `set(true)` expect both woken once and `Available`.
626    /// - Expect a reported change not to repeat, and only the latest of several changes.
627    /// - Drop the sender; expect a pending wait to resolve to `Failed`, and every clone to
628    ///   keep reporting `Failed`.
629    #[test]
630    fn status_cloned_observers() {
631        let (mut a, tx) = WorkerAvailability::create();
632        let mut b = a.clone();
633        let (w1, w2) = (
634            Arc::new(WakeCount::default()),
635            Arc::new(WakeCount::default()),
636        );
637        {
638            let mut first = std::pin::pin!(a.wait_for_update());
639            let mut second = std::pin::pin!(b.wait_for_update());
640            assert!(poll(first.as_mut(), &w1).is_pending());
641            assert!(poll(second.as_mut(), &w2).is_pending());
642
643            tx.set(true);
644            assert_eq!(w1.0.load(Ordering::SeqCst), 1);
645            assert_eq!(w2.0.load(Ordering::SeqCst), 1);
646            assert_eq!(
647                poll(second.as_mut(), &w2),
648                Poll::Ready(WorkerStatus::Available)
649            );
650            assert_eq!(
651                poll(first.as_mut(), &w1),
652                Poll::Ready(WorkerStatus::Available)
653            );
654        }
655
656        // reported changes are not reported again
657        let mut c = a.clone();
658        assert!(poll(std::pin::pin!(a.wait_for_update()), &w1).is_pending());
659        assert!(poll(std::pin::pin!(c.wait_for_update()), &w1).is_pending());
660
661        // a change between calls is reported, with the current status
662        tx.set(false);
663        tx.set(true);
664        tx.set(false);
665        let st = poll(std::pin::pin!(a.wait_for_update()), &w1);
666        assert_eq!(st, Poll::Ready(WorkerStatus::Unavailable));
667        assert!(poll(std::pin::pin!(a.wait_for_update()), &w1).is_pending());
668
669        // failed is terminal and reported immediately to every clone
670        let mut d = a.clone();
671        let mut fut = std::pin::pin!(d.wait_for_update());
672        assert!(poll(fut.as_mut(), &w2).is_pending());
673        drop(tx);
674        assert_eq!(poll(fut.as_mut(), &w2), Poll::Ready(WorkerStatus::Failed));
675        for wrk in [&mut a, &mut b, &mut c] {
676            for _ in 0..2 {
677                let st = poll(std::pin::pin!(wrk.wait_for_update()), &w1);
678                assert_eq!(st, Poll::Ready(WorkerStatus::Failed));
679            }
680        }
681        assert_eq!(a.inner.status(), WorkerStatus::Failed);
682    }
683
684    /// STATEMENT: A failed worker status does not change afterwards.
685    ///
686    /// HOW:
687    /// - Mark the worker failed, then set it available.
688    /// - Expect `Failed`.
689    #[test]
690    fn status_failed_is_terminal() {
691        let (a, tx) = WorkerAvailability::create();
692        a.inner.set_failed(false);
693        tx.set(true);
694        assert_eq!(a.inner.status(), WorkerStatus::Failed);
695    }
696
697    #[derive(Clone)]
698    struct Cfg;
699
700    struct Srv;
701
702    impl Service<(), usize> for Srv {
703        type Res = ();
704        type Error = ();
705
706        async fn call(&self, _: usize, _: Ctx<'_, Self, ()>) -> Result<(), ()> {
707            Ok(())
708        }
709    }
710
711    impl ServerConfiguration for Cfg {
712        type Item = usize;
713        type Service = Srv;
714
715        async fn create(&self) -> std::io::Result<Srv> {
716            Ok(Srv)
717        }
718    }
719
720    /// STATEMENT: A worker reports its CPUs only when its placement is applied.
721    ///
722    /// HOW:
723    /// - Start a worker with an invalid CPU placement; expect no CPUs.
724    /// - Start one with a planned placement; expect CPUs on Windows and Linux, none elsewhere.
725    #[ntex::test]
726    async fn worker_cpus() {
727        let cpu = crate::affinity::plan(crate::Affinity::Cpu).pop();
728        for (placement, placed) in [
729            (Placement::cpu(usize::MAX >> 1), false),
730            (
731                cpu.unwrap_or_else(|| Placement::cpu(0)),
732                cfg!(any(windows, target_os = "linux", target_os = "android")),
733            ),
734        ] {
735            let mut wrk = Worker::start_with("test".into(), Cfg, Some(placement), None);
736            assert_eq!(wrk.wait_for_status().await, WorkerStatus::Available);
737            assert_eq!(!wrk.cpus().is_empty(), placed);
738            wrk.stop(Millis::ZERO).await;
739        }
740    }
741}