| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! The input gate, reified sans-IO. |
| 4 | //! |
| 5 | //! A cell serves several requests at once — that is the Durable Object |
| 6 | //! contract, and D1 restores it by deleting the per-cell thread that |
| 7 | //! accidentally forbade it. Concurrency is only safe if a handler that |
| 8 | //! must not be interrupted cannot be, or it would resume to find its own |
| 9 | //! state changed underneath it by whatever ran while it waited. |
| 10 | //! |
| 11 | //! workerd's rule (`io-gate.h`): while the gate is held, **no incoming |
| 12 | //! event of any kind is delivered** to that cell except the event holding |
| 13 | //! it. Not just new requests — a subrequest's response, a timer, a stream |
| 14 | //! read. Anything that would run JS and observe state. |
| 15 | //! |
| 16 | //! **What holds it here is not storage.** In workerd the async KV API |
| 17 | //! (`actor-state.h:49`, `jsg::Promise<...> get`) can genuinely suspend on an |
| 18 | //! `ActorCache` miss, so storage is what gates; the SQL API (`sql.h:41`, |
| 19 | //! `exec` returning a `Cursor`) is synchronous and does not. In celld every |
| 20 | //! storage path is local SQLite underneath, including the async-shaped one, |
| 21 | //! whose `await Promise.resolve()` drains in the same microtask checkpoint. |
| 22 | //! A read or a write therefore completes inside the turn that started it and |
| 23 | //! never yields to another event, so there is no window for the gate to |
| 24 | //! close. |
| 25 | //! |
| 26 | //! Its user is **`blockConcurrencyWhile`** (`harness.js:1001`), which holds |
| 27 | //! across arbitrary user code — including real awaits like `fetch` — and |
| 28 | //! whose entire purpose is that nothing else runs meanwhile. |
| 29 | //! |
| 30 | //! # Why there is no queue here |
| 31 | //! |
| 32 | //! An earlier version of this file parked refused events in a `VecDeque` and |
| 33 | //! returned them from `release`. That mirrored a queue the shell already |
| 34 | //! owns: a cell's events arrive on its job channel, and an event the gate |
| 35 | //! refuses is simply **left there**, in arrival order, until a later |
| 36 | //! delivery attempt takes it. Modelling it twice bought nothing and cost the |
| 37 | //! two structures agreeing. |
| 38 | //! |
| 39 | //! # Why acquiring cannot fail |
| 40 | //! |
| 41 | //! [`acquire`](InputGate::acquire) panics if another event holds the gate, |
| 42 | //! and that is not optimism. Acquiring happens *during* an event, and an |
| 43 | //! event only runs because a delivery point found the gate open. So a second |
| 44 | //! event cannot be running to acquire second. Nested blocks within one event |
| 45 | //! are counted, not refused, because that event already holds it. |
| 46 | //! |
| 47 | //! This property is what makes the mechanism small, and losing it is what |
| 48 | //! wedged cells before: while acquiring was asynchronous, a cell could |
| 49 | //! deliver a second event in the window between a block starting and the |
| 50 | //! gate shutting. That event then had to *wait* for a gate held by an event |
| 51 | //! suspended beneath it on the stack, which nothing could ever release. |
| 52 | //! Acquiring is therefore synchronous with the JS call that asks for it, and |
| 53 | //! the panic is what says so. |
| 54 | //! |
| 55 | //! This is the decision half. The shell owns the delivery points and asks |
| 56 | //! [`is_open`](InputGate::is_open) at each one; it never decides who runs. |
| 57 | |
| 58 | /// An event delivered to a cell: a request turn, an alarm, a subrequest |
| 59 | /// response, a stream wakeup. The shell assigns the ids and only needs them |
| 60 | /// to be unique among a cell's live events. |
| 61 | pub type EventId = u64; |
| 62 | |
| 63 | /// One cell's input gate. |
| 64 | /// |
| 65 | /// Default is open, which is the common case: a cell with nothing blocking |
| 66 | /// delivers everything immediately and this costs a branch. |
| 67 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 68 | pub struct InputGate { |
| 69 | /// The event holding the gate, if any. |
| 70 | holder: Option<EventId>, |
| 71 | /// How many holds the holder has taken at once. |
| 72 | /// |
| 73 | /// `blockConcurrencyWhile` nests. Opening the gate when the innermost |
| 74 | /// block ends would admit another event while the outer ones still run, |
| 75 | /// which a boolean would do. |
| 76 | outstanding: u32, |
| 77 | } |
| 78 | |
| 79 | impl InputGate { |
| 80 | pub fn new() -> Self { |
| 81 | Self::default() |
| 82 | } |
| 83 | |
| 84 | /// May an event that is not already running be delivered now? |
| 85 | /// |
| 86 | /// The one question a delivery point asks. The holder never asks it: it |
| 87 | /// is already running, and its own continuations are not deliveries. |
| 88 | pub fn is_open(&self) -> bool { |
| 89 | self.holder.is_none() |
| 90 | } |
| 91 | |
| 92 | /// `event` entered a `blockConcurrencyWhile`. Shuts the gate, and |
| 93 | /// answers whether it got it. |
| 94 | /// |
| 95 | /// `false` means another event holds it and this one must wait. That |
| 96 | /// used to be impossible: while a cell's events came off one channel |
| 97 | /// only one ran at a time, and a delivery point had already found the |
| 98 | /// gate open. Events are independent tasks now, several are in flight |
| 99 | /// at once by design, so two can reach a block together. |
| 100 | #[must_use] |
| 101 | pub fn acquire(&mut self, event: EventId) -> bool { |
| 102 | match self.holder { |
| 103 | None => { |
| 104 | self.holder = Some(event); |
| 105 | self.outstanding = 1; |
| 106 | true |
| 107 | } |
| 108 | Some(holder) if holder == event => { |
| 109 | self.outstanding += 1; |
| 110 | true |
| 111 | } |
| 112 | Some(_) => false, |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// One of `event`'s blocks ended. The gate opens when the last one does. |
| 117 | /// |
| 118 | /// # Panics |
| 119 | /// |
| 120 | /// If `event` does not hold the gate. Opening a gate somebody else |
| 121 | /// depends on is worse than stopping. |
| 122 | pub fn release(&mut self, event: EventId) { |
| 123 | match self.holder { |
| 124 | Some(holder) if holder == event => {} |
| 125 | Some(holder) => panic!("input gate held by event {holder}, released by {event}"), |
| 126 | None => panic!("input gate released by {event} while open"), |
| 127 | } |
| 128 | self.outstanding -= 1; |
| 129 | if self.outstanding == 0 { |
| 130 | self.holder = None; |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | /// The holder died — terminated, cancelled, or timed out — and will |
| 135 | /// never release. |
| 136 | /// |
| 137 | /// Without this a request killed mid-block shuts its cell's gate |
| 138 | /// forever, and the cell accepts nothing again. JS `finally` covers |
| 139 | /// every ordinary exit, a throw included; this covers the one exit that |
| 140 | /// runs no JS. |
| 141 | pub fn abandon(&mut self) { |
| 142 | self.holder = None; |
| 143 | self.outstanding = 0; |
| 144 | } |
| 145 | } |