Skip to content

Commit

Permalink
Enable Uncurried mode (#49)
Browse files Browse the repository at this point in the history
* Uncurried mode support

* Vendore Mocha bindings with uncurried mode support
  • Loading branch information
DZakh authored Jul 2, 2024
1 parent 0822112 commit 1aff7c1
Show file tree
Hide file tree
Showing 86 changed files with 6,713 additions and 5,626 deletions.
2 changes: 1 addition & 1 deletion codegenerator/cli/src/config_parsing/entity_parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -892,7 +892,7 @@ impl RescriptType {
})
.collect::<Vec<String>>()
.join(", ");
format!("S.tuple((. s) => ({}))", inner_str)
format!("S.tuple(s => ({}))", inner_str)
}
RescriptType::EnumVariant(enum_name) => {
format!("Enums.{}.schema", &enum_name.capitalized)
Expand Down
2 changes: 1 addition & 1 deletion codegenerator/cli/src/rescript_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ impl RescriptTypeIdent {
})
.collect::<Vec<String>>()
.join(", ");
format!("S.tuple((. s) => ({}))", inner_str)
format!("S.tuple(s => ({}))", inner_str)
}
RescriptTypeIdent::SchemaEnum(enum_name) => {
format!("Enums.{}Schema", &enum_name.uncapitalized)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"license": "MIT",
"dependencies": {
"rescript": "11.1.0",
"@rescript/core": "1.5.0",
"@elastic/ecs-pino-format": "1.4.0",
"@envio-dev/hypersync-client": "0.1.10",
"@glennsl/rescript-fetch": "0.2.0",
Expand Down
18 changes: 9 additions & 9 deletions codegenerator/cli/templates/dynamic/codegen/src/ChainMap.res.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ module Chain = {
| c => Error(UndefinedChain(c))
}

module ChainIdCmp = Belt.Id.MakeComparable({
module ChainIdCmp = Belt.Id.MakeComparableU({
type t = t
let cmp = (a, b) => Pervasives.compare(a->toChainId, b->toChainId)
})
Expand Down Expand Up @@ -66,13 +66,13 @@ let get: (t<'a>, Chain.t) => 'a = (self, chain) =>
| None => UnexpectedChainDoesNoteExist(chain->Chain.toChainId)->raise
}

let set: (t<'a>, Chain.t, 'a) => t<'a> = Map.set
let values: t<'a> => array<'a> = Map.valuesToArray
let keys: t<'a> => array<Chain.t> = Map.keysToArray
let entries: t<'a> => array<(Chain.t, 'a)> = Map.toArray
let map: (t<'a>, 'a => 'b) => t<'b> = Map.map
let mapWithKey: (t<'a>, (Chain.t, 'a) => 'b) => t<'b> = Map.mapWithKey
let reduce: (t<'a>, 'b, (Chain.t, 'a, 'b) => 'b) => 'b = Map.reduce
let size: t<'a> => int = Map.size
let set: (t<'a>, Chain.t, 'a) => t<'a> = (map, chain, v) => Map.set(map, chain, v)
let values: t<'a> => array<'a> = map => Map.valuesToArray(map)
let keys: t<'a> => array<Chain.t> = map => Map.keysToArray(map)
let entries: t<'a> => array<(Chain.t, 'a)> = map => Map.toArray(map)
let map: (t<'a>, 'a => 'b) => t<'b> = (map, fn) => Map.map(map, fn)
let mapWithKey: (t<'a>, (Chain.t, 'a) => 'b) => t<'b> = (map, fn) => Map.mapWithKey(map, fn)
let reduce: (t<'a>, 'b, (Chain.t, 'a, 'b) => 'b) => 'b = (map, acc, fn) => Map.reduce(map, acc, fn)
let size: t<'a> => int = map => Map.size(map)
let update: (t<'a>, Chain.t, 'a => 'a) => t<'a> = (map, chain, updateFn) =>
Map.update(map, chain, opt => opt->Option.map(updateFn))
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ let getAddedDynamicContractRegistrations = (contextEnv: t<'eventArgs>) =>
let makeDynamicContractRegisterFn = (
~contextEnv: t<'eventArgs>,
~contractName,
~inMemoryStore,
~inMemoryStore
) => (
contractAddress: Ethers.ethAddress,
) => {
let {event, chain, addedDynamicContractRegistrations} = contextEnv
Expand All @@ -113,7 +114,7 @@ let makeDynamicContractRegisterFn = (
)
}

let makeLoader = (loadLayerRef, ~entityIdsMap, ~entityName, entityId) => {
let makeLoader = (loadLayerRef, ~entityIdsMap, ~entityName) => entityId => {
entityIdsMap->EntityIdsMap.addId(~entityId, ~entityName)
Promise.make((resolve, _reject) => {
loadLayerRef.contents->LoadLayer.LoadActionMap.add(~entityId, ~resolve)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ module {{contract.name.capitalized}} = {
module {{event.name.capitalized}} = {
let convertViemDecodedEvent: Viem.decodedEvent<'a> => Viem.decodedEvent<
Types.{{contract.name.capitalized}}.{{event.name.capitalized}}.eventArgs,
> = Obj.magic
> = X.magic

{{#unless event.params}}
@warning("-27")
Expand Down Expand Up @@ -75,7 +75,7 @@ module {{contract.name.capitalized}} = {
Array.concat(decodedEvent.indexed, decodedEvent.body)->Array.map(
HyperSyncClient.Decoder.toUnderlying,
)
Array.zip(fields, values)->Js.Dict.fromArray->Obj.magic
Array.zip(fields, values)->Js.Dict.fromArray->X.magic
{{else}}
()
{{/if}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ let runEventContractRegister = (
eventBatchQueueItem->addToDynamicContractRegistrations(
~registeringEventBlockNumber=event.blockNumber,
~registeringEventLogIndex=event.logIndex,
...
)

let val = switch (dynamicContracts, dynamicContractRegistrations) {
Expand Down Expand Up @@ -177,7 +178,7 @@ let addEventToRawEvents = (
blockHash,
blockTimestamp,
eventType: eventName,
params: switch event.params->S.serializeToJsonStringWith(. eventArgsSchema) {
params: switch event.params->S.serializeToJsonStringWith(eventArgsSchema) {
| Ok(jsonString) => jsonString
| Error(e) => S.Error.raise(e)
},
Expand Down Expand Up @@ -206,10 +207,10 @@ let updateEventSyncState = (
)
}

let readEntity = (entityMod, id) => Entities.batchRead(DbFunctions.sql, [id], ~entityMod)
let readEntity = (~entityMod) => id => Entities.batchRead(~entityMod)(DbFunctions.sql, [id])
let asyncGetters: ContextEnv.asyncGetters = {
{{#each entities as | entity |}}
get{{entity.name.capitalized}}: readEntity(module(Entities.{{entity.name.capitalized}})),
get{{entity.name.capitalized}}: readEntity(~entityMod=module(Entities.{{entity.name.capitalized}})),
{{/each}}
}

Expand Down Expand Up @@ -334,7 +335,9 @@ let rec registerDynamicContracts = (
//If an item has already been registered, it would have been
//put back on the arbitrary events queue and is now being reprocessed
dynamicContractRegistrations
->Option.map(addToUnprocessedBatch(eventBatchQueueItem))
->Option.map(dynamicContractRegistrations =>
addToUnprocessedBatch(eventBatchQueueItem, dynamicContractRegistrations)
)
->Ok
} else {
let runEventContractRegister = (eventName, event) =>
Expand All @@ -353,7 +356,9 @@ let rec registerDynamicContracts = (
)
| None =>
dynamicContractRegistrations
->Option.map(addToUnprocessedBatch(eventBatchQueueItem))
->Option.map(dynamicContractRegistrations =>
addToUnprocessedBatch(eventBatchQueueItem, dynamicContractRegistrations)
)
->Ok
}

Expand Down Expand Up @@ -453,6 +458,7 @@ let runHandlers = (
~chain,
~latestProcessedBlocks=latestProcessedBlocks.contents,
~registeredEvents,
...
)

latestProcessedBlocks :=
Expand Down
14 changes: 9 additions & 5 deletions codegenerator/cli/templates/dynamic/codegen/src/IO.res.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ let executeSetEntityWithHistory = (
~entityHistoriesToSet=Belt.Array.concatMany(entityHistoryItemsToSet),
),
if entitiesToSet->Array.length > 0 {
sql->Entities.batchSet(entitiesToSet, ~entityMod)
sql->Entities.batchSet(~entityMod)(entitiesToSet)
} else {
Promise.resolve()
},
if idsToDelete->Array.length > 0 {
sql->Entities.batchDelete(idsToDelete, ~entityMod)
sql->Entities.batchDelete(~entityMod)(idsToDelete)
} else {
Promise.resolve()
},
Expand Down Expand Up @@ -128,9 +128,9 @@ let executeDbFunctionsEntity = (

let promises =
(
entitiesToSet->Array.length > 0 ? [sql->Entities.batchSet(entitiesToSet, ~entityMod)] : []
entitiesToSet->Array.length > 0 ? [sql->Entities.batchSet(~entityMod)(entitiesToSet)] : []
)->Belt.Array.concat(
idsToDelete->Array.length > 0 ? [sql->Entities.batchDelete(idsToDelete, ~entityMod)] : [],
idsToDelete->Array.length > 0 ? [sql->Entities.batchDelete(~entityMod)(idsToDelete)] : [],
)

promises->Promise.all->Promise.thenResolve(_ => ())
Expand All @@ -142,22 +142,26 @@ let executeBatch = async (sql, ~inMemoryStore: InMemoryStore.t) => {
: executeDbFunctionsEntity

let setEventSyncState = executeSet(
_,
~dbFunction=DbFunctions.EventSyncState.batchSet,
~items=inMemoryStore.eventSyncState->InMemoryTable.values,
)

let setRawEvents = executeSet(
_,
~dbFunction=DbFunctions.RawEvents.batchSet,
~items=inMemoryStore.rawEvents->InMemoryTable.values,
)

let setDynamicContracts = executeSet(
_,
~dbFunction=DbFunctions.DynamicContractRegistry.batchSet,
~items=inMemoryStore.dynamicContractRegistry->InMemoryTable.values,
)

{{#each entities as | entity |}}
let set{{entity.name.capitalized}}s = entityDbExecutionComposer(
_,
~entityMod=module(Entities.{{entity.name.capitalized}}),
~rows=inMemoryStore.{{entity.name.uncapitalized}}->InMemoryTable.values,
)
Expand All @@ -172,7 +176,7 @@ let executeBatch = async (sql, ~inMemoryStore: InMemoryStore.t) => {
DbFunctions.EntityHistory.deleteAllEntityHistoryAfterEventIdentifier,
DbFunctions.RawEvents.deleteAllRawEventsAfterEventIdentifier,
DbFunctions.DynamicContractRegistry.deleteAllDynamicContractRegistrationsAfterEventIdentifier,
]->Belt.Array.map(fn => fn(~eventIdentifier))
]->Belt.Array.map(fn => fn(_, ~eventIdentifier))
| None => []
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
open Belt

@genType
@genType
type rawEventsKey = {
chainId: int,
eventId: string,
Expand All @@ -9,7 +8,7 @@ type rawEventsKey = {
let hashRawEventsKey = (key: rawEventsKey) =>
EventUtils.getEventIdKeyString(~chainId=key.chainId, ~eventId=key.eventId)

@genType
@genType
type dynamicContractRegistryKey = {
chainId: int,
contractAddress: Ethers.ethAddress,
Expand All @@ -32,7 +31,7 @@ type t = {
}

let makeWithRollBackEventIdentifier = (rollBackEventIdentifier): t => {
eventSyncState: InMemoryTable.make(~hash=Int.toString),
eventSyncState: InMemoryTable.make(~hash=v => v->RescriptCore.Int.toString),
rawEvents: InMemoryTable.make(~hash=hashRawEventsKey),
dynamicContractRegistry: InMemoryTable.make(~hash=hashDynamicContractRegistryKey),
{{#each entities as |entity|}}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
open Belt

module LoadActionMap = {
type loadAction<'entity> = {resolve: (. option<'entity>) => unit}
type loadAction<'entity> = {resolve: option<'entity> => unit}

type key = string
type value<'entity> = array<loadAction<'entity>>
type t<'entity> = dict<value<'entity>>
let empty: unit => t<'entity> = Js.Dict.empty
let empty: unit => t<'entity> = RescriptCore.Dict.make
let getIds = (map: t<'entity>) => map->Js.Dict.keys
let entries: t<'entity> => array<(key, value<'entity>)> = Js.Dict.entries
let entries: t<'entity> => array<(key, value<'entity>)> = RescriptCore.Dict.toArray

let add = (map: t<'entity>, ~entityId, ~resolve) => {
let loadCallback = {
Expand All @@ -21,13 +21,13 @@ module LoadActionMap = {
}

let get: (t<'entity>, 'entity) => option<value<'entity>> = (map, entity) =>
map->Js.Dict.get(Obj.magic(entity)["id"])
map->Js.Dict.get(X.magic(entity)["id"])
let deleteKeyUnsafe: (t<'entity>, string) => unit = %raw(`
function(dict, key) {
delete dict[key];
}
`)
`)
}

type t = {
Expand Down Expand Up @@ -74,7 +74,7 @@ let executeLoadActionMap = (
//Set the entity in the in memory store
inMemTable->InMemoryTable.Entity.initValue(
~allowOverWriteEntity=false,
~key=Obj.magic(entity)["id"],
~key=X.magic(entity)["id"],
~entity=Some(entity),
)
})
Expand Down Expand Up @@ -111,7 +111,7 @@ let executeLoadLayer = async (loadLayer, ~inMemoryStore: InMemoryStore.t) => {
{{#each entities as | entity |}}
loadLayer.{{entity.name.uncapitalized}}->executeLoadActionMap(
~inMemTable=inMemoryStore.{{entity.name.uncapitalized}},
~batchLoadIds=Entities.batchRead(DbFunctions.sql, ~entityMod=module(Entities.{{entity.name.capitalized}})),
~batchLoadIds=Entities.batchRead(~entityMod=module(Entities.{{entity.name.capitalized}}))(DbFunctions.sql, _),
),
{{/each}}
]->Promise.all
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ module EventFunctions = {
switch registeredEvent.loaderHandler {
| Some(handler) =>
switch await event->EventProcessing.runEventHandler(
~executeLoadLayer=TestHelpers_MockDb.executeMockDbLoadLayer(mockDbClone),
~executeLoadLayer=TestHelpers_MockDb.executeMockDbLoadLayer(mockDbClone, ...),
~inMemoryStore,
~handler,
~eventMod,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ let makeStoreOperatorEntity = (
): storeOperations<Types.id, 'entity> => {
let {get, values, set} = module(InMemoryTable.Entity)
let get = inMemoryStore->getStore->get
let get = get(inMemoryStore->getStore, _)
let getAll = () =>
inMemoryStore
Expand Down Expand Up @@ -136,7 +136,7 @@ let makeStoreOperatorMeta = (
): storeOperations<'key, 'value> => {
let {get, values, set} = module(InMemoryTable)

let get = inMemoryStore->getStore->get
let get = get(inMemoryStore->getStore, _)
// unit => array<StoreState.value>
let getAll = () => inMemoryStore->getStore->values->Array.map(row => row)

Expand Down Expand Up @@ -232,7 +232,7 @@ let cloneMockDb = (self: t) => {
clonedInternalDb->makeWithInMemoryStore
}

let batchRead = (entity: entityStoreOperations<'entity>, ids) =>
let batchRead = (entity: entityStoreOperations<'entity>) => ids =>
ids->Array.keepMap(id => entity.get(id))->Promise.resolve

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ module {{contract.name.capitalized}} = {

let eventArgsSchema =
{{#if event.params}}
S.object((. s) => {
S.object(s => {
{{#each event.params as | param |}}
{{param.param_name.uncapitalized}}: s.field("{{param.param_name.uncapitalized}}", {{param.type_rescript_schema}}),
{{/each}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ module {{entity.name.capitalized}} = {
{{/each}}
}

let schema = S.object((. s) => {
let schema = S.object(s => {
{{#each entity.params as | param |}}
{{#unless param.is_derived_from }}{{param.field_name.uncapitalized}}{{#if param.is_entity_field}}_id{{/if}}: s.field("{{param.field_name.uncapitalized}}{{#if param.is_entity_field}}_id{{/if}}", {{param.type_rescript_schema}}),{{/unless}}
{{/each}}
Expand Down Expand Up @@ -98,7 +98,7 @@ type entity =
| {{entity.name.capitalized}}({{entity.name.capitalized}}.t)
{{/each}}

let makeGetter = (schema, accessor, json) => json->S.parseWith(. schema)->Belt.Result.map(accessor)
let makeGetter = (schema, accessor) => json => json->S.parseWith(schema)->Belt.Result.map(accessor)

let getEntityParamsDecoder = (entityName: Enums.EntityType.t) =>
switch entityName {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
open RescriptMocha
open Mocha

open Belt
open TestHelpers

Expand All @@ -12,7 +12,7 @@ describe("{{contract.name.capitalized}} contract {{event.name.capitalized}} even
// Creating mock for {{contract.name.capitalized}} contract {{event.name.capitalized}} event
let event = {{event.create_mock_code}};

RescriptMocha.Promise.it("{{contract.name.capitalized}}_{{event.name.capitalized}} is created correctly", async () => {
Async.it("{{contract.name.capitalized}}_{{event.name.capitalized}} is created correctly", async () => {
// Processing the event
let mockDbUpdated = await {{contract.name.capitalized}}.{{event.name.capitalized}}.processEvent({
event,
Expand All @@ -33,7 +33,7 @@ describe("{{contract.name.capitalized}} contract {{event.name.capitalized}} even
{{/each}}
}
//Assert the expected {{contract.name.capitalized}} {{event.name.capitalized}} entity
Assert.deep_equal(
Assert.deepEqual(
actual{{contract.name.capitalized}}{{event.name.capitalized}},
expected{{contract.name.capitalized}}{{event.name.capitalized}},
~message="Actual {{contract.name.capitalized}}_{{event.name.capitalized}} should be the same as the expected {{contract.name.capitalized}}_{{event.name.capitalized}}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
"@rescript/react": "0.12.1",
"@glennsl/rescript-fetch": "0.2.0",
"@ryyppy/rescript-promise": "2.1.0",
"rescript-mocha": "^0.9.0",
"rescript": "11.1.0",
{{/if}}
{{#if is_typescript}}
Expand Down
Loading

0 comments on commit 1aff7c1

Please sign in to comment.