| 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 | //! # Acquiring and releasing a hold |
| 40 | //! |
| 41 | //! [`acquire`](InputGate::acquire) refuses an event while another event |
| 42 | //! holds the gate. The shell queues the refused caller and retries when |
| 43 | //! the gate opens. Nested holds within one event are counted, so releasing |
| 44 | //! an inner hold does not admit another event into the outer section. |
| 45 | //! |
| 46 | //! Abandoning a hold invalidates its event id. A delayed release for that |
| 47 | //! id changes nothing, even when another event has acquired the gate. |
| 48 | //! |
| 49 | //! This is the decision half. The shell owns the delivery points and asks |
| 50 | //! [`is_open`](InputGate::is_open) at each one; it never decides who runs. |
| 51 | |
| 52 | /// An event delivered to a cell: a request turn, an alarm, a subrequest |
| 53 | /// response, a stream wakeup. The shell assigns the ids and only needs them |
| 54 | /// to be unique among a cell's live events. |
| 55 | pub type EventId = u64; |
| 56 | |
| 57 | /// One cell's input gate. |
| 58 | /// |
| 59 | /// Default is open, which is the common case: a cell with nothing blocking |
| 60 | /// delivers everything immediately and this costs a branch. |
| 61 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 62 | pub struct InputGate { |
| 63 | /// The event holding the gate, if any. |
| 64 | holder: Option<EventId>, |
| 65 | /// How many holds the holder has taken at once. |
| 66 | /// |
| 67 | /// `blockConcurrencyWhile` nests. Opening the gate when the innermost |
| 68 | /// block ends would admit another event while the outer ones still run, |
| 69 | /// which a boolean would do. |
| 70 | outstanding: u32, |
| 71 | } |
| 72 | |
| 73 | impl InputGate { |
| 74 | pub fn new() -> Self { |
| 75 | Self::default() |
| 76 | } |
| 77 | |
| 78 | /// May an event that is not already running be delivered now? |
| 79 | /// |
| 80 | /// The one question a delivery point asks. The holder never asks it: it |
| 81 | /// is already running, and its own continuations are not deliveries. |
| 82 | pub fn is_open(&self) -> bool { |
| 83 | self.holder.is_none() |
| 84 | } |
| 85 | |
| 86 | /// `event` entered a `blockConcurrencyWhile`. Shuts the gate, and |
| 87 | /// answers whether it got it. |
| 88 | /// |
| 89 | /// `false` means another event holds it and this one must wait. That |
| 90 | /// used to be impossible: while a cell's events came off one channel |
| 91 | /// only one ran at a time, and a delivery point had already found the |
| 92 | /// gate open. Events are independent tasks now, several are in flight |
| 93 | /// at once by design, so two can reach a block together. |
| 94 | #[must_use] |
| 95 | pub fn acquire(&mut self, event: EventId) -> bool { |
| 96 | match self.holder { |
| 97 | None => { |
| 98 | self.holder = Some(event); |
| 99 | self.outstanding = 1; |
| 100 | true |
| 101 | } |
| 102 | Some(holder) if holder == event => { |
| 103 | self.outstanding += 1; |
| 104 | true |
| 105 | } |
| 106 | Some(_) => false, |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /// One of `event`'s blocks ended. Return true only if it opens the gate. |
| 111 | /// |
| 112 | /// A callback can finish after its hold was abandoned, including after |
| 113 | /// another event took the gate. That stale release changes nothing: |
| 114 | /// panicking can abort the process from a JS callback, and decrementing |
| 115 | /// the new holder's count would admit events into its critical section. |
| 116 | #[must_use] |
| 117 | pub fn release(&mut self, event: EventId) -> bool { |
| 118 | if self.holder != Some(event) { |
| 119 | return false; |
| 120 | } |
| 121 | self.outstanding -= 1; |
| 122 | if self.outstanding == 0 { |
| 123 | self.holder = None; |
| 124 | return true; |
| 125 | } |
| 126 | false |
| 127 | } |
| 128 | |
| 129 | /// `event` died — terminated, cancelled, or timed out — and will never |
| 130 | /// release. Answers whether it was the holder that this call abandoned. |
| 131 | /// |
| 132 | /// Without this a request killed mid-block shuts its cell's gate |
| 133 | /// forever, and the cell accepts nothing again. The event identity is |
| 134 | /// required because another event can already be running when the holder |
| 135 | /// dies. Abandoning that other event must not open this gate. |
| 136 | #[must_use] |
| 137 | pub fn abandon(&mut self, event: EventId) -> bool { |
| 138 | if self.holder != Some(event) { |
| 139 | return false; |
| 140 | } |
| 141 | self.holder = None; |
| 142 | self.outstanding = 0; |
| 143 | true |
| 144 | } |
| 145 | } |