Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Seanaye/perf/reduce cache allocations (#5492)

Sean Ayea417c81b2458
diff --git a/Cargo.toml b/Cargo.toml
index a186314028..c1ad24f027 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -296,6 +296,14 @@ unicode-segmentation = "1.9.0"
url = "2.5.0"
zip = "=2.4.2"
+# Retain Rust DWARF for local cache profiling while keeping release-level LLVM
+# optimization. wasm-pack's custom profile metadata prevents the final
+# wasm-opt pass from discarding or rewriting these locations.
+[profile.cache-wasm-profiling]
+inherits = "release"
+debug = 2
+strip = "none"
+
# The Cloudflare sync worker is size-sensitive. Package manifests cannot own
# profiles once they are workspace members, so keep its former release profile
# here without changing release optimization for the backend services.
diff --git a/apps/web/justfile b/apps/web/justfile
index ac04fa3eba..e19ce3ead7 100644
--- a/apps/web/justfile
+++ b/apps/web/justfile
@@ -163,6 +163,13 @@ cycles-ci:
build-cache-wasm:
wasm-pack build {{justfile_directory()}}/../../crates/client/cache-wasm --target web --release --out-dir {{justfile_directory()}}/src/lib/graphql-cache/wasm
+# Local profiling build: retain Rust symbols and DWARF source locations so an
+# exported Firefox profile can be symbolicated back to Rust files and lines.
+# This overwrites the gitignored release wasm package and is intentionally not
+# used by application or CI builds.
+build-cache-wasm-profile:
+ wasm-pack build {{justfile_directory()}}/../../crates/client/cache-wasm --target web --profile cache-wasm-profiling --out-dir {{justfile_directory()}}/src/lib/graphql-cache/wasm
+
# Dev fast path: build the wasm pkg only when missing or its version drifts
# from client/cache-wasm/Cargo.toml (bump that version to push a rebuild to
# dev machines). See tooling/xtask/crates/xtask_cache_wasm/src/main.rs.
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
index 6900cf546b..3ab36e63d8 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
@@ -153,7 +153,11 @@ pub struct EngineHandle {
fn wire_write_result(ops: &OpInterner, result: WriteResult) -> WriteResultWire {
WriteResultWire {
- changed: result.changed.into_iter().map(|k| k.0).collect(),
+ changed: result
+ .changed
+ .into_iter()
+ .map(|key| key.0.into_owned())
+ .collect(),
affected_ops: ops.names(result.affected_ops),
reset: result.reset,
revalidations: result.revalidations,
@@ -431,7 +435,8 @@ impl EngineHandle {
/// Evicts records by entity key; returns the affected registered op ids.
pub async fn invalidate(&self, keys: Vec<String>) -> Result<Vec<String>, String> {
- let keys: Vec<EntityKey> = keys.into_iter().map(EntityKey).collect();
+ let keys: Vec<EntityKey<'static>> =
+ keys.into_iter().map(|key| EntityKey(key.into())).collect();
let mut state = self.inner.lock().await;
let EngineState { engine, ops } = &mut *state;
let affected = engine.invalidate_keys(keys.iter());
@@ -441,7 +446,8 @@ impl EngineHandle {
/// Deletes stale records from durable and hot storage and returns the
/// registered operations that traversed them.
pub async fn delete_records(&self, keys: Vec<String>) -> Result<Vec<String>, String> {
- let keys: Vec<EntityKey> = keys.into_iter().map(EntityKey).collect();
+ let keys: Vec<EntityKey<'static>> =
+ keys.into_iter().map(|key| EntityKey(key.into())).collect();
let mut state = self.inner.lock().await;
let EngineState { engine, ops } = &mut *state;
let affected = engine.delete_keys(&keys).await.map_err(|e| e.to_string())?;
diff --git a/crates/client/cache-core/src/denormalize.rs b/crates/client/cache-core/src/denormalize.rs
index 746ee5bce1..5aefa5b596 100644
--- a/crates/client/cache-core/src/denormalize.rs
+++ b/crates/client/cache-core/src/denormalize.rs
@@ -17,17 +17,17 @@ use thiserror::Error;
/// Synchronous view over records available right now (hot tier + any
/// batch-fetched records).
pub trait RecordSource {
- fn get(&self, key: &EntityKey) -> Option<&Record>;
+ fn get(&self, key: &EntityKey<'static>) -> Option<&Record>;
}
-impl RecordSource for std::collections::BTreeMap<EntityKey, Record> {
- fn get(&self, key: &EntityKey) -> Option<&Record> {
+impl RecordSource for std::collections::BTreeMap<EntityKey<'static>, Record> {
+ fn get(&self, key: &EntityKey<'static>) -> Option<&Record> {
std::collections::BTreeMap::get(self, key)
}
}
-impl RecordSource for std::collections::HashMap<EntityKey, Record> {
- fn get(&self, key: &EntityKey) -> Option<&Record> {
+impl RecordSource for std::collections::HashMap<EntityKey<'static>, Record> {
+ fn get(&self, key: &EntityKey<'static>) -> Option<&Record> {
std::collections::HashMap::get(self, key)
}
}
@@ -48,9 +48,12 @@ pub enum ReadOutcome {
/// All selected data present.
Complete(Json),
/// Some records weren't in the [`RecordSource`]; fetch these and retry.
- NeedRecords(BTreeSet<EntityKey>),
+ NeedRecords(BTreeSet<EntityKey<'static>>),
/// A record exists but a selected field was never written → miss.
- Miss { entity: EntityKey, field: String },
+ Miss {
+ entity: EntityKey<'static>,
+ field: String,
+ },
}
/// Attempts to answer `op` from `source`. `deps` accumulates every entity
@@ -59,7 +62,7 @@ pub fn denormalize(
op: &Operation,
variables: &serde_json::Map<String, Json>,
source: &impl RecordSource,
- deps: &mut BTreeSet<EntityKey>,
+ deps: &mut BTreeSet<EntityKey<'static>>,
) -> Result<ReadOutcome, DenormalizeError> {
denormalize_record(
&EntityKey::root(),
@@ -73,12 +76,12 @@ pub fn denormalize(
/// Projects one normalized record through a fragment selection.
pub fn denormalize_record(
- key: &EntityKey,
+ key: &EntityKey<'static>,
type_name: &str,
selections: &[Selection],
variables: &serde_json::Map<String, Json>,
source: &impl RecordSource,
- deps: &mut BTreeSet<EntityKey>,
+ deps: &mut BTreeSet<EntityKey<'static>>,
) -> Result<ReadOutcome, DenormalizeError> {
let mut walk = Walk {
variables,
@@ -107,10 +110,10 @@ pub fn denormalize_record(
struct Walk<'a, S: RecordSource> {
variables: &'a serde_json::Map<String, Json>,
source: &'a S,
- deps: &'a mut BTreeSet<EntityKey>,
- missing_records: BTreeSet<EntityKey>,
+ deps: &'a mut BTreeSet<EntityKey<'static>>,
+ missing_records: BTreeSet<EntityKey<'static>>,
/// First field-level miss encountered.
- miss: Option<(EntityKey, String)>,
+ miss: Option<(EntityKey<'static>, String)>,
}
impl<'a, S: RecordSource> Walk<'a, S> {
@@ -118,7 +121,7 @@ impl<'a, S: RecordSource> Walk<'a, S> {
/// already determined to be incomplete (missing record / miss noted).
fn read_record(
&mut self,
- key: &EntityKey,
+ key: &EntityKey<'static>,
type_name: &str,
selections: &[Selection],
) -> Result<Option<Json>, DenormalizeError> {
@@ -136,7 +139,7 @@ impl<'a, S: RecordSource> Walk<'a, S> {
/// Reads selected fields out of a record's or embedded object's map.
fn read_fields(
&mut self,
- owner: &EntityKey,
+ owner: &EntityKey<'static>,
fields: &std::collections::BTreeMap<String, CacheValue>,
concrete: &str,
selections: &[Selection],
@@ -179,7 +182,7 @@ impl<'a, S: RecordSource> Walk<'a, S> {
fn read_value(
&mut self,
- owner: &EntityKey,
+ owner: &EntityKey<'static>,
field: &FieldNode,
named_type: &str,
value: &CacheValue,
diff --git a/crates/client/cache-core/src/deps.rs b/crates/client/cache-core/src/deps.rs
index 2b45dbb3df..4fc9e2c19a 100644
--- a/crates/client/cache-core/src/deps.rs
+++ b/crates/client/cache-core/src/deps.rs
@@ -11,8 +11,8 @@ pub type OpId = u64;
#[derive(Debug, Default)]
pub struct DepIndex {
- by_op: HashMap<OpId, BTreeSet<EntityKey>>,
- by_key: HashMap<EntityKey, HashSet<OpId>>,
+ by_op: HashMap<OpId, BTreeSet<EntityKey<'static>>>,
+ by_key: HashMap<EntityKey<'static>, HashSet<OpId>>,
}
impl DepIndex {
@@ -21,7 +21,7 @@ impl DepIndex {
}
/// Replaces the dependency set of an active operation.
- pub fn set_op_deps(&mut self, op: OpId, deps: BTreeSet<EntityKey>) {
+ pub fn set_op_deps(&mut self, op: OpId, deps: BTreeSet<EntityKey<'static>>) {
self.remove_op(op);
for key in &deps {
self.by_key.entry(key.clone()).or_default().insert(op);
@@ -46,7 +46,7 @@ impl DepIndex {
/// Active operations depending on any of `keys`.
pub fn ops_for_keys<'a>(
&self,
- keys: impl IntoIterator<Item = &'a EntityKey>,
+ keys: impl IntoIterator<Item = &'a EntityKey<'static>>,
) -> BTreeSet<OpId> {
let mut out = BTreeSet::new();
for key in keys {
@@ -58,7 +58,7 @@ impl DepIndex {
}
/// Keys pinned by at least one active operation (future: eviction).
- pub fn pinned(&self) -> impl Iterator<Item = &EntityKey> {
+ pub fn pinned(&self) -> impl Iterator<Item = &EntityKey<'static>> {
self.by_key.keys()
}
@@ -76,8 +76,8 @@ impl DepIndex {
mod tests {
use super::*;
- fn key(s: &str) -> EntityKey {
- EntityKey(s.to_string())
+ fn key(s: &str) -> EntityKey<'static> {
+ EntityKey(s.to_owned().into())
}
#[test]
diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rs
index 668a8a2ac4..f42e6b3cda 100644
--- a/crates/client/cache-core/src/engine.rs
+++ b/crates/client/cache-core/src/engine.rs
@@ -73,7 +73,7 @@ pub enum ReadResult {
#[derive(Debug)]
pub struct WriteResult {
/// Records whose contents changed.
- pub changed: BTreeSet<EntityKey>,
+ pub changed: BTreeSet<EntityKey<'static>>,
/// Active operations depending on changed records (host re-executes
/// these). Excludes the operation that performed the write. After a
/// `reset` this is *every* active operation except the origin.
@@ -145,7 +145,7 @@ pub const DEFAULT_HOT_CAPACITY: usize = 10_000;
pub struct Engine<S: Storage> {
storage: S,
- hot: LruCache<EntityKey, Record>,
+ hot: LruCache<EntityKey<'static>, Record>,
docs: HashMap<String, Document>,
deps: DepIndex,
identity: IdentityState,
@@ -209,7 +209,7 @@ impl<S: Storage> Engine<S> {
let after = effective_records(&bases, &replacement, &candidates);
self.optimistic = replacement;
self.optimistic_hydrated = true;
- let changed: BTreeSet<EntityKey> = candidates
+ let changed: BTreeSet<EntityKey<'static>> = candidates
.into_iter()
.filter(|key| before_all.get(key) != after.get(key))
.collect();
@@ -254,7 +254,7 @@ impl<S: Storage> Engine<S> {
detail: error.to_string(),
}
})?;
- let candidates: BTreeSet<EntityKey> = updates.keys().cloned().collect();
+ let candidates: BTreeSet<EntityKey<'static>> = updates.keys().cloned().collect();
let (candidates, bases) = self
.load_link_patch_bases(candidates, &layers, &updates, &patches)
.await?;
@@ -285,7 +285,7 @@ impl<S: Storage> Engine<S> {
/// first use. Never returns [`IdentityState::NotHydrated`].
async fn bound_identity(&mut self) -> Result<IdentityState, EngineError<S::Error>> {
if self.identity == IdentityState::NotHydrated {
- let key = EntityKey(IDENTITY_META_KEY.to_string());
+ let key = EntityKey(IDENTITY_META_KEY.into());
let fetched = self
.storage
.get_batch(std::slice::from_ref(&key))
@@ -322,7 +322,7 @@ impl<S: Storage> Engine<S> {
crate::value::CacheValue::String(identity.to_string()),
);
self.storage
- .put_batch(vec![(EntityKey(IDENTITY_META_KEY.to_string()), record)])
+ .put_batch(vec![(EntityKey(IDENTITY_META_KEY.into()), record)])
.await
.map_err(EngineError::Storage)?;
self.identity = IdentityState::Bound(identity.to_string());
@@ -356,7 +356,7 @@ impl<S: Storage> Engine<S> {
// touched keys and is never promoted into the hot tier — the durable
// LRU base must stay free of optimistic values.
let optimistic = merged_optimistic(&self.optimistic);
- let mut composed: HashMap<EntityKey, Record> = HashMap::new();
+ let mut composed: HashMap<EntityKey<'static>, Record> = HashMap::new();
for (key, update) in &optimistic {
if let Some(base) = self.hot.peek(key) {
let mut merged = base.clone();
@@ -367,8 +367,8 @@ impl<S: Storage> Engine<S> {
// Durable records fetched from storage this read (pre-merge — safe
// to promote into the hot tier afterwards).
- let mut fetched_base: HashMap<EntityKey, Record> = HashMap::new();
- let mut known_absent: BTreeSet<EntityKey> = BTreeSet::new();
+ let mut fetched_base: HashMap<EntityKey<'static>, Record> = HashMap::new();
+ let mut known_absent: BTreeSet<EntityKey<'static>> = BTreeSet::new();
let mut deps = BTreeSet::new();
let outcome = loop {
@@ -382,7 +382,7 @@ impl<S: Storage> Engine<S> {
ReadOutcome::Complete(data) => break ReadResult::Hit { data },
ReadOutcome::Miss { .. } => break ReadResult::Miss,
ReadOutcome::NeedRecords(missing) => {
- let to_fetch: Vec<EntityKey> = missing
+ let to_fetch: Vec<EntityKey<'static>> = missing
.into_iter()
.filter(|k| {
!known_absent.contains(k)
@@ -452,7 +452,7 @@ impl<S: Storage> Engine<S> {
self.hydrate_optimistic().await?;
const SCAN_BATCH_SIZE: usize = 128;
- let after = cursor.map(RecordCursor::entity_key).cloned();
+ let after: Option<EntityKey<'static>> = cursor.map(RecordCursor::entity_key).cloned();
let type_names: BTreeSet<_> = selection.type_names().iter().map(String::as_str).collect();
let optimistic = merged_optimistic(&self.optimistic);
let mut optimistic_candidates: BTreeSet<_> = optimistic
@@ -483,7 +483,7 @@ impl<S: Storage> Engine<S> {
storage_after = Some(high_key.clone());
}
- let mut candidates: BTreeMap<EntityKey, Option<Record>> = rows
+ let mut candidates: BTreeMap<EntityKey<'static>, Option<Record>> = rows
.into_iter()
.map(|(key, record)| (key, Some(record)))
.collect();
@@ -530,9 +530,9 @@ impl<S: Storage> Engine<S> {
async fn project_record_batch(
&mut self,
selection: &RecordSelection,
- candidates: BTreeMap<EntityKey, Option<Record>>,
- optimistic: &BTreeMap<EntityKey, Record>,
- ) -> Result<Vec<(EntityKey, Json)>, EngineError<S::Error>> {
+ candidates: BTreeMap<EntityKey<'static>, Option<Record>>,
+ optimistic: &BTreeMap<EntityKey<'static>, Record>,
+ ) -> Result<Vec<(EntityKey<'static>, Json)>, EngineError<S::Error>> {
let candidate_keys: Vec<_> = candidates.keys().cloned().collect();
let optimistic_only_candidates: BTreeSet<_> = candidates
.iter()
@@ -695,7 +695,7 @@ impl<S: Storage> Engine<S> {
}
let bases_after = self.load_bases(&candidates).await?;
let after = effective_records(&bases_after, &self.optimistic, &candidates);
- let visible_changed: BTreeSet<EntityKey> = candidates
+ let visible_changed: BTreeSet<EntityKey<'static>> = candidates
.into_iter()
.filter(|key| before.get(key) != after.get(key))
.collect();
@@ -722,13 +722,13 @@ impl<S: Storage> Engine<S> {
async fn persist_updates(
&mut self,
updates: RecordUpdates,
- ) -> Result<BTreeSet<EntityKey>, EngineError<S::Error>> {
+ ) -> Result<BTreeSet<EntityKey<'static>>, EngineError<S::Error>> {
// Load current values (hot tier, then storage) so merges detect real
// changes. Merges are staged in a plain map, NOT the LRU: a batch
// larger than the hot capacity would otherwise evict its own
// records mid-merge and overwrite storage with partial updates.
- let mut staging: HashMap<EntityKey, Record> = HashMap::new();
- let mut missing: Vec<EntityKey> = Vec::new();
+ let mut staging: HashMap<EntityKey<'static>, Record> = HashMap::new();
+ let mut missing: Vec<EntityKey<'static>> = Vec::new();
for key in updates.keys() {
match self.hot.peek(key) {
Some(record) => {
@@ -751,7 +751,7 @@ impl<S: Storage> Engine<S> {
}
let mut changed = BTreeSet::new();
- let mut to_persist: Vec<(EntityKey, Record)> = Vec::new();
+ let mut to_persist: Vec<(EntityKey<'static>, Record)> = Vec::new();
for (key, update) in updates {
let merged = match staging.remove(&key) {
Some(mut existing) => {
@@ -810,7 +810,7 @@ impl<S: Storage> Engine<S> {
.chain(patches.iter().map(OptimisticLinkPatch::revalidation)),
);
- let candidates: BTreeSet<EntityKey> = updates.keys().cloned().collect();
+ let candidates: BTreeSet<EntityKey<'static>> = updates.keys().cloned().collect();
let optimistic = self.optimistic.clone();
let (candidates, bases) = self
.load_link_patch_bases(candidates, &optimistic, &updates, &patches)
@@ -858,7 +858,7 @@ impl<S: Storage> Engine<S> {
});
let after = effective_records(&bases, &self.optimistic, &candidates);
- let changed: BTreeSet<EntityKey> = candidates
+ let changed: BTreeSet<EntityKey<'static>> = candidates
.into_iter()
.filter(|key| before.get(key) != after.get(key))
.collect();
@@ -973,7 +973,7 @@ impl<S: Storage> Engine<S> {
let settled_bases = self.load_bases(&candidates).await?;
let after = effective_records(&settled_bases, &replacement, &candidates);
self.optimistic = replacement;
- let visible_changed: BTreeSet<EntityKey> = candidates
+ let visible_changed: BTreeSet<EntityKey<'static>> = candidates
.into_iter()
.filter(|key| before.get(key) != after.get(key))
.collect();
@@ -1019,7 +1019,7 @@ impl<S: Storage> Engine<S> {
let current_bases = self.load_bases(&candidates).await?;
let after = effective_records(&current_bases, &replacement, &candidates);
self.optimistic = replacement;
- let visible_changed: BTreeSet<EntityKey> = candidates
+ let visible_changed: BTreeSet<EntityKey<'static>> = candidates
.into_iter()
.filter(|key| before.get(key) != after.get(key))
.collect();
@@ -1036,11 +1036,17 @@ impl<S: Storage> Engine<S> {
/// link updates, including records currently outside the hot tier.
async fn load_link_patch_bases(
&mut self,
- mut candidates: BTreeSet<EntityKey>,
+ mut candidates: BTreeSet<EntityKey<'static>>,
layers: &[OptimisticLayer],
pending_updates: &RecordUpdates,
patches: &[OptimisticLinkPatch],
- ) -> Result<(BTreeSet<EntityKey>, HashMap<EntityKey, Record>), EngineError<S::Error>> {
+ ) -> Result<
+ (
+ BTreeSet<EntityKey<'static>>,
+ HashMap<EntityKey<'static>, Record>,
+ ),
+ EngineError<S::Error>,
+ > {
if !patches.is_empty() {
candidates.insert(EntityKey::root());
}
@@ -1065,10 +1071,10 @@ impl<S: Storage> Engine<S> {
/// without touching LRU recency or persisting anything.
async fn load_bases(
&mut self,
- keys: &BTreeSet<EntityKey>,
- ) -> Result<HashMap<EntityKey, Record>, EngineError<S::Error>> {
+ keys: &BTreeSet<EntityKey<'static>>,
+ ) -> Result<HashMap<EntityKey<'static>, Record>, EngineError<S::Error>> {
let mut out = HashMap::new();
- let mut missing: Vec<EntityKey> = Vec::new();
+ let mut missing: Vec<EntityKey<'static>> = Vec::new();
for key in keys {
match self.hot.peek(key) {
Some(record) => {
@@ -1107,20 +1113,20 @@ impl<S: Storage> Engine<S> {
let prepared = prepare(&operation, &inspection.path)?;
let mut candidates = BTreeSet::from([EntityKey::root()]);
- let owner = loop {
+ let variants = loop {
let bases = self.load_bases(&candidates).await?;
let effective =
present_records(effective_records(&bases, &self.optimistic, &candidates));
match resolve_owner(&effective, &operation, &inspection.path)? {
- OwnerResolution::Owner(owner) => break owner,
+ OwnerResolution::Owner(owner) => break recover_variants(&owner, &prepared)?,
OwnerResolution::Absent => return Ok(Vec::new()),
- OwnerResolution::NeedRecord(key) if !candidates.contains(&key) => {
- candidates.insert(key);
+ OwnerResolution::NeedRecord(key) if !candidates.contains(key.as_ref()) => {
+ candidates.insert(key.into_owned());
}
OwnerResolution::NeedRecord(_) => return Ok(Vec::new()),
}
};
- Ok(recover_variants(&owner, &prepared)?
+ Ok(variants
.into_iter()
.map(|variables| CachedQueryVariant { variables })
.collect())
@@ -1184,7 +1190,7 @@ impl<S: Storage> Engine<S> {
/// storage, and returns the local active operations that depend on them.
pub fn invalidate_keys<'k>(
&mut self,
- keys: impl IntoIterator<Item = &'k EntityKey>,
+ keys: impl IntoIterator<Item = &'k EntityKey<'static>>,
) -> BTreeSet<OpId> {
let mut affected = BTreeSet::new();
for key in keys {
@@ -1203,7 +1209,7 @@ impl<S: Storage> Engine<S> {
/// [`Self::invalidate_keys`] instead.
pub async fn delete_keys(
&mut self,
- keys: &[EntityKey],
+ keys: &[EntityKey<'static>],
) -> Result<BTreeSet<OpId>, EngineError<S::Error>> {
let affected = self.deps.ops_for_keys(keys.iter());
self.storage
@@ -1256,16 +1262,16 @@ impl<S: Storage> Engine<S> {
/// `peek` (no recency mutation) — recency is refreshed once per read from
/// the dep set.
struct EngineSource<'a> {
- hot: &'a LruCache<EntityKey, Record>,
+ hot: &'a LruCache<EntityKey<'static>, Record>,
/// Durable records batch-fetched from storage during this read.
- fetched: &'a HashMap<EntityKey, Record>,
+ fetched: &'a HashMap<EntityKey<'static>, Record>,
/// Optimistically touched keys: durable base + layers, pre-merged.
/// Takes precedence over both durable tiers.
- composed: &'a HashMap<EntityKey, Record>,
+ composed: &'a HashMap<EntityKey<'static>, Record>,
}
impl RecordSource for EngineSource<'_> {
- fn get(&self, key: &EntityKey) -> Option<&Record> {
+ fn get(&self, key: &EntityKey<'static>) -> Option<&Record> {
self.composed
.get(key)
.or_else(|| self.fetched.get(key))
@@ -1275,8 +1281,8 @@ impl RecordSource for EngineSource<'_> {
/// All active optimistic layers' updates merged in creation order (later
/// layers override earlier ones field-by-field).
-fn merged_optimistic(layers: &[OptimisticLayer]) -> BTreeMap<EntityKey, Record> {
- let mut out: BTreeMap<EntityKey, Record> = BTreeMap::new();
+fn merged_optimistic(layers: &[OptimisticLayer]) -> BTreeMap<EntityKey<'static>, Record> {
+ let mut out: BTreeMap<EntityKey<'static>, Record> = BTreeMap::new();
for layer in layers {
for (key, record) in &layer.updates {
out.entry(key.clone()).or_default().merge(record.clone());
@@ -1289,9 +1295,12 @@ fn merged_optimistic(layers: &[OptimisticLayer]) -> BTreeMap<EntityKey, Record>
/// mutating the hot tier or storage. The caller can then atomically settle a
/// queued mutation before publishing the staged records in memory.
fn stage_updates(
- bases: &HashMap<EntityKey, Record>,
+ bases: &HashMap<EntityKey<'static>, Record>,
updates: RecordUpdates,
-) -> (BTreeSet<EntityKey>, Vec<(EntityKey, Record)>) {
+) -> (
+ BTreeSet<EntityKey<'static>>,
+ Vec<(EntityKey<'static>, Record)>,
+) {
let mut changed = BTreeSet::new();
let mut entries = Vec::with_capacity(updates.len());
for (key, update) in updates {
@@ -1316,10 +1325,10 @@ fn stage_updates(
/// Effective visible records for `keys`: durable base + every active layer
/// merged in order. `None` when the key exists nowhere.
fn effective_records(
- bases: &HashMap<EntityKey, Record>,
+ bases: &HashMap<EntityKey<'static>, Record>,
layers: &[OptimisticLayer],
- keys: &BTreeSet<EntityKey>,
-) -> HashMap<EntityKey, Option<Record>> {
+ keys: &BTreeSet<EntityKey<'static>>,
+) -> HashMap<EntityKey<'static>, Option<Record>> {
keys.iter()
.map(|key| {
let mut record: Option<Record> = bases.get(key).cloned();
@@ -1335,7 +1344,9 @@ fn effective_records(
.collect()
}
-fn present_records(records: HashMap<EntityKey, Option<Record>>) -> HashMap<EntityKey, Record> {
+fn present_records(
+ records: HashMap<EntityKey<'static>, Option<Record>>,
+) -> HashMap<EntityKey<'static>, Record> {
records
.into_iter()
.filter_map(|(key, record)| record.map(|record| (key, record)))
@@ -1343,7 +1354,7 @@ fn present_records(records: HashMap<EntityKey, Option<Record>>) -> HashMap<Entit
}
fn merge_updates_into_effective(
- effective: &mut HashMap<EntityKey, Record>,
+ effective: &mut HashMap<EntityKey<'static>, Record>,
updates: &RecordUpdates,
) {
for (key, update) in updates {
@@ -1354,14 +1365,14 @@ fn merge_updates_into_effective(
}
}
-fn layer_keys(layers: &[OptimisticLayer]) -> BTreeSet<EntityKey> {
+fn layer_keys(layers: &[OptimisticLayer]) -> BTreeSet<EntityKey<'static>> {
layers
.iter()
.flat_map(|layer| layer.updates.keys().cloned())
.collect()
}
-fn record_key_type(key: &EntityKey) -> Option<&str> {
+fn record_key_type<'a>(key: &'a EntityKey<'a>) -> Option<&'a str> {
key.0.split_once(':').map(|(type_name, _)| type_name)
}
diff --git a/crates/client/cache-core/src/link_patch.rs b/crates/client/cache-core/src/link_patch.rs
index 53b98f7d85..eef760e549 100644
--- a/crates/client/cache-core/src/link_patch.rs
+++ b/crates/client/cache-core/src/link_patch.rs
@@ -58,20 +58,20 @@ pub enum LinkOperation {
Remove {
/// Normalized entity key to remove.
#[serde(rename = "entityKey")]
- entity_key: EntityKey,
+ entity_key: EntityKey<'static>,
},
/// Removes every occurrence and inserts one reference at the front.
PrependUnique {
/// Normalized entity key to prepend.
#[serde(rename = "entityKey")]
- entity_key: EntityKey,
+ entity_key: EntityKey<'static>,
},
}
impl LinkOperation {
- fn entity_key(&self) -> &EntityKey {
+ fn entity_key(&self) -> EntityKey<'_> {
match self {
- Self::Remove { entity_key } | Self::PrependUnique { entity_key } => entity_key,
+ Self::Remove { entity_key } | Self::PrependUnique { entity_key } => entity_key.borrow(),
}
}
}
@@ -131,7 +131,7 @@ pub enum LinkPatchError {
InvalidEntityKey(String),
/// The selected normalized record is absent.
#[error("link update record `{0}` is missing")]
- MissingParent(EntityKey),
+ MissingParent(EntityKey<'static>),
/// The selected record field is absent.
#[error("link update field `{field}` is missing on `{parent}`")]
MissingField { parent: String, field: String },
@@ -220,16 +220,16 @@ fn validate_entrypoint(
Ok(variables)
}
-fn validate_entity_key(key: &EntityKey) -> Result<(), LinkPatchError> {
+fn validate_entity_key<'a>(key: EntityKey<'a>) -> Result<(), LinkPatchError> {
let Some((typename, value)) = key.0.split_once(':') else {
- return Err(LinkPatchError::InvalidEntityKey(key.0.clone()));
+ return Err(LinkPatchError::InvalidEntityKey(key.0.to_string()));
};
let valid_name = !typename.is_empty()
&& typename.chars().enumerate().all(|(index, ch)| {
ch == '_' || ch.is_ascii_alphabetic() || (index > 0 && ch.is_ascii_digit())
});
if !valid_name || value.is_empty() || value.chars().any(char::is_whitespace) {
- return Err(LinkPatchError::InvalidEntityKey(key.0.clone()));
+ return Err(LinkPatchError::InvalidEntityKey(key.0.to_string()));
}
Ok(())
}
@@ -248,7 +248,7 @@ fn is_json_scalar(value: &Json) -> bool {
/// mode is used during hydration and successful settlement, where stale query
/// fields must never be recreated.
pub fn apply_link_patches(
- effective: &mut HashMap<EntityKey, Record>,
+ effective: &mut HashMap<EntityKey<'static>, Record>,
updates: &mut RecordUpdates,
patches: &[OptimisticLinkPatch],
skip_not_applicable: bool,
@@ -272,7 +272,7 @@ pub fn apply_link_patches(
}
fn apply_one(
- effective: &mut HashMap<EntityKey, Record>,
+ effective: &mut HashMap<EntityKey<'static>, Record>,
updates: &mut RecordUpdates,
patch: &OptimisticLinkPatch,
) -> Result<(), LinkPatchError> {
@@ -285,7 +285,7 @@ fn apply_one(
.get(&resolved.field_key)
.cloned()
.ok_or_else(|| LinkPatchError::MissingField {
- parent: resolved.parent_entity_key.0.clone(),
+ parent: resolved.parent_entity_key.0.to_string(),
field: resolved.field_key.clone(),
})?;
let target = traverse(&mut field_value, &resolved.path)?;
@@ -306,9 +306,11 @@ fn apply_one(
}
let entity_key = patch.operation.entity_key();
- links.retain(|value| !matches!(value, CacheValue::Ref(key) if key == entity_key));
+ links.retain(
+ |value| !matches!(value, CacheValue::Ref(key) if key.0.as_ref() == entity_key.0.as_ref()),
+ );
if matches!(patch.operation, LinkOperation::PrependUnique { .. }) {
- links.insert(0, CacheValue::Ref(entity_key.clone()));
+ links.insert(0, CacheValue::Ref(entity_key.into_owned()));
}
record
@@ -324,7 +326,7 @@ fn apply_one(
#[derive(Debug)]
struct ResolvedTarget {
- parent_entity_key: EntityKey,
+ parent_entity_key: EntityKey<'static>,
field_key: FieldKey,
path: Vec<LinkPathSegment>,
}
@@ -333,9 +335,9 @@ struct ResolvedTarget {
/// update. Engines use this to hydrate graph links from cold storage before
/// applying the update.
pub fn missing_patch_record(
- effective: &HashMap<EntityKey, Record>,
+ effective: &HashMap<EntityKey<'static>, Record>,
patch: &OptimisticLinkPatch,
-) -> Option<EntityKey> {
+) -> Option<EntityKey<'static>> {
match resolve_target(effective, patch) {
Err(LinkPatchError::MissingParent(key)) => Some(key),
_ => None,
@@ -343,7 +345,7 @@ pub fn missing_patch_record(
}
fn resolve_target(
- effective: &HashMap<EntityKey, Record>,
+ effective: &HashMap<EntityKey<'static>, Record>,
patch: &OptimisticLinkPatch,
) -> Result<ResolvedTarget, LinkPatchError> {
let variables = validate_entrypoint(patch)?;
@@ -363,8 +365,8 @@ fn resolve_target(
}
fn resolve_from_record(
- effective: &HashMap<EntityKey, Record>,
- owner: &EntityKey,
+ effective: &HashMap<EntityKey<'static>, Record>,
+ owner: &EntityKey<'static>,
type_name: &str,
selections: &[Selection],
variables: &serde_json::Map<String, Json>,
@@ -386,7 +388,7 @@ fn resolve_from_record(
.fields
.get(&storage_key)
.ok_or_else(|| LinkPatchError::MissingField {
- parent: owner.0.clone(),
+ parent: owner.0.to_string(),
field: storage_key.clone(),
})?;
let named_type = selected_type(concrete, selected)?;
@@ -407,7 +409,7 @@ fn resolve_from_record(
struct ValueCursor<'a> {
value: &'a CacheValue,
- owner: EntityKey,
+ owner: EntityKey<'static>,
anchor_field: FieldKey,
relative_path: Vec<LinkPathSegment>,
type_name: &'a str,
@@ -415,7 +417,7 @@ struct ValueCursor<'a> {
}
fn resolve_from_value(
- effective: &HashMap<EntityKey, Record>,
+ effective: &HashMap<EntityKey<'static>, Record>,
variables: &serde_json::Map<String, Json>,
cursor: ValueCursor<'_>,
path: &[LinkPathSegment],
@@ -622,7 +624,7 @@ mod tests {
const QUERY: &str = "query { user { groupSoup { bins { key items { id } } } } }";
- fn record() -> (EntityKey, Record) {
+ fn record() -> (EntityKey<'static>, Record) {
let parent = EntityKey("GraphqlUser:user-1".into());
let bin = |key: &str, items: Vec<CacheValue>| {
CacheValue::Object(BTreeMap::from([
diff --git a/crates/client/cache-core/src/normalize.rs b/crates/client/cache-core/src/normalize.rs
index 284dabe276..8b8e4cf4e6 100644
--- a/crates/client/cache-core/src/normalize.rs
+++ b/crates/client/cache-core/src/normalize.rs
@@ -36,7 +36,7 @@ pub enum NormalizeError {
/// Records produced by normalizing one response. Each record contains only
/// the fields this response provided — the store merges them into existing
/// records.
-pub type RecordUpdates = BTreeMap<EntityKey, Record>;
+pub type RecordUpdates = BTreeMap<EntityKey<'static>, Record>;
/// Normalizes a response's `data` object into record updates.
///
@@ -79,7 +79,7 @@ pub fn normalize(
Ok(records)
}
-fn merge_into(records: &mut RecordUpdates, key: EntityKey, record: Record) {
+fn merge_into(records: &mut RecordUpdates, key: EntityKey<'static>, record: Record) {
records.entry(key).or_default().merge(record);
}
diff --git a/crates/client/cache-core/src/query_inspection.rs b/crates/client/cache-core/src/query_inspection.rs
index 5ac93f9936..398a3985cc 100644
--- a/crates/client/cache-core/src/query_inspection.rs
+++ b/crates/client/cache-core/src/query_inspection.rs
@@ -96,15 +96,15 @@ pub(crate) struct PreparedInspection {
}
/// The effective owner record and final selected field.
-pub(crate) struct InspectionOwner {
- pub fields: BTreeMap<String, CacheValue>,
- pub field: FieldNode,
+pub(crate) struct InspectionOwner<'records, 'selection> {
+ pub fields: &'records BTreeMap<String, CacheValue>,
+ pub field: &'selection FieldNode,
}
/// Result of resolving the owner through currently loaded effective records.
-pub(crate) enum OwnerResolution {
- Owner(InspectionOwner),
- NeedRecord(EntityKey),
+pub(crate) enum OwnerResolution<'records, 'selection> {
+ Owner(InspectionOwner<'records, 'selection>),
+ NeedRecord(EntityKey<'records>),
Absent,
}
@@ -182,50 +182,47 @@ pub(crate) fn prepare(
}
/// Resolves the record/object that owns the final selected field.
-pub(crate) fn resolve_owner(
- records: &HashMap<EntityKey, Record>,
- operation: &Operation,
+pub(crate) fn resolve_owner<'records, 'selection>(
+ records: &'records HashMap<EntityKey<'static>, Record>,
+ operation: &'selection Operation,
path: &[String],
-) -> Result<OwnerResolution, QueryInspectionError> {
+) -> Result<OwnerResolution<'records, 'selection>, QueryInspectionError> {
resolve_record_owner(
records,
- &EntityKey::root(),
+ EntityKey::root(),
meta::QUERY_ROOT_TYPE,
&operation.selection_set,
path,
)
}
-fn resolve_record_owner(
- records: &HashMap<EntityKey, Record>,
- key: &EntityKey,
+fn resolve_record_owner<'records, 'selection>(
+ records: &'records HashMap<EntityKey<'static>, Record>,
+ key: EntityKey<'records>,
declared_type: &str,
- selections: &[Selection],
+ selections: &'selection [Selection],
path: &[String],
-) -> Result<OwnerResolution, QueryInspectionError> {
- let Some(record) = records.get(key) else {
- return Ok(OwnerResolution::NeedRecord(key.clone()));
+) -> Result<OwnerResolution<'records, 'selection>, QueryInspectionError> {
+ let Some(record) = records.get(key.as_ref()) else {
+ return Ok(OwnerResolution::NeedRecord(key));
};
let concrete = record.typename().unwrap_or(declared_type);
resolve_fields_owner(records, &record.fields, concrete, selections, path)
}
-fn resolve_fields_owner(
- records: &HashMap<EntityKey, Record>,
- fields: &BTreeMap<String, CacheValue>,
+fn resolve_fields_owner<'records, 'selection>(
+ records: &'records HashMap<EntityKey<'static>, Record>,
+ fields: &'records BTreeMap<String, CacheValue>,
concrete: &str,
- selections: &[Selection],
+ selections: &'selection [Selection],
path: &[String],
-) -> Result<OwnerResolution, QueryInspectionError> {
+) -> Result<OwnerResolution<'records, 'selection>, QueryInspectionError> {
let response_key = &path[0];
let Some(field) = selected_field(selections, concrete, response_key) else {
return Ok(OwnerResolution::Absent);
};
if path.len() == 1 {
- return Ok(OwnerResolution::Owner(InspectionOwner {
- fields: fields.clone(),
- field: field.clone(),
- }));
+ return Ok(OwnerResolution::Owner(InspectionOwner { fields, field }));
}
let storage_key = selected_storage_key(field, &serde_json::Map::new())
@@ -239,9 +236,13 @@ fn resolve_fields_owner(
field: response_key.clone(),
})?;
match value {
- CacheValue::Ref(key) => {
- resolve_record_owner(records, key, next_type, &field.selection_set, &path[1..])
- }
+ CacheValue::Ref(key) => resolve_record_owner(
+ records,
+ key.borrow(),
+ next_type,
+ &field.selection_set,
+ &path[1..],
+ ),
CacheValue::Object(object) => {
let concrete = object
.get("__typename")
@@ -259,7 +260,7 @@ fn resolve_fields_owner(
/// Recovers and canonically deduplicates variables from matching owner fields.
pub(crate) fn recover_variants(
- owner: &InspectionOwner,
+ owner: &InspectionOwner<'_, '_>,
prepared: &PreparedInspection,
) -> Result<Vec<serde_json::Map<String, Json>>, QueryInspectionError> {
let mut matching = 0usize;
@@ -275,7 +276,7 @@ pub(crate) fn recover_variants(
maximum: MAX_INSPECTED_VARIANTS,
});
}
- let Some(variables) = invert_arguments(&owner.field, &stored_arguments) else {
+ let Some(variables) = invert_arguments(owner.field, &stored_arguments) else {
continue;
};
if prepared
diff --git a/crates/client/cache-core/src/query_inspection/test.rs b/crates/client/cache-core/src/query_inspection/test.rs
index 9b096e026a..cd15ea9f25 100644
--- a/crates/client/cache-core/src/query_inspection/test.rs
+++ b/crates/client/cache-core/src/query_inspection/test.rs
@@ -18,8 +18,9 @@ fn concrete_union_member_outside_selected_fragment_is_absent() {
})],
}];
+ let records = HashMap::new();
let result = resolve_fields_owner(
- &HashMap::new(),
+ &records,
&fields,
"GraphqlSoupChannel",
&selections,
diff --git a/crates/client/cache-core/src/record_selection.rs b/crates/client/cache-core/src/record_selection.rs
index 557118aea4..0f4a0e2414 100644
--- a/crates/client/cache-core/src/record_selection.rs
+++ b/crates/client/cache-core/src/record_selection.rs
@@ -9,6 +9,7 @@ use crate::meta::{self, FieldKind, TypeKind};
use crate::value::EntityKey;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
use serde_json::Value as Json;
+use std::borrow::Cow;
use std::collections::BTreeSet;
use thiserror::Error;
@@ -62,14 +63,14 @@ impl RecordSelection {
/// Opaque exclusive cursor into entity-key record ordering.
#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct RecordCursor(EntityKey);
+pub struct RecordCursor(EntityKey<'static>);
impl RecordCursor {
- pub(crate) fn new(entity_key: EntityKey) -> Self {
+ pub(crate) fn new(entity_key: EntityKey<'static>) -> Self {
Self(entity_key)
}
- pub(crate) fn entity_key(&self) -> &EntityKey {
+ pub(crate) fn entity_key(&self) -> &EntityKey<'static> {
&self.0
}
}
@@ -247,7 +248,7 @@ fn referenced_variable(value: &ArgValue) -> Option<&str> {
}
}
-fn encode_cursor(entity_key: &EntityKey) -> String {
+fn encode_cursor(entity_key: &EntityKey<'_>) -> String {
let encoded: String = entity_key
.0
.as_bytes()
@@ -257,7 +258,7 @@ fn encode_cursor(entity_key: &EntityKey) -> String {
format!("r1.{encoded}")
}
-fn decode_cursor(value: &str) -> Result<EntityKey, &'static str> {
+fn decode_cursor(value: &str) -> Result<EntityKey<'static>, &'static str> {
let encoded = value
.strip_prefix("r1.")
.ok_or("invalid record-selection cursor")?;
@@ -273,6 +274,7 @@ fn decode_cursor(value: &str) -> Result<EntityKey, &'static str> {
})
.collect::<Result<Vec<_>, _>>()?;
String::from_utf8(bytes)
+ .map(Cow::Owned)
.map(EntityKey)
.map_err(|_| "invalid record-selection cursor")
}
diff --git a/crates/client/cache-core/src/record_selection/test.rs b/crates/client/cache-core/src/record_selection/test.rs
index 54f93c2821..d43cf4c6d9 100644
--- a/crates/client/cache-core/src/record_selection/test.rs
+++ b/crates/client/cache-core/src/record_selection/test.rs
@@ -101,7 +101,7 @@ fn validates_page_limits() {
#[test]
fn cursor_has_opaque_roundtrip() {
- let cursor = RecordCursor::new(EntityKey("GraphqlSoupDocument:item-1".to_string()));
+ let cursor = RecordCursor::new(EntityKey("GraphqlSoupDocument:item-1".into()));
let encoded = serde_json::to_value(&cursor).unwrap();
assert_eq!(
serde_json::from_value::<RecordCursor>(encoded).unwrap(),
diff --git a/crates/client/cache-core/src/store.rs b/crates/client/cache-core/src/store.rs
index c079b2d87a..eabd08beab 100644
--- a/crates/client/cache-core/src/store.rs
+++ b/crates/client/cache-core/src/store.rs
@@ -23,19 +23,19 @@ pub trait Storage: MaybeSend {
/// Fetches records; result is aligned with `keys` (`None` = absent).
fn get_batch(
&self,
- keys: &[EntityKey],
+ keys: &[EntityKey<'static>],
) -> impl Future<Output = Result<Vec<Option<Record>>, Self::Error>> + MaybeSend;
/// Upserts records atomically (all-or-nothing per batch).
fn put_batch(
&mut self,
- entries: Vec<(EntityKey, Record)>,
+ entries: Vec<(EntityKey<'static>, Record)>,
) -> impl Future<Output = Result<(), Self::Error>> + MaybeSend;
/// Deletes records (absent keys are ignored).
fn delete_batch(
&mut self,
- keys: &[EntityKey],
+ keys: &[EntityKey<'static>],
) -> impl Future<Output = Result<(), Self::Error>> + MaybeSend;
/// Scans normalized records of the requested concrete types in ascending
@@ -43,9 +43,9 @@ pub trait Storage: MaybeSend {
fn scan_records(
&self,
type_names: &[String],
- after: Option<&EntityKey>,
+ after: Option<&EntityKey<'static>>,
limit: usize,
- ) -> impl Future<Output = Result<Vec<(EntityKey, Record)>, Self::Error>> + MaybeSend;
+ ) -> impl Future<Output = Result<Vec<(EntityKey<'static>, Record)>, Self::Error>> + MaybeSend;
/// Atomically appends a mutation and its optimistic layer to the queue.
fn enqueue_mutation(
@@ -82,7 +82,7 @@ pub trait Storage: MaybeSend {
&mut self,
id: MutationId,
claim: MutationClaimToken,
- entries: Vec<(EntityKey, Record)>,
+ entries: Vec<(EntityKey<'static>, Record)>,
) -> impl Future<Output = Result<bool, Self::Error>> + MaybeSend;
/// Atomically removes a permanently failed mutation and its optimistic
@@ -101,7 +101,7 @@ pub trait Storage: MaybeSend {
/// Hash-map storage for tests and as the Phase 1 default.
#[derive(Clone, Debug, Default)]
pub struct InMemoryStorage {
- records: HashMap<EntityKey, Record>,
+ records: HashMap<EntityKey<'static>, Record>,
mutations: BTreeMap<
MutationId,
(
@@ -129,18 +129,24 @@ impl InMemoryStorage {
impl Storage for InMemoryStorage {
type Error = Infallible;
- async fn get_batch(&self, keys: &[EntityKey]) -> Result<Vec<Option<Record>>, Self::Error> {
+ async fn get_batch(
+ &self,
+ keys: &[EntityKey<'static>],
+ ) -> Result<Vec<Option<Record>>, Self::Error> {
Ok(keys.iter().map(|k| self.records.get(k).cloned()).collect())
}
- async fn put_batch(&mut self, entries: Vec<(EntityKey, Record)>) -> Result<(), Self::Error> {
+ async fn put_batch(
+ &mut self,
+ entries: Vec<(EntityKey<'static>, Record)>,
+ ) -> Result<(), Self::Error> {
for (k, v) in entries {
self.records.insert(k, v);
}
Ok(())
}
- async fn delete_batch(&mut self, keys: &[EntityKey]) -> Result<(), Self::Error> {
+ async fn delete_batch(&mut self, keys: &[EntityKey<'static>]) -> Result<(), Self::Error> {
for k in keys {
self.records.remove(k);
}
@@ -150,9 +156,9 @@ impl Storage for InMemoryStorage {
async fn scan_records(
&self,
type_names: &[String],
- after: Option<&EntityKey>,
+ after: Option<&EntityKey<'static>>,
limit: usize,
- ) -> Result<Vec<(EntityKey, Record)>, Self::Error> {
+ ) -> Result<Vec<(EntityKey<'static>, Record)>, Self::Error> {
if limit == 0 || type_names.is_empty() {
return Ok(Vec::new());
}
@@ -161,7 +167,7 @@ impl Storage for InMemoryStorage {
let mut records: Vec<_> = self
.records
.iter()
- .filter(|(key, _)| after.is_none_or(|after| *key > after))
+ .filter(|(key, _)| after.as_ref().is_none_or(|after| *key > after))
.filter(|(key, _)| {
key.0
.split_once(':')
@@ -254,7 +260,7 @@ impl Storage for InMemoryStorage {
&mut self,
id: MutationId,
claim: MutationClaimToken,
- entries: Vec<(EntityKey, Record)>,
+ entries: Vec<(EntityKey<'static>, Record)>,
) -> Result<bool, Self::Error> {
let Some((mutation, _)) = self.mutations.get(&id) else {
return Ok(false);
diff --git a/crates/client/cache-core/src/value.rs b/crates/client/cache-core/src/value.rs
index c844ac6bd1..35c5bdbf57 100644
--- a/crates/client/cache-core/src/value.rs
+++ b/crates/client/cache-core/src/value.rs
@@ -2,21 +2,22 @@
//! values.
use serde::{Deserialize, Serialize};
+use std::borrow::{Borrow, Cow};
use std::collections::BTreeMap;
use std::fmt;
/// Key of a normalized record: `"Typename:keyValue"`, or [`ROOT_QUERY`].
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
-pub struct EntityKey(pub String);
+pub struct EntityKey<'a>(pub Cow<'a, str>);
/// The singleton record holding root-level query fields (graphcache's
/// `Query` record). Field keys on it embed arguments, e.g.
/// `soup({"input":{...}})`.
pub const ROOT_QUERY: &str = "ROOT_QUERY";
-impl EntityKey {
+impl EntityKey<'static> {
pub fn root() -> Self {
- EntityKey(ROOT_QUERY.to_string())
+ EntityKey(Cow::Borrowed(ROOT_QUERY))
}
pub fn entity(typename: &str, key_values: &[&str]) -> Self {
@@ -26,15 +27,38 @@ impl EntityKey {
s.push(':');
s.push_str(v);
}
- EntityKey(s)
+ EntityKey(s.into())
}
+}
+impl<'a> EntityKey<'a> {
pub fn is_root(&self) -> bool {
self.0 == ROOT_QUERY
}
+
+ pub fn borrow(&self) -> EntityKey<'_> {
+ EntityKey(Cow::Borrowed(self.0.as_ref()))
+ }
+
+ /// Converts this key into an owned key that can be stored independently.
+ pub fn into_owned(self) -> EntityKey<'static> {
+ EntityKey(Cow::Owned(self.0.into_owned()))
+ }
+}
+
+impl Borrow<str> for EntityKey<'_> {
+ fn borrow(&self) -> &str {
+ self.0.as_ref()
+ }
+}
+
+impl AsRef<str> for EntityKey<'_> {
+ fn as_ref(&self) -> &str {
+ self.0.as_ref()
+ }
}
-impl fmt::Display for EntityKey {
+impl<'a> fmt::Display for EntityKey<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
@@ -93,7 +117,7 @@ pub enum CacheValue {
Number(CacheNumber),
String(String),
/// Link to another normalized record.
- Ref(EntityKey),
+ Ref(EntityKey<'static>),
/// Embedded (non-keyable) object. `__typename` is stored as a regular
/// field when known, for fragment matching on read.
Object(BTreeMap<FieldKey, CacheValue>),
diff --git a/crates/client/cache-core/tests/optimistic.rs b/crates/client/cache-core/tests/optimistic.rs
index ed8546caf8..65e538571b 100644
--- a/crates/client/cache-core/tests/optimistic.rs
+++ b/crates/client/cache-core/tests/optimistic.rs
@@ -163,7 +163,7 @@ async fn claim_head(
async fn durable_value(engine: &Engine<InMemoryStorage>) -> Option<String> {
let records = engine
.storage()
- .get_batch(&[EntityKey(PROPERTY_KEY.to_string())])
+ .get_batch(&[EntityKey(PROPERTY_KEY.to_string().into())])
.await
.unwrap();
let record = records.into_iter().next().flatten()?;
diff --git a/crates/client/cache-core/tests/query_inspection.rs b/crates/client/cache-core/tests/query_inspection.rs
index 75674feab5..79c669872e 100644
--- a/crates/client/cache-core/tests/query_inspection.rs
+++ b/crates/client/cache-core/tests/query_inspection.rs
@@ -88,7 +88,10 @@ struct OwnerOnlyStorage(InMemoryStorage);
impl Storage for OwnerOnlyStorage {
type Error = std::convert::Infallible;
- async fn get_batch(&self, keys: &[EntityKey]) -> Result<Vec<Option<Record>>, Self::Error> {
+ async fn get_batch(
+ &self,
+ keys: &[EntityKey<'static>],
+ ) -> Result<Vec<Option<Record>>, Self::Error> {
assert!(
keys.iter()
.all(|key| key.is_root() || key.0 == "GraphqlUser:user-1"),
@@ -97,20 +100,23 @@ impl Storage for OwnerOnlyStorage {
self.0.get_batch(keys).await
}
- async fn put_batch(&mut self, entries: Vec<(EntityKey, Record)>) -> Result<(), Self::Error> {
+ async fn put_batch(
+ &mut self,
+ entries: Vec<(EntityKey<'static>, Record)>,
+ ) -> Result<(), Self::Error> {
self.0.put_batch(entries).await
}
- async fn delete_batch(&mut self, keys: &[EntityKey]) -> Result<(), Self::Error> {
+ async fn delete_batch(&mut self, keys: &[EntityKey<'static>]) -> Result<(), Self::Error> {
self.0.delete_batch(keys).await
}
async fn scan_records(
&self,
type_names: &[String],
- after: Option<&EntityKey>,
+ after: Option<&EntityKey<'static>>,
limit: usize,
- ) -> Result<Vec<(EntityKey, Record)>, Self::Error> {
+ ) -> Result<Vec<(EntityKey<'static>, Record)>, Self::Error> {
self.0.scan_records(type_names, after, limit).await
}
@@ -148,7 +154,7 @@ impl Storage for OwnerOnlyStorage {
&mut self,
id: MutationId,
claim: MutationClaimToken,
- entries: Vec<(EntityKey, Record)>,
+ entries: Vec<(EntityKey<'static>, Record)>,
) -> Result<bool, Self::Error> {
self.0.complete_mutation(id, claim, entries).await
}
diff --git a/crates/client/cache-core/tests/record_selection.rs b/crates/client/cache-core/tests/record_selection.rs
index e878e0442b..0aa5cd0521 100644
--- a/crates/client/cache-core/tests/record_selection.rs
+++ b/crates/client/cache-core/tests/record_selection.rs
@@ -19,11 +19,11 @@ fn record(type_name: &str, fields: impl IntoIterator<Item = (&'static str, Cache
Record { fields: values }
}
-fn key(value: &str) -> EntityKey {
- EntityKey(value.to_string())
+fn key(value: &str) -> EntityKey<'static> {
+ EntityKey(value.to_string().into())
}
-fn linked_document(id: &str, property: Option<EntityKey>) -> (EntityKey, Record) {
+fn linked_document(id: &str, property: Option<EntityKey<'static>>) -> (EntityKey<'static>, Record) {
let mut fields = vec![("id", CacheValue::String(id.to_string()))];
if let Some(property) = property {
fields.push((
@@ -37,7 +37,7 @@ fn linked_document(id: &str, property: Option<EntityKey>) -> (EntityKey, Record)
)
}
-fn property(id: &str, name: &str) -> (EntityKey, Record) {
+fn property(id: &str, name: &str) -> (EntityKey<'static>, Record) {
(
key(&format!("GraphqlProperty:{id}")),
record(
@@ -50,7 +50,7 @@ fn property(id: &str, name: &str) -> (EntityKey, Record) {
)
}
-fn document(id: &str, name: &str) -> (EntityKey, Record) {
+fn document(id: &str, name: &str) -> (EntityKey<'static>, Record) {
(
key(&format!("GraphqlSoupDocument:{id}")),
record(
diff --git a/crates/client/cache-core/tests/roundtrip.rs b/crates/client/cache-core/tests/roundtrip.rs
index 17d4453594..44763301ce 100644
--- a/crates/client/cache-core/tests/roundtrip.rs
+++ b/crates/client/cache-core/tests/roundtrip.rs
@@ -134,7 +134,7 @@ fn response_data() -> Json {
})
}
-fn write(records: &mut BTreeMap<EntityKey, Record>, doc: &Document, data: &Json) {
+fn write(records: &mut BTreeMap<EntityKey<'static>, Record>, doc: &Document, data: &Json) {
let op = doc.operation(Some("Soup")).unwrap();
let updates = normalize(op, &variables(), data).unwrap();
for (key, record) in updates {
@@ -148,7 +148,7 @@ fn normalizes_expected_records() {
let mut records = BTreeMap::new();
write(&mut records, &doc, &response_data());
- let keys: Vec<&str> = records.keys().map(|k| k.0.as_str()).collect();
+ let keys: Vec<&str> = records.keys().map(|k| k.0.as_ref()).collect();
assert_eq!(
keys,
vec![
@@ -211,7 +211,7 @@ fn round_trip_reproduces_response() {
assert_eq!(data, response_data());
// Dependencies include every entity visited.
- let dep_keys: Vec<&str> = deps.iter().map(|k| k.0.as_str()).collect();
+ let dep_keys: Vec<&str> = deps.iter().map(|k| k.0.as_ref()).collect();
assert_eq!(
dep_keys,
vec![
@@ -262,7 +262,7 @@ fn entity_update_visible_through_other_query() {
for (key, record) in updates {
let entry = records.entry(key.clone()).or_default();
if entry.merge(record) {
- changed.push(key.0);
+ changed.push(key.0.into_owned());
}
}
// The document record changed; the soup page (same args) also rewritten.
@@ -316,7 +316,7 @@ fn missing_records_reported_for_batch_fetch() {
panic!("expected NeedRecords, got {outcome:?}");
};
assert_eq!(
- missing.iter().map(|k| k.0.as_str()).collect::<Vec<_>>(),
+ missing.iter().map(|k| k.0.as_ref()).collect::<Vec<_>>(),
vec!["GraphqlSoupChannel:ch-1"]
);
}
diff --git a/crates/client/cache-idb/src/idb_storage.rs b/crates/client/cache-idb/src/idb_storage.rs
index 4feb71f635..b5aec790c8 100644
--- a/crates/client/cache-idb/src/idb_storage.rs
+++ b/crates/client/cache-idb/src/idb_storage.rs
@@ -190,7 +190,10 @@ impl IdbStorage {
impl Storage for IdbStorage {
type Error = IdbStorageError;
- async fn get_batch(&self, keys: &[EntityKey]) -> Result<Vec<Option<Record>>, Self::Error> {
+ async fn get_batch(
+ &self,
+ keys: &[EntityKey<'static>],
+ ) -> Result<Vec<Option<Record>>, Self::Error> {
let tx = self
.db
.transaction(&[RECORDS_STORE], TransactionMode::ReadOnly)?;
@@ -200,7 +203,7 @@ impl Storage for IdbStorage {
// transaction), then await in order.
let mut requests = Vec::with_capacity(keys.len());
for key in keys {
- requests.push(store.get(JsValue::from_str(&key.0))?);
+ requests.push(store.get(JsValue::from_str(key.0.as_ref()))?);
}
let mut out = Vec::with_capacity(keys.len());
for request in requests {
@@ -213,27 +216,33 @@ impl Storage for IdbStorage {
Ok(out)
}
- async fn put_batch(&mut self, entries: Vec<(EntityKey, Record)>) -> Result<(), Self::Error> {
+ async fn put_batch(
+ &mut self,
+ entries: Vec<(EntityKey<'static>, Record)>,
+ ) -> Result<(), Self::Error> {
let tx = self
.db
.transaction(&[RECORDS_STORE], TransactionMode::ReadWrite)?;
let store = tx.object_store(RECORDS_STORE)?;
for (key, record) in &entries {
let bytes = encode_record(record);
- store.put(&bytes_to_js(&bytes), Some(&JsValue::from_str(&key.0)))?;
+ store.put(
+ &bytes_to_js(&bytes),
+ Some(&JsValue::from_str(key.0.as_ref())),
+ )?;
}
// Committing the transaction is what makes the batch atomic.
tx.commit()?.await?;
Ok(())
}
- async fn delete_batch(&mut self, keys: &[EntityKey]) -> Result<(), Self::Error> {
+ async fn delete_batch(&mut self, keys: &[EntityKey<'static>]) -> Result<(), Self::Error> {
let tx = self
.db
.transaction(&[RECORDS_STORE], TransactionMode::ReadWrite)?;
let store = tx.object_store(RECORDS_STORE)?;
for key in keys {
- store.delete(JsValue::from_str(&key.0))?;
+ store.delete(JsValue::from_str(key.0.as_ref()))?;
}
tx.commit()?.await?;
Ok(())
@@ -242,9 +251,9 @@ impl Storage for IdbStorage {
async fn scan_records(
&self,
type_names: &[String],
- after: Option<&EntityKey>,
+ after: Option<&EntityKey<'static>>,
limit: usize,
- ) -> Result<Vec<(EntityKey, Record)>, Self::Error> {
+ ) -> Result<Vec<(EntityKey<'static>, Record)>, Self::Error> {
if type_names.is_empty() || limit == 0 {
return Ok(Vec::new());
}
@@ -259,11 +268,11 @@ impl Storage for IdbStorage {
}
let prefix = format!("{type_name}:");
let upper = format!("{type_name};");
- if after.is_some_and(|after| after.0.as_str() >= upper.as_str()) {
+ if after.is_some_and(|after| after.0.as_ref() >= upper.as_str()) {
continue;
}
let (lower, lower_open) = match after {
- Some(after) if after.0.as_str() >= prefix.as_str() => (after.0.as_str(), true),
+ Some(after) if after.0.as_ref() >= prefix.as_str() => (after.0.as_ref(), true),
_ => (prefix.as_str(), false),
};
let range = KeyRange::bound(
@@ -291,7 +300,10 @@ impl Storage for IdbStorage {
break;
};
let key = key.as_string().ok_or(IdbStorageError::NotString)?;
- records.push((EntityKey(key), decode_record(&bytes_from_js(value)?)?));
+ records.push((
+ EntityKey(key.into()),
+ decode_record(&bytes_from_js(value)?)?,
+ ));
cursor.next(None).await?;
}
}
@@ -466,7 +478,7 @@ impl Storage for IdbStorage {
&mut self,
id: MutationId,
claim: MutationClaimToken,
- entries: Vec<(EntityKey, Record)>,
+ entries: Vec<(EntityKey<'static>, Record)>,
) -> Result<bool, Self::Error> {
let key = mutation_id_to_js(id)?;
let tx = self.db.transaction(
@@ -487,7 +499,7 @@ impl Storage for IdbStorage {
for (record_key, record) in &entries {
records.put(
&bytes_to_js(&encode_record(record)),
- Some(&JsValue::from_str(&record_key.0)),
+ Some(&JsValue::from_str(record_key.0.as_ref())),
)?;
}
queue.delete(key.clone())?;
diff --git a/crates/client/cache-idb/tests/web.rs b/crates/client/cache-idb/tests/web.rs
index f3f2d013e0..e728fedc54 100644
--- a/crates/client/cache-idb/tests/web.rs
+++ b/crates/client/cache-idb/tests/web.rs
@@ -24,8 +24,8 @@ fn record(name: &str) -> Record {
r
}
-fn key(s: &str) -> EntityKey {
- EntityKey(s.to_string())
+fn key(s: &str) -> EntityKey<'static> {
+ EntityKey(s.to_string().into())
}
fn queued(name: &str) -> NewQueuedMutation {
@@ -96,7 +96,7 @@ async fn scans_selected_record_types_in_key_order() {
assert_eq!(
first
.iter()
- .map(|(key, _)| key.0.as_str())
+ .map(|(key, _)| key.0.as_ref())
.collect::<Vec<_>>(),
vec!["TypeA:1", "TypeA:2"]
);
@@ -107,7 +107,7 @@ async fn scans_selected_record_types_in_key_order() {
assert_eq!(
second
.iter()
- .map(|(key, _)| key.0.as_str())
+ .map(|(key, _)| key.0.as_ref())
.collect::<Vec<_>>(),
vec!["TypeB:2"]
);
diff --git a/crates/client/cache-sqlite/src/lib.rs b/crates/client/cache-sqlite/src/lib.rs
index 8e13770ba8..7ed5b9a815 100644
--- a/crates/client/cache-sqlite/src/lib.rs
+++ b/crates/client/cache-sqlite/src/lib.rs
@@ -224,13 +224,16 @@ fn claim_is_current(
impl Storage for SqliteStorage {
type Error = SqliteStorageError;
- async fn get_batch(&self, keys: &[EntityKey]) -> Result<Vec<Option<Record>>, Self::Error> {
+ async fn get_batch(
+ &self,
+ keys: &[EntityKey<'static>],
+ ) -> Result<Vec<Option<Record>>, Self::Error> {
let conn = self.conn();
let mut stmt = conn.prepare_cached("SELECT value FROM records WHERE key = ?1")?;
let mut out = Vec::with_capacity(keys.len());
for key in keys {
let bytes: Option<Vec<u8>> = stmt
- .query_row(params![key.0], |row| row.get(0))
+ .query_row(params![key.0.as_ref()], |row| row.get(0))
.optional()?;
out.push(match bytes {
Some(b) => Some(decode_record(&b)?),
@@ -240,7 +243,10 @@ impl Storage for SqliteStorage {
Ok(out)
}
- async fn put_batch(&mut self, entries: Vec<(EntityKey, Record)>) -> Result<(), Self::Error> {
+ async fn put_batch(
+ &mut self,
+ entries: Vec<(EntityKey<'static>, Record)>,
+ ) -> Result<(), Self::Error> {
let mut conn = self.conn();
let tx = conn.transaction()?;
{
@@ -249,20 +255,20 @@ impl Storage for SqliteStorage {
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
)?;
for (key, record) in &entries {
- stmt.execute(params![key.0, encode_record(record)])?;
+ stmt.execute(params![key.0.as_ref(), encode_record(record)])?;
}
}
tx.commit()?;
Ok(())
}
- async fn delete_batch(&mut self, keys: &[EntityKey]) -> Result<(), Self::Error> {
+ async fn delete_batch(&mut self, keys: &[EntityKey<'static>]) -> Result<(), Self::Error> {
let mut conn = self.conn();
let tx = conn.transaction()?;
{
let mut stmt = tx.prepare_cached("DELETE FROM records WHERE key = ?1")?;
for key in keys {
- stmt.execute(params![key.0])?;
+ stmt.execute(params![key.0.as_ref()])?;
}
}
tx.commit()?;
@@ -272,9 +278,9 @@ impl Storage for SqliteStorage {
async fn scan_records(
&self,
type_names: &[String],
- after: Option<&EntityKey>,
+ after: Option<&EntityKey<'static>>,
limit: usize,
- ) -> Result<Vec<(EntityKey, Record)>, Self::Error> {
+ ) -> Result<Vec<(EntityKey<'static>, Record)>, Self::Error> {
if type_names.is_empty() || limit == 0 {
return Ok(Vec::new());
}
@@ -283,7 +289,7 @@ impl Storage for SqliteStorage {
let mut values = Vec::<rusqlite::types::Value>::new();
if let Some(after) = after {
sql.push_str("key > ? AND ");
- values.push(after.0.clone().into());
+ values.push(after.0.to_string().into());
}
sql.push('(');
for (index, type_name) in type_names.iter().enumerate() {
@@ -305,7 +311,7 @@ impl Storage for SqliteStorage {
let mut records = Vec::new();
for row in rows {
let (key, value) = row?;
- records.push((EntityKey(key), decode_record(&value)?));
+ records.push((EntityKey(key.into()), decode_record(&value)?));
}
Ok(records)
}
@@ -498,7 +504,7 @@ impl Storage for SqliteStorage {
&mut self,
id: MutationId,
claim: MutationClaimToken,
- entries: Vec<(EntityKey, Record)>,
+ entries: Vec<(EntityKey<'static>, Record)>,
) -> Result<bool, Self::Error> {
let sql_id = mutation_id_to_sql(id)?;
let mut conn = self.conn();
@@ -513,7 +519,7 @@ impl Storage for SqliteStorage {
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
)?;
for (key, record) in &entries {
- stmt.execute(params![key.0, encode_record(record)])?;
+ stmt.execute(params![key.0.as_ref(), encode_record(record)])?;
}
}
tx.execute("DELETE FROM mutation_queue WHERE id = ?1", params![sql_id])?;
@@ -562,8 +568,8 @@ mod tests {
r
}
- fn key(s: &str) -> EntityKey {
- EntityKey(s.to_string())
+ fn key(s: &str) -> EntityKey<'static> {
+ EntityKey(s.to_string().into())
}
#[test]
@@ -616,7 +622,7 @@ mod tests {
assert_eq!(
first
.iter()
- .map(|(key, _)| key.0.as_str())
+ .map(|(key, _)| key.0.as_ref())
.collect::<Vec<_>>(),
vec!["TypeA:1", "TypeA:2"]
);
@@ -627,7 +633,7 @@ mod tests {
assert_eq!(
second
.iter()
- .map(|(key, _)| key.0.as_str())
+ .map(|(key, _)| key.0.as_ref())
.collect::<Vec<_>>(),
vec!["TypeB:2"]
);
diff --git a/crates/client/cache-wasm/Cargo.toml b/crates/client/cache-wasm/Cargo.toml
index 6a652eda70..8405d0bb76 100644
--- a/crates/client/cache-wasm/Cargo.toml
+++ b/crates/client/cache-wasm/Cargo.toml
@@ -7,6 +7,16 @@ version = "0.3.2"
[lib]
crate-type = ["cdylib", "rlib"]
+# Custom profiles are reserved for local profiling builds. Keep Rust DWARF in
+# wasm-bindgen's output and skip wasm-opt, which otherwise strips or rewrites
+# the source locations needed to symbolicate Firefox profiles.
+[package.metadata.wasm-pack.profile.custom]
+wasm-opt = false
+
+[package.metadata.wasm-pack.profile.custom.wasm-bindgen]
+demangle-name-section = true
+dwarf-debug-info = true
+
# Browser-only wasm-bindgen shell around the engine + IDB storage. Like
# cache-idb, it compiles to an empty shell off-wasm so workspace `cargo test`
# stays green.
diff --git a/crates/client/cache-wasm/src/shell.rs b/crates/client/cache-wasm/src/shell.rs
index 4b42b32cf9..d0b6b0af8e 100644
--- a/crates/client/cache-wasm/src/shell.rs
+++ b/crates/client/cache-wasm/src/shell.rs
@@ -327,7 +327,11 @@ impl CacheEngine {
.await
.map_err(err_js)?;
to_js(&JsWriteResult {
- changed: result.changed.into_iter().map(|k| k.0).collect(),
+ changed: result
+ .changed
+ .into_iter()
+ .map(|key| key.0.into_owned())
+ .collect(),
affected_ops: ops.borrow().names(result.affected_ops),
reset: result.reset,
revalidations: result.revalidations,
@@ -377,7 +381,11 @@ impl CacheEngine {
.map_err(err_js)?;
to_js(&JsOptimisticWriteResult {
transaction_id: transaction.to_string(),
- changed: result.changed.into_iter().map(|k| k.0).collect(),
+ changed: result
+ .changed
+ .into_iter()
+ .map(|key| key.0.into_owned())
+ .collect(),
affected_ops: ops.borrow().names(result.affected_ops),
reset: result.reset,
revalidations: result.revalidations,
@@ -525,7 +533,11 @@ impl CacheEngine {
.await
.map_err(err_js)?;
to_js(&JsWriteResult {
- changed: result.changed.into_iter().map(|k| k.0).collect(),
+ changed: result
+ .changed
+ .into_iter()
+ .map(|key| key.0.into_owned())
+ .collect(),
affected_ops: ops.borrow().names(result.affected_ops),
reset: result.reset,
revalidations: result.revalidations,
@@ -556,7 +568,11 @@ impl CacheEngine {
.await
.map_err(err_js)?;
to_js(&JsWriteResult {
- changed: result.changed.into_iter().map(|k| k.0).collect(),
+ changed: result
+ .changed
+ .into_iter()
+ .map(|key| key.0.into_owned())
+ .collect(),
affected_ops: ops.borrow().names(result.affected_ops),
reset: result.reset,
revalidations: result.revalidations,
@@ -572,7 +588,8 @@ impl CacheEngine {
let engine = self.engine.clone();
let ops = self.ops.clone();
future_to_promise(async move {
- let keys: Vec<EntityKey> = keys.into_iter().map(EntityKey).collect();
+ let keys: Vec<EntityKey<'static>> =
+ keys.into_iter().map(|key| EntityKey(key.into())).collect();
let mut engine = engine.lock().await;
let affected = engine.invalidate_keys(keys.iter());
to_js(&ops.borrow().names(affected))
@@ -586,7 +603,8 @@ impl CacheEngine {
let engine = self.engine.clone();
let ops = self.ops.clone();
future_to_promise(async move {
- let keys: Vec<EntityKey> = keys.into_iter().map(EntityKey).collect();
+ let keys: Vec<EntityKey<'static>> =
+ keys.into_iter().map(|key| EntityKey(key.into())).collect();
let affected = engine
.lock()
.await
@@ -611,7 +629,11 @@ impl CacheEngine {
.await
.map_err(err_js)?;
to_js(&JsWriteResult {
- changed: result.changed.into_iter().map(|key| key.0).collect(),
+ changed: result
+ .changed
+ .into_iter()
+ .map(|key| key.0.into_owned())
+ .collect(),
affected_ops: ops.borrow().names(result.affected_ops),
reset: result.reset,
revalidations: result.revalidations,
diff --git a/nix/js-app.nix b/nix/js-app.nix
index bebc1ec961..c517cb5f73 100644
--- a/nix/js-app.nix
+++ b/nix/js-app.nix
@@ -50,6 +50,7 @@
complete.clippy
complete.rustfmt
complete.rust-analyzer
+ targets.wasm32-unknown-unknown.latest.rust-std
];
jsRustToolchain = with fenix.packages.${system}; combine jsRustComponents;
@@ -77,6 +78,8 @@
cargo-tauri
cargo-info
cargo-udeps
+ wasm-pack
+ wasm-bindgen-cli
cmake
nasm
pulumi
@@ -153,15 +156,18 @@
);
}
// pkgs.lib.optionalAttrs isLinux {
- js-app-android = jsPkgs.mkShell ({
- buildInputs = jsAndroidPackages ++ jsLibraries;
- PKG_CONFIG_PATH = jsPkgConfigPath;
- shellHook = jsLinuxShellHook;
- ANDROID_HOME = "${android_sdk}/libexec/android-sdk";
- NDK_HOME = "${android_sdk}/libexec/android-sdk/ndk/26.3.11579264";
- GRADLE_OPTS = "-Dorg.gradle.project.android.aapt2FromMavenOverride=${android_sdk}/libexec/android-sdk/build-tools/35.0.0/aapt2";
- GIO_MODULE_DIR = "${jsPkgs.glib-networking}/lib/gio/modules/";
- } // jsCmakeFixEnv);
+ js-app-android = jsPkgs.mkShell (
+ {
+ buildInputs = jsAndroidPackages ++ jsLibraries;
+ PKG_CONFIG_PATH = jsPkgConfigPath;
+ shellHook = jsLinuxShellHook;
+ ANDROID_HOME = "${android_sdk}/libexec/android-sdk";
+ NDK_HOME = "${android_sdk}/libexec/android-sdk/ndk/26.3.11579264";
+ GRADLE_OPTS = "-Dorg.gradle.project.android.aapt2FromMavenOverride=${android_sdk}/libexec/android-sdk/build-tools/35.0.0/aapt2";
+ GIO_MODULE_DIR = "${jsPkgs.glib-networking}/lib/gio/modules/";
+ }
+ // jsCmakeFixEnv
+ );
};
};
}