query_flow/
asset.rs

1//! Asset types for external resources.
2//!
3//! Assets are external inputs (files, network resources, etc.) that:
4//! - Are always leaves in the dependency graph (no dependencies)
5//! - May need IO to load
6//! - Loading differs by platform (filesystem locally, network/memory in playground)
7//! - Can be depended upon by queries with proper dependency tracking
8
9use std::any::{Any, TypeId};
10use std::fmt::Debug;
11use std::sync::Arc;
12
13use crate::db::Db;
14use crate::error::QueryError;
15use crate::key::Key;
16
17/// Durability levels for dependency tracking optimization.
18///
19/// Higher values indicate the data changes less frequently.
20/// Durability is specified when resolving assets, not on the type itself.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
22#[repr(u8)]
23pub enum DurabilityLevel {
24    /// Changes frequently (user input, live feeds).
25    #[default]
26    Volatile = 0,
27    /// Changes occasionally (configuration, session data).
28    Transient = 1,
29    /// Changes rarely (external dependencies).
30    Stable = 2,
31    /// Fixed for this session (bundled assets, constants).
32    Static = 3,
33}
34
35impl DurabilityLevel {
36    /// Convert to u8 for whale integration.
37    pub fn as_u8(self) -> u8 {
38        self as u8
39    }
40}
41
42/// Trait for asset keys that map to loadable assets.
43///
44/// Asset keys identify external resources (files, URLs, etc.) and define
45/// the type of asset they load. Assets are leaf nodes in the dependency
46/// graph - they have no dependencies but can be depended upon by queries.
47///
48/// Durability is specified when calling `resolve_asset()`, not on the key type.
49///
50/// # Example
51///
52/// ```ignore
53/// use query_flow::{asset_key, AssetKey};
54///
55/// #[asset_key(asset = String)]
56/// pub struct ConfigFile(pub PathBuf);
57///
58/// // Or manually:
59/// pub struct TextureId(pub u32);
60///
61/// impl AssetKey for TextureId {
62///     type Asset = ImageData;
63///
64///     fn asset_eq(old: &Self::Asset, new: &Self::Asset) -> bool {
65///         old.bytes == new.bytes
66///     }
67/// }
68/// ```
69pub trait AssetKey: Key + 'static {
70    /// The asset type this key loads.
71    type Asset: Send + Sync + 'static;
72
73    /// Compare two asset values for equality (for early cutoff).
74    ///
75    /// When an asset is re-resolved with the same value, dependent queries
76    /// can skip recomputation (early cutoff).
77    fn asset_eq(old: &Self::Asset, new: &Self::Asset) -> bool;
78}
79
80/// Result of locating an asset.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub enum LocateResult<A> {
83    /// Asset is immediately available (e.g., from memory cache).
84    Ready {
85        /// The asset value.
86        value: A,
87        /// The durability level of this asset.
88        durability: DurabilityLevel,
89    },
90    /// Asset needs to be loaded asynchronously.
91    /// The runtime will track this as a pending request.
92    Pending,
93}
94
95/// Trait for locating and loading assets.
96///
97/// Implement this trait to define how assets are found for a given key type.
98/// Different locators can be registered for different platforms:
99/// - Filesystem locator for desktop
100/// - Network locator for web/playground
101/// - Memory locator for testing
102///
103/// # Database Access
104///
105/// The `locate` method receives a database handle, allowing locators to:
106/// - Query configuration to determine loading behavior
107/// - Access other assets as dependencies
108/// - Make dynamic decisions based on runtime state
109///
110/// Any queries or assets accessed during `locate()` are tracked as dependencies
111/// of the calling query.
112///
113/// # Example
114///
115/// ```ignore
116/// struct ConfigAwareLocator;
117///
118/// impl AssetLocator<FilePath> for ConfigAwareLocator {
119///     fn locate(&self, db: &impl Db, key: &FilePath) -> Result<LocateResult<String>, QueryError> {
120///         // Access config to check if path is allowed
121///         let config = db.query(GetConfig)?.clone();
122///         if !config.allowed_paths.contains(&key.0) {
123///             return Err(anyhow::anyhow!("Path not allowed: {:?}", key.0).into());
124///         }
125///
126///         // Return pending for async loading
127///         Ok(LocateResult::Pending)
128///     }
129/// }
130/// ```
131pub trait AssetLocator<K: AssetKey>: Send + Sync + 'static {
132    /// Attempt to locate an asset for the given key.
133    ///
134    /// # Arguments
135    /// * `db` - Database handle for accessing queries and other assets
136    /// * `key` - The asset key to locate
137    ///
138    /// # Returns
139    /// * `Ok(Ready { value, durability })` - Asset is immediately available
140    /// * `Ok(Pending)` - Asset needs async loading (will be added to pending list)
141    /// * `Err(QueryError)` - Location failed (will NOT be added to pending list)
142    ///
143    /// # Dependency Tracking
144    ///
145    /// Any `db.query()` or `db.asset()` calls made during this method
146    /// become dependencies of the query that requested this asset.
147    fn locate(&self, db: &impl Db, key: &K) -> Result<LocateResult<K::Asset>, QueryError>;
148}
149
150/// A pending asset request that needs to be resolved.
151#[derive(Clone)]
152pub struct PendingAsset {
153    /// Type-erased key for the asset (stored as Arc for efficient cloning)
154    key: Arc<dyn Any + Send + Sync>,
155    /// Type ID of the AssetKey type
156    key_type: TypeId,
157    /// Debug representation
158    debug_repr: String,
159}
160
161impl PendingAsset {
162    /// Create a new pending asset.
163    pub fn new<K: AssetKey>(key: K) -> Self {
164        Self {
165            debug_repr: format!("{:?}", key),
166            key_type: TypeId::of::<K>(),
167            key: Arc::new(key),
168        }
169    }
170
171    /// Create from pre-computed parts (used by PendingStorage).
172    pub(crate) fn new_from_parts(
173        key_type: TypeId,
174        debug_repr: &str,
175        key: Arc<dyn Any + Send + Sync>,
176    ) -> Self {
177        Self {
178            key_type,
179            debug_repr: debug_repr.to_string(),
180            key,
181        }
182    }
183
184    /// Downcast the key to its concrete type.
185    pub fn key<K: AssetKey>(&self) -> Option<&K> {
186        if self.key_type == TypeId::of::<K>() {
187            self.key.downcast_ref()
188        } else {
189            None
190        }
191    }
192
193    /// Check if this pending asset is for the given key type.
194    pub fn is<K: AssetKey>(&self) -> bool {
195        self.key_type == TypeId::of::<K>()
196    }
197
198    /// Get the TypeId of the key type.
199    pub fn key_type(&self) -> TypeId {
200        self.key_type
201    }
202
203    /// Get debug representation.
204    pub fn debug_repr(&self) -> &str {
205        &self.debug_repr
206    }
207}
208
209impl Debug for PendingAsset {
210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211        write!(f, "PendingAsset({})", self.debug_repr)
212    }
213}
214
215/// Full cache key for assets (includes AssetKey type information).
216///
217/// This is similar to `FullCacheKey` for queries but marks the entry
218/// as an asset in the dependency graph.
219#[derive(Clone)]
220pub(crate) struct FullAssetKey {
221    /// Type ID of the AssetKey type
222    key_type: TypeId,
223    /// Hash of the key value
224    key_hash: u64,
225    /// Debug representation
226    debug_repr: Arc<str>,
227}
228
229impl FullAssetKey {
230    /// Create a new full asset key.
231    pub fn new<K: AssetKey>(key: &K) -> Self {
232        use std::hash::Hasher;
233        let mut hasher = ahash::AHasher::default();
234        key.hash(&mut hasher);
235        let key_hash = hasher.finish();
236
237        Self {
238            key_type: TypeId::of::<K>(),
239            key_hash,
240            debug_repr: Arc::from(format!("Asset:{}({:?})", std::any::type_name::<K>(), key)),
241        }
242    }
243
244    /// Get debug representation for error messages.
245    pub fn debug_repr(&self) -> &str {
246        &self.debug_repr
247    }
248
249    /// Get the key type.
250    pub fn key_type(&self) -> TypeId {
251        self.key_type
252    }
253
254    /// Get the key hash.
255    pub fn key_hash(&self) -> u64 {
256        self.key_hash
257    }
258}
259
260impl Debug for FullAssetKey {
261    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
262        write!(f, "{}", self.debug_repr)
263    }
264}
265
266impl std::hash::Hash for FullAssetKey {
267    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
268        self.key_type.hash(state);
269        self.key_hash.hash(state);
270    }
271}
272
273impl PartialEq for FullAssetKey {
274    fn eq(&self, other: &Self) -> bool {
275        self.key_type == other.key_type && self.key_hash == other.key_hash
276    }
277}
278
279impl Eq for FullAssetKey {}