@latticexyz/store-indexer 2.0.6-main-8c3dcf77 → 2.0.6-main-56712f79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as b,b as T,c as L}from"../chunk-ZS3IQEZ4.js";import{a as $}from"../chunk-VCBWGHIO.js";import{a as A,c as N}from"../chunk-NHP2EYE7.js";import{a as x}from"../chunk-KDDXIBYJ.js";import{a as I}from"../chunk-OUZYPRYF.js";import"dotenv/config";import{z as h}from"zod";import oe from"koa";import te from"@koa/cors";import{createKoaMiddleware as ne}from"trpc-koa-adapter";import{createAppRouter as ae}from"@latticexyz/store-sync/trpc-indexer";import{drizzle as se}from"drizzle-orm/postgres-js";import de from"postgres";import{getAddress as w}from"viem";import{isTableRegistrationLog as W,logToTable as J,storeTables as Y}from"@latticexyz/store-sync";import{decodeKey as K,decodeValueArgs as U}from"@latticexyz/protocol-parser/internal";import{tables as i}from"@latticexyz/store-sync/postgres";import{and as Q,asc as z,eq as l,or as C}from"drizzle-orm";import{bigIntMax as F}from"@latticexyz/common/utils";import{decodeDynamicField as M}from"@latticexyz/protocol-parser/internal";function S(e){return{address:e.address,eventName:"Store_SetRecord",args:{tableId:e.tableId,keyTuple:M("bytes32[]",e.keyBytes),staticData:e.staticData??"0x",encodedLengths:e.encodedLengths??"0x",dynamicData:e.dynamicData??"0x"}}}import{createBenchmark as H}from"@latticexyz/common";async function k(e,{chainId:t,address:r,filters:a=[]}){let o=H("drizzleGetLogs"),n=a.length?a.map(s=>Q(r!=null?l(i.recordsTable.address,r):void 0,l(i.recordsTable.tableId,s.tableId),s.key0!=null?l(i.recordsTable.key0,s.key0):void 0,s.key1!=null?l(i.recordsTable.key1,s.key1):void 0)):r!=null?[l(i.recordsTable.address,r)]:[];o("parse config");let p=(await e.select().from(i.configTable).where(l(i.configTable.chainId,t)).limit(1).execute().then(s=>s.find(()=>!0)))?.blockNumber??0n;o("query chainState");let g=await e.select().from(i.recordsTable).where(C(...n)).orderBy(z(i.recordsTable.blockNumber));o("query records");let d=g.reduce((s,y)=>F(s,y.blockNumber??0n),p);o("find block number");let R=g.filter(s=>!s.isDeleted).map(S);return o("map records to logs"),{blockNumber:d,logs:R}}import{groupBy as V}from"@latticexyz/common/utils";async function D(e){return{async getLogs(r){return k(e,r)},async findAll(r){let a=r.filters??[],{blockNumber:o,logs:n}=await k(e,{...r,filters:a.length>0?[...a,{tableId:Y.Tables.tableId}]:[]}),u=n.filter(W).map(J),p=V(n,d=>`${w(d.address)}:${d.args.tableId}`),g=u.map(d=>{let s=(p.get(`${w(d.address)}:${d.tableId}`)??[]).map(y=>({key:K(d.keySchema,y.args.keyTuple),value:U(d.valueSchema,y.args)}));return{...d,records:s}});return b("findAll: decoded %d logs across %d tables",n.length,u.length),{blockNumber:o,tables:g}}}}import G from"@koa/router";import X from"koa-compose";import{input as Z}from"@latticexyz/store-sync/indexer-client";import{storeTables as ee}from"@latticexyz/store-sync";import{isNotNull as _}from"@latticexyz/common/utils";import{hexToBytes as f}from"viem";import{transformSchemaName as j}from"@latticexyz/store-sync/postgres";var E=j("mud");function O(e,t){return e`(${t.reduce((r,a)=>e`${r} AND ${a}`)})`}function q(e,t){return e`(${t.reduce((r,a)=>e`${r} OR ${a}`)})`}function B(e,t){let r=t.filters.length?t.filters.map(o=>O(e,[t.address!=null?e`address = ${f(t.address)}`:null,e`table_id = ${f(o.tableId)}`,o.key0!=null?e`key0 = ${f(o.key0)}`:null,o.key1!=null?e`key1 = ${f(o.key1)}`:null].filter(_))):t.address!=null?[e`address = ${f(t.address)}`]:[],a=e`WHERE ${O(e,[e`is_deleted != true`,r.length?q(e,r):null].filter(_))}`;return e`
2
+ import{a as b,b as T,c as $}from"../chunk-ZS3IQEZ4.js";import{a as L}from"../chunk-VCBWGHIO.js";import{a as A,c as N}from"../chunk-NHP2EYE7.js";import{a as x}from"../chunk-KDDXIBYJ.js";import{a as w}from"../chunk-OUZYPRYF.js";import"dotenv/config";import{z as h}from"zod";import oe from"koa";import te from"@koa/cors";import{createKoaMiddleware as ne}from"trpc-koa-adapter";import{createAppRouter as ae}from"@latticexyz/store-sync/trpc-indexer";import{drizzle as se}from"drizzle-orm/postgres-js";import ie from"postgres";import{getAddress as I}from"viem";import{isTableRegistrationLog as H,logToTable as J,storeTables as j}from"@latticexyz/store-sync";import{decodeKey as Y,decodeValueArgs as K}from"@latticexyz/protocol-parser/internal";import{tables as d}from"@latticexyz/store-sync/postgres";import{and as M,asc as Q,eq as p,or as z}from"drizzle-orm";import{bigIntMax as F}from"@latticexyz/common/utils";import{decodeDynamicField as C}from"@latticexyz/protocol-parser/internal";function S(e){return{address:e.address,eventName:"Store_SetRecord",args:{tableId:e.tableId,keyTuple:C("bytes32[]",e.keyBytes),staticData:e.staticData??"0x",encodedLengths:e.encodedLengths??"0x",dynamicData:e.dynamicData??"0x"}}}import{createBenchmark as W}from"@latticexyz/common";async function k(e,{chainId:t,address:r,filters:a=[]}){let o=W("drizzleGetLogs"),n=a.length?a.map(s=>M(r!=null?p(d.recordsTable.address,r):void 0,p(d.recordsTable.tableId,s.tableId),s.key0!=null?p(d.recordsTable.key0,s.key0):void 0,s.key1!=null?p(d.recordsTable.key1,s.key1):void 0)):r!=null?[p(d.recordsTable.address,r)]:[];o("parse config");let f=(await e.select().from(d.configTable).where(p(d.configTable.chainId,t)).limit(1).execute().then(s=>s.find(()=>!0)))?.blockNumber??0n;o("query chainState");let l=await e.select().from(d.recordsTable).where(z(...n)).orderBy(Q(d.recordsTable.blockNumber));o("query records");let i=l.reduce((s,y)=>F(s,y.blockNumber??0n),f);o("find block number");let R=l.filter(s=>!s.isDeleted).map(S);return o("map records to logs"),{blockNumber:i,logs:R}}import{groupBy as U}from"@latticexyz/common/utils";async function D(e){return{async getLogs(r){return k(e,r)},async findAll(r){let a=r.filters??[],{blockNumber:o,logs:n}=await k(e,{...r,filters:a.length>0?[...a,{tableId:j.Tables.tableId}]:[]}),u=n.filter(H).map(J),f=U(n,i=>`${I(i.address)}:${i.args.tableId}`),l=u.map(i=>{let s=(f.get(`${I(i.address)}:${i.tableId}`)??[]).map(y=>({key:Y(i.keySchema,y.args.keyTuple),value:K(i.valueSchema,y.args)}));return{...i,records:s}});return b("findAll: decoded %d logs across %d tables",n.length,u.length),{blockNumber:o,tables:l}}}}import G from"@koa/router";import X from"koa-compose";import{input as Z}from"@latticexyz/store-sync/indexer-client";import{storeTables as ee}from"@latticexyz/store-sync";import{isNotNull as _}from"@latticexyz/common/utils";import{hexToBytes as g}from"viem";import{transformSchemaName as V}from"@latticexyz/store-sync/postgres";var E=V("mud");function O(e,t){return e`(${t.reduce((r,a)=>e`${r} AND ${a}`)})`}function q(e,t){return e`(${t.reduce((r,a)=>e`${r} OR ${a}`)})`}function B(e,t){let r=t.filters.length?t.filters.map(o=>O(e,[t.address!=null?e`address = ${g(t.address)}`:null,e`table_id = ${g(o.tableId)}`,o.key0!=null?e`key0 = ${g(o.key0)}`:null,o.key1!=null?e`key1 = ${g(o.key1)}`:null].filter(_))):t.address!=null?[e`address = ${g(t.address)}`]:[],a=e`WHERE ${O(e,[e`is_deleted != true`,r.length?q(e,r):null].filter(_))}`;return e`
3
3
  WITH
4
4
  config AS (
5
5
  SELECT
@@ -27,5 +27,5 @@ import{a as b,b as T,c as L}from"../chunk-ZS3IQEZ4.js";import{a as $}from"../chu
27
27
  (SELECT COUNT(*) FROM records) AS "totalRows",
28
28
  *
29
29
  FROM config, records
30
- `}import{createBenchmark as re}from"@latticexyz/common";function P(e){let t=new G;return t.get("/api/logs",L(),async r=>{let a=re("postgres:logs"),o;try{o=Z.parse(typeof r.query.input=="string"?JSON.parse(r.query.input):{})}catch(n){r.status=400,r.body=JSON.stringify(n),b(n);return}try{o.filters=o.filters.length>0?[...o.filters,{tableId:ee.Tables.tableId}]:[];let n=await B(e,o??{}).execute();a("query records");let u=n.map(S);if(a("map records to logs"),n.length===0){r.status=404,r.body="no logs found",T(`no logs found for chainId ${o.chainId}, address ${o.address}, filters ${JSON.stringify(o.filters)}`);return}let p=n[0].chainBlockNumber;r.body=JSON.stringify({blockNumber:p,logs:u}),r.status=200}catch(n){r.status=500,r.body=JSON.stringify(n),T(n)}}),X([t.routes(),t.allowedMethods()])}var c=N(h.intersection(A,h.object({DATABASE_URL:h.string(),SENTRY_DSN:h.string().optional()}))),v=de(c.DATABASE_URL,{prepare:!1}),m=new oe;c.SENTRY_DSN&&m.use($(c.SENTRY_DSN));m.use(te());m.use(x());m.use(I());m.use(P(v));m.use(ne({prefix:"/trpc",router:ae(),createContext:async()=>({queryAdapter:await D(se(v))})}));m.listen({host:c.HOST,port:c.PORT});console.log(`postgres indexer frontend listening on http://${c.HOST}:${c.PORT}`);
30
+ `}import{createBenchmark as re}from"@latticexyz/common";function P(e){let t=new G;return t.get("/api/logs",$(),async r=>{let a=re("postgres:logs"),o;try{o=Z.parse(typeof r.query.input=="string"?JSON.parse(r.query.input):{})}catch(n){r.status=400,r.set("Content-Type","application/json"),r.body=JSON.stringify(n),b(n);return}try{o.filters=o.filters.length>0?[...o.filters,{tableId:ee.Tables.tableId}]:[];let n=await B(e,o??{}).execute();a("query records");let u=n.map(S);if(a("map records to logs"),n.length===0){r.status=404,r.body="no logs found",T(`no logs found for chainId ${o.chainId}, address ${o.address}, filters ${JSON.stringify(o.filters)}`);return}let f=n[0].chainBlockNumber;r.status=200;let l=60*5,i=4e3*2;r.set("Cache-Control",`public, max-age=${l}, stale-while-revalidate=${i}`),r.set("Content-Type","application/json"),r.body=JSON.stringify({blockNumber:f,logs:u})}catch(n){r.status=500,r.set("Content-Type","application/json"),r.body=JSON.stringify(n),T(n)}}),X([t.routes(),t.allowedMethods()])}var c=N(h.intersection(A,h.object({DATABASE_URL:h.string(),SENTRY_DSN:h.string().optional()}))),v=ie(c.DATABASE_URL,{prepare:!1}),m=new oe;c.SENTRY_DSN&&m.use(L(c.SENTRY_DSN));m.use(te());m.use(x());m.use(w());m.use(P(v));m.use(ne({prefix:"/trpc",router:ae(),createContext:async()=>({queryAdapter:await D(se(v))})}));m.listen({host:c.HOST,port:c.PORT});console.log(`postgres indexer frontend listening on http://${c.HOST}:${c.PORT}`);
31
31
  //# sourceMappingURL=postgres-frontend.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../bin/postgres-frontend.ts","../../src/postgres/deprecated/createQueryAdapter.ts","../../src/postgres/deprecated/getLogs.ts","../../src/postgres/recordToLog.ts","../../src/postgres/apiRoutes.ts","../../src/postgres/queryLogs.ts"],"sourcesContent":["#!/usr/bin/env node\nimport \"dotenv/config\";\nimport { z } from \"zod\";\nimport Koa from \"koa\";\nimport cors from \"@koa/cors\";\nimport { createKoaMiddleware } from \"trpc-koa-adapter\";\nimport { createAppRouter } from \"@latticexyz/store-sync/trpc-indexer\";\nimport { drizzle } from \"drizzle-orm/postgres-js\";\nimport postgres from \"postgres\";\nimport { frontendEnvSchema, parseEnv } from \"./parseEnv\";\nimport { createQueryAdapter } from \"../src/postgres/deprecated/createQueryAdapter\";\nimport { apiRoutes } from \"../src/postgres/apiRoutes\";\nimport { sentry } from \"../src/koa-middleware/sentry\";\nimport { healthcheck } from \"../src/koa-middleware/healthcheck\";\nimport { helloWorld } from \"../src/koa-middleware/helloWorld\";\n\nconst env = parseEnv(\n z.intersection(\n frontendEnvSchema,\n z.object({\n DATABASE_URL: z.string(),\n SENTRY_DSN: z.string().optional(),\n }),\n ),\n);\n\nconst database = postgres(env.DATABASE_URL, { prepare: false });\n\nconst server = new Koa();\n\nif (env.SENTRY_DSN) {\n server.use(sentry(env.SENTRY_DSN));\n}\n\nserver.use(cors());\nserver.use(healthcheck());\nserver.use(helloWorld());\nserver.use(apiRoutes(database));\n\nserver.use(\n createKoaMiddleware({\n prefix: \"/trpc\",\n router: createAppRouter(),\n createContext: async () => ({\n queryAdapter: await createQueryAdapter(drizzle(database)),\n }),\n }),\n);\n\nserver.listen({ host: env.HOST, port: env.PORT });\nconsole.log(`postgres indexer frontend listening on http://${env.HOST}:${env.PORT}`);\n","import { getAddress } from \"viem\";\nimport { PgDatabase } from \"drizzle-orm/pg-core\";\nimport { TableWithRecords, isTableRegistrationLog, logToTable, storeTables } from \"@latticexyz/store-sync\";\nimport { decodeKey, decodeValueArgs } from \"@latticexyz/protocol-parser/internal\";\nimport { QueryAdapter } from \"@latticexyz/store-sync/trpc-indexer\";\nimport { debug } from \"../../debug\";\nimport { getLogs } from \"./getLogs\";\nimport { groupBy } from \"@latticexyz/common/utils\";\n\n/**\n * Creates a query adapter for the tRPC server/client to query data from Postgres.\n *\n * @param {PgDatabase<any>} database Postgres database object from Drizzle\n * @returns {Promise<QueryAdapter>} A set of methods used by tRPC endpoints.\n * @deprecated\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function createQueryAdapter(database: PgDatabase<any>): Promise<QueryAdapter> {\n const adapter: QueryAdapter = {\n async getLogs(opts) {\n return getLogs(database, opts);\n },\n async findAll(opts) {\n const filters = opts.filters ?? [];\n const { blockNumber, logs } = await getLogs(database, {\n ...opts,\n // make sure we're always retrieving `store.Tables` table, so we can decode table values\n filters: filters.length > 0 ? [...filters, { tableId: storeTables.Tables.tableId }] : [],\n });\n\n const tables = logs.filter(isTableRegistrationLog).map(logToTable);\n\n const logsByTable = groupBy(logs, (log) => `${getAddress(log.address)}:${log.args.tableId}`);\n\n const tablesWithRecords: TableWithRecords[] = tables.map((table) => {\n const tableLogs = logsByTable.get(`${getAddress(table.address)}:${table.tableId}`) ?? [];\n const records = tableLogs.map((log) => ({\n key: decodeKey(table.keySchema, log.args.keyTuple),\n value: decodeValueArgs(table.valueSchema, log.args),\n }));\n\n return {\n ...table,\n records,\n };\n });\n\n debug(\"findAll: decoded %d logs across %d tables\", logs.length, tables.length);\n\n return {\n blockNumber,\n tables: tablesWithRecords,\n };\n },\n };\n return adapter;\n}\n","import { PgDatabase } from \"drizzle-orm/pg-core\";\nimport { Hex } from \"viem\";\nimport { StorageAdapterLog, SyncFilter } from \"@latticexyz/store-sync\";\nimport { tables } from \"@latticexyz/store-sync/postgres\";\nimport { and, asc, eq, or } from \"drizzle-orm\";\nimport { bigIntMax } from \"@latticexyz/common/utils\";\nimport { recordToLog } from \"../recordToLog\";\nimport { createBenchmark } from \"@latticexyz/common\";\n\n/**\n * @deprecated\n */\nexport async function getLogs(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n database: PgDatabase<any>,\n {\n chainId,\n address,\n filters = [],\n }: {\n readonly chainId: number;\n readonly address?: Hex;\n readonly filters?: readonly SyncFilter[];\n },\n): Promise<{ blockNumber: bigint; logs: (StorageAdapterLog & { eventName: \"Store_SetRecord\" })[] }> {\n const benchmark = createBenchmark(\"drizzleGetLogs\");\n\n const conditions = filters.length\n ? filters.map((filter) =>\n and(\n address != null ? eq(tables.recordsTable.address, address) : undefined,\n eq(tables.recordsTable.tableId, filter.tableId),\n filter.key0 != null ? eq(tables.recordsTable.key0, filter.key0) : undefined,\n filter.key1 != null ? eq(tables.recordsTable.key1, filter.key1) : undefined,\n ),\n )\n : address != null\n ? [eq(tables.recordsTable.address, address)]\n : [];\n benchmark(\"parse config\");\n\n // Query for the block number that the indexer (i.e. chain) is at, in case the\n // indexer is further along in the chain than a given store/table's last updated\n // block number. We'll then take the highest block number between the indexer's\n // chain state and all the records in the query (in case the records updated\n // between these queries). Using just the highest block number from the queries\n // could potentially signal to the client an older-than-necessary block number,\n // for stores/tables that haven't seen recent activity.\n // TODO: move the block number query into the records query for atomicity so we don't have to merge them here\n const chainState = await database\n .select()\n .from(tables.configTable)\n .where(eq(tables.configTable.chainId, chainId))\n .limit(1)\n .execute()\n // Get the first record in a way that returns a possible `undefined`\n // TODO: move this to `.findFirst` after upgrading drizzle or `rows[0]` after enabling `noUncheckedIndexedAccess: true`\n .then((rows) => rows.find(() => true));\n const indexerBlockNumber = chainState?.blockNumber ?? 0n;\n benchmark(\"query chainState\");\n\n const records = await database\n .select()\n .from(tables.recordsTable)\n .where(or(...conditions))\n .orderBy(\n asc(tables.recordsTable.blockNumber),\n // TODO: add logIndex (https://github.com/latticexyz/mud/issues/1979)\n );\n benchmark(\"query records\");\n\n const blockNumber = records.reduce((max, record) => bigIntMax(max, record.blockNumber ?? 0n), indexerBlockNumber);\n benchmark(\"find block number\");\n\n const logs = records\n // TODO: add this to the query, assuming we can optimize with an index\n .filter((record) => !record.isDeleted)\n .map(recordToLog);\n benchmark(\"map records to logs\");\n\n return { blockNumber, logs };\n}\n","import { StorageAdapterLog } from \"@latticexyz/store-sync\";\nimport { decodeDynamicField } from \"@latticexyz/protocol-parser/internal\";\nimport { RecordData } from \"./common\";\n\nexport function recordToLog(\n record: Omit<RecordData, \"recordBlockNumber\">,\n): StorageAdapterLog & { eventName: \"Store_SetRecord\" } {\n return {\n address: record.address,\n eventName: \"Store_SetRecord\",\n args: {\n tableId: record.tableId,\n keyTuple: decodeDynamicField(\"bytes32[]\", record.keyBytes),\n staticData: record.staticData ?? \"0x\",\n encodedLengths: record.encodedLengths ?? \"0x\",\n dynamicData: record.dynamicData ?? \"0x\",\n },\n } as const;\n}\n","import { Sql } from \"postgres\";\nimport { Middleware } from \"koa\";\nimport Router from \"@koa/router\";\nimport compose from \"koa-compose\";\nimport { input } from \"@latticexyz/store-sync/indexer-client\";\nimport { storeTables } from \"@latticexyz/store-sync\";\nimport { queryLogs } from \"./queryLogs\";\nimport { recordToLog } from \"./recordToLog\";\nimport { debug, error } from \"../debug\";\nimport { createBenchmark } from \"@latticexyz/common\";\nimport { compress } from \"../koa-middleware/compress\";\n\nexport function apiRoutes(database: Sql): Middleware {\n const router = new Router();\n\n router.get(\"/api/logs\", compress(), async (ctx) => {\n const benchmark = createBenchmark(\"postgres:logs\");\n let options: ReturnType<typeof input.parse>;\n\n try {\n options = input.parse(typeof ctx.query.input === \"string\" ? JSON.parse(ctx.query.input) : {});\n } catch (e) {\n ctx.status = 400;\n ctx.body = JSON.stringify(e);\n debug(e);\n return;\n }\n\n try {\n options.filters = options.filters.length > 0 ? [...options.filters, { tableId: storeTables.Tables.tableId }] : [];\n const records = await queryLogs(database, options ?? {}).execute();\n benchmark(\"query records\");\n const logs = records.map(recordToLog);\n benchmark(\"map records to logs\");\n\n if (records.length === 0) {\n ctx.status = 404;\n ctx.body = \"no logs found\";\n error(\n `no logs found for chainId ${options.chainId}, address ${options.address}, filters ${JSON.stringify(\n options.filters,\n )}`,\n );\n return;\n }\n\n const blockNumber = records[0].chainBlockNumber;\n ctx.body = JSON.stringify({ blockNumber, logs });\n ctx.status = 200;\n } catch (e) {\n ctx.status = 500;\n ctx.body = JSON.stringify(e);\n error(e);\n }\n });\n\n return compose([router.routes(), router.allowedMethods()]) as Middleware;\n}\n","import { isNotNull } from \"@latticexyz/common/utils\";\nimport { PendingQuery, Row, Sql } from \"postgres\";\nimport { hexToBytes } from \"viem\";\nimport { z } from \"zod\";\nimport { input } from \"@latticexyz/store-sync/indexer-client\";\nimport { transformSchemaName } from \"@latticexyz/store-sync/postgres\";\nimport { Record } from \"./common\";\n\nconst schemaName = transformSchemaName(\"mud\");\n\nfunction and(sql: Sql, conditions: PendingQuery<Row[]>[]): PendingQuery<Row[]> {\n return sql`(${conditions.reduce((query, condition) => sql`${query} AND ${condition}`)})`;\n}\n\nfunction or(sql: Sql, conditions: PendingQuery<Row[]>[]): PendingQuery<Row[]> {\n return sql`(${conditions.reduce((query, condition) => sql`${query} OR ${condition}`)})`;\n}\n\nexport function queryLogs(sql: Sql, opts: z.infer<typeof input>): PendingQuery<Record[]> {\n const conditions = opts.filters.length\n ? opts.filters.map((filter) =>\n and(\n sql,\n [\n opts.address != null ? sql`address = ${hexToBytes(opts.address)}` : null,\n sql`table_id = ${hexToBytes(filter.tableId)}`,\n filter.key0 != null ? sql`key0 = ${hexToBytes(filter.key0)}` : null,\n filter.key1 != null ? sql`key1 = ${hexToBytes(filter.key1)}` : null,\n ].filter(isNotNull),\n ),\n )\n : opts.address != null\n ? [sql`address = ${hexToBytes(opts.address)}`]\n : [];\n\n const where = sql`WHERE ${and(\n sql,\n [sql`is_deleted != true`, conditions.length ? or(sql, conditions) : null].filter(isNotNull),\n )}`;\n\n // TODO: implement bytea <> hex columns via custom types: https://github.com/porsager/postgres#custom-types\n return sql<Record[]>`\n WITH\n config AS (\n SELECT\n version AS \"indexerVersion\",\n chain_id AS \"chainId\",\n block_number AS \"chainBlockNumber\"\n FROM ${sql(`${schemaName}.config`)}\n LIMIT 1\n ),\n records AS (\n SELECT\n '0x' || encode(address, 'hex') AS address,\n '0x' || encode(table_id, 'hex') AS \"tableId\",\n '0x' || encode(key_bytes, 'hex') AS \"keyBytes\",\n '0x' || encode(static_data, 'hex') AS \"staticData\",\n '0x' || encode(encoded_lengths, 'hex') AS \"encodedLengths\",\n '0x' || encode(dynamic_data, 'hex') AS \"dynamicData\",\n block_number AS \"recordBlockNumber\",\n log_index AS \"logIndex\"\n FROM ${sql(`${schemaName}.records`)}\n ${where}\n ORDER BY block_number, log_index ASC\n )\n SELECT\n (SELECT COUNT(*) FROM records) AS \"totalRows\",\n *\n FROM config, records\n `;\n}\n"],"mappings":";kOACA,MAAO,gBACP,OAAS,KAAAA,MAAS,MAClB,OAAOC,OAAS,MAChB,OAAOC,OAAU,YACjB,OAAS,uBAAAC,OAA2B,mBACpC,OAAS,mBAAAC,OAAuB,sCAChC,OAAS,WAAAC,OAAe,0BACxB,OAAOC,OAAc,WCRrB,OAAS,cAAAC,MAAkB,OAE3B,OAA2B,0BAAAC,EAAwB,cAAAC,EAAY,eAAAC,MAAmB,yBAClF,OAAS,aAAAC,EAAW,mBAAAC,MAAuB,uCCA3C,OAAS,UAAAC,MAAc,kCACvB,OAAS,OAAAC,EAAK,OAAAC,EAAK,MAAAC,EAAI,MAAAC,MAAU,cACjC,OAAS,aAAAC,MAAiB,2BCJ1B,OAAS,sBAAAC,MAA0B,uCAG5B,SAASC,EACdC,EACsD,CACtD,MAAO,CACL,QAASA,EAAO,QAChB,UAAW,kBACX,KAAM,CACJ,QAASA,EAAO,QAChB,SAAUF,EAAmB,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,EAExDM,EAAS,IAAIC,GAEfP,EAAI,YACNM,EAAO,IAAIE,EAAOR,EAAI,UAAU,CAAC,EAGnCM,EAAO,IAAIG,GAAK,CAAC,EACjBH,EAAO,IAAII,EAAY,CAAC,EACxBJ,EAAO,IAAIK,EAAW,CAAC,EACvBL,EAAO,IAAIM,EAAUR,CAAQ,CAAC,EAE9BE,EAAO,IACLO,GAAoB,CAClB,OAAQ,QACR,OAAQC,GAAgB,EACxB,cAAe,UAAa,CAC1B,aAAc,MAAMC,EAAmBC,GAAQZ,CAAQ,CAAC,CAC1D,EACF,CAAC,CACH,EAEAE,EAAO,OAAO,CAAE,KAAMN,EAAI,KAAM,KAAMA,EAAI,IAAK,CAAC,EAChD,QAAQ,IAAI,iDAAiDA,EAAI,QAAQA,EAAI,MAAM","names":["z","Koa","cors","createKoaMiddleware","createAppRouter","drizzle","postgres","getAddress","isTableRegistrationLog","logToTable","storeTables","decodeKey","decodeValueArgs","tables","and","asc","eq","or","bigIntMax","decodeDynamicField","recordToLog","record","createBenchmark","getLogs","database","chainId","address","filters","benchmark","conditions","filter","and","eq","tables","indexerBlockNumber","rows","records","or","asc","blockNumber","max","record","bigIntMax","logs","recordToLog","groupBy","createQueryAdapter","database","opts","getLogs","filters","blockNumber","logs","storeTables","tables","isTableRegistrationLog","logToTable","logsByTable","log","getAddress","tablesWithRecords","table","records","decodeKey","decodeValueArgs","debug","Router","compose","input","storeTables","isNotNull","hexToBytes","transformSchemaName","schemaName","and","sql","conditions","query","condition","or","queryLogs","opts","filter","where","createBenchmark","apiRoutes","database","router","Router","compress","ctx","benchmark","createBenchmark","options","input","e","debug","storeTables","records","queryLogs","logs","recordToLog","error","blockNumber","compose","env","parseEnv","z","frontendEnvSchema","database","postgres","server","Koa","sentry","cors","healthcheck","helloWorld","apiRoutes","createKoaMiddleware","createAppRouter","createQueryAdapter","drizzle"]}
1
+ {"version":3,"sources":["../../bin/postgres-frontend.ts","../../src/postgres/deprecated/createQueryAdapter.ts","../../src/postgres/deprecated/getLogs.ts","../../src/postgres/recordToLog.ts","../../src/postgres/apiRoutes.ts","../../src/postgres/queryLogs.ts"],"sourcesContent":["#!/usr/bin/env node\nimport \"dotenv/config\";\nimport { z } from \"zod\";\nimport Koa from \"koa\";\nimport cors from \"@koa/cors\";\nimport { createKoaMiddleware } from \"trpc-koa-adapter\";\nimport { createAppRouter } from \"@latticexyz/store-sync/trpc-indexer\";\nimport { drizzle } from \"drizzle-orm/postgres-js\";\nimport postgres from \"postgres\";\nimport { frontendEnvSchema, parseEnv } from \"./parseEnv\";\nimport { createQueryAdapter } from \"../src/postgres/deprecated/createQueryAdapter\";\nimport { apiRoutes } from \"../src/postgres/apiRoutes\";\nimport { sentry } from \"../src/koa-middleware/sentry\";\nimport { healthcheck } from \"../src/koa-middleware/healthcheck\";\nimport { helloWorld } from \"../src/koa-middleware/helloWorld\";\n\nconst env = parseEnv(\n z.intersection(\n frontendEnvSchema,\n z.object({\n DATABASE_URL: z.string(),\n SENTRY_DSN: z.string().optional(),\n }),\n ),\n);\n\nconst database = postgres(env.DATABASE_URL, { prepare: false });\n\nconst server = new Koa();\n\nif (env.SENTRY_DSN) {\n server.use(sentry(env.SENTRY_DSN));\n}\n\nserver.use(cors());\nserver.use(healthcheck());\nserver.use(helloWorld());\nserver.use(apiRoutes(database));\n\nserver.use(\n createKoaMiddleware({\n prefix: \"/trpc\",\n router: createAppRouter(),\n createContext: async () => ({\n queryAdapter: await createQueryAdapter(drizzle(database)),\n }),\n }),\n);\n\nserver.listen({ host: env.HOST, port: env.PORT });\nconsole.log(`postgres indexer frontend listening on http://${env.HOST}:${env.PORT}`);\n","import { getAddress } from \"viem\";\nimport { PgDatabase } from \"drizzle-orm/pg-core\";\nimport { TableWithRecords, isTableRegistrationLog, logToTable, storeTables } from \"@latticexyz/store-sync\";\nimport { decodeKey, decodeValueArgs } from \"@latticexyz/protocol-parser/internal\";\nimport { QueryAdapter } from \"@latticexyz/store-sync/trpc-indexer\";\nimport { debug } from \"../../debug\";\nimport { getLogs } from \"./getLogs\";\nimport { groupBy } from \"@latticexyz/common/utils\";\n\n/**\n * Creates a query adapter for the tRPC server/client to query data from Postgres.\n *\n * @param {PgDatabase<any>} database Postgres database object from Drizzle\n * @returns {Promise<QueryAdapter>} A set of methods used by tRPC endpoints.\n * @deprecated\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function createQueryAdapter(database: PgDatabase<any>): Promise<QueryAdapter> {\n const adapter: QueryAdapter = {\n async getLogs(opts) {\n return getLogs(database, opts);\n },\n async findAll(opts) {\n const filters = opts.filters ?? [];\n const { blockNumber, logs } = await getLogs(database, {\n ...opts,\n // make sure we're always retrieving `store.Tables` table, so we can decode table values\n filters: filters.length > 0 ? [...filters, { tableId: storeTables.Tables.tableId }] : [],\n });\n\n const tables = logs.filter(isTableRegistrationLog).map(logToTable);\n\n const logsByTable = groupBy(logs, (log) => `${getAddress(log.address)}:${log.args.tableId}`);\n\n const tablesWithRecords: TableWithRecords[] = tables.map((table) => {\n const tableLogs = logsByTable.get(`${getAddress(table.address)}:${table.tableId}`) ?? [];\n const records = tableLogs.map((log) => ({\n key: decodeKey(table.keySchema, log.args.keyTuple),\n value: decodeValueArgs(table.valueSchema, log.args),\n }));\n\n return {\n ...table,\n records,\n };\n });\n\n debug(\"findAll: decoded %d logs across %d tables\", logs.length, tables.length);\n\n return {\n blockNumber,\n tables: tablesWithRecords,\n };\n },\n };\n return adapter;\n}\n","import { PgDatabase } from \"drizzle-orm/pg-core\";\nimport { Hex } from \"viem\";\nimport { StorageAdapterLog, SyncFilter } from \"@latticexyz/store-sync\";\nimport { tables } from \"@latticexyz/store-sync/postgres\";\nimport { and, asc, eq, or } from \"drizzle-orm\";\nimport { bigIntMax } from \"@latticexyz/common/utils\";\nimport { recordToLog } from \"../recordToLog\";\nimport { createBenchmark } from \"@latticexyz/common\";\n\n/**\n * @deprecated\n */\nexport async function getLogs(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n database: PgDatabase<any>,\n {\n chainId,\n address,\n filters = [],\n }: {\n readonly chainId: number;\n readonly address?: Hex;\n readonly filters?: readonly SyncFilter[];\n },\n): Promise<{ blockNumber: bigint; logs: (StorageAdapterLog & { eventName: \"Store_SetRecord\" })[] }> {\n const benchmark = createBenchmark(\"drizzleGetLogs\");\n\n const conditions = filters.length\n ? filters.map((filter) =>\n and(\n address != null ? eq(tables.recordsTable.address, address) : undefined,\n eq(tables.recordsTable.tableId, filter.tableId),\n filter.key0 != null ? eq(tables.recordsTable.key0, filter.key0) : undefined,\n filter.key1 != null ? eq(tables.recordsTable.key1, filter.key1) : undefined,\n ),\n )\n : address != null\n ? [eq(tables.recordsTable.address, address)]\n : [];\n benchmark(\"parse config\");\n\n // Query for the block number that the indexer (i.e. chain) is at, in case the\n // indexer is further along in the chain than a given store/table's last updated\n // block number. We'll then take the highest block number between the indexer's\n // chain state and all the records in the query (in case the records updated\n // between these queries). Using just the highest block number from the queries\n // could potentially signal to the client an older-than-necessary block number,\n // for stores/tables that haven't seen recent activity.\n // TODO: move the block number query into the records query for atomicity so we don't have to merge them here\n const chainState = await database\n .select()\n .from(tables.configTable)\n .where(eq(tables.configTable.chainId, chainId))\n .limit(1)\n .execute()\n // Get the first record in a way that returns a possible `undefined`\n // TODO: move this to `.findFirst` after upgrading drizzle or `rows[0]` after enabling `noUncheckedIndexedAccess: true`\n .then((rows) => rows.find(() => true));\n const indexerBlockNumber = chainState?.blockNumber ?? 0n;\n benchmark(\"query chainState\");\n\n const records = await database\n .select()\n .from(tables.recordsTable)\n .where(or(...conditions))\n .orderBy(\n asc(tables.recordsTable.blockNumber),\n // TODO: add logIndex (https://github.com/latticexyz/mud/issues/1979)\n );\n benchmark(\"query records\");\n\n const blockNumber = records.reduce((max, record) => bigIntMax(max, record.blockNumber ?? 0n), indexerBlockNumber);\n benchmark(\"find block number\");\n\n const logs = records\n // TODO: add this to the query, assuming we can optimize with an index\n .filter((record) => !record.isDeleted)\n .map(recordToLog);\n benchmark(\"map records to logs\");\n\n return { blockNumber, logs };\n}\n","import { StorageAdapterLog } from \"@latticexyz/store-sync\";\nimport { decodeDynamicField } from \"@latticexyz/protocol-parser/internal\";\nimport { RecordData } from \"./common\";\n\nexport function recordToLog(\n record: Omit<RecordData, \"recordBlockNumber\">,\n): StorageAdapterLog & { eventName: \"Store_SetRecord\" } {\n return {\n address: record.address,\n eventName: \"Store_SetRecord\",\n args: {\n tableId: record.tableId,\n keyTuple: decodeDynamicField(\"bytes32[]\", record.keyBytes),\n staticData: record.staticData ?? \"0x\",\n encodedLengths: record.encodedLengths ?? \"0x\",\n dynamicData: record.dynamicData ?? \"0x\",\n },\n } as const;\n}\n","import { Sql } from \"postgres\";\nimport { Middleware } from \"koa\";\nimport Router from \"@koa/router\";\nimport compose from \"koa-compose\";\nimport { input } from \"@latticexyz/store-sync/indexer-client\";\nimport { storeTables } from \"@latticexyz/store-sync\";\nimport { queryLogs } from \"./queryLogs\";\nimport { recordToLog } from \"./recordToLog\";\nimport { debug, error } from \"../debug\";\nimport { createBenchmark } from \"@latticexyz/common\";\nimport { compress } from \"../koa-middleware/compress\";\n\nexport function apiRoutes(database: Sql): Middleware {\n const router = new Router();\n\n router.get(\"/api/logs\", compress(), async (ctx) => {\n const benchmark = createBenchmark(\"postgres:logs\");\n let options: ReturnType<typeof input.parse>;\n\n try {\n options = input.parse(typeof ctx.query.input === \"string\" ? JSON.parse(ctx.query.input) : {});\n } catch (e) {\n ctx.status = 400;\n ctx.set(\"Content-Type\", \"application/json\");\n ctx.body = JSON.stringify(e);\n debug(e);\n return;\n }\n\n try {\n options.filters = options.filters.length > 0 ? [...options.filters, { tableId: storeTables.Tables.tableId }] : [];\n const records = await queryLogs(database, options ?? {}).execute();\n benchmark(\"query records\");\n const logs = records.map(recordToLog);\n benchmark(\"map records to logs\");\n\n // Ideally we would immediately return an error if the request is for a Store that the indexer\n // is not configured to index. Since we don't have easy access to this information here,\n // we return an error if there are no logs found for a given Store, since that would never\n // be the case for a Store that is being indexed (since there would at least be records for the\n // Tables table with tables created during Store initialization).\n if (records.length === 0) {\n ctx.status = 404;\n ctx.body = \"no logs found\";\n error(\n `no logs found for chainId ${options.chainId}, address ${options.address}, filters ${JSON.stringify(\n options.filters,\n )}`,\n );\n return;\n }\n\n const blockNumber = records[0].chainBlockNumber;\n ctx.status = 200;\n\n // max age is set to several multiples of the uncached response time (currently ~10s, but using 60s for wiggle room) to ensure only ~one origin request at a time\n // and stale-while-revalidate below means that the cache is refreshed under the hood while still responding fast (cached)\n const maxAgeSeconds = 60 * 5;\n // we set stale-while-revalidate to the time elapsed by the number of blocks we can fetch from the RPC in the same amount of time as an uncached response\n // meaning it would take ~the same about of time to get an uncached response from the origin as it would to catch up from the currently cached response\n // if an uncached response takes ~10 seconds, we have ~10s to catch up, so let's say we can do enough RPC calls to fetch 4000 blocks\n // with a block per 2 seconds, that means we can serve a stale/cached response for 8000 seconds before we should require the response be returned by the origin\n const staleWhileRevalidateSeconds = 4000 * 2;\n\n ctx.set(\n \"Cache-Control\",\n `public, max-age=${maxAgeSeconds}, stale-while-revalidate=${staleWhileRevalidateSeconds}`,\n );\n\n ctx.set(\"Content-Type\", \"application/json\");\n ctx.body = JSON.stringify({ blockNumber, logs });\n } catch (e) {\n ctx.status = 500;\n ctx.set(\"Content-Type\", \"application/json\");\n ctx.body = JSON.stringify(e);\n error(e);\n }\n });\n\n return compose([router.routes(), router.allowedMethods()]) as Middleware;\n}\n","import { isNotNull } from \"@latticexyz/common/utils\";\nimport { PendingQuery, Row, Sql } from \"postgres\";\nimport { hexToBytes } from \"viem\";\nimport { z } from \"zod\";\nimport { input } from \"@latticexyz/store-sync/indexer-client\";\nimport { transformSchemaName } from \"@latticexyz/store-sync/postgres\";\nimport { Record } from \"./common\";\n\nconst schemaName = transformSchemaName(\"mud\");\n\nfunction and(sql: Sql, conditions: PendingQuery<Row[]>[]): PendingQuery<Row[]> {\n return sql`(${conditions.reduce((query, condition) => sql`${query} AND ${condition}`)})`;\n}\n\nfunction or(sql: Sql, conditions: PendingQuery<Row[]>[]): PendingQuery<Row[]> {\n return sql`(${conditions.reduce((query, condition) => sql`${query} OR ${condition}`)})`;\n}\n\nexport function queryLogs(sql: Sql, opts: z.infer<typeof input>): PendingQuery<Record[]> {\n const conditions = opts.filters.length\n ? opts.filters.map((filter) =>\n and(\n sql,\n [\n opts.address != null ? sql`address = ${hexToBytes(opts.address)}` : null,\n sql`table_id = ${hexToBytes(filter.tableId)}`,\n filter.key0 != null ? sql`key0 = ${hexToBytes(filter.key0)}` : null,\n filter.key1 != null ? sql`key1 = ${hexToBytes(filter.key1)}` : null,\n ].filter(isNotNull),\n ),\n )\n : opts.address != null\n ? [sql`address = ${hexToBytes(opts.address)}`]\n : [];\n\n const where = sql`WHERE ${and(\n sql,\n [sql`is_deleted != true`, conditions.length ? or(sql, conditions) : null].filter(isNotNull),\n )}`;\n\n // TODO: implement bytea <> hex columns via custom types: https://github.com/porsager/postgres#custom-types\n return sql<Record[]>`\n WITH\n config AS (\n SELECT\n version AS \"indexerVersion\",\n chain_id AS \"chainId\",\n block_number AS \"chainBlockNumber\"\n FROM ${sql(`${schemaName}.config`)}\n LIMIT 1\n ),\n records AS (\n SELECT\n '0x' || encode(address, 'hex') AS address,\n '0x' || encode(table_id, 'hex') AS \"tableId\",\n '0x' || encode(key_bytes, 'hex') AS \"keyBytes\",\n '0x' || encode(static_data, 'hex') AS \"staticData\",\n '0x' || encode(encoded_lengths, 'hex') AS \"encodedLengths\",\n '0x' || encode(dynamic_data, 'hex') AS \"dynamicData\",\n block_number AS \"recordBlockNumber\",\n log_index AS \"logIndex\"\n FROM ${sql(`${schemaName}.records`)}\n ${where}\n ORDER BY block_number, log_index ASC\n )\n SELECT\n (SELECT COUNT(*) FROM records) AS \"totalRows\",\n *\n FROM config, records\n `;\n}\n"],"mappings":";kOACA,MAAO,gBACP,OAAS,KAAAA,MAAS,MAClB,OAAOC,OAAS,MAChB,OAAOC,OAAU,YACjB,OAAS,uBAAAC,OAA2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TableRegistrationLog","logToTable","storeTables","decodeKey","decodeValueArgs","tables","and","asc","eq","or","bigIntMax","decodeDynamicField","recordToLog","record","createBenchmark","getLogs","database","chainId","address","filters","benchmark","conditions","filter","and","eq","tables","indexerBlockNumber","rows","records","or","asc","blockNumber","max","record","bigIntMax","logs","recordToLog","groupBy","createQueryAdapter","database","opts","getLogs","filters","blockNumber","logs","storeTables","tables","isTableRegistrationLog","logToTable","logsByTable","log","getAddress","tablesWithRecords","table","records","decodeKey","decodeValueArgs","debug","Router","compose","input","storeTables","isNotNull","hexToBytes","transformSchemaName","schemaName","and","sql","conditions","query","condition","or","queryLogs","opts","filter","where","createBenchmark","apiRoutes","database","router","Router","compress","ctx","benchmark","createBenchmark","options","input","e","debug","storeTables","records","queryLogs","logs","recordToLog","error","blockNumber","maxAgeSeconds","staleWhileRevalidateSeconds","compose","env","parseEnv","z","frontendEnvSchema","database","postgres","server","Koa","sentry","cors","healthcheck","helloWorld","apiRoutes","createKoaMiddleware","createAppRouter","createQueryAdapter","drizzle"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@latticexyz/store-indexer",
3
- "version": "2.0.6-main-8c3dcf77",
3
+ "version": "2.0.6-main-56712f79",
4
4
  "description": "Minimal Typescript indexer for Store",
5
5
  "repository": {
6
6
  "type": "git",
@@ -40,11 +40,11 @@
40
40
  "trpc-koa-adapter": "^1.1.3",
41
41
  "viem": "2.9.16",
42
42
  "zod": "^3.21.4",
43
- "@latticexyz/block-logs-stream": "2.0.6-main-8c3dcf77",
44
- "@latticexyz/common": "2.0.6-main-8c3dcf77",
45
- "@latticexyz/protocol-parser": "2.0.6-main-8c3dcf77",
46
- "@latticexyz/store": "2.0.6-main-8c3dcf77",
47
- "@latticexyz/store-sync": "2.0.6-main-8c3dcf77"
43
+ "@latticexyz/block-logs-stream": "2.0.6-main-56712f79",
44
+ "@latticexyz/protocol-parser": "2.0.6-main-56712f79",
45
+ "@latticexyz/common": "2.0.6-main-56712f79",
46
+ "@latticexyz/store": "2.0.6-main-56712f79",
47
+ "@latticexyz/store-sync": "2.0.6-main-56712f79"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@types/accepts": "^1.3.7",
@@ -21,6 +21,7 @@ export function apiRoutes(database: Sql): Middleware {
21
21
  options = input.parse(typeof ctx.query.input === "string" ? JSON.parse(ctx.query.input) : {});
22
22
  } catch (e) {
23
23
  ctx.status = 400;
24
+ ctx.set("Content-Type", "application/json");
24
25
  ctx.body = JSON.stringify(e);
25
26
  debug(e);
26
27
  return;
@@ -33,6 +34,11 @@ export function apiRoutes(database: Sql): Middleware {
33
34
  const logs = records.map(recordToLog);
34
35
  benchmark("map records to logs");
35
36
 
37
+ // Ideally we would immediately return an error if the request is for a Store that the indexer
38
+ // is not configured to index. Since we don't have easy access to this information here,
39
+ // we return an error if there are no logs found for a given Store, since that would never
40
+ // be the case for a Store that is being indexed (since there would at least be records for the
41
+ // Tables table with tables created during Store initialization).
36
42
  if (records.length === 0) {
37
43
  ctx.status = 404;
38
44
  ctx.body = "no logs found";
@@ -45,10 +51,27 @@ export function apiRoutes(database: Sql): Middleware {
45
51
  }
46
52
 
47
53
  const blockNumber = records[0].chainBlockNumber;
48
- ctx.body = JSON.stringify({ blockNumber, logs });
49
54
  ctx.status = 200;
55
+
56
+ // max age is set to several multiples of the uncached response time (currently ~10s, but using 60s for wiggle room) to ensure only ~one origin request at a time
57
+ // and stale-while-revalidate below means that the cache is refreshed under the hood while still responding fast (cached)
58
+ const maxAgeSeconds = 60 * 5;
59
+ // we set stale-while-revalidate to the time elapsed by the number of blocks we can fetch from the RPC in the same amount of time as an uncached response
60
+ // meaning it would take ~the same about of time to get an uncached response from the origin as it would to catch up from the currently cached response
61
+ // if an uncached response takes ~10 seconds, we have ~10s to catch up, so let's say we can do enough RPC calls to fetch 4000 blocks
62
+ // with a block per 2 seconds, that means we can serve a stale/cached response for 8000 seconds before we should require the response be returned by the origin
63
+ const staleWhileRevalidateSeconds = 4000 * 2;
64
+
65
+ ctx.set(
66
+ "Cache-Control",
67
+ `public, max-age=${maxAgeSeconds}, stale-while-revalidate=${staleWhileRevalidateSeconds}`,
68
+ );
69
+
70
+ ctx.set("Content-Type", "application/json");
71
+ ctx.body = JSON.stringify({ blockNumber, logs });
50
72
  } catch (e) {
51
73
  ctx.status = 500;
74
+ ctx.set("Content-Type", "application/json");
52
75
  ctx.body = JSON.stringify(e);
53
76
  error(e);
54
77
  }