1use std::collections::VecDeque;
2use std::pin::Pin;
3use std::sync::Arc;
4use std::sync::atomic::AtomicUsize;
5use std::task::{Context, Poll, Waker};
6
7use crate::backend::*;
8use crate::task::Task;
9use crate::worker::context::WorkerContext;
10use dashmap::DashMap;
11use futures_core::ready;
12use futures_sink::Sink;
13use futures_util::lock::Mutex;
14use futures_util::{FutureExt, SinkExt, StreamExt};
15
16#[derive(Debug)]
17struct Inner<B> {
18 backend: Mutex<B>,
19 wakers: DashMap<usize, Waker>,
20 next_key: std::sync::atomic::AtomicUsize,
21}
22
23#[derive(Debug)]
25pub struct Shared<B: WireFormatBackend> {
26 inner: Arc<Inner<B>>,
27 waker_key: usize,
28 codec: B::Codec,
29 sink: VecDeque<Task<B::Compact>>,
30}
31
32impl<B> Clone for Shared<B>
33where
34 B::Codec: Clone,
35 B: WireFormatBackend,
36{
37 fn clone(&self) -> Self {
38 let inner = self.inner.clone();
39 let waker_key = inner
40 .next_key
41 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
42 Self {
43 inner,
44 waker_key,
45 codec: self.codec.clone(),
46 sink: Default::default(),
47 }
48 }
49}
50
51impl<B: WireFormatBackend> Shared<B>
52where
53 B::Codec: Clone,
54{
55 pub fn new(backend: B) -> Self {
57 let codec = backend.codec().clone();
58 Self {
59 inner: Inner {
60 backend: Mutex::new(backend),
61 next_key: AtomicUsize::new(0),
62 wakers: Default::default(),
63 }
64 .into(),
65 waker_key: 0,
66 codec,
67 sink: VecDeque::new(),
68 }
69 }
70}
71
72impl<B: WireFormatBackend> Shared<B> {
73 fn poll_drain_buffer(
74 backend: &mut B,
75 sink: &mut VecDeque<Task<B::Compact>>,
76 cx: &mut Context<'_>,
77 ) -> Poll<Result<(), B::Error>>
78 where
79 B: Sink<Task<B::Compact>> + Unpin,
80 {
81 while !sink.is_empty() {
82 ready!(backend.poll_ready_unpin(cx))?;
83 let item = sink.pop_front().unwrap();
84 backend.start_send_unpin(item)?;
85 }
86 Poll::Ready(Ok(()))
87 }
88
89 fn register_waker(inner: &Inner<B>, key: usize, cx: &Context<'_>) {
90 let res = &inner.wakers;
91 res.insert(key, cx.waker().clone());
92 }
93
94 fn wake_others(inner: &Inner<B>, except: usize) {
95 let wakers = &inner.wakers;
96 wakers.retain(|key, waker| {
97 if *key != except {
98 waker.wake_by_ref();
99 }
100 true
101 });
102 }
103}
104
105impl<B> Backend for Shared<B>
106where
107 B: Backend + WireFormatBackend,
108{
109 type Task = B::Task;
110 type Error = B::Error;
111
112 fn poll_ready(
113 &mut self,
114 cx: &mut Context<'_>,
115 worker: &WorkerContext,
116 ) -> Poll<Result<(), Self::Error>> {
117 if let Some(mut guard) = self.inner.backend.try_lock() {
118 let result = guard.poll_ready(cx, worker);
119 drop(guard);
120
121 if result.is_ready() {
122 Self::wake_others(&self.inner, self.waker_key);
123 }
124 result
125 } else {
126 Self::register_waker(&self.inner, self.waker_key, cx);
127 Poll::Pending
128 }
129 }
130
131 fn poll_next(
132 &mut self,
133 cx: &mut Context<'_>,
134 worker: &WorkerContext,
135 ) -> Poll<Option<Result<Self::Task, Self::Error>>> {
136 let inner = &self.inner;
137
138 if let Some(mut guard) = inner.backend.try_lock() {
139 let result = guard.poll_next(cx, worker);
140 drop(guard);
141 Self::wake_others(inner, self.waker_key);
142 result
143 } else {
144 Self::register_waker(inner, self.waker_key, cx);
145 Poll::Pending
146 }
147 }
148
149 fn poll_close(
150 &mut self,
151 cx: &mut Context<'_>,
152 worker: &WorkerContext,
153 ) -> Poll<Result<(), Self::Error>> {
154 let inner = self.inner.as_ref();
155
156 if let Some(mut guard) = inner.backend.try_lock() {
157 let result = guard.poll_close(cx, worker);
158 drop(guard);
159 if result.is_ready() {
160 inner.wakers.remove(&self.waker_key);
161 Self::wake_others(inner, self.waker_key);
162 } else {
163 Self::wake_others(inner, self.waker_key);
164 }
165 result
166 } else {
167 Self::register_waker(inner, self.waker_key, cx);
168 Poll::Pending
169 }
170 }
171}
172
173impl<B: WireFormatBackend> WireFormatBackend for Shared<B> {
174 type Codec = B::Codec;
175
176 type Compact = B::Compact;
177
178 fn codec(&self) -> &Self::Codec {
179 &self.codec
180 }
181}
182
183impl<B, Err> Sink<Task<B::Compact>> for Shared<B>
184where
185 B: Backend<Error = Err> + Sink<Task<B::Compact>, Error = Err> + Unpin,
186 B: WireFormatBackend,
187 B::Codec: Unpin,
188 B::Compact: Unpin,
189{
190 type Error = Err;
191 fn start_send(self: Pin<&mut Self>, item: Task<B::Compact>) -> Result<(), Self::Error> {
192 let this = self.get_mut();
193
194 if let Some(mut guard) = this.inner.backend.try_lock() {
195 let result = guard.start_send_unpin(item);
196 drop(guard);
197 if result.is_ok() {
198 Self::wake_others(&this.inner, this.waker_key);
199 }
200 result
201 } else {
202 this.sink.push_back(item);
203 Ok(())
204 }
205 }
206 fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
207 let this = self.get_mut();
208 let mut guard = ready!(this.inner.backend.lock().poll_unpin(cx));
209 ready!(Self::poll_drain_buffer(&mut guard, &mut this.sink, cx))?;
210
211 guard.poll_ready_unpin(cx)
212 }
213 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
214 let this = self.get_mut();
215 let mut guard = ready!(this.inner.backend.lock().poll_unpin(cx));
216 ready!(Self::poll_drain_buffer(&mut guard, &mut this.sink, cx))?;
217 guard.poll_flush_unpin(cx)
218 }
219 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
220 let this = self.get_mut();
221 let mut guard = ready!(this.inner.backend.lock().poll_unpin(cx));
222 ready!(Self::poll_drain_buffer(&mut guard, &mut this.sink, cx))?;
223 guard.poll_close_unpin(cx)
224 }
225}
226
227impl<B> BackendConfig for Shared<B>
230where
231 B: BackendConfig + WireFormatBackend,
232{
233 type Id = B::Id;
234 type Args = B::Args;
235 type Kind = B::Kind;
236 type Config = B::Config;
237 type Layer = B::Layer;
238 fn config(&self) -> &Self::Config {
239 unreachable!("Dont call config on shared")
240 }
241 fn middleware(&mut self, worker: &mut WorkerContext) -> Self::Layer {
242 self.inner.backend.try_lock().unwrap().middleware(worker)
243 }
244}
245
246impl<B> FetchById for Shared<B>
247where
248 B: FetchById,
249 B::Task: Send,
250 B: Backend + WireFormatBackend + Send,
251 B::Codec: Send,
252 B::Compact: Send,
253{
254 async fn fetch_by_id(
255 &mut self,
256 task_id: &crate::task::task_id::TaskId,
257 ) -> Result<Option<B::Task>, Self::Error> {
258 self.inner.backend.lock().await.fetch_by_id(task_id).await
259 }
260}
261impl<B> Update for Shared<B>
262where
263 B: Update + Send,
264 B::Task: Send,
265 B: Backend + WireFormatBackend + Send,
266 B::Codec: Send,
267 B::Compact: Send,
268{
269 async fn update(&mut self, task: Self::Task) -> Result<(), Self::Error> {
270 self.inner.backend.lock().await.update(task).await
271 }
272}
273impl<B> Reschedule for Shared<B>
274where
275 B: Reschedule,
276 B::Task: Send,
277 B: Backend + WireFormatBackend + Send,
278 B::Codec: Send,
279 B::Compact: Send,
280{
281 async fn reschedule(
282 &mut self,
283 task: Self::Task,
284 wait: std::time::Duration,
285 ) -> Result<(), Self::Error> {
286 self.inner.backend.lock().await.reschedule(task, wait).await
287 }
288}
289impl<B> Vacuum for Shared<B>
290where
291 B: Vacuum,
292 B: Backend + WireFormatBackend + Send,
293 B::Codec: Send,
294 B::Compact: Send,
295{
296 async fn vacuum(&mut self) -> Result<usize, Self::Error> {
297 self.inner.backend.lock().await.vacuum().await
298 }
299 async fn vacuum_before(&mut self, duration: Duration) -> Result<usize, Self::Error> {
300 self.inner
301 .backend
302 .lock()
303 .await
304 .vacuum_before(duration)
305 .await
306 }
307}
308impl<B> ResumeById for Shared<B>
309where
310 B: ResumeById,
311 B: Backend + WireFormatBackend + Send,
312 B::Codec: Send,
313 B::Compact: Send,
314{
315 async fn resume_by_id(&mut self, id: TaskId) -> Result<bool, Self::Error> {
316 self.inner.backend.lock().await.resume_by_id(id).await
317 }
318}
319impl<B> ResumeAbandoned for Shared<B>
320where
321 B: ResumeAbandoned,
322 B: Backend + WireFormatBackend + Send,
323 B::Codec: Send,
324 B::Compact: Send,
325{
326 async fn resume_abandoned(&mut self) -> Result<usize, Self::Error> {
327 self.inner.backend.lock().await.resume_abandoned().await
328 }
329}
330impl<B> RegisterWorker for Shared<B>
331where
332 B: RegisterWorker,
333 B: Backend + WireFormatBackend + Send,
334 B::Codec: Send,
335 B::Compact: Send,
336{
337 async fn register_worker(&mut self, worker_id: String) -> Result<(), Self::Error> {
338 self.inner
339 .backend
340 .lock()
341 .await
342 .register_worker(worker_id)
343 .await
344 }
345}
346impl<Output, B> WaitForCompletion<Output> for Shared<B>
347where
348 B: WaitForCompletion<Output> + Sync + 'static,
349 Output: Send + 'static,
350 B: Backend + WireFormatBackend + Send,
351 B::Codec: Sync,
352 B::Codec: Send,
353 B::Compact: Send + Sync,
354{
355 type ResultStream =
356 futures_core::stream::BoxStream<'static, Result<TaskResult<Output>, Self::Error>>;
357 fn wait_for(&mut self, task_ids: impl IntoIterator<Item = TaskId>) -> Self::ResultStream {
358 let inner = self.inner.clone();
359 let task_ids: Vec<_> = task_ids.into_iter().collect();
360 futures_util::stream::once(async move {
361 let mut backend = inner.backend.lock().await;
362 backend.wait_for(task_ids)
363 })
364 .flatten()
365 .boxed()
366 }
367 async fn check_status(
368 &mut self,
369 task_ids: impl IntoIterator<Item = TaskId> + Send,
370 ) -> Result<Vec<TaskResult<Output>>, Self::Error> {
371 self.inner.backend.lock().await.check_status(task_ids).await
372 }
373}
374
375impl<B: WireFormatBackend> Drop for Shared<B> {
376 fn drop(&mut self) {
377 if let Some((_key, waker)) = self.inner.wakers.remove(&self.waker_key) {
378 waker.wake();
379 }
380 }
381}