Diffinery

homeflare/celldpublic

568 lines · 19.1 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3#![warn(clippy::disallowed_methods, clippy::disallowed_types)]
4
5//! Effect adapters for the clean-sheet core.
6//!
7//! The executable owns one serial actor which is the only caller of
8//! `celld_logic::on_event`. Adapter futures never borrow core state; they send
9//! versioned completion events back through its mailbox.
10
11// This implementation is substantially adapted from Tokio 1.53.1 select.rs.
12// Copyright (c) Tokio Contributors. MIT license. See ../../LICENSE.tokio.
13//
14// Every `tokio::` item re-exported below is `doc(hidden)` upstream, so none of
15// them carries a compatibility guarantee. Tokio can rename, reshape, or delete
16// any of them in a patch release without breaking its own semver promise, and
17// the `tokio = "1"` caret range in ../../Cargo.toml does not prevent that. A
18// Tokio version bump must therefore re-check this facade against the select.rs
19// of the new version.
20//
21// The failure mode is a compile error in celld, not a behavior change, so
22// nothing broken ships and no test passes wrongly. Without this note the person
23// who runs `cargo update` sees a macro that no longer resolves and gets no
24// pointer to the cause.
25//
26// Rejected: narrowing the `tokio` constraint to the range this facade is known
27// to work with. That blocks unrelated Tokio fixes for the whole dependency tree
28// to guard against a break the compiler already makes un-missable. Do not
29// "fix" this by pinning.
30#[doc(hidden)]
31pub mod __asyncrt_select_support {
32 pub use std::future::{poll_fn, Future, IntoFuture};
33 pub use std::pin::Pin;
34 pub use std::task::{ready, Poll};
35 pub use tokio::macros::support::poll_budget_available;
36 pub use tokio::{
37 count, count_field, select_priv_clean_pattern, select_priv_declare_output_enum,
38 select_variant,
39 };
40}
41
42#[macro_export]
43macro_rules! __celld_domain_select {
44 (@reason $reason:literal) => {{
45 const _: () = {
46 let reason: &str = $reason;
47 assert!(
48 !reason.is_empty(),
49 "select_biased! requires a non-empty reason string"
50 );
51 };
52 }};
53 (@start fair $branches:expr) => {
54 $crate::asyncrt::select_start($branches)
55 };
56 (@start (biased $reason:literal) $_branches:expr) => {{
57 $crate::__celld_domain_select!(@reason $reason);
58 0_u32
59 }};
60 (@ {
61 mode=$mode:tt;
62 ( $($count:tt)* )
63 $( ( $($skip:tt)* ) $bind:pat = $future:expr, if $condition:expr => $handler:expr, )+
64 ; $else:expr
65 }) => {{
66 #[doc(hidden)]
67 mod __celld_select_util {
68 $crate::__asyncrt_select_support::select_priv_declare_output_enum!(
69 ( $($count)* )
70 );
71 }
72
73 const BRANCHES: u32 = $crate::__asyncrt_select_support::count!($($count)*);
74 let mut disabled: __celld_select_util::Mask = Default::default();
75
76 $(
77 if !$condition {
78 let mask: __celld_select_util::Mask =
79 1 << $crate::__asyncrt_select_support::count!($($skip)*);
80 disabled |= mask;
81 }
82 )*
83
84 #[allow(unused_mut)]
85 let mut output = {
86 let futures_init = ($($future,)+);
87 let mut futures = ($(
88 $crate::__asyncrt_select_support::IntoFuture::into_future(
89 $crate::__asyncrt_select_support::count_field!(
90 futures_init.$($skip)*
91 )
92 ),
93 )+);
94 #[allow(unused_mut)]
95 let mut futures = &mut futures;
96
97 $crate::__asyncrt_select_support::poll_fn(|context| {
98 $crate::__asyncrt_select_support::ready!(
99 $crate::__asyncrt_select_support::poll_budget_available(context)
100 );
101
102 let mut is_pending = false;
103 let start = $crate::__celld_domain_select!(@start $mode BRANCHES);
104
105 for offset in 0..BRANCHES {
106 let branch;
107 #[allow(clippy::modulo_one)]
108 {
109 branch = (start + offset) % BRANCHES;
110 }
111 match branch {
112 $(
113 #[allow(unreachable_code)]
114 $crate::__asyncrt_select_support::count!($($skip)*) => {
115 let mask = 1 << branch;
116 if disabled & mask == mask {
117 continue;
118 }
119
120 let ($($skip,)* future, ..) = &mut *futures;
121 // SAFETY: The tuple stays on the stack and no future moves.
122 let future = unsafe {
123 $crate::__asyncrt_select_support::Pin::new_unchecked(future)
124 };
125 let value = match $crate::__asyncrt_select_support::Future::poll(
126 future,
127 context,
128 ) {
129 $crate::__asyncrt_select_support::Poll::Ready(value) => value,
130 $crate::__asyncrt_select_support::Poll::Pending => {
131 is_pending = true;
132 continue;
133 }
134 };
135
136 disabled |= mask;
137 #[allow(unreachable_patterns, unused_variables, unused_mut)]
138 match &value {
139 $crate::__asyncrt_select_support::select_priv_clean_pattern!(
140 $bind
141 ) => {}
142 _ => continue,
143 }
144
145 return $crate::__asyncrt_select_support::Poll::Ready(
146 $crate::__asyncrt_select_support::select_variant!(
147 __celld_select_util::Out,
148 ($($skip)*)
149 )(value),
150 );
151 }
152 )*
153 _ => unreachable!("the select branch index is out of range"),
154 }
155 }
156
157 if is_pending {
158 $crate::__asyncrt_select_support::Poll::Pending
159 } else {
160 $crate::__asyncrt_select_support::Poll::Ready(
161 __celld_select_util::Out::Disabled,
162 )
163 }
164 })
165 .await
166 };
167
168 #[allow(unreachable_patterns)]
169 match output {
170 $(
171 $crate::__asyncrt_select_support::select_variant!(
172 __celld_select_util::Out,
173 ($($skip)*) ($bind)
174 ) => $handler,
175 )*
176 __celld_select_util::Out::Disabled => $else,
177 _ => unreachable!("the select output does not match a branch"),
178 }
179 }};
180
181 (@ { mode=$mode:tt; $($tokens:tt)* }) => {
182 $crate::__celld_domain_select!(@ {
183 mode=$mode;
184 $($tokens)*;
185 panic!("all branches are disabled and there is no else branch")
186 })
187 };
188 (@ { mode=$mode:tt; $($tokens:tt)* } else => $else:expr $(,)?) => {
189 $crate::__celld_domain_select!(@ { mode=$mode; $($tokens)*; $else })
190 };
191 (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
192 $pattern:pat = $future:expr, if $condition:expr => $handler:block, $($rest:tt)*) => {
193 $crate::__celld_domain_select!(@ {
194 mode=$mode;
195 ($($skip)* _)
196 $($tokens)*
197 ($($skip)*) $pattern = $future, if $condition => $handler,
198 } $($rest)*)
199 };
200 (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
201 $pattern:pat = $future:expr => $handler:block, $($rest:tt)*) => {
202 $crate::__celld_domain_select!(@ {
203 mode=$mode;
204 ($($skip)* _)
205 $($tokens)*
206 ($($skip)*) $pattern = $future, if true => $handler,
207 } $($rest)*)
208 };
209 (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
210 $pattern:pat = $future:expr, if $condition:expr => $handler:block $($rest:tt)*) => {
211 $crate::__celld_domain_select!(@ {
212 mode=$mode;
213 ($($skip)* _)
214 $($tokens)*
215 ($($skip)*) $pattern = $future, if $condition => $handler,
216 } $($rest)*)
217 };
218 (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
219 $pattern:pat = $future:expr => $handler:block $($rest:tt)*) => {
220 $crate::__celld_domain_select!(@ {
221 mode=$mode;
222 ($($skip)* _)
223 $($tokens)*
224 ($($skip)*) $pattern = $future, if true => $handler,
225 } $($rest)*)
226 };
227 (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
228 $pattern:pat = $future:expr, if $condition:expr => $handler:expr) => {
229 $crate::__celld_domain_select!(@ {
230 mode=$mode;
231 ($($skip)* _)
232 $($tokens)*
233 ($($skip)*) $pattern = $future, if $condition => $handler,
234 })
235 };
236 (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
237 $pattern:pat = $future:expr => $handler:expr) => {
238 $crate::__celld_domain_select!(@ {
239 mode=$mode;
240 ($($skip)* _)
241 $($tokens)*
242 ($($skip)*) $pattern = $future, if true => $handler,
243 })
244 };
245 (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
246 $pattern:pat = $future:expr, if $condition:expr => $handler:expr, $($rest:tt)*) => {
247 $crate::__celld_domain_select!(@ {
248 mode=$mode;
249 ($($skip)* _)
250 $($tokens)*
251 ($($skip)*) $pattern = $future, if $condition => $handler,
252 } $($rest)*)
253 };
254 (@ { mode=$mode:tt; ($($skip:tt)*) $($tokens:tt)* }
255 $pattern:pat = $future:expr => $handler:expr, $($rest:tt)*) => {
256 $crate::__celld_domain_select!(@ {
257 mode=$mode;
258 ($($skip)* _)
259 $($tokens)*
260 ($($skip)*) $pattern = $future, if true => $handler,
261 } $($rest)*)
262 };
263
264 (biased; $($tokens:tt)*) => {
265 compile_error!(
266 "select! is fair and does not accept `biased;`; use select_biased! with a reason"
267 )
268 };
269 (else => $else:expr $(,)?) => {{ $else }};
270 ($pattern:pat = $($tokens:tt)*) => {
271 $crate::__celld_domain_select!(@ {
272 mode=fair;
273 ()
274 } $pattern = $($tokens)*)
275 };
276 () => {
277 compile_error!("select! requires at least one branch")
278 };
279}
280
281#[doc(hidden)]
282#[macro_export]
283macro_rules! __celld_domain_select_biased {
284 ($reason:literal; else => $else:expr $(,)?) => {{
285 $crate::__celld_domain_select!(@reason $reason);
286 $else
287 }};
288 ($reason:literal; $pattern:pat = $($tokens:tt)*) => {{
289 $crate::__celld_domain_select!(@ {
290 mode=(biased $reason);
291 ()
292 } $pattern = $($tokens)*)
293 }};
294 ($($tokens:tt)*) => {
295 compile_error!("select_biased! requires a non-empty reason string as its first token")
296 };
297}
298
299pub mod actor;
300#[cfg(all(test, celld_internal_tests))]
301mod conformance_core_loop_tests {
302 include!(env!("CELLD_CONFORMANCE_CORE_LOOP_TESTS"));
303}
304#[cfg(all(test, celld_internal_tests))]
305mod conformance_facet_failure_tests {
306 include!(env!("CELLD_CONFORMANCE_FACET_FAILURE_TESTS"));
307}
308pub mod assets;
309#[cfg(not(celld_internal_tests))]
310pub mod asyncrt;
311// The corpus flag alone selects the simulated asyncrt, so an external
312// test harness built with the flag sees the same simulated world the
313// in-crate suites see. `test` must not be part of the gate:
314// a dependency never has it, and the harness binary builds unflagged,
315// so the shipped and harness builds keep the real asyncrt.
316#[cfg(celld_internal_tests)]
317#[allow(clippy::disallowed_methods, clippy::disallowed_types)]
318pub mod asyncrt {
319 include!(env!("CELLD_INTERNAL_ASYNCRT"));
320}
321#[cfg(all(test, celld_internal_tests))]
322mod asyncrt_contract_tests {
323 include!(env!("CELLD_INTERNAL_ASYNCRT_TESTS"));
324}
325pub mod bucket;
326pub mod cell_cli;
327pub mod cli_options;
328pub mod cli_output;
329pub mod container;
330pub mod control_plane;
331pub mod d1_cli;
332pub mod dead_node_gc;
333pub mod deploy;
334pub mod dev;
335pub mod docker;
336pub mod drain_token;
337pub mod env_vars;
338#[cfg(celld_internal_tests)]
339#[allow(clippy::disallowed_methods)]
340#[doc(hidden)]
341pub mod fault {
342 include!(env!("CELLD_INTERNAL_SQLITE_FAULT"));
343}
344pub mod fleet;
345pub mod generation;
346pub mod host_services;
347pub mod js;
348pub mod kv_cli;
349pub(crate) mod local_store;
350pub mod ltx_repl;
351pub mod machine;
352pub mod memory;
353pub mod node_log;
354pub(crate) mod operator_cell;
355#[doc(hidden)]
356pub mod otlp;
357pub mod ownership_store;
358pub mod peer_auth;
359pub mod peer_probe;
360pub mod pool;
361pub mod protocol;
362pub(crate) mod queue_batching;
363pub mod queue_cli;
364pub mod replication;
365pub mod runtime;
366pub mod startup;
367pub mod storage;
368pub mod telemetry;
369pub mod wake;
370pub mod wake_format;
371pub mod ws_client;
372
373#[cfg(all(test, celld_internal_tests))]
374mod composed_simulation {
375 include!(env!("CELLD_INTERNAL_COMPOSED_SIMULATION"));
376}
377
378#[cfg(all(test, celld_internal_tests))]
379mod simulation_reproduction {
380 include!(env!("CELLD_INTERNAL_SIMULATION_REPRODUCTION"));
381}
382
383#[cfg(all(test, celld_internal_tests))]
384mod token_lifecycle_tests {
385 include!(env!("CELLD_INTERNAL_TOKEN_PROBE"));
386}
387
388#[cfg(all(test, celld_internal_tests))]
389mod conformance_world_tests {
390 include!(env!("CELLD_CONFORMANCE_WORLD_TESTS"));
391}
392
393#[cfg(all(test, celld_internal_tests))]
394#[allow(clippy::disallowed_methods)]
395mod conformance_world_s2_tests {
396 include!(env!("CELLD_CONFORMANCE_WORLD_S2_TESTS"));
397}
398
399#[cfg(all(test, celld_internal_tests))]
400#[allow(clippy::disallowed_methods)]
401mod conformance_o3_oracle {
402 include!(env!("CELLD_CONFORMANCE_O3_ORACLE_TESTS"));
403}
404
405#[cfg(all(test, celld_internal_tests))]
406#[allow(clippy::disallowed_methods)]
407mod conformance_world_s5a_tests {
408 include!(env!("CELLD_CONFORMANCE_WORLD_S5A_TESTS"));
409}
410
411#[cfg(all(test, celld_internal_tests))]
412#[allow(clippy::disallowed_methods)]
413mod conformance_world_s5c_tests {
414 include!(env!("CELLD_CONFORMANCE_WORLD_S5C_TESTS"));
415}
416
417#[cfg(celld_internal_tests)]
418#[allow(clippy::disallowed_methods)]
419#[doc(hidden)]
420pub mod conformance_sim_store {
421 include!(env!("CELLD_CONFORMANCE_SIM_STORE_TESTS"));
422}
423
424#[cfg(celld_internal_tests)]
425#[allow(clippy::disallowed_methods)]
426#[doc(hidden)]
427pub mod conformance_sim_cell_host {
428 include!(env!("CELLD_CONFORMANCE_SIM_CELL_HOST_TESTS"));
429}
430
431#[cfg(all(test, celld_internal_tests))]
432#[allow(clippy::disallowed_methods)]
433pub(crate) mod conformance_world_s1_tests {
434 include!(env!("CELLD_CONFORMANCE_WORLD_S1_TESTS"));
435}
436
437#[cfg(all(test, celld_internal_tests))]
438#[allow(clippy::disallowed_methods)]
439pub(crate) mod conformance_world_coverage {
440 include!(env!("CELLD_CONFORMANCE_WORLD_COVERAGE_TESTS"));
441}
442
443#[cfg(all(test, celld_internal_tests))]
444#[allow(clippy::disallowed_methods)]
445mod conformance_world_s3_tests {
446 include!(env!("CELLD_CONFORMANCE_WORLD_S3_TESTS"));
447}
448
449#[cfg(all(test, celld_internal_tests))]
450#[allow(clippy::disallowed_methods)]
451mod conformance_world_s5b_tests {
452 include!(env!("CELLD_CONFORMANCE_WORLD_S5B_TESTS"));
453}
454
455/// Completion token for a resident-isolate reservation made by the decision
456/// core. Dropping the queued/running job reports that the cell is idle again;
457/// the token contains no selection or lifecycle policy of its own.
458pub struct CellActivityGuard {
459 finish: Option<Box<dyn FnOnce() + Send>>,
460}
461
462impl CellActivityGuard {
463 pub fn new(finish: impl FnOnce() + Send + 'static) -> Self {
464 Self {
465 finish: Some(Box::new(finish)),
466 }
467 }
468}
469
470impl Drop for CellActivityGuard {
471 fn drop(&mut self) {
472 if let Some(finish) = self.finish.take() {
473 finish();
474 }
475 }
476}
477
478/// A stateless entrypoint selected for one fetch request.
479#[derive(Clone, Debug, PartialEq)]
480pub struct WorkerFetchEntrypoint {
481 pub name: String,
482 /// The caller's `ctx.props` as V8 structured-clone bytes. An empty vector
483 /// represents an omitted or `undefined` props value.
484 pub props: Vec<u8>,
485}
486
487/// One operation on a Worker entrypoint. A property read has no arguments,
488/// while a call owns its complete receiver path and structured-clone payload.
489pub enum WorkerRpcOperation {
490 Get { path: Vec<String> },
491 Call { path: Vec<String>, args: Vec<u8> },
492}
493
494pub enum WorkerJob {
495 Fetch {
496 queued_at: std::time::Instant,
497 /// An entrypoint dispatcher target, or the direct default export when
498 /// absent.
499 entrypoint: Option<WorkerFetchEntrypoint>,
500 url: String,
501 method: String,
502 body: js::RequestBody,
503 headers: Vec<(String, String)>,
504 request_id: Option<js::RequestId>,
505 reply: tokio::sync::oneshot::Sender<anyhow::Result<js::HttpResponse>>,
506 },
507 Rpc {
508 entrypoint: String,
509 operation: WorkerRpcOperation,
510 /// The caller's `ctx.props` as V8 structured-clone bytes, the same
511 /// encoding as `args`. It is empty when the caller sent none, which no
512 /// encoded value can be. A Worker Loader entrypoint or a transferred
513 /// Service Binding can set it.
514 props: Vec<u8>,
515 reply: tokio::sync::oneshot::Sender<anyhow::Result<Vec<u8>>>,
516 },
517 Queue {
518 queued_at: std::time::Instant,
519 batch: js::QueueBatch,
520 reply: tokio::sync::oneshot::Sender<anyhow::Result<js::QueueDispatchResult>>,
521 },
522}
523
524/// Temporary host seam required by the verbatim JS adapter. The runtime
525/// adapter will construct the real shared Worker queue; lifecycle policy does
526/// not move into this type.
527/// Compatibility switches copied with the JS adapter. These are runtime
528/// semantics, not lifecycle decisions.
529pub fn worker_compat(metadata: &serde_json::Value) -> js::Compat {
530 let flags = metadata
531 .get("compatibility_flags")
532 .and_then(serde_json::Value::as_array);
533 let has_flag = |name: &str| {
534 flags.is_some_and(|flags| {
535 flags
536 .iter()
537 .any(|flag| flag.as_str().is_some_and(|flag| flag == name))
538 })
539 };
540 let date = metadata
541 .get("compatibility_date")
542 .and_then(serde_json::Value::as_str);
543 let switch = |enable: &str, disable: &str, since: &str| {
544 if has_flag(enable) {
545 return true;
546 }
547 if has_flag(disable) {
548 return false;
549 }
550 date.is_some_and(|date| date >= since)
551 };
552 js::Compat {
553 delete_all_deletes_alarm: switch(
554 "delete_all_deletes_alarm",
555 "delete_all_preserves_alarm",
556 "2026-02-24",
557 ),
558 js_rpc: has_flag("js_rpc"),
559 fetcher_get_put_delete: !switch(
560 "fetcher_no_get_put_delete",
561 "fetcher_has_get_put_delete",
562 "2024-03-26",
563 ),
564 sqlite_vec: has_flag("sqlite_vec"),
565 websocket_standard_binary_type: has_flag("websocket_standard_binary_type"),
566 queue_json_messages: switch("queue_json_messages", "queue_v8_messages", "2024-03-18"),
567 }
568}