mln-rs-runtime 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
use std::any::Any;
use std::cell::Cell;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, OnceLock, Weak};
use std::thread::ThreadId;
use std::time::Duration;

use mln_style::error::Error;
use mln_style::size::Size;
use parking_lot::Mutex;

use super::{DemandGuard, RenderSessionCapabilities, RenderSessionState};
use crate::completion::{Completion, Home, Resolver};
use crate::frame_pacer::{FramePacer, RefreshWaiter};
use crate::log_target;
use crate::map::Map;
use crate::render::frame::{FrameDemand, FrameResult};
use crate::render::target::{DeviceLease, Driver, FrameTexture, GpuSync, Wake};
use crate::render::worker::{self, SessionQueue, Worker};

/// The ID of a render session, unique in the process.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct SessionId(pub(super) u64);

/// A frame of a borrowed ring that the session published, and what the
/// host waits for before it reads it.
#[derive(Clone, Debug)]
pub(crate) struct Published {
    pub(crate) result: FrameResult,
    pub(crate) sync: GpuSync,
    pub(crate) texture: Option<FrameTexture>,
}

/// One texture of a borrowed ring.
#[derive(Clone, Debug, Default)]
pub(crate) struct RingSlot {
    /// The newest frame rendered into the texture, which the host hasn't
    /// acquired.
    pub(crate) frame: Option<Published>,
    pub(crate) acquired: bool,
    pub(crate) rendering: bool,
    /// The host's GPU may still read the texture, so the session renders
    /// into it no more, even when a new ring has it again, until a release
    /// of the ring.
    pub(crate) quarantined: bool,
    /// The host holds an exported ring's image from before a resize, which
    /// gave the slot a new one that never reached the host: giving the old
    /// one up quarantines nothing.
    pub(crate) retired: bool,
}

impl RingSlot {
    pub(crate) fn busy(&self) -> bool {
        self.acquired || self.rendering || self.quarantined
    }
}

/// Work sent to a session's thread, whose completion an abandon can fail at
/// once instead of waiting for the thread to run it.
pub(crate) trait PendingWork: Any + Send {
    fn fail(self: Box<Self>, error: Error);
}

impl<T: Send + 'static> PendingWork for Resolver<T> {
    fn fail(self: Box<Self>, error: Error) {
        (*self).resolve(Err(error));
    }
}

/// The ID of a piece of work that waits for a session's thread.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct WorkId(u64);

/// The state that a session's handle and its thread share.
pub(crate) struct SessionState {
    pub(crate) lifecycle: RenderSessionState,
    pub(crate) released: bool,
    pub(crate) size: Size,
    /// The scale factor that the target has, as `size` does.
    pub(crate) scale_factor: f64,
    /// The scale factor of the last resize sent, which a later resize that
    /// names none keeps.
    pub(crate) sent_scale_factor: f64,
    pub(crate) generation: u64,
    pub(crate) frame_generation: u64,
    pub(crate) failure: Option<Error>,
    /// Whether the session has a target to render to: false from a release
    /// of its target until it gets a new one.
    pub(crate) has_target: bool,
    /// The frame results that wait for a drain.
    pub(crate) results: Vec<FrameResult>,
    /// Whether the frame wake ran since the last drain.
    pub(crate) frame_woken: bool,
    /// Whether the redraw wake may run: from the last demand until it runs.
    /// Once it ran, the map has something new to draw that no demand has
    /// answered.
    pub(crate) redraw_armed: bool,
    /// Host frame demands that haven't been evaluated or ended yet: while one
    /// is on its way, redraw wakes wait so that an earlier update can't disarm
    /// the wake that the demand answers.
    pub(crate) pending_demands: usize,
    /// The frame pacer that takes the redraw wake's place, while one paces
    /// the session.
    pub(super) pacing: Option<Pacing>,
    /// The attach's completion, until the map binds the session.
    pub(crate) attach: Option<Resolver<()>>,
    /// The completions of the detaches on their way.
    pub(crate) detach_waiters: Vec<Resolver<()>>,
    /// The completions of the releases on their way.
    pub(crate) release_waiters: Vec<Resolver<()>>,
    /// The completions of the work that waits for the session's thread.
    pub(super) pending: BTreeMap<WorkId, Box<dyn PendingWork>>,
    pub(super) next_work: u64,
    /// The session's map, until the session lets go of it.
    pub(crate) map: Option<Map>,
    /// What the session's thread builds the renderer from, until it does:
    /// an [`Init`](crate::render::worker::Init). It is boxed as `Any` so that
    /// the state names no graphics types, whose auto traits are deep to prove
    /// for every type that holds a map handle.
    pub(crate) init: Option<Box<dyn Any + Send>>,
    /// Counts the resizes sent, which run on the map's thread before they
    /// reach the session's.
    pub(crate) resizes_sent: u64,
    /// How many graphics objects the session's thread holds.
    pub(crate) graphics_objects: u32,
    /// Whether the session's thread keeps its graphics objects until the
    /// process exits, instead of freeing them, when the session ends.
    pub(crate) keep_graphics: bool,
    /// Whether an abandon keeps the graphics objects on any thread, as
    /// `Device::abandon_keeps_graphics` says of the session's device.
    pub(crate) abandon_keeps_graphics: bool,
    /// The slots of a borrowed ring, and none for another target.
    pub(crate) ring: Vec<RingSlot>,
    /// How many of the ring's frames the host holds.
    pub(crate) acquired_frames: u32,
    /// The ring replacements and releases on their way: no frame is
    /// acquired until they ran, since the frames published before one name
    /// textures it replaces or lets go of.
    pub(crate) pending_retargets: u32,
    /// How many views are open on the session's acquired frames.
    pub(crate) views: u32,
    /// Whether the session's thread keeps graphics objects that the open
    /// views name, which it lets go of once the last view ends.
    pub(crate) viewed_teardown: bool,
}

impl SessionState {
    /// Keeps `resolver` until the session's thread takes it.
    pub(super) fn register<T: Send + 'static>(&mut self, resolver: Resolver<T>) -> WorkId {
        self.next_work += 1;
        let id = WorkId(self.next_work);
        self.pending.insert(id, Box::new(resolver));
        id
    }

    /// What an end of the session completes, once the state is unlocked.
    pub(crate) fn take_waiters(&mut self) -> Waiters {
        Waiters {
            attach: self.attach.take(),
            pending: std::mem::take(&mut self.pending).into_values().collect(),
            detaches: std::mem::take(&mut self.detach_waiters),
            releases: std::mem::take(&mut self.release_waiters),
        }
    }
}

/// The completions that wait for a session when it ends.
pub(crate) struct Waiters {
    attach: Option<Resolver<()>>,
    pending: Vec<Box<dyn PendingWork>>,
    detaches: Vec<Resolver<()>>,
    releases: Vec<Resolver<()>>,
}

impl Waiters {
    /// Completes the releases, and the detaches with `detached`. The attach
    /// and the work that never ran fail with `lost`.
    pub(crate) fn settle(self, detached: &Result<(), Error>, lost: impl Fn() -> Error) {
        if let Some(attach) = self.attach {
            attach.resolve(Err(lost()));
        }
        for work in self.pending {
            work.fail(lost());
        }
        for waiter in self.detaches {
            waiter.resolve(detached.clone());
        }
        for waiter in self.releases {
            waiter.resolve(Ok(()));
        }
    }
}

/// Who abandons a session.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Abandoner {
    /// The host, through the handle.
    Host,
    /// The library, for a session that the host released, or stopped
    /// servicing.
    Library,
}

/// A session's frame pacer, and what waits for its refreshes.
pub(super) struct Pacing {
    pub(super) pacer: Arc<FramePacer>,
    /// The session, as the pacer calls it back. Each pacing has its own, so
    /// a refresh that an earlier pacing asked for demands nothing.
    waiter: Arc<dyn RefreshWaiter>,
}

impl Pacing {
    pub(super) fn new(pacer: Arc<FramePacer>, session: Weak<SessionShared>) -> Self {
        Self { pacer, waiter: Arc::new(PacedSession(session)) }
    }

    /// What asks the pacer for a refresh, in place of the redraw wake.
    pub(super) fn request(&self) -> Wake {
        let (pacer, waiter) = (Arc::clone(&self.pacer), Arc::clone(&self.waiter));
        Arc::new(move || pacer.request(&waiter))
    }
}

/// A paced session, as its pacer holds it while it waits for a refresh.
struct PacedSession(Weak<SessionShared>);

impl RefreshWaiter for PacedSession {
    fn refresh(&self, _time: Duration) {
        if let Some(shared) = self.0.upgrade() {
            shared.demand_paced(self);
        }
    }
}

pub(crate) struct SessionShared {
    pub(crate) id: SessionId,
    pub(crate) driver: Driver,
    /// The work of the thread that runs the session.
    pub(crate) queue: SessionQueue,
    /// The thread that runs the session's work, once it is known: a core
    /// worker's from the attach, and a caller thread's from when the host
    /// takes the driver work.
    pub(crate) thread: Arc<OnceLock<ThreadId>>,
    /// The thread of the map's runtime, which runs the map's side of the
    /// session's work.
    pub(super) runtime_thread: ThreadId,
    pub(crate) state: Mutex<SessionState>,
    /// Held while the session's thread runs a task, so an abandon waits for
    /// the graphics work in progress.
    pub(crate) gate: Mutex<()>,
    /// The session's lease on the host's device, which an abandon revokes,
    /// since graphics objects that it keeps hold the device.
    pub(super) lease: DeviceLease,
    /// Held while [`RenderSession::send_then`](super::RenderSession::send_then)
    /// sends a command and attaches its callback, and while an attach hands
    /// its completion out, which the session's thread waits for before it
    /// delivers results.
    pub(super) sending: Mutex<()>,
    /// Whether the session's thread is inside a driver call: a core worker
    /// running a task and delivering what it sent the host, or a service of
    /// a caller-driven session.
    pub(crate) in_call: AtomicBool,
    pub(crate) frame_wake: Option<Wake>,
    pub(crate) redraw_wake: Option<Wake>,
    pub(super) capabilities: RenderSessionCapabilities,
    pub(super) driver_work_taken: AtomicBool,
    /// Whether the driver-work wake may run: from the start of the last
    /// service until it runs.
    pub(crate) driver_armed: Arc<AtomicBool>,
    /// The first of the map's commands that the session's work waits for,
    /// or `u64::MAX` for none: the map tells the session's thread when it
    /// ran a command only from that one on, so a command that no work waits
    /// for wakes no caller's driver.
    pub(crate) awaited_command: Arc<AtomicU64>,
    /// In the browser, whether a caller-driven session waits for the device
    /// that it asked the browser's WebGPU for: its services build nothing
    /// until the device is there, and the driver-work wake runs then.
    pub(crate) preparing: AtomicBool,
}

impl SessionShared {
    /// A completion that the session's thread resolves.
    pub(super) fn completion<T: Send + 'static>(&self) -> (Completion<T>, Resolver<T>) {
        Completion::at(Home::Later(Arc::clone(&self.thread), self.runtime_thread))
    }

    /// The completion of the work `id`, unless an end of the session
    /// completed it first.
    pub(crate) fn take_work<T: Send + 'static>(&self, id: WorkId) -> Option<Resolver<T>> {
        let work: Box<dyn Any + Send> = self.state.lock().pending.remove(&id)?;
        work.downcast::<Resolver<T>>().ok().map(|resolver| *resolver)
    }

    pub(crate) fn is_released(&self) -> bool {
        self.state.lock().released
    }

    /// The redraw wake that tells the host the map has something new to
    /// draw, unless the host was told since its last demand, a demand is on
    /// its way, or the session has no target. The host isn't told again until
    /// its next demand.
    pub(crate) fn take_redraw_wake(&self) -> Option<Wake> {
        let mut state = self.state.lock();
        let wake = state.redraw_armed
            && state.pending_demands == 0
            && state.has_target
            && state.lifecycle == RenderSessionState::Attached;
        state.redraw_armed &= !wake;
        if !wake {
            return None;
        }
        match &state.pacing {
            Some(pacing) => Some(pacing.request()),
            None => self.redraw_wake.clone(),
        }
    }

    /// Sends `demand` to the session's thread. The state is locked.
    pub(super) fn demand_locked(self: &Arc<Self>, state: &mut SessionState, demand: FrameDemand) -> Result<(), Error> {
        check_usable(state)?;
        if !state.ring.is_empty() && state.ring.iter().all(|slot| slot.quarantined) {
            return Err(Error::invalid_state(
                "every texture of the ring is quarantined: give the session new textures",
            ));
        }
        let (sequence, sample) = state.map.as_ref().map_or((0, 0), |map| (map.sent_sequence(), map.frame_demanded()));
        state.redraw_armed = true;
        state.pending_demands += 1;
        let guard = DemandGuard(Arc::clone(self));
        worker::post(&self.queue, move |worker, outbox| worker.demand(demand, sequence, sample, guard, outbox));
        Ok(())
    }

    /// Demands the frame that the map has to draw at `waiter`'s refresh,
    /// unless a demand came first or `waiter`'s pacing ended.
    fn demand_paced(self: &Arc<Self>, waiter: &PacedSession) {
        with_unlocked_wakes(|| {
            let mut state = self.state.lock();
            let current = state
                .pacing
                .as_ref()
                .is_some_and(|pacing| core::ptr::addr_eq(Arc::as_ptr(&pacing.waiter), core::ptr::from_ref(waiter)));
            if current && !state.redraw_armed {
                // A session that failed or ended since it asked takes no demand.
                let _ = self.demand_locked(&mut state, FrameDemand::new(crate::render::DemandMode::IfChanged, 0));
            }
        });
    }

    /// Starts a detach on the session's thread, after the work sent before.
    /// The state is locked, and the session usable or failed.
    pub(super) fn start_detach(&self, state: &mut SessionState) {
        state.lifecycle = RenderSessionState::Detaching;
        worker::post(&self.queue, Worker::detach);
    }

    /// Releases the session without waiting: it detaches, unless it is
    /// detached or abandoned already, and every call on it fails after. A
    /// caller-driven session that isn't attached, or whose map was released,
    /// is abandoned instead, so the release doesn't wait for the host to
    /// service it.
    pub(super) fn dispose(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
        with_unlocked_wakes(|| self.dispose_locked(done))
    }

    /// Releases the session without waiting and without graphics calls past
    /// the one in progress: a session that hasn't ended is abandoned, and
    /// keeps its graphics objects until the process exits.
    pub(super) fn dispose_keeping_graphics(&self) -> Result<(), Error> {
        with_unlocked_wakes(|| {
            {
                let mut state = self.state.lock();
                if state.released {
                    return Err(released());
                }
                state.released = true;
                state.pacing = None;
                state.keep_graphics = true;
                if matches!(state.lifecycle, RenderSessionState::Detached | RenderSessionState::Abandoned) {
                    return Ok(());
                }
            }
            if self.abandon_locked(Abandoner::Library, true).is_err() {
                // Only the session's own work could hold the gate here: the
                // session detaches after it, keeping its graphics objects.
                let mut state = self.state.lock();
                if !matches!(
                    state.lifecycle,
                    RenderSessionState::Detaching | RenderSessionState::Detached | RenderSessionState::Abandoned
                ) {
                    self.start_detach(&mut state);
                }
            }
            Ok(())
        })
    }

    fn dispose_locked(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
        let mut state = self.state.lock();
        if state.released {
            return Err(released());
        }
        state.released = true;
        state.pacing = None;
        // A released map waits for no service of its session's detach.
        let map_released = state.map.as_ref().is_some_and(Map::is_released);
        match state.lifecycle {
            RenderSessionState::Detached | RenderSessionState::Abandoned => {
                drop(state);
                if let Some(done) = done {
                    done.resolve(Ok(()));
                }
                return Ok(());
            }
            RenderSessionState::Detaching => {}
            RenderSessionState::Attaching | RenderSessionState::Failed if self.driver == Driver::CallerThread => {
                state.release_waiters.extend(done);
                drop(state);
                self.abandon_or_detach();
                return Ok(());
            }
            RenderSessionState::Attached if self.driver == Driver::CallerThread && map_released => {
                state.release_waiters.extend(done);
                drop(state);
                self.abandon_or_detach();
                return Ok(());
            }
            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Failed => {
                self.start_detach(&mut state);
            }
        }
        state.release_waiters.extend(done);
        Ok(())
    }

    /// Abandons the released session, or detaches it when its own work
    /// holds the gate, which only it could here.
    fn abandon_or_detach(&self) {
        if self.abandon(Abandoner::Library).is_err() {
            let mut state = self.state.lock();
            if state.lifecycle != RenderSessionState::Abandoned {
                self.start_detach(&mut state);
            }
        }
    }

    /// Stops the session at once, as [`RenderSession::abandon`](super::RenderSession::abandon)
    /// documents, and returns how many graphics objects it keeps. The library
    /// may abandon a released session too.
    pub(crate) fn abandon(&self, by: Abandoner) -> Result<u32, Error> {
        with_unlocked_wakes(|| self.abandon_locked(by, false))
    }

    /// Waits for a [`RenderSession::send_then`](super::RenderSession::send_then)
    /// in progress to attach its callback. The session's thread calls it before
    /// it delivers what it sent the host, so that a command's result reaches
    /// the callback there, inside the driver call.
    pub(crate) fn wait_for_senders(&self) {
        drop(self.sending.lock());
    }

    /// Takes the sending lock, which the session's thread waits for before
    /// it delivers results, unless this thread holds it already: a send
    /// inside another, such as from a completion that a release settles at
    /// once on this thread, is delivered after the outer one too.
    pub(super) fn hold_sending(&self) -> Option<Sending<'_>> {
        if with_sending(|sending| sending.contains(&self.id)) {
            return None;
        }
        let guard = self.sending.lock();
        with_sending(|sending| sending.push(self.id));
        Some(Sending { id: self.id, _guard: guard })
    }

    /// Marks the session's thread as inside a driver call until the guard
    /// drops.
    pub(crate) fn enter_call(&self) -> InCall<'_> {
        InCall { shared: self, previous: self.in_call.swap(true, Ordering::SeqCst) }
    }

    /// Abandons the session, which keeps its graphics objects until the
    /// process exits if `keep_graphics`, and returns how many it keeps.
    ///
    /// A driver call can't be waited for on its own thread, where the
    /// session's callbacks run inside it, and a host's service on another
    /// thread is the host's to end, so either is busy. A core worker's call
    /// on another thread is waited for. A caller-driven session that is
    /// abandoned off its thread keeps its graphics objects, which only its
    /// thread may free: once this returns, the host may destroy what they
    /// were made on.
    pub(super) fn abandon_locked(&self, by: Abandoner, keep_graphics: bool) -> Result<u32, Error> {
        let on_driver = self.thread.get() == Some(&std::thread::current().id());
        if self.in_call.load(Ordering::SeqCst) {
            if on_driver {
                return Err(Error::busy("the render session's driver call is running on this thread"));
            }
            if self.driver == Driver::CallerThread && by == Abandoner::Host {
                return Err(Error::busy("the render session's driver work is running on another thread"));
            }
        }
        let off_thread = self.driver == Driver::CallerThread && !on_driver;
        let gate = if on_driver {
            self.gate.try_lock().ok_or_else(|| Error::busy("the render session is rendering on this thread"))?
        } else {
            self.gate.lock()
        };
        let (waiters, map, kept) = {
            let mut state = self.state.lock();
            if by == Abandoner::Host && state.released {
                return Err(released());
            }
            match state.lifecycle {
                RenderSessionState::Attaching
                | RenderSessionState::Attached
                | RenderSessionState::Detaching
                | RenderSessionState::Failed => {}
                RenderSessionState::Detached | RenderSessionState::Abandoned => {
                    return Err(Error::invalid_state("the render session was detached or abandoned"));
                }
            }
            // The views keep the frames' sync objects in place, which the
            // abandon would let go of. A library's abandon, of a session
            // that the host released, keeps them until the views end.
            if by == Abandoner::Host && state.views != 0 {
                return Err(Error::busy("a view is open on one of the render session's acquired frames"));
            }
            state.lifecycle = RenderSessionState::Abandoned;
            state.keep_graphics |= keep_graphics || off_thread || state.abandon_keeps_graphics;
            let kept = if state.keep_graphics { state.graphics_objects } else { 0 };
            (state.take_waiters(), state.map.take(), kept)
        };
        match &map {
            // The map unbinds the session before another can attach.
            Some(map) => {
                map.unbind_session_then(self.id, self.queue.clone(), Worker::finish);
                map.release_session_claim(self.id);
            }
            None => worker::post(&self.queue, Worker::finish),
        }
        // A core worker lets go of its graphics objects at its next task,
        // which runs before this returns: the host may destroy what they were
        // made on once it does.
        // In the browser the session's queue runs on this thread, which runs
        // that task here instead, unless it is inside the session's work.
        #[cfg(target_family = "wasm")]
        let run_now = self.driver == Driver::CoreWorker
            && !self.in_call.load(Ordering::SeqCst)
            && !with_sending(|sending| sending.contains(&self.id));
        let torn_down = (self.driver == Driver::CoreWorker && !on_driver).then(|| {
            let (sender, receiver) = std::sync::mpsc::sync_channel::<()>(1);
            worker::post(&self.queue, move |_, _| {
                let _ = sender.send(());
            });
            receiver
        });
        drop(gate);
        if let Some(receiver) = torn_down {
            // A worker that ended drops the task, and the sender with it.
            let _ = receiver.recv();
        }
        #[cfg(target_family = "wasm")]
        if run_now {
            worker::post(&self.queue, |_, _| {});
            crate::web::run_session_now(self.id);
        }
        // Off the session's thread, the session makes no more graphics
        // calls: a core worker tore down above, and a caller-driven session
        // keeps its graphics objects. On it, the teardown that follows
        // still needs the device.
        if !on_driver {
            self.lease.revoke();
        }
        if kept != 0 {
            let reason = if keep_graphics {
                "it was abandoned without graphics calls"
            } else if off_thread {
                "only the thread that services it may free them"
            } else {
                "only a detach frees OpenGL and WebGPU objects"
            };
            tracing::warn!(
                target: log_target::RENDER,
                count = kept,
                reason,
                "An abandoned render session keeps graphics objects until the process exits"
            );
        }
        let lost = || Error::target_lost("the render session was abandoned");
        waiters.settle(&Err(lost()), lost);
        drop(map);
        Ok(kept)
    }
}

/// Marks a session's thread as inside a driver call, as
/// [`SessionShared::enter_call`] does.
pub(crate) struct InCall<'a> {
    shared: &'a SessionShared,
    previous: bool,
}

impl Drop for InCall<'_> {
    fn drop(&mut self) {
        self.shared.in_call.store(self.previous, Ordering::SeqCst);
    }
}

pub(super) fn released() -> Error {
    Error::invalid_state("the render session was released")
}

/// Fails unless the session takes work: it is attaching or attached, and
/// not released.
pub(super) fn check_usable(state: &SessionState) -> Result<(), Error> {
    if state.released {
        return Err(released());
    }
    match state.lifecycle {
        RenderSessionState::Attaching | RenderSessionState::Attached => Ok(()),
        RenderSessionState::Failed => {
            Err(state.failure.clone().unwrap_or_else(|| Error::failed("the render session failed")))
        }
        RenderSessionState::Detaching | RenderSessionState::Detached | RenderSessionState::Abandoned => {
            Err(Error::invalid_state("the render session is not attached: it was detached or abandoned"))
        }
    }
}

thread_local! {
    /// The driver wakes that this thread's posts asked for during a handle
    /// call, which may hold the session's locks.
    static DEFERRED_WAKES: Cell<Option<Vec<Wake>>> = const { Cell::new(None) };
    /// The sessions whose sending lock this thread holds.
    static SENDING: Cell<Vec<SessionId>> = const { Cell::new(Vec::new()) };
}

fn with_sending<R>(f: impl FnOnce(&mut Vec<SessionId>) -> R) -> R {
    SENDING.with(|sending| {
        let mut ids = sending.take();
        let result = f(&mut ids);
        sending.set(ids);
        result
    })
}

/// A session's sending lock, which [`SessionShared::hold_sending`] took.
pub(super) struct Sending<'a> {
    id: SessionId,
    _guard: parking_lot::MutexGuard<'a, ()>,
}

impl Drop for Sending<'_> {
    fn drop(&mut self) {
        with_sending(|sending| sending.retain(|id| *id != self.id));
    }
}

/// Runs `call`, which may post to a session's queue with the session's locks
/// held, then the driver wakes that its posts asked for, with nothing locked.
pub(super) fn with_unlocked_wakes<R>(call: impl FnOnce() -> R) -> R {
    let outer = DEFERRED_WAKES.with(|deferred| deferred.replace(Some(Vec::new())));
    let result = call();
    let wakes = DEFERRED_WAKES.with(|deferred| {
        let wakes = deferred.take().unwrap_or_default();
        match outer {
            // The outer call runs them.
            Some(mut outer) => {
                outer.extend(wakes);
                deferred.set(Some(outer));
                Vec::new()
            }
            None => wakes,
        }
    });
    for wake in wakes {
        wake();
    }
    result
}

/// Runs `wake` now, or once the handle call on this thread returns.
pub(super) fn wake_unlocked(wake: &Wake) {
    let deferred = DEFERRED_WAKES.with(|deferred| match deferred.take() {
        Some(mut wakes) => {
            wakes.push(Arc::clone(wake));
            deferred.set(Some(wakes));
            true
        }
        None => false,
    });
    if !deferred {
        wake();
    }
}