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

Replace QueryHelpers with rescript-rest #147

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion codegenerator/cli/templates/dynamic/codegen/package.json.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
"rescript": "11.1.0",
"rescript-envsafe": "4.2.0",
"rescript-express": "0.4.1",
"rescript-schema": "8.0.0",
"rescript-schema": "8.0.3",
"rescript-rest": "0.8.0",
"root": "{{relative_path_to_root_from_generated}}",
"viem": "1.16.6",
"yargs": "17.7.2"
Expand Down
3 changes: 2 additions & 1 deletion codegenerator/cli/templates/static/codegen/rescript.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"rescript-schema",
"rescript-express",
"@glennsl/rescript-fetch",
"@rescript/react"
"@rescript/react",
"rescript-rest"
],
"bsc-flags": ["-open RescriptSchema"]
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
open Belt
//Manage clients in cache so we don't need to reinstantiate each time
//Ideally client should be passed in as a param to the functions but
//we are still sharing the same signature with eth archive query builder
Expand Down Expand Up @@ -60,34 +61,20 @@ type missingParams = {
queryName: string,
missingParams: array<string>,
}
type queryError =
UnexpectedMissingParams(missingParams) | QueryError(HyperFuelJsonApi.Query.queryError)
type queryError = UnexpectedMissingParams(missingParams) | QueryError(exn)

exception UnexpectedMissingParamsExn(missingParams)

let queryErrorToMsq = (e: queryError): string => {
let getMsgFromExn = (exn: exn) =>
exn
->Js.Exn.asJsExn
->Belt.Option.flatMap(exn => exn->Js.Exn.message)
->Belt.Option.getWithDefault("No message on exception")
switch e {
| UnexpectedMissingParams({queryName, missingParams}) =>
`${queryName} query failed due to unexpected missing params on response:
${missingParams->Js.Array2.joinWith(", ")}`
| QueryError(e) =>
switch e {
| FailedToFetch(e) =>
let msg = e->getMsgFromExn

`Failed during fetch query: ${msg}`
| FailedToParseJson(e) =>
let msg = e->getMsgFromExn
`Failed during parse of json: ${msg}`
| Other(e) =>
let msg = e->getMsgFromExn
`Failed for unknown reason during query: ${msg}`
}
| QueryError(exn) =>
exn
->Js.Exn.asJsExn
->Option.flatMap(exn => exn->Js.Exn.message)
->Option.getWithDefault("No message on exception")
}
}

Expand Down Expand Up @@ -217,9 +204,12 @@ module LogsQuery = {

let executeQuery = () => hyperFuelClient->HyperFuelClient.getSelectedData(query)

let res = await executeQuery->Time.retryAsyncWithExponentialBackOff(~logger=Some(logger))

res->convertResponse
try {
let res = await executeQuery->Time.retryAsyncWithExponentialBackOff(~logger=Some(logger))
res->convertResponse
} catch {
| exn => Error(QueryError(exn))
}
}
}

Expand All @@ -237,65 +227,64 @@ module BlockTimestampQuery = {
// includeAllBlocks: true,
}

let convertResponse = (
res: result<HyperFuelJsonApi.ResponseTypes.queryResponse, HyperFuelJsonApi.Query.queryError>,
): queryResponse<blockTimestampPage> => {
switch res {
| Error(e) => Error(QueryError(e))
| Ok(successRes) =>
let {nextBlock, archiveHeight, data} = successRes

data
->Belt.Array.flatMap(item => {
item.blocks->Belt.Option.mapWithDefault([], blocks => {
blocks->Belt.Array.map(
block => {
switch (block.height, block.time) {
| (Some(blockNumber), Some(blockTimestamp)) =>
let timestamp = blockTimestamp
Ok(
(
{
timestamp,
blockNumber,
}: blockNumberAndTimestamp
),
)
| _ =>
let missingParams =
[
block.height->Utils.Option.mapNone("block.height"),
block.time->Utils.Option.mapNone("block.time"),
]->Belt.Array.keepMap(p => p)

Error(
UnexpectedMissingParams({
queryName: "queryBlockTimestampsPage HyperSync",
missingParams,
}),
)
}
},
)
})
})
->Utils.Array.transposeResults
->Belt.Result.map((items): blockTimestampPage => {
nextBlock,
archiveHeight,
items,
let convertResponse = (res: HyperFuelJsonApi.ResponseTypes.queryResponse): queryResponse<
blockTimestampPage,
> => {
let {nextBlock, archiveHeight, data} = res

data
->Belt.Array.flatMap(item => {
item.blocks->Belt.Option.mapWithDefault([], blocks => {
blocks->Belt.Array.map(
block => {
switch (block.height, block.time) {
| (Some(blockNumber), Some(blockTimestamp)) =>
let timestamp = blockTimestamp
Ok(
(
{
timestamp,
blockNumber,
}: blockNumberAndTimestamp
),
)
| _ =>
let missingParams =
[
block.height->Utils.Option.mapNone("block.height"),
block.time->Utils.Option.mapNone("block.time"),
]->Belt.Array.keepMap(p => p)

Error(
UnexpectedMissingParams({
queryName: "queryBlockTimestampsPage HyperSync",
missingParams,
}),
)
}
},
)
})
}
})
->Utils.Array.transposeResults
->Belt.Result.map((items): blockTimestampPage => {
nextBlock,
archiveHeight,
items,
})
}

let queryBlockTimestampsPage = async (~serverUrl, ~fromBlock, ~toBlock): queryResponse<
blockTimestampPage,
> => {
let body = makeRequestBody(~fromBlock, ~toBlockInclusive=toBlock)

let res = await HyperFuelJsonApi.executeHyperSyncQuery(~postQueryBody=body, ~serverUrl)

res->convertResponse
try {
let res = await HyperFuelJsonApi.executeHyperSyncQuery->Rest.fetch(serverUrl, body)
res->convertResponse
} catch {
| exn => Error(QueryError(exn))
}
}
}

Expand All @@ -310,17 +299,17 @@ module HeightQuery = {

//Retry if the heigth is 0 (expect height to be greater)
while height.contents <= 0 {
let res = await HyperFuelJsonApi.getArchiveHeight(~serverUrl)
Logging.debug({"msg": "querying height", "response": res})
switch res {
| Ok({height: newHeight}) => height := newHeight
| Error(e) =>
logger->Logging.childWarn({
"message": `Failed to get height from endpoint. Retrying in ${retryIntervalMillis.contents->Belt.Int.toString}ms...`,
"error": e,
})
await Time.resolvePromiseAfterDelay(~delayMilliseconds=retryIntervalMillis.contents)
retryIntervalMillis := retryIntervalMillis.contents * backOffMultiplicative
try {
height := await HyperSyncJsonApi.getArchiveHeight->Rest.fetch(serverUrl, ())
} catch {
| e => {
logger->Logging.childWarn({
"message": `Failed to get height from endpoint. Retrying in ${retryIntervalMillis.contents->Int.toString}ms...`,
"error": e,
})
await Time.resolvePromiseAfterDelay(~delayMilliseconds=retryIntervalMillis.contents)
retryIntervalMillis := retryIntervalMillis.contents * backOffMultiplicative
}
}
}

Expand Down Expand Up @@ -354,63 +343,63 @@ module BlockHashes = {
// includeAllBlocks: true,
}

let convertResponse = (
res: result<HyperFuelJsonApi.ResponseTypes.queryResponse, HyperFuelJsonApi.Query.queryError>,
): queryResponse<array<blockNumberAndHash>> => {
switch res {
| Error(e) => Error(QueryError(e))
| Ok(successRes) =>
successRes.data
->Belt.Array.flatMap(item => {
item.blocks->Belt.Option.mapWithDefault([], blocks => {
blocks->Belt.Array.map(
block => {
switch (block.height, block.id) {
| (Some(blockNumber), Some(hash)) =>
Ok(
(
{
blockNumber,
hash,
}: blockNumberAndHash
),
)
| _ =>
let missingParams =
[
block.height->Utils.Option.mapNone("block.height"),
block.id->Utils.Option.mapNone("block.id"),
]->Belt.Array.keepMap(p => p)

Error(
UnexpectedMissingParams({
queryName: "query block hash HyperSync",
missingParams,
}),
)
}
},
)
})
let convertResponse = (res: HyperFuelJsonApi.ResponseTypes.queryResponse): queryResponse<
array<blockNumberAndHash>,
> => {
res.data
->Belt.Array.flatMap(item => {
item.blocks->Belt.Option.mapWithDefault([], blocks => {
blocks->Belt.Array.map(
block => {
switch (block.height, block.id) {
| (Some(blockNumber), Some(hash)) =>
Ok(
(
{
blockNumber,
hash,
}: blockNumberAndHash
),
)
| _ =>
let missingParams =
[
block.height->Utils.Option.mapNone("block.height"),
block.id->Utils.Option.mapNone("block.id"),
]->Belt.Array.keepMap(p => p)

Error(
UnexpectedMissingParams({
queryName: "query block hash HyperSync",
missingParams,
}),
)
}
},
)
})
->Utils.Array.transposeResults
}
})
->Utils.Array.transposeResults
}

let queryBlockHash = async (~serverUrl, ~blockNumber): queryResponse<
array<blockNumberAndHash>,
> => {
let body = makeRequestBody(~blockNumber)

let executeQuery = () => HyperFuelJsonApi.executeHyperSyncQuery(~postQueryBody=body, ~serverUrl)

let logger = Logging.createChild(
~params={"type": "hypersync get blockhash query", "blockNumber": blockNumber},
)

let res = await executeQuery->Time.retryAsyncWithExponentialBackOff(~logger=Some(logger))

res->convertResponse
try {
let res = await Time.retryAsyncWithExponentialBackOff(
() => HyperFuelJsonApi.executeHyperSyncQuery->Rest.fetch(serverUrl, body),
~logger=Some(logger),
)
res->convertResponse
} catch {
| exn => Error(QueryError(exn))
}
}

let queryBlockHashes = async (~serverUrl, ~blockNumbers) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ type missingParams = {
queryName: string,
missingParams: array<string>,
}
type queryError =
UnexpectedMissingParams(missingParams) | QueryError(HyperFuelJsonApi.Query.queryError)
type queryError = UnexpectedMissingParams(missingParams) | QueryError(exn)

exception UnexpectedMissingParamsExn(missingParams)

Expand Down
Loading
Loading