Skip to content

Commit 68be888

Browse files
committed
Don't dump hash on HS, allow cache minification via schema, fix psql for local dev
1 parent 38b4732 commit 68be888

File tree

7 files changed

+69
-44
lines changed

7 files changed

+69
-44
lines changed

codegenerator/cli/npm/envio/src/Envio.res

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ let experimental_createEffect = (
5050
>
5151
),
5252
callsCount: 0,
53+
input: options.input->(Utils.magic: S.t<'input> => S.t<Internal.effectInput>),
5354
output: options.output->(Utils.magic: S.t<'output> => S.t<Internal.effectOutput>),
5455
cache: options.cache->Belt.Option.getWithDefault(false),
5556
}->(Utils.magic: Internal.effect => effect<'input, 'output>)

codegenerator/cli/npm/envio/src/Internal.res

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ type effect = {
199199
handler: effectArgs => promise<effectOutput>,
200200
cache: bool,
201201
output: S.t<effectOutput>,
202+
input: S.t<effectInput>,
202203
mutable callsCount: int,
203204
}
204205

codegenerator/cli/npm/envio/src/PgStorage.res

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ let setOrThrow = async (sql, ~items, ~table: Table.table, ~itemSchema, ~pgSchema
387387
raise(
388388
Persistence.StorageError({
389389
message: `Failed to insert items into table "${table.tableName}"`,
390-
reason: exn,
390+
reason: exn->Internal.prettifyExn,
391391
}),
392392
)
393393
}
@@ -455,22 +455,27 @@ let makeSchemaCacheTableInfoQuery = (~pgSchema) => {
455455
type psqlExecState =
456456
Unknown | Pending(promise<result<string, string>>) | Resolved(result<string, string>)
457457

458-
let getPsqlExec = {
458+
let getConnectedPsqlExec = {
459+
let pgDockerServiceName = "envio-postgres"
460+
// Should use the default port, since we're executing the command
461+
// from the postgres container's network.
462+
let pgDockerServicePort = 5432
463+
459464
// For development: We run the indexer process locally,
460465
// and there might not be psql installed on the user's machine.
461466
// So we use docker-compose to run psql existing in the postgres container.
462467
// For production: We expect indexer to be running in a container,
463468
// with psql installed. So we can call it directly.
464469
let psqlExecState = ref(Unknown)
465-
async (~pgUser, ~pgHost) => {
470+
async (~pgUser, ~pgHost, ~pgDatabase, ~pgPort) => {
466471
switch psqlExecState.contents {
467472
| Unknown => {
468473
let promise = Promise.make((resolve, _reject) => {
469474
let binary = "psql"
470475
NodeJs.ChildProcess.exec(`${binary} --version`, (~error, ~stdout as _, ~stderr as _) => {
471476
switch error {
472477
| Value(_) => {
473-
let binary = `docker-compose exec -T -u ${pgUser} ${pgHost} psql`
478+
let binary = `docker-compose exec -T -u ${pgUser} ${pgDockerServiceName} psql`
474479
NodeJs.ChildProcess.exec(
475480
`${binary} --version`,
476481
(~error, ~stdout as _, ~stderr as _) => {
@@ -479,12 +484,22 @@ let getPsqlExec = {
479484
resolve(
480485
Error(`Please check if "psql" binary is installed or docker-compose is running for the local indexer.`),
481486
)
482-
| Null => resolve(Ok(binary))
487+
| Null =>
488+
resolve(
489+
Ok(
490+
`${binary} -h ${pgHost} -p ${pgDockerServicePort->Js.Int.toString} -U ${pgUser} -d ${pgDatabase}`,
491+
),
492+
)
483493
}
484494
},
485495
)
486496
}
487-
| Null => resolve(Ok(binary))
497+
| Null =>
498+
resolve(
499+
Ok(
500+
`${binary} -h ${pgHost} -p ${pgPort->Js.Int.toString} -U ${pgUser} -d ${pgDatabase}`,
501+
),
502+
)
488503
}
489504
})
490505
})
@@ -676,7 +691,7 @@ let make = (
676691
cacheTablePrefix ++ effectName,
677692
~fields=[
678693
Table.mkField("id", Text, ~fieldSchema=S.string, ~isPrimaryKey=true),
679-
Table.mkField("output", JsonB, ~fieldSchema=outputSchema),
694+
Table.mkField("output", JsonB, ~fieldSchema=S.json(~validate=false)),
680695
],
681696
~compositeIndices=[],
682697
)
@@ -731,7 +746,7 @@ let make = (
731746
// Command for testing. Run from generated
732747
// docker-compose exec -T -u postgres envio-postgres psql -d envio-dev -c 'COPY "public"."envio_effect_getTokenMetadata" TO STDOUT (FORMAT text, HEADER);' > ../.envio/cache/getTokenMetadata.tsv
733748

734-
switch await getPsqlExec(~pgUser, ~pgHost) {
749+
switch await getConnectedPsqlExec(~pgUser, ~pgHost, ~pgDatabase, ~pgPort) {
735750
| Ok(psqlExec) => {
736751
Logging.info(
737752
`Dumping cache: ${cacheTableInfo
@@ -746,7 +761,7 @@ let make = (
746761
let outputFile =
747762
NodeJs.Path.join(cacheDirPath, cacheName ++ ".tsv")->NodeJs.Path.toString
748763

749-
let command = `${psqlExec} -h ${pgHost} -p ${pgPort->Js.Int.toString} -U ${pgUser} -d ${pgDatabase} -c 'COPY "${pgSchema}"."${tableName}" TO STDOUT WITH (FORMAT text, HEADER);' > ${outputFile}`
764+
let command = `${psqlExec} -c 'COPY "${pgSchema}"."${tableName}" TO STDOUT WITH (FORMAT text, HEADER);' > ${outputFile}`
750765

751766
Promise.make((resolve, reject) => {
752767
NodeJs.ChildProcess.execWithOptions(
@@ -782,7 +797,7 @@ let make = (
782797
NodeJs.Fs.Promises.readdir(cacheDirPath)
783798
->Promise.thenResolve(e => Ok(e))
784799
->Promise.catch(_ => Promise.resolve(Error(nothingToUploadErrorMessage))),
785-
getPsqlExec(~pgUser, ~pgHost),
800+
getConnectedPsqlExec(~pgUser, ~pgHost, ~pgDatabase, ~pgPort),
786801
)) {
787802
| (Ok(entries), Ok(psqlExec)) => {
788803
let cacheFiles = entries->Js.Array2.filter(entry => {
@@ -808,7 +823,7 @@ let make = (
808823
->Promise.then(() => {
809824
let inputFile = NodeJs.Path.join(cacheDirPath, entry)->NodeJs.Path.toString
810825

811-
let command = `${psqlExec} -h ${pgHost} -p ${pgPort->Js.Int.toString} -U ${pgUser} -d ${pgDatabase} -c 'COPY "${pgSchema}"."${tableName}" FROM STDIN WITH (FORMAT text, HEADER);' < ${inputFile}`
826+
let command = `${psqlExec} -c 'COPY "${pgSchema}"."${tableName}" FROM STDIN WITH (FORMAT text, HEADER);' < ${inputFile}`
812827

813828
Promise.make(
814829
(resolve, reject) => {
@@ -827,6 +842,8 @@ let make = (
827842
})
828843
})
829844
->Promise.all
845+
846+
Logging.info("Successfully uploaded cache.")
830847
}
831848
| (Error(message), _)
832849
| (_, Error(message)) =>

codegenerator/cli/templates/static/codegen/src/Config.res

Lines changed: 37 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -91,46 +91,54 @@ let codegenPersistence = Persistence.make(
9191
~pgSchema=storagePgSchema,
9292
~pgHost=Env.Db.host,
9393
~pgUser=Env.Db.user,
94+
~pgPort=Env.Db.port,
9495
~pgDatabase=Env.Db.database,
9596
~pgPassword=Env.Db.password,
96-
~pgPort=Env.Db.port,
97-
~onInitialize=() => {
97+
~onInitialize=?{
9898
if Env.Hasura.enabled {
99-
Hasura.trackDatabase(
100-
~endpoint=Env.Hasura.graphqlEndpoint,
101-
~auth={
102-
role: Env.Hasura.role,
103-
secret: Env.Hasura.secret,
99+
Some(
100+
() => {
101+
Hasura.trackDatabase(
102+
~endpoint=Env.Hasura.graphqlEndpoint,
103+
~auth={
104+
role: Env.Hasura.role,
105+
secret: Env.Hasura.secret,
106+
},
107+
~pgSchema=storagePgSchema,
108+
~allStaticTables=Db.allStaticTables,
109+
~allEntityTables=Db.allEntityTables,
110+
~responseLimit=Env.Hasura.responseLimit,
111+
~schema=Db.schema,
112+
~aggregateEntities=Env.Hasura.aggregateEntities,
113+
)->Promise.catch(err => {
114+
Logging.errorWithExn(
115+
err->Internal.prettifyExn,
116+
`EE803: Error tracking tables`,
117+
)->Promise.resolve
118+
})
104119
},
105-
~pgSchema=storagePgSchema,
106-
~allStaticTables=Db.allStaticTables,
107-
~allEntityTables=Db.allEntityTables,
108-
~responseLimit=Env.Hasura.responseLimit,
109-
~schema=Db.schema,
110-
~aggregateEntities=Env.Hasura.aggregateEntities,
111-
)->Promise.catch(err => {
112-
Logging.errorWithExn(
113-
err->Internal.prettifyExn,
114-
`EE803: Error tracking tables`,
115-
)->Promise.resolve
116-
})
120+
)
117121
} else {
118-
Promise.resolve()
122+
None
119123
}
120124
},
121-
~onNewTables=(~tableNames) => {
125+
~onNewTables=?{
122126
if Env.Hasura.enabled {
123-
Hasura.trackTables(
124-
~endpoint=Env.Hasura.graphqlEndpoint,
125-
~auth={
126-
role: Env.Hasura.role,
127-
secret: Env.Hasura.secret,
127+
Some(
128+
(~tableNames) => {
129+
Hasura.trackTables(
130+
~endpoint=Env.Hasura.graphqlEndpoint,
131+
~auth={
132+
role: Env.Hasura.role,
133+
secret: Env.Hasura.secret,
134+
},
135+
~pgSchema=storagePgSchema,
136+
~tableNames,
137+
)
128138
},
129-
~pgSchema=storagePgSchema,
130-
~tableNames,
131139
)
132140
} else {
133-
Promise.resolve()
141+
None
134142
}
135143
},
136144
),

codegenerator/cli/templates/static/codegen/src/LoadLayer.res

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ let loadEffect = (
8383
`envio_effect_${effect.name}`,
8484
~fields=[
8585
Table.mkField("id", Text, ~fieldSchema=S.string, ~isPrimaryKey=true),
86-
Table.mkField("output", JsonB, ~fieldSchema=effect.output),
86+
Table.mkField("output", JsonB, ~fieldSchema=S.json(~validate=false)),
8787
],
8888
~compositeIndices=[],
8989
),

codegenerator/cli/templates/static/codegen/src/UserContext.res

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ let rec initEffect = (params: contextParams) => (
3434
~effectArgs={
3535
input,
3636
context: params->Utils.Proxy.make(effectTraps)->Utils.magic,
37-
cacheKey: input->Utils.Hash.makeOrThrow,
37+
cacheKey: input->S.reverseConvertOrThrow(effect.input)->Utils.Hash.makeOrThrow,
3838
},
3939
~inMemoryStore=params.inMemoryStore,
4040
~shouldGroup=params.isPreload,

codegenerator/cli/templates/static/codegen/src/globalState/GlobalState.res

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -862,8 +862,6 @@ let injectedTaskReducer = (
862862
switch shouldExit {
863863
| ExitWithSuccess =>
864864
updateChainMetadataTable(chainManager, ~throttler=writeThrottlers.chainMetaData)
865-
// Dump cache to disk when we reached the end block with tui off
866-
->Promise.then(_ => state.config.persistence.storage.dumpEffectCache())
867865
->Promise.thenResolve(_ => dispatchAction(SuccessExit))
868866
->ignore
869867
| NoExit | NoExitWithCacheDump =>

0 commit comments

Comments
 (0)