Skip to content

Commit 57682c3

Browse files
committed
chore(refactor): custom moudle meta data
1 parent 464ca29 commit 57682c3

File tree

20 files changed

+525
-349
lines changed

20 files changed

+525
-349
lines changed

crates/compiler/src/update/regenerate_resources/mod.rs

Lines changed: 7 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,11 @@ use farmfe_core::{
66
enhanced_magic_string::types::SourceMapOptions,
77
error::CompilationError,
88
module::{module_group::ModuleGroupId, Module, ModuleId},
9-
resource::resource_pot::{ResourcePot, ResourcePotMetaData, ResourcePotType},
9+
resource::resource_pot::{ResourcePot, ResourcePotType},
1010
};
1111

12-
use farmfe_plugin_runtime::render_resource_pot::{
13-
resource_pot_to_runtime_object, RenderedJsResourcePot,
14-
};
15-
use farmfe_plugin_runtime::ASYNC_MODULES;
16-
use farmfe_toolkit::hash::base64_encode;
17-
use farmfe_utils::relative;
18-
1912
use crate::{
20-
generate::render_resource_pots::{
21-
render_resource_pot_generate_resources, render_resource_pots_and_generate_resources,
22-
},
23-
write_cache,
13+
generate::render_resource_pots::render_resource_pots_and_generate_resources, write_cache,
2414
};
2515

2616
use super::diff_and_patch_module_graph::DiffResult;
@@ -78,68 +68,11 @@ pub fn render_and_generate_update_resource(
7868

7969
let gen_resource_pot_code =
8070
|resource_pot: &mut ResourcePot| -> farmfe_core::error::Result<String> {
81-
let async_modules = context.custom.get(ASYNC_MODULES).unwrap();
82-
let async_modules = async_modules.downcast_ref::<HashSet<ModuleId>>().unwrap();
83-
// if !resource_pot.modules().is_empty() {
84-
// let RenderedJsResourcePot {
85-
// mut bundle,
86-
// rendered_modules,
87-
// ..
88-
// } = resource_pot_to_runtime_object(resource_pot, &module_graph, async_modules, context)?;
89-
// bundle.prepend("(");
90-
// bundle.append(")", None);
91-
92-
// let mut rendered_map_chain = vec![];
93-
94-
// if context.config.sourcemap.enabled(resource_pot.immutable) {
95-
// let root = context.config.root.clone();
96-
// let map = bundle
97-
// .generate_map(SourceMapOptions {
98-
// include_content: Some(true),
99-
// remap_source: Some(Box::new(move |src| format!("/{}", relative(&root, src)))),
100-
// ..Default::default()
101-
// })
102-
// .map_err(|_| CompilationError::GenerateSourceMapError {
103-
// id: resource_pot.id.clone(),
104-
// })?;
105-
106-
// let mut buf = vec![];
107-
// map.to_writer(&mut buf).expect("failed to write sourcemap");
108-
// rendered_map_chain.push(Arc::new(String::from_utf8(buf).unwrap()));
109-
// }
110-
// // The hmr result should alway be a js resource
111-
// resource_pot.meta = ResourcePotMetaData {
112-
// rendered_modules,
113-
// rendered_content: Arc::new(bundle.to_string()),
114-
// rendered_map_chain,
115-
// ..Default::default()
116-
// };
117-
118-
// let (mut update_resources, _) = render_resource_pot_generate_resources(
119-
// resource_pot,
120-
// context,
121-
// &Default::default(),
122-
// true,
123-
// &mut None,
124-
// )?;
125-
126-
// if let Some(map) = update_resources.source_map {
127-
// // inline source map
128-
// update_resources.resource.bytes.append(
129-
// &mut format!(
130-
// "\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,{}",
131-
// base64_encode(&map.bytes)
132-
// )
133-
// .into_bytes(),
134-
// );
135-
// }
136-
137-
// let code = String::from_utf8(update_resources.resource.bytes).unwrap();
138-
139-
// return Ok(code);
140-
// }
141-
142-
Ok("{}".to_string())
71+
let res = context
72+
.plugin_driver
73+
.render_update_resource_pot(resource_pot, context)?;
74+
75+
res.map_or(Ok("{}".to_string()), |r| Ok(r.content))
14376
};
14477

14578
let immutable_update_resource = gen_resource_pot_code(&mut immutable_update_resource_pot)?;

crates/core/src/cache/cache_store.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use std::{
99

1010
use crate::config::Mode;
1111

12-
const FARM_CACHE_VERSION: &str = "0.6.0";
12+
const FARM_CACHE_VERSION: &str = "0.6.1";
1313
const FARM_CACHE_MANIFEST_FILE: &str = "farm-cache.json";
1414

1515
// TODO make CacheStore a trait and implement DiskCacheStore or RemoteCacheStore or more.

crates/core/src/cache/cacheable.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
use downcast_rs::{impl_downcast, Downcast};
2+
3+
pub trait Cacheable: std::any::Any + Send + Sync + Downcast {
4+
/// Serialize the data to bytes
5+
fn serialize_bytes(&self) -> Result<Vec<u8>, String>;
6+
/// Deserialize the bytes to data
7+
fn deserialize_bytes(&self, bytes: Vec<u8>) -> Result<Box<dyn Cacheable>, String>;
8+
}
9+
10+
impl_downcast!(Cacheable);

crates/core/src/cache/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use crate::config::Mode;
55
use self::{cache_store::CacheStore, plugin_cache::PluginCacheManager};
66

77
pub mod cache_store;
8+
pub mod cacheable;
89
pub mod module_cache;
910
pub mod plugin_cache;
1011
pub mod resource_cache;

crates/core/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ pub mod plugin;
1818
pub mod resource;
1919
pub mod stats;
2020

21+
pub use cache::cacheable::*;
2122
pub use farmfe_macro_cache_item::cache_item;
2223

2324
/// Version of this core crate, if the core data structures changed,
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
use crate::Cacheable;
2+
use dashmap::DashMap;
3+
use rkyv::*;
4+
use std::collections::{hash_map::Iter, HashMap};
5+
6+
#[derive(Default)]
7+
pub struct CustomMetaDataMap {
8+
map: HashMap<String, Box<dyn Cacheable>>,
9+
/// The bytes map is used to store the serialized data of the map above
10+
bytes_map: DashMap<String, Vec<u8>>,
11+
}
12+
13+
impl CustomMetaDataMap {
14+
pub fn new() -> Self {
15+
Self {
16+
map: HashMap::new(),
17+
bytes_map: DashMap::new(),
18+
}
19+
}
20+
21+
pub fn is_empty(&self) -> bool {
22+
self.map.is_empty()
23+
}
24+
25+
pub fn iter(&self) -> Iter<String, Box<dyn Cacheable>> {
26+
self.map.iter()
27+
}
28+
29+
pub fn get_mut<T: Cacheable + Default>(&mut self, key: &str) -> Option<&mut T> {
30+
if let Some((_, bytes)) = self.bytes_map.remove(key) {
31+
let value = T::deserialize_bytes(&T::default(), bytes).unwrap();
32+
self.map.insert(key.to_string(), value);
33+
}
34+
35+
self.map.get_mut(key).and_then(|v| v.downcast_mut::<T>())
36+
}
37+
}
38+
39+
impl From<HashMap<String, Box<dyn Cacheable>>> for CustomMetaDataMap {
40+
fn from(map: HashMap<String, Box<dyn Cacheable>>) -> Self {
41+
Self {
42+
map,
43+
bytes_map: DashMap::new(),
44+
}
45+
}
46+
}
47+
48+
impl Clone for CustomMetaDataMap {
49+
fn clone(&self) -> Self {
50+
let custom = if self.map.is_empty() {
51+
HashMap::new()
52+
} else {
53+
let mut custom = HashMap::new();
54+
for (k, v) in self.map.iter() {
55+
let cloned_data = v.serialize_bytes().unwrap();
56+
let cloned_custom = v.deserialize_bytes(cloned_data).unwrap();
57+
custom.insert(k.clone(), cloned_custom);
58+
}
59+
custom
60+
};
61+
62+
Self {
63+
map: custom,
64+
bytes_map: self.bytes_map.clone(),
65+
}
66+
}
67+
}
68+
69+
impl<__D: Fallible + ?Sized> Deserialize<CustomMetaDataMap, __D> for Archived<CustomMetaDataMap> {
70+
#[inline]
71+
fn deserialize(
72+
&self,
73+
deserializer: &mut __D,
74+
) -> ::core::result::Result<CustomMetaDataMap, __D::Error> {
75+
let map = Deserialize::<HashMap<String, Vec<u8>>, __D>::deserialize(&self.map, deserializer)?;
76+
let mut res = CustomMetaDataMap {
77+
map: HashMap::new(),
78+
bytes_map: DashMap::new(),
79+
};
80+
81+
res.bytes_map = map.into_iter().collect();
82+
Ok(res)
83+
}
84+
}
85+
86+
impl<__S: Fallible + ?Sized> Serialize<__S> for CustomMetaDataMap
87+
where
88+
__S: rkyv::ser::Serializer + rkyv::ser::ScratchSpace,
89+
{
90+
#[inline]
91+
fn serialize(&self, serializer: &mut __S) -> ::core::result::Result<Self::Resolver, __S::Error> {
92+
let mut map = HashMap::<String, Vec<u8>>::new();
93+
94+
for (k, v) in self.map.iter() {
95+
let cloned_data = v.serialize_bytes().unwrap();
96+
map.insert(k.clone(), cloned_data);
97+
}
98+
99+
let resolver_map = Serialize::<__S>::serialize(&map, serializer)?;
100+
101+
for (k, v) in map {
102+
self.bytes_map.insert(k, v);
103+
}
104+
105+
Ok(CustomMetaDataMapResolver { map: resolver_map })
106+
}
107+
}
108+
109+
pub struct ArchivedCustomMetaDataMap {
110+
///The archived counterpart of [`CustomMetaDataMap::map`]
111+
pub map: ::rkyv::Archived<HashMap<String, Vec<u8>>>,
112+
}
113+
114+
pub struct CustomMetaDataMapResolver {
115+
map: ::rkyv::Resolver<HashMap<String, Vec<u8>>>,
116+
}
117+
118+
impl Archive for CustomMetaDataMap {
119+
type Archived = ArchivedCustomMetaDataMap;
120+
type Resolver = CustomMetaDataMapResolver;
121+
#[allow(clippy::unit_arg)]
122+
#[inline]
123+
unsafe fn resolve(&self, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived) {
124+
let (fp, fo) = {
125+
#[allow(unused_unsafe)]
126+
unsafe {
127+
let fo = &raw mut (*out).map;
128+
(fo.cast::<u8>().offset_from(out.cast::<u8>()) as usize, fo)
129+
}
130+
};
131+
let mut map = HashMap::<String, Vec<u8>>::new();
132+
let mut keys = vec![];
133+
134+
for item in self.bytes_map.iter() {
135+
keys.push(item.key().clone());
136+
}
137+
138+
for key in keys {
139+
let (k, v) = self.bytes_map.remove(&key).unwrap();
140+
map.insert(k, v);
141+
}
142+
143+
::rkyv::Archive::resolve(&map, pos + fp, resolver.map, fo);
144+
}
145+
}

0 commit comments

Comments
 (0)