grow-graylog 0.2.0

Rust SDK for Graylog Open by Grow Codes
Documentation
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! Background batching of log records (SPEC §4 `BatchProcessor`).

use std::collections::VecDeque;
use std::fmt;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::{Duration, Instant};

use serde::Serialize;
use tokio::runtime::{Handle, RuntimeFlavor};
use tokio::sync::{watch, Notify};
use tokio::task::JoinHandle;

use super::{ExportOptions, LogExporter, LogRecord};
use crate::core::{Error, Result};

/// What happens when the queue is full.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DropPolicy {
    /// Drop the record being added (default).
    #[default]
    DropNewest,
    /// Drop the oldest queued record to make room.
    DropOldest,
    /// Wait for room, up to `export_timeout`.
    ///
    /// The async [`BatchProcessor::add_async`] always waits. The sync [`BatchProcessor::add`]
    /// blocks the calling thread (bounded by `export_timeout`); on a current-thread runtime it
    /// cannot block without stalling the worker, so it drops the record (`queue_full`)
    /// instead. In async code prefer `add_async` / `BatchingLogClient::send_async`.
    Block,
}

/// Why records were dropped (passed to `on_drop`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DropReason {
    /// The queue was full.
    QueueFull,
    /// The processor was shut down.
    Shutdown,
    /// The exporter failed and retries were exhausted.
    ExportFailed,
}

impl DropReason {
    /// Wire value: `queue_full`, `shutdown` or `export_failed`.
    pub fn as_str(self) -> &'static str {
        match self {
            DropReason::QueueFull => "queue_full",
            DropReason::Shutdown => "shutdown",
            DropReason::ExportFailed => "export_failed",
        }
    }
}

impl fmt::Display for DropReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Callback for dropped records.
pub type DropCallback = Arc<dyn Fn(&[LogRecord], DropReason) + Send + Sync>;
/// Callback for export errors.
pub type ErrorCallback = Arc<dyn Fn(&Error, &[LogRecord]) + Send + Sync>;

/// Batch processor options (SPEC §4 `BatchOptions`).
#[derive(Clone)]
pub struct BatchOptions {
    /// Maximum queued records (default 2048).
    pub max_queue_size: usize,
    /// Maximum records per export (default 512).
    pub max_batch_size: usize,
    /// Maximum UTF-8 JSON bytes per export (default 1 MiB). A single larger record is sent alone.
    pub max_batch_bytes: usize,
    /// Export at least this often (default 1 s).
    pub flush_interval: Duration,
    /// Deadline per export attempt (default 30 s); also the `Block` wait limit.
    pub export_timeout: Duration,
    /// Queue-full behaviour (default [`DropPolicy::DropNewest`]).
    pub drop_policy: DropPolicy,
    /// Ask the exporter to gzip payloads (default `true`).
    pub gzip: bool,
    /// Extra attempts for a batch whose export failed with a retryable error (default 2).
    pub max_export_retries: u32,
    /// Wait before retry *n* (1-based) is `retry_backoff * 2^(n-1)` (default 200 ms).
    pub retry_backoff: Duration,
    /// Called with records that were dropped.
    pub on_drop: Option<DropCallback>,
    /// Called when an export fails or partially fails.
    pub on_error: Option<ErrorCallback>,
}

impl Default for BatchOptions {
    fn default() -> Self {
        BatchOptions {
            max_queue_size: 2048,
            max_batch_size: 512,
            max_batch_bytes: 1_048_576,
            flush_interval: Duration::from_millis(1000),
            export_timeout: Duration::from_millis(30_000),
            drop_policy: DropPolicy::DropNewest,
            gzip: true,
            max_export_retries: 2,
            retry_backoff: Duration::from_millis(200),
            on_drop: None,
            on_error: None,
        }
    }
}

impl fmt::Debug for BatchOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BatchOptions")
            .field("max_queue_size", &self.max_queue_size)
            .field("max_batch_size", &self.max_batch_size)
            .field("max_batch_bytes", &self.max_batch_bytes)
            .field("flush_interval", &self.flush_interval)
            .field("export_timeout", &self.export_timeout)
            .field("drop_policy", &self.drop_policy)
            .field("gzip", &self.gzip)
            .field("max_export_retries", &self.max_export_retries)
            .field("retry_backoff", &self.retry_backoff)
            .field("on_drop", &self.on_drop.is_some())
            .field("on_error", &self.on_error.is_some())
            .finish()
    }
}

impl BatchOptions {
    /// Sets `max_queue_size`.
    pub fn max_queue_size(mut self, n: usize) -> Self {
        self.max_queue_size = n;
        self
    }
    /// Sets `max_batch_size`.
    pub fn max_batch_size(mut self, n: usize) -> Self {
        self.max_batch_size = n;
        self
    }
    /// Sets `max_batch_bytes`.
    pub fn max_batch_bytes(mut self, n: usize) -> Self {
        self.max_batch_bytes = n;
        self
    }
    /// Sets `flush_interval`.
    pub fn flush_interval(mut self, d: Duration) -> Self {
        self.flush_interval = d;
        self
    }
    /// Sets `export_timeout`.
    pub fn export_timeout(mut self, d: Duration) -> Self {
        self.export_timeout = d;
        self
    }
    /// Sets `drop_policy`.
    pub fn drop_policy(mut self, p: DropPolicy) -> Self {
        self.drop_policy = p;
        self
    }
    /// Sets `gzip`.
    pub fn gzip(mut self, on: bool) -> Self {
        self.gzip = on;
        self
    }
    /// Sets `max_export_retries`.
    pub fn max_export_retries(mut self, n: u32) -> Self {
        self.max_export_retries = n;
        self
    }
    /// Sets `retry_backoff`.
    pub fn retry_backoff(mut self, d: Duration) -> Self {
        self.retry_backoff = d;
        self
    }
    /// Sets the drop callback.
    pub fn on_drop(mut self, f: impl Fn(&[LogRecord], DropReason) + Send + Sync + 'static) -> Self {
        self.on_drop = Some(Arc::new(f));
        self
    }
    /// Sets the error callback.
    pub fn on_error(mut self, f: impl Fn(&Error, &[LogRecord]) + Send + Sync + 'static) -> Self {
        self.on_error = Some(Arc::new(f));
        self
    }

    /// Checks that every limit and duration is positive.
    pub fn validate(&self) -> Result<()> {
        let checks = [
            (self.max_queue_size == 0, "maxQueueSize"),
            (self.max_batch_size == 0, "maxBatchSize"),
            (self.max_batch_bytes == 0, "maxBatchBytes"),
            (self.flush_interval.is_zero(), "flushInterval"),
            (self.export_timeout.is_zero(), "exportTimeout"),
        ];
        match checks.iter().find(|(bad, _)| *bad) {
            Some((_, name)) => Err(Error::config(format!(
                "batch option {name} must be positive"
            ))),
            None => Ok(()),
        }
    }
}

/// Processor counters (SPEC §4 `BatchStats`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BatchStats {
    /// Records waiting in the queue or being exported now.
    pub queued: u64,
    /// Records the exporter accepted.
    pub sent: u64,
    /// Records dropped before export (queue full, shutdown).
    pub dropped: u64,
    /// Records whose export failed or was rejected.
    pub failed: u64,
    /// Export retry attempts.
    pub retries: u64,
}

struct Item {
    record: LogRecord,
    bytes: usize,
}

#[derive(Default)]
struct State {
    queue: VecDeque<Item>,
    queued_bytes: usize,
    in_flight: Option<Arc<Vec<LogRecord>>>,
    accepted_total: u64,
    flush_target: u64,
    closed: bool,
}

struct Shared {
    opts: BatchOptions,
    exporter: Arc<dyn LogExporter>,
    state: Mutex<State>,
    space: Condvar,
    space_async: Notify,
    wake: Notify,
    processed: watch::Sender<u64>,
    sent: AtomicU64,
    dropped: AtomicU64,
    failed: AtomicU64,
    retries: AtomicU64,
}

/// Generic background batcher: queues records and exports them from a tokio task.
pub struct BatchProcessor {
    shared: Arc<Shared>,
    worker: Mutex<Option<JoinHandle<()>>>,
    shutdown_lock: tokio::sync::Mutex<bool>,
}

impl fmt::Debug for BatchProcessor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BatchProcessor")
            .field("options", &self.shared.opts)
            .field("stats", &self.stats())
            .finish()
    }
}

enum Admit<'a> {
    Room(MutexGuard<'a, State>),
    Full,
    Closed,
}

impl BatchProcessor {
    /// Starts a processor; must be called inside a tokio runtime.
    pub fn new(exporter: Arc<dyn LogExporter>, opts: BatchOptions) -> Result<Self> {
        opts.validate()?;
        let handle = Handle::try_current().map_err(|_| {
            Error::config("BatchProcessor::new must be called inside a tokio runtime")
        })?;
        let shared = Arc::new(Shared {
            opts,
            exporter,
            state: Mutex::new(State::default()),
            space: Condvar::new(),
            space_async: Notify::new(),
            wake: Notify::new(),
            processed: watch::Sender::new(0),
            sent: AtomicU64::new(0),
            dropped: AtomicU64::new(0),
            failed: AtomicU64::new(0),
            retries: AtomicU64::new(0),
        });
        let worker = handle.spawn(run_worker(Arc::clone(&shared)));
        Ok(BatchProcessor {
            shared,
            worker: Mutex::new(Some(worker)),
            shutdown_lock: tokio::sync::Mutex::new(false),
        })
    }

    /// Options in use.
    pub fn options(&self) -> &BatchOptions {
        &self.shared.opts
    }

    /// Enqueues a record; returns `false` when it was dropped. Never blocks unless the policy
    /// is [`DropPolicy::Block`].
    pub fn add(&self, record: LogRecord) -> bool {
        let bytes = record.json_size();
        let shared = &self.shared;
        let admit = match shared.lock() {
            st if st.closed => Admit::Closed,
            st if st.queue.len() < shared.opts.max_queue_size => Admit::Room(st),
            st => match shared.opts.drop_policy {
                DropPolicy::DropNewest => Admit::Full,
                DropPolicy::DropOldest => Admit::Room(st),
                DropPolicy::Block => shared.block_for_space(st),
            },
        };
        shared.admit(admit, record, bytes)
    }

    /// Like [`add`](Self::add), but waits asynchronously for room under [`DropPolicy::Block`].
    pub async fn add_async(&self, record: LogRecord) -> bool {
        let shared = &self.shared;
        if shared.opts.drop_policy != DropPolicy::Block {
            return self.add(record);
        }
        let bytes = record.json_size();
        let deadline = tokio::time::Instant::now() + shared.opts.export_timeout;
        loop {
            let notified = shared.space_async.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();
            {
                let st = shared.lock();
                if st.closed {
                    drop(st);
                    return shared.admit(Admit::Closed, record, bytes);
                }
                if st.queue.len() < shared.opts.max_queue_size {
                    return shared.admit(Admit::Room(st), record, bytes);
                }
            }
            if tokio::time::timeout_at(deadline, notified).await.is_err() {
                return shared.admit(Admit::Full, record, bytes);
            }
        }
    }

    /// Exports everything queued at the time of the call. `None` waits without a limit (every
    /// export attempt is still bounded by `export_timeout`); on expiry returns `TIMEOUT`.
    pub async fn flush(&self, timeout: Option<Duration>) -> Result<()> {
        let shared = &self.shared;
        let target = {
            let mut st = shared.lock();
            st.flush_target = st.flush_target.max(st.accepted_total);
            st.accepted_total
        };
        shared.wake.notify_one();
        let mut rx = shared.processed.subscribe();
        let wait = async move {
            // The sender lives in `shared`, which we hold, so this cannot fail.
            let _ = rx.wait_for(|p| *p >= target).await;
        };
        match timeout {
            None => {
                wait.await;
                Ok(())
            }
            Some(t) => tokio::time::timeout(t, wait)
                .await
                .map_err(|_| Error::timeout(format!("log flush did not finish within {t:?}"))),
        }
    }

    /// Drains the queue, stops the worker and shuts the exporter down. Idempotent; later
    /// [`add`](Self::add) calls drop records with reason `shutdown`. When `timeout` expires the
    /// remaining records are dropped and `TIMEOUT` is returned.
    pub async fn shutdown(&self, timeout: Option<Duration>) -> Result<()> {
        let mut done = self.shutdown_lock.lock().await;
        if *done {
            return Ok(());
        }
        *done = true;
        let shared = &self.shared;
        shared.lock().closed = true;
        shared.wake.notify_one();
        shared.notify_space();
        let worker = self.worker.lock().unwrap_or_else(|e| e.into_inner()).take();
        let mut result = Ok(());
        if let Some(mut worker) = worker {
            let finished = match timeout {
                None => {
                    let _ = (&mut worker).await;
                    true
                }
                Some(t) => tokio::time::timeout(t, &mut worker).await.is_ok(),
            };
            if !finished {
                worker.abort();
                let _ = worker.await;
                shared.drop_remaining();
                result = Err(Error::timeout(format!(
                    "log shutdown did not drain within {:?}",
                    timeout.unwrap_or_default()
                )));
            }
        }
        let exporter = shared.exporter.shutdown().await;
        result.and(exporter)
    }

    /// Current counters.
    pub fn stats(&self) -> BatchStats {
        let s = &self.shared;
        BatchStats {
            queued: {
                let st = s.lock();
                (st.queue.len() + st.in_flight.as_ref().map_or(0, |b| b.len())) as u64
            },
            sent: s.sent.load(Ordering::Relaxed),
            dropped: s.dropped.load(Ordering::Relaxed),
            failed: s.failed.load(Ordering::Relaxed),
            retries: s.retries.load(Ordering::Relaxed),
        }
    }
}

impl Drop for BatchProcessor {
    /// Best effort: marks the processor closed so the worker exports what is queued and exits.
    fn drop(&mut self) {
        self.shared.lock().closed = true;
        self.shared.wake.notify_one();
        self.shared.notify_space();
    }
}

impl Shared {
    /// Locks the state, recovering from poisoning (callbacks never run under the lock).
    fn lock(&self) -> MutexGuard<'_, State> {
        self.state.lock().unwrap_or_else(|e| e.into_inner())
    }

    fn notify_space(&self) {
        self.space.notify_all();
        self.space_async.notify_waiters();
    }

    fn block_for_space<'a>(&'a self, st: MutexGuard<'a, State>) -> Admit<'a> {
        let wait = |mut st: MutexGuard<'a, State>| {
            let deadline = Instant::now() + self.opts.export_timeout;
            loop {
                if st.closed {
                    return Admit::Closed;
                }
                if st.queue.len() < self.opts.max_queue_size {
                    return Admit::Room(st);
                }
                let now = Instant::now();
                if now >= deadline {
                    return Admit::Full;
                }
                st = self
                    .space
                    .wait_timeout(st, deadline - now)
                    .unwrap_or_else(|e| e.into_inner())
                    .0;
            }
        };
        match Handle::try_current().map(|h| h.runtime_flavor()) {
            // Blocking here would stall the only thread, including the worker.
            Ok(RuntimeFlavor::CurrentThread) => Admit::Full,
            // Other runtime threads keep running the worker; the wait is bounded.
            _ => wait(st),
        }
    }

    fn admit(&self, admit: Admit<'_>, record: LogRecord, bytes: usize) -> bool {
        let mut st = match admit {
            Admit::Room(st) => st,
            Admit::Full => {
                self.dropped_records(&[record], DropReason::QueueFull);
                return false;
            }
            Admit::Closed => {
                self.dropped_records(&[record], DropReason::Shutdown);
                return false;
            }
        };
        let evicted = if st.queue.len() >= self.opts.max_queue_size {
            st.queue
                .pop_front()
                .inspect(|old| st.queued_bytes -= old.bytes)
        } else {
            None
        };
        st.queue.push_back(Item { record, bytes });
        st.queued_bytes += bytes;
        st.accepted_total += 1;
        let wake = st.queue.len() >= self.opts.max_batch_size
            || st.queued_bytes >= self.opts.max_batch_bytes;
        drop(st);
        if let Some(old) = evicted {
            self.processed.send_modify(|p| *p += 1);
            self.dropped_records(&[old.record], DropReason::QueueFull);
        }
        if wake {
            self.wake.notify_one();
        }
        true
    }

    fn dropped_records(&self, records: &[LogRecord], reason: DropReason) {
        self.dropped
            .fetch_add(records.len() as u64, Ordering::Relaxed);
        if let Some(cb) = &self.opts.on_drop {
            let _ = catch_unwind(AssertUnwindSafe(|| cb(records, reason)));
        }
    }

    fn report_error(&self, error: &Error, records: &[LogRecord]) {
        if let Some(cb) = &self.opts.on_error {
            let _ = catch_unwind(AssertUnwindSafe(|| cb(error, records)));
        }
    }

    /// Drops the in-flight batch of an aborted worker and everything queued.
    fn drop_remaining(&self) {
        let records: Vec<LogRecord> = {
            let mut st = self.lock();
            st.queued_bytes = 0;
            let in_flight = st.in_flight.take();
            let mut records: Vec<LogRecord> =
                in_flight.map(|b| b.as_ref().clone()).unwrap_or_default();
            records.extend(st.queue.drain(..).map(|i| i.record));
            records
        };
        if records.is_empty() {
            return;
        }
        self.processed.send_modify(|p| *p += records.len() as u64);
        self.dropped_records(&records, DropReason::Shutdown);
    }

    /// Takes the next batch when one is due; `None` when the worker should wait.
    fn next_batch(&self, due: bool) -> Option<Arc<Vec<LogRecord>>> {
        let mut st = self.lock();
        let flushing = *self.processed.borrow() < st.flush_target;
        let full = st.queue.len() >= self.opts.max_batch_size
            || st.queued_bytes >= self.opts.max_batch_bytes;
        if st.queue.is_empty() || !(due || flushing || full || st.closed) {
            return None;
        }
        let mut batch = Vec::new();
        let mut bytes = 0usize;
        while let Some(item) = st.queue.front() {
            let over = bytes + item.bytes > self.opts.max_batch_bytes;
            if batch.len() >= self.opts.max_batch_size || (!batch.is_empty() && over) {
                break;
            }
            bytes += item.bytes;
            let item = st.queue.pop_front().expect("front exists");
            batch.push(item.record);
        }
        st.queued_bytes -= bytes;
        let batch = Arc::new(batch);
        st.in_flight = Some(Arc::clone(&batch));
        drop(st);
        self.notify_space();
        Some(batch)
    }

    async fn export_batch(&self, records: Arc<Vec<LogRecord>>) {
        let n = records.len() as u64;
        let opts = ExportOptions::new(self.opts.gzip);
        let mut attempt = 0u32;
        loop {
            let res = tokio::time::timeout(
                self.opts.export_timeout,
                self.exporter.export(&records, opts),
            )
            .await
            .unwrap_or_else(|_| {
                Err(Error::timeout(format!(
                    "log export timed out after {:?}",
                    self.opts.export_timeout
                )))
            });
            match res {
                Ok(r) => {
                    let accepted = (r.accepted as u64).min(n);
                    self.sent.fetch_add(accepted, Ordering::Relaxed);
                    let failed = n - accepted;
                    self.failed.fetch_add(failed, Ordering::Relaxed);
                    match r.error {
                        Some(e) => self.report_error(&e, &records),
                        None if failed > 0 => self.report_error(
                            &Error::validation(format!(
                                "{failed} of {n} log records were rejected"
                            )),
                            &records,
                        ),
                        None => {}
                    }
                }
                Err(e) if e.is_retryable() && attempt < self.opts.max_export_retries => {
                    attempt += 1;
                    self.retries.fetch_add(1, Ordering::Relaxed);
                    let backoff = self.opts.retry_backoff * (1u32 << (attempt - 1).min(16));
                    tokio::time::sleep(backoff).await;
                    continue;
                }
                Err(e) => {
                    self.failed.fetch_add(n, Ordering::Relaxed);
                    self.report_error(&e, &records);
                    if let Some(cb) = &self.opts.on_drop {
                        let _ = catch_unwind(AssertUnwindSafe(|| {
                            cb(&records, DropReason::ExportFailed)
                        }));
                    }
                }
            }
            break;
        }
        self.lock().in_flight = None;
        self.processed.send_modify(|p| *p += n);
    }
}

async fn run_worker(shared: Arc<Shared>) {
    let interval = shared.opts.flush_interval;
    let mut deadline = tokio::time::Instant::now() + interval;
    loop {
        let due = tokio::time::Instant::now() >= deadline;
        if let Some(batch) = shared.next_batch(due) {
            shared.export_batch(batch).await;
            continue;
        }
        if due {
            deadline = tokio::time::Instant::now() + interval;
        }
        {
            let st = shared.lock();
            if st.closed && st.queue.is_empty() {
                return;
            }
        }
        tokio::select! {
            _ = shared.wake.notified() => {}
            _ = tokio::time::sleep_until(deadline) => {}
        }
    }
}