1use std::any::Any;
2use std::cell::RefCell;
3use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
4use std::future::Future;
5use std::marker::PhantomData;
6use std::pin::Pin;
7use std::rc::{Rc, Weak};
8use std::time::Duration;
9
10use crate::RuntimeId;
11use crate::arena::{Arena, Key};
12#[path = "dependencies.rs"]
13mod dependencies;
14use dependencies::Dependencies;
15#[path = "subscribers.rs"]
16mod subscribers;
17use glory_render::profile::{Phase, Profile};
18use subscribers::Subscribers;
19#[path = "fields.rs"]
20mod fields;
21#[path = "keyed.rs"]
22mod keyed;
23pub use keyed::{KeyedEntry, KeyedList, ListError, RowToken};
24#[path = "selector.rs"]
25mod selector;
26pub use selector::{Selected, Selector, SelectorStats};
27
28pub type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
29type Cancel = Box<dyn FnOnce()>;
30type Value = Rc<RefCell<Box<dyn Any>>>;
31type Mapper = Rc<dyn Fn() -> Box<dyn Any>>;
32type Equal = Rc<dyn Fn(&dyn Any, &dyn Any) -> bool>;
33type Callback = Rc<RefCell<dyn FnMut()>>;
34type Shared = Rc<RefCell<State>>;
35const QUEUE_SLACK: usize = 64;
36
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct HostError(pub String);
39impl std::fmt::Display for HostError {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 f.write_str(&self.0)
42 }
43}
44impl std::error::Error for HostError {}
45
46pub trait Host {
50 fn spawn(&self, future: LocalFuture) -> Result<Cancel, HostError>;
51 fn wake(&self);
52 fn now(&self) -> Duration;
53}
54
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub enum AccessError {
57 RuntimeGone,
58 Disposed,
59 WrongRuntime,
60 Borrowed,
61 TypeMismatch,
62 Cycle,
63 WriteDuringCompute,
64 ReentrantFlush,
65 RunawayEffect,
66 NoHost,
67 Host(HostError),
68 InvalidField(&'static str),
69 MissingField,
70 OutOfBounds,
71 Capacity,
72}
73impl std::fmt::Display for AccessError {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 write!(f, "{self:?}")
76 }
77}
78impl std::error::Error for AccessError {}
79
80#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
81pub struct RuntimeStats {
82 pub source_writes: u64,
83 pub marked: u64,
84 pub validations: u64,
85 pub derived_runs: u64,
86 pub binding_runs: u64,
87 pub structural_runs: u64,
88 pub effect_runs: u64,
89 pub nodes: usize,
90 pub node_slots: usize,
91 pub owners: usize,
92 pub owner_slots: usize,
93 pub instances: usize,
94 pub instance_slots: usize,
95 pub tasks: usize,
96 pub task_slots: usize,
97 pub edges: usize,
98 pub queued: usize,
99 pub queue_entries: usize,
101 pub queue_capacity: usize,
103 pub queue_compactions: u64,
104 pub queue_compaction_visits: u64,
106 pub fields: usize,
107 pub field_slots: usize,
108 pub entry_keys: usize,
109 pub entry_buckets: usize,
110 pub field_target_builds: u64,
111 pub field_target_hits: u64,
112 pub field_target_visits: u64,
113 pub field_target_caches: usize,
114 pub field_target_keys: usize,
115}
116
117#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
121pub struct GraphStats {
122 pub nodes: [usize; 5],
123 pub dependencies: [[usize; 7]; 5],
124 pub subscribers: [[usize; 7]; 5],
125}
126
127#[derive(Clone, Copy, PartialEq, Eq)]
128enum Mode {
129 Pure,
130 Effect,
131}
132#[derive(Clone, Copy, PartialEq, Eq)]
133enum Status {
134 Clean,
135 Check,
136 Dirty,
137 Computing,
138}
139
140#[derive(Clone)]
141enum Compute {
142 Source,
143 Derived {
144 mapper: Mapper,
145 equal: Option<Equal>,
146 },
147 Binding(Callback),
148 Structure(Callback),
149 Effect(Callback),
150}
151
152struct Node {
153 owner: Key,
154 compute: Compute,
155 value: Option<Value>,
156 version: u64,
157 status: Status,
158 rerun: bool,
159 propagated: bool,
163 queued: bool,
164 last_flush: u64,
165 flush_runs: u32,
166 dependencies: Dependencies,
167 subscribers: Subscribers,
168}
169
170#[derive(Default)]
171struct OwnerData {
172 parent: Option<Key>,
173 children: BTreeSet<Key>,
174 nodes: BTreeSet<Key>,
175 tasks: BTreeSet<Key>,
176 cleanup: Vec<Cancel>,
177 instance: Option<Key>,
178}
179
180struct Instance {
181 owner: Key,
182 parent: Option<Key>,
183}
184struct TaskState {
185 owner: Key,
186 cancel: Option<Cancel>,
187}
188
189struct State {
190 pending_invalidations: Vec<Key>,
191 root: Key,
192 nodes: Arena<Node>,
193 owners: Arena<OwnerData>,
194 instances: Arena<Instance>,
195 tasks: Arena<TaskState>,
196 bindings: VecDeque<Key>,
197 structures: VecDeque<Key>,
198 effects: VecDeque<Key>,
199 queued: usize,
200 queue_retired: usize,
201 flushing: bool,
202 batch_depth: usize,
203 flush_epoch: u64,
204 host: Option<Rc<dyn Host>>,
205 stats: RuntimeStats,
206 profile: Option<Profile>,
207 fields: fields::Fields,
208}
209
210struct Frame {
211 runtime: RuntimeId,
212 key: Key,
213 dependencies: Dependencies,
214}
215thread_local! {
216 static RUNTIMES: RefCell<HashMap<RuntimeId, Weak<RefCell<State>>>> = RefCell::new(HashMap::new());
219 static TRACKING: RefCell<Vec<Option<Frame>>> = const { RefCell::new(Vec::new()) };
220 static EVALUATING: RefCell<Vec<Mode>> = const { RefCell::new(Vec::new()) };
221 static CONSTRUCTING: RefCell<Vec<(RuntimeId, Key)>> = const { RefCell::new(Vec::new()) };
222}
223
224fn allow_creation() -> Result<(), AccessError> {
225 if EVALUATING.with_borrow(|stack| stack.last() == Some(&Mode::Pure)) {
226 Err(AccessError::WriteDuringCompute)
227 } else {
228 Ok(())
229 }
230}
231
232fn enter_owner<R>(runtime: RuntimeId, owner: Key, f: impl FnOnce() -> R) -> R {
233 struct Enter(usize);
234 impl Drop for Enter {
235 fn drop(&mut self) {
236 CONSTRUCTING.with_borrow_mut(|stack| stack.truncate(self.0));
237 }
238 }
239 let previous = CONSTRUCTING.with_borrow_mut(|stack| {
240 let len = stack.len();
241 stack.push((runtime, owner));
242 len
243 });
244 let _guard = Enter(previous);
245 f()
246}
247
248fn lookup(runtime: RuntimeId) -> Result<Shared, AccessError> {
249 RUNTIMES
250 .with_borrow(|runtimes| runtimes.get(&runtime).and_then(Weak::upgrade))
251 .ok_or(AccessError::RuntimeGone)
252}
253
254fn check_reader(runtime: RuntimeId) -> Result<(), AccessError> {
255 TRACKING.with_borrow(|stack| {
256 if stack
257 .last()
258 .and_then(Option::as_ref)
259 .is_some_and(|frame| frame.runtime != runtime)
260 {
261 Err(AccessError::WrongRuntime)
262 } else {
263 Ok(())
264 }
265 })
266}
267
268fn track(runtime: RuntimeId, key: Key, version: u64) -> Result<(), AccessError> {
269 TRACKING.with_borrow_mut(|stack| {
270 if let Some(Some(frame)) = stack.last_mut() {
271 if frame.runtime != runtime {
272 return Err(AccessError::WrongRuntime);
273 }
274 frame.dependencies.insert(key, version);
275 }
276 Ok(())
277 })
278}
279
280struct TrackingPause(usize);
281impl Drop for TrackingPause {
282 fn drop(&mut self) {
283 TRACKING.with_borrow_mut(|stack| stack.truncate(self.0));
284 }
285}
286
287pub fn untracked<R>(f: impl FnOnce() -> R) -> R {
290 let previous = TRACKING.with_borrow_mut(|stack| {
291 let len = stack.len();
292 stack.push(None);
293 len
294 });
295 let _guard = TrackingPause(previous);
296 f()
297}
298
299impl State {
300 fn new() -> Self {
301 let mut owners = Arena::default();
302 let root = owners.insert(OwnerData::default());
303 Self {
304 pending_invalidations: Vec::new(),
305 root,
306 owners,
307 nodes: Arena::default(),
308 instances: Arena::default(),
309 tasks: Arena::default(),
310 bindings: VecDeque::new(),
311 structures: VecDeque::new(),
312 effects: VecDeque::new(),
313 queued: 0,
314 queue_retired: 0,
315 flushing: false,
316 batch_depth: 0,
317 flush_epoch: 0,
318 host: None,
319 stats: RuntimeStats::default(),
320 profile: None,
321 fields: fields::Fields::default(),
322 }
323 }
324
325 fn enqueue(&mut self, key: Key) {
326 let Some(node) = self.nodes.get_mut(key) else {
327 return;
328 };
329 let phase = match node.compute {
330 Compute::Structure(_) => 0,
331 Compute::Binding(_) => 1,
332 Compute::Effect(_) => 2,
333 _ => return,
334 };
335 if !node.queued {
336 node.queued = true;
337 self.queued += 1;
338 match phase {
339 0 => self.structures.push_back(key),
340 1 => self.bindings.push_back(key),
341 _ => self.effects.push_back(key),
342 }
343 }
344 }
345
346 fn queue_entries(&self) -> usize {
347 self.structures.len() + self.bindings.len() + self.effects.len()
348 }
349
350 fn compact_queues(&mut self) {
351 debug_assert_eq!(self.queue_entries(), self.queued + self.queue_retired);
352 if self.queue_retired == 0 {
353 return;
354 }
355 let live = self.queued;
356 if live == 0 {
357 self.structures.clear();
359 self.bindings.clear();
360 self.effects.clear();
361 } else if self.queue_retired > live.saturating_add(QUEUE_SLACK) {
362 self.stats.queue_compaction_visits += self.queue_entries() as u64;
365 self.structures.retain(|key| self.nodes.get(*key).is_some());
366 self.bindings.retain(|key| self.nodes.get(*key).is_some());
367 self.effects.retain(|key| self.nodes.get(*key).is_some());
368 } else {
369 return;
370 }
371 self.queue_retired = 0;
372 self.stats.queue_compactions += 1;
373 }
374
375 fn next_observer(&mut self) -> Option<Key> {
376 loop {
377 let key = self
378 .structures
379 .pop_front()
380 .or_else(|| self.bindings.pop_front())
381 .or_else(|| self.effects.pop_front())?;
382 if let Some(node) = self.nodes.get_mut(key)
383 && node.queued
384 {
385 node.queued = false;
386 self.queued -= 1;
387 self.compact_queues();
390 return Some(key);
391 }
392 self.queue_retired -= 1;
393 }
394 }
395
396 fn invalidate(&mut self) {
398 while let Some(key) = self.pending_invalidations.pop() {
399 let Some(node) = self.nodes.get_mut(key) else {
400 continue;
401 };
402 if node.propagated {
403 continue;
404 }
405 node.propagated = true;
406 self.stats.marked += 1;
407 match node.status {
408 Status::Clean => node.status = Status::Check,
409 Status::Computing => node.rerun = true,
410 _ => {}
411 }
412 self.pending_invalidations
413 .extend(node.subscribers.iter().copied());
414 self.enqueue(key);
415 }
416 }
417
418 fn publish(&mut self, key: Key) {
419 let Some(node) = self.nodes.get_mut(key) else {
420 return;
421 };
422 node.version = node
423 .version
424 .checked_add(1)
425 .expect("source version exhausted");
426 self.stats.source_writes += 1;
427 if node.propagated {
428 return;
429 }
430 node.propagated = true;
431 self.pending_invalidations
432 .extend(node.subscribers.iter().copied());
433 self.invalidate();
434 }
435
436 fn insert_node(&mut self, owner: Key, node: Node) -> Result<Key, AccessError> {
437 let owner = self.owners.get_mut(owner).ok_or(AccessError::Disposed)?;
438 let key = self.nodes.insert(node);
439 owner.nodes.insert(key);
440 self.enqueue(key);
441 Ok(key)
442 }
443
444 fn remove_node(&mut self, key: Key, cleanup: &mut Cleanup) {
445 let Some(node) = self.nodes.remove(key) else {
446 return;
447 };
448 if let Some(owner) = self.owners.get_mut(node.owner) {
449 owner.nodes.remove(&key);
450 }
451 for source in node.dependencies.keys() {
452 if let Some(source) = self.nodes.get_mut(*source) {
453 source.subscribers.remove(&key);
454 }
455 }
456 if node.queued {
457 self.queued -= 1;
458 self.queue_retired += 1;
461 self.compact_queues();
462 }
463 self.pending_invalidations
464 .extend(node.subscribers.iter().copied());
465 self.invalidate();
466 if self.pending_invalidations.capacity() / 2 > self.nodes.len() {
468 self.pending_invalidations = Vec::new();
469 }
470 let removal = self.fields.detach(key, node.owner);
471 cleanup.fields.extend(removal.fields);
472 cleanup.nodes.push(node);
473 for alias in removal.aliases {
474 self.remove_node(alias, cleanup);
475 }
476 }
477
478 fn remove_task(&mut self, key: Key) -> Option<TaskState> {
479 let task = self.tasks.remove(key)?;
480 if let Some(owner) = self.owners.get_mut(task.owner) {
481 owner.tasks.remove(&key);
482 }
483 Some(task)
484 }
485
486 fn dispose_owner(&mut self, key: Key) -> Cleanup {
487 let mut cleanup = Cleanup::default();
488 let Some(mut owner) = self.owners.remove(key) else {
489 return cleanup;
490 };
491 let mut pending = Vec::new();
494 let mut key = key;
495 loop {
496 if let Some(parent) = owner.parent.and_then(|parent| self.owners.get_mut(parent)) {
497 parent.children.remove(&key);
498 }
499 pending.extend(owner.children);
500 if let Some(instance) = owner.instance {
501 self.instances.remove(instance);
502 }
503 if !owner.cleanup.is_empty() {
504 cleanup.callbacks.push((key, owner.cleanup));
505 }
506 for task in owner.tasks {
507 if let Some(task) = self.remove_task(task) {
508 cleanup.tasks.push(task);
509 }
510 }
511 for node in owner.nodes {
512 self.remove_node(node, &mut cleanup);
513 }
514 loop {
515 let Some(next) = pending.pop() else {
516 return cleanup;
517 };
518 if let Some(next_owner) = self.owners.remove(next) {
519 key = next;
520 owner = next_owner;
521 break;
522 }
523 }
524 }
525 }
526}
527
528#[derive(Default)]
529struct Cleanup {
530 nodes: Vec<Node>,
531 tasks: Vec<TaskState>,
532 callbacks: Vec<(Key, Vec<Cancel>)>,
533 fields: Vec<fields::FieldData>,
534}
535impl Cleanup {
536 fn run(self, runtime: RuntimeId) {
537 for task in self.tasks {
540 if let Some(cancel) = task.cancel {
541 untracked(|| enter_owner(runtime, task.owner, cancel));
542 }
543 }
544 for (owner, callbacks) in self.callbacks.into_iter().rev() {
545 untracked(|| {
546 enter_owner(runtime, owner, || {
547 for callback in callbacks.into_iter().rev() {
548 callback();
549 }
550 });
551 });
552 }
553 drop(self.nodes);
554 drop(self.fields);
555 }
556}
557
558struct Evaluation {
559 state: Shared,
560 key: Key,
561 frame: Option<usize>,
562 complete: bool,
563}
564impl Evaluation {
565 fn new(state: &Shared, key: Key, mode: Mode) -> Self {
566 EVALUATING.with_borrow_mut(|stack| stack.push(mode));
567 Self {
568 state: state.clone(),
569 key,
570 frame: None,
571 complete: false,
572 }
573 }
574
575 fn start_tracking(&mut self, runtime: RuntimeId) {
576 self.frame = Some(TRACKING.with_borrow_mut(|stack| {
577 let previous = stack.len();
578 stack.push(Some(Frame {
579 runtime,
580 key: self.key,
581 dependencies: Dependencies::new(),
582 }));
583 previous
584 }));
585 }
586
587 fn dependencies(&mut self) -> Dependencies {
588 self.frame.take();
589 TRACKING.with_borrow_mut(|stack| {
590 let frame = stack.pop().flatten().expect("evaluation tracking frame");
591 debug_assert_eq!(frame.key, self.key);
592 frame.dependencies
593 })
594 }
595}
596
597impl Drop for Evaluation {
598 fn drop(&mut self) {
599 if let Some(previous) = self.frame {
600 TRACKING.with_borrow_mut(|stack| stack.truncate(previous));
601 }
602 if !self.complete {
603 let mut state = self.state.borrow_mut();
604 if let Some(node) = state.nodes.get_mut(self.key) {
605 node.status = Status::Dirty;
606 node.propagated = false;
607 state.enqueue(self.key);
608 }
609 }
610 EVALUATING.with_borrow_mut(|stack| {
611 stack.pop();
612 });
613 }
614}
615
616fn ensure(runtime: RuntimeId, state: &Shared, key: Key) -> Result<(), AccessError> {
617 let (compute, old_status, old_dependencies, old_value, profile) = {
618 let mut state = state.try_borrow_mut().map_err(|_| AccessError::Borrowed)?;
619 let node = state.nodes.get_mut(key).ok_or(AccessError::Disposed)?;
620 if node.status == Status::Computing {
621 return Err(AccessError::Cycle);
622 }
623 if node.status == Status::Clean {
624 return Ok(());
625 }
626 let job = (
627 node.compute.clone(),
628 node.status,
629 node.dependencies.clone(),
630 node.value.clone(),
631 );
632 node.status = Status::Computing;
633 node.propagated = false;
634 for dependency in job.2.keys() {
638 if let Some(source) = state.nodes.get_mut(*dependency) {
639 source.propagated = false;
640 }
641 }
642 state.stats.validations += 1;
643 (job.0, job.1, job.2, job.3, state.profile.clone())
644 };
645 let _validation = profile.as_ref().map(|profile| {
646 profile
647 .span(Phase::Validate)
648 .work(old_dependencies.len() as u64)
649 });
650 let mode = if matches!(compute, Compute::Effect(_) | Compute::Structure(_)) {
651 Mode::Effect
652 } else {
653 Mode::Pure
654 };
655 let mut evaluation = Evaluation::new(state, key, mode);
656 if old_status == Status::Check {
657 let mut changed = false;
658 for (dependency, version) in &old_dependencies {
659 if state.borrow().nodes.get(*dependency).is_none() {
660 changed = true;
661 continue;
662 }
663 ensure(runtime, state, *dependency)?;
664 changed |= state
665 .borrow()
666 .nodes
667 .get(*dependency)
668 .is_none_or(|source| source.version != *version);
669 }
670 if !changed {
671 if let Some(node) = state.borrow_mut().nodes.get_mut(key) {
672 node.status = Status::Clean;
673 }
674 evaluation.complete = true;
675 return Ok(());
676 }
677 }
678
679 evaluation.start_tracking(runtime);
680 let output = {
681 let phase = match &compute {
682 Compute::Derived { .. } => Some(Phase::Derive),
683 Compute::Binding(_) => Some(Phase::Bind),
684 Compute::Structure(_) => Some(Phase::Structure),
685 Compute::Effect(_) => Some(Phase::Effect),
686 Compute::Source => None,
687 };
688 let _compute = profile
689 .as_ref()
690 .zip(phase)
691 .map(|(profile, phase)| profile.span(phase));
692 let owner = state.borrow().nodes.get(key).map(|node| node.owner);
695 if let Some(owner) = owner {
696 enter_owner(runtime, owner, || {
697 Ok::<_, AccessError>(match &compute {
698 Compute::Derived { mapper, .. } => Some(mapper()),
699 Compute::Binding(callback)
700 | Compute::Structure(callback)
701 | Compute::Effect(callback) => {
702 callback
703 .try_borrow_mut()
704 .map_err(|_| AccessError::Borrowed)?();
705 None
706 }
707 Compute::Source => None,
708 })
709 })?
710 } else {
711 None
712 }
713 };
714 let dependencies = evaluation.dependencies();
715 let changed = if let (
716 Some(output),
717 Some(old),
718 Compute::Derived {
719 equal: Some(equal), ..
720 },
721 ) = (&output, &old_value, &compute)
722 {
723 untracked(|| !equal(old.borrow().as_ref(), output.as_ref()))
724 } else {
725 output.is_some()
726 };
727
728 let mut state = state.borrow_mut();
729 if state.nodes.get(key).is_none() {
730 evaluation.complete = true;
731 return Ok(());
732 }
733 for dependency in old_dependencies.keys() {
734 if !dependencies.contains_key(dependency)
735 && let Some(source) = state.nodes.get_mut(*dependency)
736 {
737 source.subscribers.remove(&key);
738 }
739 }
740 let mut needs_rerun = false;
741 for (dependency, version) in &dependencies {
742 if let Some(source) = state.nodes.get_mut(*dependency) {
743 if !old_dependencies.contains_key(dependency) {
746 source.subscribers.insert(key);
747 }
748 source.propagated = false;
751 needs_rerun |= source.version != *version;
752 } else {
753 needs_rerun = true;
754 }
755 }
756 let node = state.nodes.get_mut(key).expect("live evaluation");
757 node.dependencies = dependencies;
758 let discarded = if changed {
759 node.version = node
760 .version
761 .checked_add(1)
762 .expect("derived version exhausted");
763 output.map(|output| node.value.replace(Rc::new(RefCell::new(output))))
764 } else {
765 None
766 };
767 needs_rerun |= node.rerun;
768 node.rerun = false;
769 node.status = if needs_rerun {
770 Status::Check
771 } else {
772 Status::Clean
773 };
774 node.propagated = false;
775 match compute {
776 Compute::Derived { .. } => state.stats.derived_runs += 1,
777 Compute::Binding(_) => state.stats.binding_runs += 1,
778 Compute::Structure(_) => state.stats.structural_runs += 1,
779 Compute::Effect(_) => state.stats.effect_runs += 1,
780 Compute::Source => {}
781 }
782 if needs_rerun {
783 state.enqueue(key);
784 }
785 evaluation.complete = true;
786 drop(state);
787 drop(discarded);
788 Ok(())
789}
790
791pub struct Runtime {
793 id: RuntimeId,
794 state: Shared,
795}
796impl Default for Runtime {
797 fn default() -> Self {
798 Self::new()
799 }
800}
801impl Runtime {
802 pub fn new() -> Self {
803 let id = RuntimeId::new();
804 let state = Rc::new(RefCell::new(State::new()));
805 RUNTIMES.with_borrow_mut(|runtimes| runtimes.insert(id, Rc::downgrade(&state)));
806 Self { id, state }
807 }
808 pub fn with_host(host: Rc<dyn Host>) -> Self {
809 let runtime = Self::new();
810 runtime.state.borrow_mut().host = Some(host);
811 runtime
812 }
813 pub fn id(&self) -> RuntimeId {
814 self.id
815 }
816 pub fn profile(&self) -> Option<Profile> {
817 self.state.borrow().profile.clone()
818 }
819 pub fn set_profile(&self, profile: Option<Profile>) {
820 let previous = std::mem::replace(&mut self.state.borrow_mut().profile, profile);
821 drop(previous);
822 }
823 pub fn now(&self) -> Option<Duration> {
824 self.state.borrow().host.as_ref().map(|host| host.now())
825 }
826 pub fn request_observe(&self) -> bool {
829 let host = self.state.borrow().host.clone();
830 if let Some(host) = host {
831 host.wake();
832 true
833 } else {
834 false
835 }
836 }
837 pub fn owner(&self) -> Owner {
838 let root = self.state.borrow().root;
839 make_owner(self.id, &self.state, root).expect("runtime root is live")
840 }
841 pub fn scope(&self) -> Scope {
842 make_scope(self.owner(), None).expect("runtime is live")
843 }
844
845 #[inline]
850 pub fn enter<R>(&self, instance: InstanceId, f: impl FnOnce() -> R) -> Result<R, AccessError> {
851 if instance.runtime != self.id {
852 return Err(AccessError::WrongRuntime);
853 }
854 let owner = {
855 let state = self.state.borrow();
856 let owner = state
857 .instances
858 .get(instance.key)
859 .ok_or(AccessError::Disposed)?
860 .owner;
861 state.owners.get(owner).ok_or(AccessError::Disposed)?;
862 owner
863 };
864 Ok(enter_owner(self.id, owner, f))
865 }
866
867 pub fn batch<R>(&self, f: impl FnOnce() -> R) -> Result<R, AccessError> {
870 self.state.borrow_mut().batch_depth += 1;
871 struct Batch(Shared);
872 impl Drop for Batch {
873 fn drop(&mut self) {
874 self.0.borrow_mut().batch_depth -= 1;
875 }
876 }
877 let guard = Batch(self.state.clone());
878 let value = f();
879 drop(guard);
880 let flush = {
881 let state = self.state.borrow();
882 state.batch_depth == 0 && !state.flushing
883 };
884 if flush {
885 self.flush()?;
886 }
887 Ok(value)
888 }
889
890 pub fn flush(&self) -> Result<(), AccessError> {
891 if self.state.borrow().batch_depth != 0 {
892 return Ok(());
893 }
894 if self.state.borrow().flushing {
895 return Err(AccessError::ReentrantFlush);
896 }
897 let _span = self.profile().map(|profile| profile.span(Phase::Flush));
898 self.state.borrow_mut().flushing = true;
899 let epoch = {
900 let mut state = self.state.borrow_mut();
901 state.flush_epoch = state
902 .flush_epoch
903 .checked_add(1)
904 .expect("flush epoch exhausted");
905 state.flush_epoch
906 };
907 struct Flush(Shared);
908 impl Drop for Flush {
909 fn drop(&mut self) {
910 self.0.borrow_mut().flushing = false;
911 }
912 }
913 let _guard = Flush(self.state.clone());
914 loop {
915 let key = self.state.borrow_mut().next_observer();
916 let Some(key) = key else { break };
917 {
918 let mut state = self.state.borrow_mut();
919 let Some(node) = state.nodes.get_mut(key) else {
920 continue;
921 };
922 if node.last_flush != epoch {
923 node.last_flush = epoch;
924 node.flush_runs = 0;
925 }
926 node.flush_runs += 1;
927 if node.flush_runs > 1024 {
930 state.enqueue(key);
931 return Err(AccessError::RunawayEffect);
932 }
933 }
934 ensure(self.id, &self.state, key)?;
935 }
936 Ok(())
937 }
938
939 pub fn graph_stats(&self) -> GraphStats {
942 fn bin(degree: usize) -> usize {
943 match degree {
944 0 => 0,
945 1 => 1,
946 2 => 2,
947 3..=4 => 3,
948 5..=8 => 4,
949 9..=64 => 5,
950 _ => 6,
951 }
952 }
953 let state = self.state.borrow();
954 let mut result = GraphStats::default();
955 for node in state.nodes.values() {
956 let kind = match node.compute {
957 Compute::Source => 0,
958 Compute::Derived { .. } => 1,
959 Compute::Structure(_) => 2,
960 Compute::Binding(_) => 3,
961 Compute::Effect(_) => 4,
962 };
963 result.nodes[kind] += 1;
964 result.dependencies[kind][bin(node.dependencies.len())] += 1;
965 result.subscribers[kind][bin(node.subscribers.len())] += 1;
966 }
967 result
968 }
969 pub fn stats(&self) -> RuntimeStats {
970 let state = self.state.borrow();
971 let (entry_keys, entry_buckets) = state.fields.entry_stats();
972 let (field_target_caches, field_target_keys) = state.fields.target_stats();
973 RuntimeStats {
974 nodes: state.nodes.len(),
975 node_slots: state.nodes.capacity(),
976 owners: state.owners.len(),
977 owner_slots: state.owners.capacity(),
978 instances: state.instances.len(),
979 instance_slots: state.instances.capacity(),
980 tasks: state.tasks.len(),
981 task_slots: state.tasks.capacity(),
982 edges: state
983 .nodes
984 .values()
985 .map(|node| node.dependencies.len())
986 .sum(),
987 queued: state.queued,
988 queue_entries: state.queue_entries(),
989 queue_capacity: state.structures.capacity()
990 + state.bindings.capacity()
991 + state.effects.capacity(),
992 fields: state.fields.len(),
993 field_slots: state.fields.capacity(),
994 entry_keys,
995 entry_buckets,
996 field_target_caches,
997 field_target_keys,
998 ..state.stats
999 }
1000 }
1001}
1002impl Drop for Runtime {
1003 fn drop(&mut self) {
1004 RUNTIMES.with_borrow_mut(|runtimes| runtimes.remove(&self.id));
1005 let root = self.state.borrow().root;
1006 let cleanup = self.state.borrow_mut().dispose_owner(root);
1007 cleanup.run(self.id);
1008 }
1009}
1010
1011pub struct Owner {
1012 runtime: RuntimeId,
1013 key: Key,
1014 local: PhantomData<Rc<()>>,
1015}
1016#[derive(Clone, Copy)]
1019pub(crate) struct OwnerHandle {
1020 runtime: RuntimeId,
1021 key: Key,
1022}
1023impl Owner {
1024 pub(crate) fn handle(&self) -> OwnerHandle {
1025 OwnerHandle {
1026 runtime: self.runtime,
1027 key: self.key,
1028 }
1029 }
1030 pub fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
1033 assert!(self.is_alive(), "enter live owner");
1034 enter_owner(self.runtime, self.key, f)
1035 }
1036 pub fn runtime(&self) -> RuntimeId {
1037 self.runtime
1038 }
1039 pub fn is_alive(&self) -> bool {
1040 lookup(self.runtime).is_ok_and(|state| state.borrow().owners.get(self.key).is_some())
1041 }
1042 pub fn check_write(&self) -> Result<(), AccessError> {
1045 allow_creation()?;
1046 let state = lookup(self.runtime)?;
1047 if state.borrow().owners.get(self.key).is_none() {
1048 return Err(AccessError::Disposed);
1049 }
1050 Ok(())
1051 }
1052 pub fn child(&self) -> Self {
1053 make_owner(
1054 self.runtime,
1055 &lookup(self.runtime).expect("live runtime"),
1056 self.key,
1057 )
1058 .expect("live owner")
1059 }
1060 pub fn dispose(&self) {
1061 if let Ok(state) = lookup(self.runtime) {
1062 let cleanup = state.borrow_mut().dispose_owner(self.key);
1063 cleanup.run(self.runtime);
1064 }
1065 }
1066 pub fn on_cleanup(&self, cleanup: impl FnOnce() + 'static) -> Result<(), AccessError> {
1072 let state = lookup(self.runtime)?;
1073 state
1074 .borrow_mut()
1075 .owners
1076 .get_mut(self.key)
1077 .ok_or(AccessError::Disposed)?
1078 .cleanup
1079 .push(Box::new(cleanup));
1080 Ok(())
1081 }
1082
1083 pub fn cage<T: 'static>(&self, value: T) -> Cage<T> {
1084 make_cage(self.runtime, self.key, value).expect("create state under a live non-pure Owner")
1085 }
1086
1087 pub fn compute<T>(&self, f: impl FnOnce() -> T) -> Result<T, AccessError> {
1091 let state = lookup(self.runtime)?;
1092 if state.borrow().owners.get(self.key).is_none() {
1093 return Err(AccessError::Disposed);
1094 }
1095 struct Pure;
1096 impl Drop for Pure {
1097 fn drop(&mut self) {
1098 EVALUATING.with_borrow_mut(|stack| {
1099 stack.pop();
1100 });
1101 }
1102 }
1103 Ok(enter_owner(self.runtime, self.key, || {
1104 EVALUATING.with_borrow_mut(|stack| stack.push(Mode::Pure));
1105 let _pure = Pure;
1106 untracked(f)
1107 }))
1108 }
1109 pub fn bond<T: 'static>(&self, mapper: impl Fn() -> T + 'static) -> Bond<T> {
1110 make_bond(self.runtime, self.key, mapper).expect("live owner")
1111 }
1112
1113 pub fn binding(&self, callback: impl FnMut() + 'static) -> BindingId {
1114 self.observer(callback, 1)
1115 }
1116 pub fn effect(&self, callback: impl FnMut() + 'static) -> BindingId {
1119 self.observer(callback, 2)
1120 }
1121 pub fn structural(&self, callback: impl FnMut() + 'static) -> BindingId {
1124 self.observer(callback, 0)
1125 }
1126 fn observer(&self, callback: impl FnMut() + 'static, phase: u8) -> BindingId {
1127 allow_creation().expect("observer creation is not allowed in a pure computation");
1128 let callback: Callback = Rc::new(RefCell::new(callback));
1129 let compute = match phase {
1130 0 => Compute::Structure(callback),
1131 1 => Compute::Binding(callback),
1132 _ => Compute::Effect(callback),
1133 };
1134 let node = Node {
1135 owner: self.key,
1136 compute,
1137 value: None,
1138 version: 0,
1139 status: Status::Dirty,
1140 rerun: false,
1141 propagated: false,
1142 queued: false,
1143 last_flush: 0,
1144 flush_runs: 0,
1145 dependencies: Dependencies::new(),
1146 subscribers: Subscribers::new(),
1147 };
1148 let key = lookup(self.runtime)
1149 .expect("live runtime")
1150 .borrow_mut()
1151 .insert_node(self.key, node)
1152 .expect("live owner");
1153 BindingId {
1154 runtime: self.runtime,
1155 key,
1156 local: PhantomData,
1157 }
1158 }
1159
1160 pub fn task(&self) -> Task {
1161 self.handle().task()
1162 }
1163
1164 pub fn spawn(
1165 &self,
1166 future: impl Future<Output = ()> + 'static,
1167 ) -> Result<TaskToken, AccessError> {
1168 self.handle().spawn(future)
1169 }
1170}
1171
1172fn make_cage<T: 'static>(runtime: RuntimeId, owner: Key, value: T) -> Result<Cage<T>, AccessError> {
1173 allow_creation()?;
1174 let node = Node {
1175 owner,
1176 compute: Compute::Source,
1177 value: Some(Rc::new(RefCell::new(Box::new(value)))),
1178 version: 1,
1179 status: Status::Clean,
1180 rerun: false,
1181 propagated: false,
1182 queued: false,
1183 last_flush: 0,
1184 flush_runs: 0,
1185 dependencies: Dependencies::new(),
1186 subscribers: Subscribers::new(),
1187 };
1188 let key = lookup(runtime)?.borrow_mut().insert_node(owner, node)?;
1189 Ok(Cage {
1190 handle: Handle::new(runtime, key),
1191 })
1192}
1193impl OwnerHandle {
1194 fn task(self) -> Task {
1195 allow_creation().expect("task creation is not allowed in a pure computation");
1196 let state = lookup(self.runtime).expect("live runtime");
1197 let mut state = state.borrow_mut();
1198 assert!(state.owners.get(self.key).is_some(), "live owner");
1199 let key = state.tasks.insert(TaskState {
1200 owner: self.key,
1201 cancel: None,
1202 });
1203 state
1204 .owners
1205 .get_mut(self.key)
1206 .expect("live owner")
1207 .tasks
1208 .insert(key);
1209 Task {
1210 token: TaskToken {
1211 runtime: self.runtime,
1212 key,
1213 local: PhantomData,
1214 },
1215 detached: false,
1216 }
1217 }
1218
1219 pub(crate) fn spawn(
1220 self,
1221 future: impl Future<Output = ()> + 'static,
1222 ) -> Result<TaskToken, AccessError> {
1223 allow_creation()?;
1224 let state = lookup(self.runtime)?;
1225 if state.borrow().owners.get(self.key).is_none() {
1226 return Err(AccessError::Disposed);
1227 }
1228 let host = state.borrow().host.clone().ok_or(AccessError::NoHost)?;
1229 let task = self.task();
1230 let token = task.token();
1231 struct Completion(TaskToken);
1232 impl Drop for Completion {
1233 fn drop(&mut self) {
1234 finish_task(self.0, false);
1235 }
1236 }
1237 let cancel = host
1238 .spawn(Box::pin(async move {
1239 let _completion = Completion(token);
1240 if token.is_current() {
1241 let mut future = Box::pin(future);
1242 std::future::poll_fn(move |context| {
1243 let Ok(state) = lookup(token.runtime) else {
1244 return std::task::Poll::Ready(());
1245 };
1246 let owner = state.borrow().tasks.get(token.key).map(|task| task.owner);
1247 let Some(owner) = owner else {
1248 return std::task::Poll::Ready(());
1249 };
1250 let profile = state.borrow().profile.clone();
1251 let _span = profile.map(|profile| profile.span(Phase::Task));
1252 enter_owner(token.runtime, owner, || future.as_mut().poll(context))
1253 })
1254 .await;
1255 }
1256 }))
1257 .map_err(AccessError::Host)?;
1258 let mut cancel = Some(cancel);
1259 if let Some(task) = state.borrow_mut().tasks.get_mut(token.key) {
1260 task.cancel = cancel.take();
1261 }
1262 if let Some(cancel) = cancel {
1263 cancel();
1264 }
1265 Ok(task.detach())
1266 }
1267}
1268impl Drop for Owner {
1269 fn drop(&mut self) {
1270 self.dispose();
1271 }
1272}
1273impl std::fmt::Debug for Owner {
1274 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1275 f.debug_struct("Owner")
1276 .field("runtime", &self.runtime)
1277 .field("key", &self.key)
1278 .finish()
1279 }
1280}
1281
1282fn make_owner(runtime: RuntimeId, state: &Shared, parent: Key) -> Result<Owner, AccessError> {
1283 let mut state = state.borrow_mut();
1284 if state.owners.get(parent).is_none() {
1285 return Err(AccessError::Disposed);
1286 }
1287 let key = state.owners.insert(OwnerData {
1288 parent: Some(parent),
1289 ..OwnerData::default()
1290 });
1291 state
1292 .owners
1293 .get_mut(parent)
1294 .expect("live parent")
1295 .children
1296 .insert(key);
1297 Ok(Owner {
1298 runtime,
1299 key,
1300 local: PhantomData,
1301 })
1302}
1303
1304#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1305pub struct InstanceId {
1306 runtime: RuntimeId,
1307 key: Key,
1308}
1309impl InstanceId {
1310 pub fn child_scope(self) -> Result<Scope, AccessError> {
1313 allow_creation()?;
1314 let state = lookup(self.runtime)?;
1315 let owner = {
1316 let state = state.borrow();
1317 let instance = state.instances.get(self.key).ok_or(AccessError::Disposed)?;
1318 if state.owners.get(instance.owner).is_none() {
1319 return Err(AccessError::Disposed);
1320 }
1321 instance.owner
1322 };
1323 make_scope(make_owner(self.runtime, &state, owner)?, Some(self.key))
1324 }
1325 pub fn is_alive(self) -> bool {
1328 lookup(self.runtime).is_ok_and(|state| {
1329 let state = state.borrow();
1330 state
1331 .instances
1332 .get(self.key)
1333 .is_some_and(|instance| state.owners.get(instance.owner).is_some())
1334 })
1335 }
1336 pub fn runtime(self) -> RuntimeId {
1337 self.runtime
1338 }
1339 pub fn slot(self) -> u32 {
1340 self.key.slot
1341 }
1342 pub fn generation(self) -> u32 {
1343 self.key.generation
1344 }
1345}
1346
1347#[derive(Debug)]
1348pub struct Scope {
1349 owner: Owner,
1350 id: InstanceId,
1351}
1352impl Scope {
1353 pub fn id(&self) -> InstanceId {
1354 self.id
1355 }
1356 pub fn owner(&self) -> &Owner {
1357 &self.owner
1358 }
1359 pub fn has_task_host(&self) -> Result<bool, AccessError> {
1363 let state = lookup(self.id.runtime)?;
1364 let state = state.borrow();
1365 let instance = state
1366 .instances
1367 .get(self.id.key)
1368 .ok_or(AccessError::Disposed)?;
1369 if instance.owner != self.owner.key || state.owners.get(self.owner.key).is_none() {
1370 return Err(AccessError::Disposed);
1371 }
1372 Ok(state.host.is_some())
1373 }
1374 pub fn child(&self) -> Self {
1375 make_scope(self.owner.child(), Some(self.id.key)).expect("live scope")
1376 }
1377 pub fn parent(&self) -> Option<InstanceId> {
1378 let state = lookup(self.id.runtime).ok()?;
1379 let state = state.borrow();
1380 let parent = state.instances.get(self.id.key)?.parent?;
1381 Some(InstanceId {
1382 runtime: self.id.runtime,
1383 key: parent,
1384 })
1385 }
1386 pub fn is_alive(&self) -> bool {
1387 lookup(self.id.runtime).is_ok_and(|state| {
1388 state
1389 .borrow()
1390 .instances
1391 .get(self.id.key)
1392 .is_some_and(|instance| instance.owner == self.owner.key)
1393 })
1394 }
1395}
1396impl std::ops::Deref for Scope {
1397 type Target = Owner;
1398 fn deref(&self) -> &Owner {
1399 &self.owner
1400 }
1401}
1402fn make_scope(owner: Owner, parent: Option<Key>) -> Result<Scope, AccessError> {
1403 let state = lookup(owner.runtime)?;
1404 let mut state = state.borrow_mut();
1405 if state.owners.get(owner.key).is_none() {
1406 return Err(AccessError::Disposed);
1407 }
1408 if let Some(parent) = parent
1409 && state.instances.get(parent).is_none()
1410 {
1411 return Err(AccessError::Disposed);
1412 }
1413 let key = state.instances.insert(Instance {
1414 owner: owner.key,
1415 parent,
1416 });
1417 state
1418 .owners
1419 .get_mut(owner.key)
1420 .expect("live owner")
1421 .instance = Some(key);
1422 Ok(Scope {
1423 id: InstanceId {
1424 runtime: owner.runtime,
1425 key,
1426 },
1427 owner,
1428 })
1429}
1430
1431#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1432pub struct BindingId {
1433 runtime: RuntimeId,
1434 key: Key,
1435 local: PhantomData<Rc<()>>,
1436}
1437impl BindingId {
1438 pub fn dispose(self) {
1439 if let Ok(state) = lookup(self.runtime) {
1440 let mut cleanup = Cleanup::default();
1441 state.borrow_mut().remove_node(self.key, &mut cleanup);
1442 cleanup.run(self.runtime);
1443 }
1444 }
1445 pub fn is_alive(self) -> bool {
1446 lookup(self.runtime).is_ok_and(|state| state.borrow().nodes.get(self.key).is_some())
1447 }
1448}
1449
1450struct Handle<T: 'static> {
1451 runtime: RuntimeId,
1452 key: Key,
1453 local: PhantomData<Rc<T>>,
1454}
1455impl<T> Copy for Handle<T> {}
1456impl<T> Clone for Handle<T> {
1457 fn clone(&self) -> Self {
1458 *self
1459 }
1460}
1461impl<T> Handle<T> {
1462 fn new(runtime: RuntimeId, key: Key) -> Self {
1463 Self {
1464 runtime,
1465 key,
1466 local: PhantomData,
1467 }
1468 }
1469 fn with<R>(self, tracked: bool, f: impl FnOnce(&T) -> R) -> Result<R, AccessError> {
1470 fields::allow_read()?;
1471 if tracked {
1472 check_reader(self.runtime)?;
1473 }
1474 let state = lookup(self.runtime)?;
1475 ensure(self.runtime, &state, self.key)?;
1476 let (path, version) = {
1477 let state = state.borrow();
1478 let node = state.nodes.get(self.key).ok_or(AccessError::Disposed)?;
1479 (state.value_path(self.key, node)?, node.version)
1480 };
1481 if tracked {
1482 track(self.runtime, self.key, version)?;
1483 }
1484 let value = path.value.try_borrow().map_err(|_| AccessError::Borrowed)?;
1485 let value = path.read(value.as_ref())?;
1486 Ok(f(value.downcast_ref().ok_or(AccessError::TypeMismatch)?))
1487 }
1488}
1489
1490pub struct Cage<T: 'static> {
1500 handle: Handle<T>,
1501}
1502pub struct Bond<T: 'static> {
1503 handle: Handle<T>,
1504}
1505macro_rules! read_handle {
1506 ($name:ident) => {
1507 impl<T> Copy for $name<T> {}
1508 impl<T> Clone for $name<T> {
1509 fn clone(&self) -> Self {
1510 *self
1511 }
1512 }
1513 impl<T> std::fmt::Debug for $name<T> {
1514 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1515 f.debug_struct(stringify!($name))
1516 .field("runtime", &self.handle.runtime)
1517 .field("key", &self.handle.key)
1518 .finish()
1519 }
1520 }
1521 impl<T> $name<T> {
1522 pub fn runtime(self) -> RuntimeId {
1523 self.handle.runtime
1524 }
1525 pub fn try_with<R>(self, f: impl FnOnce(&T) -> R) -> Result<R, AccessError> {
1526 self.handle.with(true, f)
1527 }
1528 pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1529 self.try_with(f).expect("read live reactive value")
1530 }
1531 pub fn try_with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> Result<R, AccessError> {
1532 self.handle.with(false, f)
1533 }
1534 pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
1535 self.try_with_untracked(f)
1536 .expect("read live reactive value")
1537 }
1538 pub fn try_get(self) -> Result<T, AccessError>
1539 where
1540 T: Clone,
1541 {
1542 self.try_with(Clone::clone)
1543 }
1544 pub fn get(self) -> T
1545 where
1546 T: Clone,
1547 {
1548 self.with(Clone::clone)
1549 }
1550 pub fn get_untracked(self) -> T
1551 where
1552 T: Clone,
1553 {
1554 self.with_untracked(Clone::clone)
1555 }
1556 pub fn is_alive(self) -> bool {
1557 lookup(self.handle.runtime)
1558 .is_ok_and(|state| state.borrow().nodes.get(self.handle.key).is_some())
1559 }
1560 }
1561 };
1562}
1563read_handle!(Cage);
1564read_handle!(Bond);
1565
1566struct Write {
1567 state: Shared,
1568 key: Key,
1569}
1570impl Drop for Write {
1571 fn drop(&mut self) {
1572 let host = {
1573 let mut state = self.state.borrow_mut();
1574 state.publish(self.key);
1575 state.host.clone()
1576 };
1577 if let Some(host) = host {
1578 host.wake();
1579 }
1580 }
1581}
1582impl<T> Cage<T> {
1583 pub fn try_version(self) -> Result<u64, AccessError> {
1588 fields::allow_read()?;
1589 let state = lookup(self.handle.runtime)?;
1590 let state = state.borrow();
1591 Ok(state
1592 .nodes
1593 .get(self.handle.key)
1594 .ok_or(AccessError::Disposed)?
1595 .version)
1596 }
1597 pub fn try_revise<R>(self, f: impl FnOnce(&mut T) -> R) -> Result<R, AccessError> {
1598 if EVALUATING.with_borrow(|stack| stack.last().is_some_and(|mode| *mode == Mode::Pure)) {
1599 return Err(AccessError::WriteDuringCompute);
1600 }
1601 let state = lookup(self.handle.runtime)?;
1602 let value = {
1603 let state = state.borrow();
1604 let node = state
1605 .nodes
1606 .get(self.handle.key)
1607 .ok_or(AccessError::Disposed)?;
1608 if !matches!(node.compute, Compute::Source) {
1609 return Err(AccessError::TypeMismatch);
1610 }
1611 node.version
1612 .checked_add(1)
1613 .expect("source version exhausted");
1614 if state.fields.has_root(self.handle.key) {
1615 None
1616 } else {
1617 node.value.clone()
1618 }
1619 };
1620 let Some(value) = value else {
1621 return fields::revise(state, self.handle.key, f);
1622 };
1623 let mut borrowed = value.try_borrow_mut().map_err(|_| AccessError::Borrowed)?;
1624 let value = borrowed.downcast_mut().ok_or(AccessError::TypeMismatch)?;
1625 let write = Write {
1626 state,
1627 key: self.handle.key,
1628 };
1629 let result = f(value);
1630 drop(borrowed);
1631 drop(write);
1632 Ok(result)
1633 }
1634 pub fn revise<R>(self, f: impl FnOnce(&mut T) -> R) -> R {
1635 self.try_revise(f)
1636 .expect("revise live reactive value outside pure computation")
1637 }
1638 pub fn map<U: 'static>(self, mapper: impl Fn(&T) -> U + 'static) -> Bond<U> {
1639 let state = lookup(self.handle.runtime).expect("live runtime");
1640 let source_owner = state
1641 .borrow()
1642 .nodes
1643 .get(self.handle.key)
1644 .expect("live source")
1645 .owner;
1646 let owner = CONSTRUCTING.with_borrow(|stack| {
1647 stack
1648 .last()
1649 .filter(|(runtime, _)| *runtime == self.handle.runtime)
1650 .map(|(_, owner)| *owner)
1651 .unwrap_or(source_owner)
1652 });
1653 make_bond(self.handle.runtime, owner, move || self.with(&mapper)).expect("live owner")
1654 }
1655}
1656
1657fn make_bond<T: 'static>(
1658 runtime: RuntimeId,
1659 owner: Key,
1660 mapper: impl Fn() -> T + 'static,
1661) -> Result<Bond<T>, AccessError> {
1662 allow_creation()?;
1663 let key = register_bond(runtime, owner, Rc::new(move || Box::new(mapper())))?;
1664 Ok(Bond {
1665 handle: Handle::new(runtime, key),
1666 })
1667}
1668
1669fn register_bond(runtime: RuntimeId, owner: Key, mapper: Mapper) -> Result<Key, AccessError> {
1671 let compute = Compute::Derived {
1672 mapper,
1673 equal: None,
1674 };
1675 let node = Node {
1676 owner,
1677 compute,
1678 value: None,
1679 version: 0,
1680 status: Status::Dirty,
1681 rerun: false,
1682 propagated: false,
1683 queued: false,
1684 last_flush: 0,
1685 flush_runs: 0,
1686 dependencies: Dependencies::new(),
1687 subscribers: Subscribers::new(),
1688 };
1689 lookup(runtime)?.borrow_mut().insert_node(owner, node)
1690}
1691impl<T> Bond<T> {
1692 pub fn with_eq(self, equal: impl Fn(&T, &T) -> bool + 'static) -> Self {
1693 let state = lookup(self.handle.runtime).expect("live runtime");
1694 let mut state = state.borrow_mut();
1695 let node = state.nodes.get_mut(self.handle.key).expect("live bond");
1696 let Compute::Derived {
1697 equal: comparator, ..
1698 } = &mut node.compute
1699 else {
1700 unreachable!()
1701 };
1702 let previous = comparator.replace(Rc::new(move |a, b| {
1703 equal(
1704 a.downcast_ref().expect("bond type"),
1705 b.downcast_ref().expect("bond type"),
1706 )
1707 }));
1708 drop(state);
1709 drop(previous);
1710 self
1711 }
1712 pub fn with_partial_eq(self) -> Self
1713 where
1714 T: PartialEq,
1715 {
1716 self.with_eq(PartialEq::eq)
1717 }
1718}
1719
1720#[derive(Clone, Debug)]
1721pub enum Vary<T: 'static> {
1722 Value(T),
1723 Cage(Cage<T>),
1724 Bond(Bond<T>),
1725}
1726impl<T> Vary<T> {
1727 pub fn try_with<R>(&self, f: impl FnOnce(&T) -> R) -> Result<R, AccessError> {
1728 match self {
1729 Self::Value(value) => Ok(f(value)),
1730 Self::Cage(value) => value.try_with(f),
1731 Self::Bond(value) => value.try_with(f),
1732 }
1733 }
1734 pub fn try_get(&self) -> Result<T, AccessError>
1735 where
1736 T: Clone,
1737 {
1738 self.try_with(Clone::clone)
1739 }
1740 pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
1741 match self {
1742 Self::Value(value) => f(value),
1743 Self::Cage(value) => value.with(f),
1744 Self::Bond(value) => value.with(f),
1745 }
1746 }
1747 pub fn get(&self) -> T
1748 where
1749 T: Clone,
1750 {
1751 self.with(Clone::clone)
1752 }
1753 pub fn is_reactive(&self) -> bool {
1754 !matches!(self, Self::Value(_))
1755 }
1756}
1757impl<T> From<T> for Vary<T> {
1758 fn from(value: T) -> Self {
1759 Self::Value(value)
1760 }
1761}
1762impl<T> From<Cage<T>> for Vary<T> {
1763 fn from(value: Cage<T>) -> Self {
1764 Self::Cage(value)
1765 }
1766}
1767impl<T> From<Bond<T>> for Vary<T> {
1768 fn from(value: Bond<T>) -> Self {
1769 Self::Bond(value)
1770 }
1771}
1772impl From<&str> for Vary<String> {
1773 fn from(value: &str) -> Self {
1774 Self::Value(value.to_owned())
1775 }
1776}
1777
1778#[derive(Clone, Copy, Debug)]
1779pub struct TaskToken {
1780 runtime: RuntimeId,
1781 key: Key,
1782 local: PhantomData<Rc<()>>,
1783}
1784impl TaskToken {
1785 pub fn is_current(self) -> bool {
1786 lookup(self.runtime).is_ok_and(|state| state.borrow().tasks.get(self.key).is_some())
1787 }
1788 pub fn commit<R>(self, f: impl FnOnce() -> R) -> Result<R, AccessError> {
1789 let state = lookup(self.runtime)?;
1790 let owner = state
1791 .borrow()
1792 .tasks
1793 .get(self.key)
1794 .ok_or(AccessError::Disposed)?
1795 .owner;
1796 Ok(enter_owner(self.runtime, owner, f))
1797 }
1798 pub fn cancel(self) {
1799 finish_task(self, true);
1800 }
1801}
1802
1803pub struct Task {
1804 token: TaskToken,
1805 detached: bool,
1806}
1807impl Task {
1808 pub fn token(&self) -> TaskToken {
1809 self.token
1810 }
1811 pub fn on_cancel(&self, cancel: impl FnOnce() + 'static) -> Result<(), AccessError> {
1812 let state = lookup(self.token.runtime)?;
1813 let mut state = state.borrow_mut();
1814 let task = state
1815 .tasks
1816 .get_mut(self.token.key)
1817 .ok_or(AccessError::Disposed)?;
1818 let previous = task.cancel.take();
1819 task.cancel = Some(Box::new(move || {
1820 if let Some(previous) = previous {
1821 previous();
1822 }
1823 cancel();
1824 }));
1825 Ok(())
1826 }
1827 pub fn detach(mut self) -> TaskToken {
1828 self.detached = true;
1829 self.token
1830 }
1831 pub fn complete(mut self) {
1832 finish_task(self.token, false);
1833 self.detached = true;
1834 }
1835}
1836impl Drop for Task {
1837 fn drop(&mut self) {
1838 if !self.detached {
1839 finish_task(self.token, true);
1840 }
1841 }
1842}
1843fn finish_task(token: TaskToken, cancel: bool) {
1844 if let Ok(state) = lookup(token.runtime) {
1845 let task = state.borrow_mut().remove_task(token.key);
1846 if cancel
1847 && let Some(task) = task
1848 && let Some(cancel) = task.cancel
1849 {
1850 untracked(|| enter_owner(token.runtime, task.owner, cancel));
1851 }
1852 }
1853}
1854
1855#[cfg(test)]
1856mod invalidation_tests {
1857 use super::Runtime;
1858
1859 #[test]
1860 fn retiring_a_wide_graph_releases_its_traversal_buffer() {
1861 let runtime = Runtime::new();
1862 let parent = runtime.owner();
1863 let source = parent.cage(0);
1864 let children = parent.child();
1865 for _ in 0..1024 {
1866 children.binding(move || {
1867 source.get();
1868 });
1869 }
1870 runtime.flush().unwrap();
1871 source.revise(|value| *value += 1);
1872 runtime.flush().unwrap();
1873 assert!(runtime.state.borrow().pending_invalidations.capacity() >= 1024);
1874
1875 children.dispose();
1876 assert_eq!(runtime.state.borrow().pending_invalidations.capacity(), 0);
1877 assert_eq!(source.get(), 1);
1878 }
1879}