|
| 1 | +use core::cell::UnsafeCell; |
| 2 | +use core::future::Future; |
| 3 | +use core::mem; |
| 4 | +use core::ptr::{self, NonNull}; |
| 5 | + |
| 6 | +#[cfg(all(not(feature = "std"), feature = "alloc"))] |
| 7 | +use alloc::collections::vec_deque::VecDeque; |
| 8 | +#[cfg(feature = "std")] |
| 9 | +use std::collections::vec_deque::VecDeque; |
| 10 | + |
| 11 | +pub use async_task::Task; |
| 12 | +use async_task::{Runnable, ScheduleInfo, WithInfo}; |
| 13 | +use nginx_sys::{ |
| 14 | + ngx_del_timer, ngx_delete_posted_event, ngx_event_t, ngx_post_event, ngx_posted_next_events, |
| 15 | +}; |
| 16 | + |
| 17 | +use crate::log::ngx_cycle_log; |
| 18 | +use crate::{ngx_container_of, ngx_log_debug}; |
| 19 | + |
| 20 | +static SCHEDULER: Scheduler = Scheduler::new(); |
| 21 | + |
| 22 | +struct Scheduler(UnsafeCell<SchedulerInner>); |
| 23 | + |
| 24 | +// SAFETY: Scheduler must only be used from the main thread of a worker process. |
| 25 | +unsafe impl Send for Scheduler {} |
| 26 | +unsafe impl Sync for Scheduler {} |
| 27 | + |
| 28 | +impl Scheduler { |
| 29 | + const fn new() -> Self { |
| 30 | + Self(UnsafeCell::new(SchedulerInner::new())) |
| 31 | + } |
| 32 | + |
| 33 | + pub fn schedule(&self, runnable: Runnable) { |
| 34 | + // SAFETY: the cell is not empty, and we have exclusive access due to being a |
| 35 | + // single-threaded application. |
| 36 | + let inner = unsafe { &mut *UnsafeCell::raw_get(&self.0) }; |
| 37 | + inner.send(runnable) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +#[repr(C)] |
| 42 | +struct SchedulerInner { |
| 43 | + _ident: [usize; 4], // `ngx_event_ident` compatibility |
| 44 | + event: ngx_event_t, |
| 45 | + queue: VecDeque<Runnable>, |
| 46 | +} |
| 47 | + |
| 48 | +impl SchedulerInner { |
| 49 | + const fn new() -> Self { |
| 50 | + let mut event: ngx_event_t = unsafe { mem::zeroed() }; |
| 51 | + event.handler = Some(Self::scheduler_event_handler); |
| 52 | + |
| 53 | + Self { |
| 54 | + _ident: [ |
| 55 | + 0, 0, 0, 0x4153594e, // ASYN |
| 56 | + ], |
| 57 | + event, |
| 58 | + queue: VecDeque::new(), |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + pub fn send(&mut self, runnable: Runnable) { |
| 63 | + // Cached `ngx_cycle.log` can be invalidated when reloading configuration in a single |
| 64 | + // process mode. Update `log` every time to avoid using stale log pointer. |
| 65 | + self.event.log = ngx_cycle_log().as_ptr(); |
| 66 | + |
| 67 | + // While this event is not used as a timer at the moment, we still want to ensure that it is |
| 68 | + // compatible with `ngx_event_ident`. |
| 69 | + if self.event.data.is_null() { |
| 70 | + self.event.data = ptr::from_mut(self).cast(); |
| 71 | + } |
| 72 | + |
| 73 | + // FIXME: VecDeque::push could panic on an allocation failure, switch to a datastructure |
| 74 | + // which will not and propagate the failure. |
| 75 | + self.queue.push_back(runnable); |
| 76 | + unsafe { ngx_post_event(&mut self.event, ptr::addr_of_mut!(ngx_posted_next_events)) } |
| 77 | + } |
| 78 | + |
| 79 | + /// This event handler is called by ngx_event_process_posted at the end of |
| 80 | + /// ngx_process_events_and_timers. |
| 81 | + extern "C" fn scheduler_event_handler(ev: *mut ngx_event_t) { |
| 82 | + let mut runnables = { |
| 83 | + // SAFETY: |
| 84 | + // This handler always receives a non-null pointer to an event embedded into a |
| 85 | + // SchedulerInner instance. |
| 86 | + // We modify the contents of `UnsafeCell`, but we ensured that the access is unique due |
| 87 | + // to being single-threaded and dropping the reference before we start processing queued |
| 88 | + // runnables. |
| 89 | + let this = |
| 90 | + unsafe { ngx_container_of!(NonNull::new_unchecked(ev), Self, event).as_mut() }; |
| 91 | + |
| 92 | + ngx_log_debug!( |
| 93 | + this.event.log, |
| 94 | + "async: processing {} deferred wakeups", |
| 95 | + this.queue.len() |
| 96 | + ); |
| 97 | + |
| 98 | + // Move runnables to a new queue to avoid borrowing from the SchedulerInner and limit |
| 99 | + // processing to already queued wakeups. This ensures that we correctly handle tasks |
| 100 | + // that keep scheduling themselves (e.g. using yield_now() in a loop). |
| 101 | + // We can't use drain() as it borrows from self and breaks aliasing rules. |
| 102 | + mem::take(&mut this.queue) |
| 103 | + }; |
| 104 | + |
| 105 | + for runnable in runnables.drain(..) { |
| 106 | + runnable.run(); |
| 107 | + } |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +impl Drop for SchedulerInner { |
| 112 | + fn drop(&mut self) { |
| 113 | + if self.event.posted() != 0 { |
| 114 | + unsafe { ngx_delete_posted_event(&mut self.event) }; |
| 115 | + } |
| 116 | + |
| 117 | + if self.event.timer_set() != 0 { |
| 118 | + unsafe { ngx_del_timer(&mut self.event) }; |
| 119 | + } |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +fn schedule(runnable: Runnable, info: ScheduleInfo) { |
| 124 | + if info.woken_while_running { |
| 125 | + SCHEDULER.schedule(runnable); |
| 126 | + ngx_log_debug!( |
| 127 | + ngx_cycle_log().as_ptr(), |
| 128 | + "async: task scheduled while running" |
| 129 | + ); |
| 130 | + } else { |
| 131 | + runnable.run(); |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +/// Creates a new task running on the NGINX event loop. |
| 136 | +pub fn spawn<F, T>(future: F) -> Task<T> |
| 137 | +where |
| 138 | + F: Future<Output = T> + 'static, |
| 139 | + T: 'static, |
| 140 | +{ |
| 141 | + ngx_log_debug!(ngx_cycle_log().as_ptr(), "async: spawning new task"); |
| 142 | + let scheduler = WithInfo(schedule); |
| 143 | + // Safety: single threaded embedding takes care of send/sync requirements for future and |
| 144 | + // scheduler. Future and scheduler are both 'static. |
| 145 | + let (runnable, task) = unsafe { async_task::spawn_unchecked(future, scheduler) }; |
| 146 | + runnable.schedule(); |
| 147 | + task |
| 148 | +} |
0 commit comments