Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add logEntity function #405

Merged
merged 6 commits into from
Sep 11, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ run_script = "0.9"
regex = "1.5.4"
serde_yaml = "0.8.21"
graphql-parser = "0.4.0"
serde = "1.0.139"

[dev-dependencies]
serial_test = "0.5.1"
200 changes: 142 additions & 58 deletions src/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use graph_runtime_wasm::{
ExperimentalFeatures,
};
use lazy_static::lazy_static;
use serde::Serialize;
use serde_json::to_string_pretty;

use crate::logging;
Expand Down Expand Up @@ -64,24 +65,34 @@ lazy_static! {
};
}

type Store = HashMap<String, HashMap<String, HashMap<String, Value>>>;
type Store = HashMap<String, HashMap<String, StoreEntity>>;

/// Type of the store that needs to be accessed
pub enum StoreScope {
Global,
Cache,
}

#[derive(Serialize)]
#[serde(untagged)]
enum LogEntityValue {
Native(Value),
Derived(Vec<StoreEntity>),
}

type Entity = Vec<(Word, graph::prelude::Value)>;

trait Sortable {
fn sorted(&mut self) -> &Entity;
type StoreEntity = HashMap<String, Value>;

trait ConvertableEntity {
arrusev marked this conversation as resolved.
Show resolved Hide resolved
fn to_entity(&mut self) -> Entity;
}

impl Sortable for Entity {
fn sorted(&mut self) -> &Entity {
self.sort_by(|(k1, _), (k2, _)| k1.cmp(k2));
self
impl ConvertableEntity for StoreEntity {
fn to_entity(&mut self) -> Entity {
self.iter_mut()
.map(|(k, v)| (Word::from(k.to_string()), v.clone()))
.collect()
}
}

Expand Down Expand Up @@ -188,6 +199,85 @@ impl<C: Blockchain> MatchstickInstanceContext<C> {
Ok(())
}

/// function logEntity(entity: string, id: string, showRelated: bool): void
pub fn log_entity(
&mut self,
_gas: &GasCounter,
entity_type_ptr: AscPtr<AscString>,
entity_id_ptr: AscPtr<AscString>,
show_related_ptr: AscPtr<bool>,
) -> Result<(), HostExportError> {
let entity_type: String = asc_get(&self.wasm_ctx, entity_type_ptr, &GasCounter::new(), 0)?;
let entity_id: String = asc_get(&self.wasm_ctx, entity_id_ptr, &GasCounter::new(), 0)?;
let show_related: bool = bool::from(EnumPayload(show_related_ptr.to_payload()));

let mut log: HashMap<String, LogEntityValue> = HashMap::new();

// validates whether the provided entity exists in the schema file
let is_invalid_entity = SCHEMA
arrusev marked this conversation as resolved.
Show resolved Hide resolved
.definitions
.iter()
.filter(|def| {
if let schema::Definition::TypeDefinition(schema::TypeDefinition::Object(
entity_def,
)) = def
{
entity_def.name.eq(&entity_type)
} else {
false
}
})
.count()
== 0;

if is_invalid_entity {
panic!(
"Entity \"{}\" does not match any of the schema definitions",
&entity_type
);
}

if let Some(entities) = self.store.get(&entity_type) {
if let Some(entity) = entities.get(&entity_id) {
let mut virtual_fields: Vec<String> = Vec::new();
let has_virtual_fields = self.derived.contains_key(&entity_type);

// prepares entity's native fields
for (field, value) in entity.iter() {
log.insert(field.clone(), LogEntityValue::Native(value.clone()));
}

// prepares entity's dervied fields
if show_related && has_virtual_fields {
virtual_fields = self
.derived
.get(&entity_type)
.unwrap()
.clone()
.into_keys()
.collect();
}

for virtual_field in virtual_fields.iter() {
let related_entities: Vec<HashMap<String, Value>> =
self.load_related_entities(&entity_type, &entity_id, virtual_field);

log.insert(
virtual_field.clone(),
LogEntityValue::Derived(related_entities),
);
}
}
}

logging::debug!(
"{}",
to_string_pretty(&log).unwrap_or_else(|err| logging::critical!(err)),
);

Ok(())
}

/// function clearStore(): void
pub fn clear_store(&mut self, _gas: &GasCounter) -> Result<(), HostExportError> {
self.store.clear();
Expand Down Expand Up @@ -383,52 +473,35 @@ impl<C: Blockchain> MatchstickInstanceContext<C> {

if store.contains_key(&entity_type) && store.get(&entity_type).unwrap().contains_key(&id) {
let entities = store.get(&entity_type).unwrap();
let mut entity: Entity = entities
.get(&id)
.unwrap()
.clone()
.into_iter()
.map(|(k, v)| (Word::from(k), v))
.collect();
let entity: Entity = entities.get(&id).unwrap().clone().to_entity();

let res = asc_new(&mut self.wasm_ctx, &entity.sorted(), &GasCounter::new())?;
let res = asc_new(&mut self.wasm_ctx, &entity, &GasCounter::new())?;
return Ok(res);
}

Ok(AscPtr::null())
}

/// function store.loadRelated(entity: string, id: string, field: string): Array<Entity>;
pub fn mock_store_load_related(
fn load_related_entities(
&mut self,
_gas: &GasCounter,
entity_type_ptr: AscPtr<AscString>,
entity_id_ptr: AscPtr<AscString>,
entity_virtual_field_ptr: AscPtr<AscString>,
) -> Result<AscPtr<Array<AscPtr<AscEntity>>>, HostExportError> {
let entity_type: String = asc_get(&self.wasm_ctx, entity_type_ptr, &GasCounter::new(), 0)?;
let entity_id: String = asc_get(&self.wasm_ctx, entity_id_ptr, &GasCounter::new(), 0)?;
let entity_virtual_field: String = asc_get(
&self.wasm_ctx,
entity_virtual_field_ptr,
&GasCounter::new(),
0,
)?;
entity_type: &String,
entity_id: &String,
entity_virtual_field: &String,
) -> Vec<StoreEntity> {
let mut related_entities: Vec<StoreEntity> = Vec::new();

let mut related_entities: Vec<Entity> = Vec::new();

if self.derived.contains_key(&entity_type)
if self.derived.contains_key(entity_type)
arrusev marked this conversation as resolved.
Show resolved Hide resolved
&& self
.derived
.get(&entity_type)
.get(entity_type)
.unwrap()
.contains_key(&entity_virtual_field)
.contains_key(entity_virtual_field)
{
let (derived_from_entity_type, derived_from_entity_field) = self
.derived
.get(&entity_type)
.get(entity_type)
.unwrap()
.get(&entity_virtual_field)
.get(entity_virtual_field)
.unwrap();

if self.store.contains_key(&derived_from_entity_type.clone()) {
Expand Down Expand Up @@ -457,7 +530,7 @@ impl<C: Blockchain> MatchstickInstanceContext<C> {

let no_relation_found: bool = derived_entity_ids
.iter()
.filter(|&derived_id| derived_id.to_string().eq(&entity_id))
.filter(|&derived_id| derived_id.to_string().eq(entity_id))
.count()
== 0;

Expand All @@ -471,26 +544,42 @@ impl<C: Blockchain> MatchstickInstanceContext<C> {
.unwrap()
.get(&derived_entity_id.clone())
.unwrap()
.clone()
// convert to Entity
.into_iter()
.map(|(k, v)| (Word::from(k), v))
.collect(),
.clone(),
);
}
}
}
let related_entities_sorted: Vec<Entity> = related_entities
.into_iter()
.map(|mut v| v.sorted().clone())
.collect();

let related_entities_ptr: AscPtr<Array<AscPtr<AscEntity>>> = asc_new(
&mut self.wasm_ctx,
&related_entities_sorted,
related_entities
}

/// function store.loadRelated(entity: string, id: string, field: string): Array<Entity>;
pub fn mock_store_load_related(
&mut self,
_gas: &GasCounter,
entity_type_ptr: AscPtr<AscString>,
entity_id_ptr: AscPtr<AscString>,
entity_virtual_field_ptr: AscPtr<AscString>,
) -> Result<AscPtr<Array<AscPtr<AscEntity>>>, HostExportError> {
let entity_type: String = asc_get(&self.wasm_ctx, entity_type_ptr, &GasCounter::new(), 0)?;
let entity_id: String = asc_get(&self.wasm_ctx, entity_id_ptr, &GasCounter::new(), 0)?;
let entity_virtual_field: String = asc_get(
&self.wasm_ctx,
entity_virtual_field_ptr,
&GasCounter::new(),
0,
)?;

let related_entities: Vec<Entity> = self
.load_related_entities(&entity_type, &entity_id, &entity_virtual_field)
// convert to Entity
.into_iter()
.map(|mut v: StoreEntity| v.to_entity())
.collect();

let related_entities_ptr: AscPtr<Array<AscPtr<AscEntity>>> =
asc_new(&mut self.wasm_ctx, &related_entities, &GasCounter::new())?;

Ok(related_entities_ptr)
}

Expand Down Expand Up @@ -524,8 +613,7 @@ impl<C: Blockchain> MatchstickInstanceContext<C> {
) -> Result<(), HostExportError> {
let entity_type: String = asc_get(&self.wasm_ctx, entity_type_ptr, &GasCounter::new(), 0)?;
let id: String = asc_get(&self.wasm_ctx, id_ptr, &GasCounter::new(), 0)?;
let data: HashMap<String, Value> =
asc_get(&self.wasm_ctx, data_ptr, &GasCounter::new(), 0)?;
let data: StoreEntity = asc_get(&self.wasm_ctx, data_ptr, &GasCounter::new(), 0)?;

let required_fields = SCHEMA
.definitions
Expand Down Expand Up @@ -876,13 +964,9 @@ impl<C: Blockchain> MatchstickInstanceContext<C> {
let default_context_val: Entity = Vec::new();
let result = match &self.data_source_return_value.2 {
Some(value) => {
let mut entity: Entity = value
.clone()
.into_iter()
.map(|(k, v)| (Word::from(k), v))
.collect();
let entity: Entity = value.clone().to_entity();

asc_new(&mut self.wasm_ctx, &entity.sorted(), &GasCounter::new()).unwrap()
asc_new(&mut self.wasm_ctx, &entity, &GasCounter::new()).unwrap()
}
None => asc_new(&mut self.wasm_ctx, &default_context_val, &GasCounter::new()).unwrap(),
};
Expand Down
8 changes: 8 additions & 0 deletions src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,14 @@ impl<C: Blockchain> MatchstickInstance<C> {
link!("clearStore", clear_store,);
link!("clearInBlockStore", clear_cache_store,);
link!("logStore", log_store,);
link!(
"logEntity",
log_entity,
entity_type_ptr,
entity_id_ptr,
show_related_ptr
);

link!(
"store.get",
mock_store_get,
Expand Down