@latticexyz/store-indexer 2.0.7-main-f736c43d → 2.0.7-main-7dfb82f7
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.
- package/dist/bin/postgres-frontend.js +4 -4
- package/dist/bin/postgres-frontend.js.map +1 -1
- package/dist/bin/postgres-indexer.js +1 -1
- package/dist/bin/postgres-indexer.js.map +1 -1
- package/dist/bin/sqlite-indexer.js +1 -1
- package/dist/bin/sqlite-indexer.js.map +1 -1
- package/dist/chunk-WOLC7XUT.js +2 -0
- package/dist/chunk-WOLC7XUT.js.map +1 -0
- package/dist/metrics-IL7G7G42.js +2 -0
- package/dist/metrics-IL7G7G42.js.map +1 -0
- package/package.json +7 -6
- package/src/koa-middleware/metrics.ts +73 -0
@@ -1,12 +1,12 @@
|
|
1
1
|
#!/usr/bin/env node
|
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
|
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{a as I}from"../chunk-WOLC7XUT.js";import"dotenv/config";import{z as h}from"zod";import te from"koa";import ne from"@koa/cors";import{createKoaMiddleware as ae}from"trpc-koa-adapter";import{createAppRouter as se}from"@latticexyz/store-sync/trpc-indexer";import{drizzle as ie}from"drizzle-orm/postgres-js";import de from"postgres";import{getAddress as D}from"viem";import{isTableRegistrationLog as J,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 d}from"@latticexyz/store-sync/postgres";import{and as Q,asc as z,eq as p,or as F}from"drizzle-orm";import{bigIntMax as H}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 W}from"@latticexyz/common";async function k(e,{chainId:t,address:r,filters:a=[]}){let o=W("drizzleGetLogs"),n=a.length?a.map(s=>Q(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(F(...n)).orderBy(z(d.recordsTable.blockNumber));o("query records");let i=l.reduce((s,y)=>H(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 V}from"@latticexyz/common/utils";async function _(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(J).map(j),f=V(n,i=>`${D(i.address)}:${i.args.tableId}`),l=u.map(i=>{let s=(f.get(`${D(i.address)}:${i.tableId}`)??[]).map(y=>({key:K(i.keySchema,y.args.keyTuple),value:U(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 X from"@koa/router";import Z from"koa-compose";import{input as ee}from"@latticexyz/store-sync/indexer-client";import{storeTables as re}from"@latticexyz/store-sync";import{isNotNull as E}from"@latticexyz/common/utils";import{hexToBytes as g}from"viem";import{transformSchemaName as q}from"@latticexyz/store-sync/postgres";var O=q("mud");function B(e,t){return e`(${t.reduce((r,a)=>e`${r} AND ${a}`)})`}function G(e,t){return e`(${t.reduce((r,a)=>e`${r} OR ${a}`)})`}function P(e,t){let r=t.filters.length?t.filters.map(o=>B(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(E))):t.address!=null?[e`address = ${g(t.address)}`]:[],a=e`WHERE ${B(e,[e`is_deleted != true`,r.length?G(e,r):null].filter(E))}`;return e`
|
3
3
|
WITH
|
4
4
|
config AS (
|
5
5
|
SELECT
|
6
6
|
version AS "indexerVersion",
|
7
7
|
chain_id AS "chainId",
|
8
8
|
block_number AS "chainBlockNumber"
|
9
|
-
FROM ${e(`${
|
9
|
+
FROM ${e(`${O}.config`)}
|
10
10
|
LIMIT 1
|
11
11
|
),
|
12
12
|
records AS (
|
@@ -19,7 +19,7 @@ import{a as b,b as T,c as $}from"../chunk-ZS3IQEZ4.js";import{a as L}from"../chu
|
|
19
19
|
'0x' || encode(dynamic_data, 'hex') AS "dynamicData",
|
20
20
|
block_number AS "recordBlockNumber",
|
21
21
|
log_index AS "logIndex"
|
22
|
-
FROM ${e(`${
|
22
|
+
FROM ${e(`${O}.records`)}
|
23
23
|
${a}
|
24
24
|
ORDER BY block_number, log_index ASC
|
25
25
|
)
|
@@ -27,5 +27,5 @@ import{a as b,b as T,c as $}from"../chunk-ZS3IQEZ4.js";import{a as L}from"../chu
|
|
27
27
|
(SELECT COUNT(*) FROM records) AS "totalRows",
|
28
28
|
*
|
29
29
|
FROM config, records
|
30
|
-
`}import{createBenchmark as
|
30
|
+
`}import{createBenchmark as oe}from"@latticexyz/common";function v(e){let t=new X;return t.get("/api/logs",$(),async r=>{let a=oe("postgres:logs"),o;try{o=ee.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:re.Tables.tableId}]:[];let n=await P(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)}}),Z([t.routes(),t.allowedMethods()])}var m=N(h.intersection(A,h.object({DATABASE_URL:h.string(),SENTRY_DSN:h.string().optional()}))),C=de(m.DATABASE_URL,{prepare:!1}),c=new te;m.SENTRY_DSN&&c.use(L(m.SENTRY_DSN));c.use(ne());c.use(x());c.use(I({isHealthy:()=>!0,isReady:()=>!0}));c.use(w());c.use(v(C));c.use(ae({prefix:"/trpc",router:se(),createContext:async()=>({queryAdapter:await _(ie(C))})}));c.listen({host:m.HOST,port:m.PORT});console.log(`postgres indexer frontend listening on http://${m.HOST}:${m.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.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,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,EAA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ACjD,OAASL,EAAP,CACAL,EAAI,OAAS,IACbA,EAAI,IAAI,eAAgB,kBAAkB,EAC1CA,EAAI,KAAO,KAAK,UAAUK,CAAC,EAC3BO,EAAMP,CAAC,CACT,CACF,CAAC,EAEMW,EAAQ,CAACnB,EAAO,OAAO,EAAGA,EAAO,eAAe,CAAC,CAAC,CAC3D,CJhEA,IAAMoB,EAAMC,EACVC,EAAE,aACAC,EACAD,EAAE,OAAO,CACP,aAAcA,EAAE,OAAO,EACvB,WAAYA,EAAE,OAAO,EAAE,SAAS,CAClC,CAAC,CACH,CACF,EAEME,EAAWC,GAASL,EAAI,aAAc,CAAE,QAAS,EAAM,CAAC,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","maxAgeSeconds","staleWhileRevalidateSeconds","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\";\nimport { metrics } from \"../src/koa-middleware/metrics\";\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(\n metrics({\n isHealthy: () => true,\n isReady: () => true,\n }),\n);\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":";2QACA,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,YAAaE,EAAO,QAAQ,EACzD,WAAYA,EAAO,YAAc,KACjC,eAAgBA,EAAO,gBAAkB,KACzC,YAAaA,EAAO,aAAe,IACrC,CACF,CACF,CDXA,OAAS,mBAAAC,MAAuB,qBAKhC,eAAsBC,EAEpBC,EACA,CACE,QAAAC,EACA,QAAAC,EACA,QAAAC,EAAU,CAAC,CACb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IAAIC,GAEfP,EAAI,YACNM,EAAO,IAAIE,EAAOR,EAAI,UAAU,CAAC,EAGnCM,EAAO,IAAIG,GAAK,CAAC,EACjBH,EAAO,IAAII,EAAY,CAAC,EACxBJ,EAAO,IACLK,EAAQ,CACN,UAAW,IAAM,GACjB,QAAS,IAAM,EACjB,CAAC,CACH,EACAL,EAAO,IAAIM,EAAW,CAAC,EACvBN,EAAO,IAAIO,EAAUT,CAAQ,CAAC,EAE9BE,EAAO,IACLQ,GAAoB,CAClB,OAAQ,QACR,OAAQC,GAAgB,EACxB,cAAe,UAAa,CAC1B,aAAc,MAAMC,EAAmBC,GAAQb,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","maxAgeSeconds","staleWhileRevalidateSeconds","compose","env","parseEnv","z","frontendEnvSchema","database","postgres","server","Koa","sentry","cors","healthcheck","metrics","helloWorld","apiRoutes","createKoaMiddleware","createAppRouter","createQueryAdapter","drizzle"]}
|
@@ -1,3 +1,3 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import{b as
|
2
|
+
import{b as c,c as m}from"../chunk-NHP2EYE7.js";import"dotenv/config";import{z as a}from"zod";import{eq as L}from"drizzle-orm";import{createPublicClient as _,fallback as g,webSocket as h,http as E}from"viem";import{isDefined as A}from"@latticexyz/common/utils";import{combineLatest as R,filter as S,first as O}from"rxjs";import{drizzle as w}from"drizzle-orm/postgres-js";import k from"postgres";import{cleanDatabase as B,createStorageAdapter as K,shouldCleanDatabase as P}from"@latticexyz/store-sync/postgres";import{createStoreSync as N}from"@latticexyz/store-sync";var t=m(a.intersection(c,a.object({DATABASE_URL:a.string(),HEALTHCHECK_HOST:a.string().optional(),HEALTHCHECK_PORT:a.coerce.number().optional()}))),v=[t.RPC_WS_URL?h(t.RPC_WS_URL):void 0,t.RPC_HTTP_URL?E(t.RPC_HTTP_URL):void 0].filter(A),l=_({transport:g(v),pollingInterval:t.POLLING_INTERVAL}),d=await l.getChainId(),i=w(k(t.DATABASE_URL,{prepare:!1}));await P(i,d)&&(console.log("outdated database detected, clearing data to start fresh"),await B(i));var{storageAdapter:D,tables:p}=await K({database:i,publicClient:l}),n=t.START_BLOCK;async function f(){try{return(await i.select().from(p.configTable).where(L(p.configTable.chainId,d)).limit(1).execute().then(o=>o.find(()=>!0)))?.blockNumber}catch{}}var u=await f();u!=null&&(n=u+1n,console.log("resuming from block number",n));var{latestBlockNumber$:U,storedBlockLogs$:T}=await N({storageAdapter:D,publicClient:l,followBlockTag:t.FOLLOW_BLOCK_TAG,startBlock:n,maxBlockRange:t.MAX_BLOCK_RANGE,address:t.STORE_ADDRESS});T.subscribe();var s=!1;R([U,T]).pipe(S(([e,{blockNumber:o}])=>e===o),O()).subscribe(()=>{s=!0,console.log("all caught up")});if(t.HEALTHCHECK_HOST!=null||t.HEALTHCHECK_PORT!=null){let{default:e}=await import("koa"),{default:o}=await import("@koa/cors"),{healthcheck:H}=await import("../healthcheck-7XXWJH5U.js"),{metrics:b}=await import("../metrics-IL7G7G42.js"),{helloWorld:C}=await import("../helloWorld-BMBNVEA7.js"),r=new e;r.use(o()),r.use(H({isReady:()=>s})),r.use(b({isHealthy:()=>!0,isReady:()=>s,getLatestStoredBlockNumber:f,followBlockTag:t.FOLLOW_BLOCK_TAG})),r.use(C()),r.listen({host:t.HEALTHCHECK_HOST,port:t.HEALTHCHECK_PORT}),console.log(`postgres indexer healthcheck server listening on http://${t.HEALTHCHECK_HOST}:${t.HEALTHCHECK_PORT}`)}
|
3
3
|
//# sourceMappingURL=postgres-indexer.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../bin/postgres-indexer.ts"],"sourcesContent":["#!/usr/bin/env node\nimport \"dotenv/config\";\nimport { z } from \"zod\";\nimport { eq } from \"drizzle-orm\";\nimport { createPublicClient, fallback, webSocket, http, Transport } from \"viem\";\nimport { isDefined } from \"@latticexyz/common/utils\";\nimport { combineLatest, filter, first } from \"rxjs\";\nimport { drizzle } from \"drizzle-orm/postgres-js\";\nimport postgres from \"postgres\";\nimport { cleanDatabase, createStorageAdapter, shouldCleanDatabase } from \"@latticexyz/store-sync/postgres\";\nimport { createStoreSync } from \"@latticexyz/store-sync\";\nimport { indexerEnvSchema, parseEnv } from \"./parseEnv\";\n\nconst env = parseEnv(\n z.intersection(\n indexerEnvSchema,\n z.object({\n DATABASE_URL: z.string(),\n HEALTHCHECK_HOST: z.string().optional(),\n HEALTHCHECK_PORT: z.coerce.number().optional(),\n }),\n ),\n);\n\nconst transports: Transport[] = [\n // prefer WS when specified\n env.RPC_WS_URL ? webSocket(env.RPC_WS_URL) : undefined,\n // otherwise use or fallback to HTTP\n env.RPC_HTTP_URL ? http(env.RPC_HTTP_URL) : undefined,\n].filter(isDefined);\n\nconst publicClient = createPublicClient({\n transport: fallback(transports),\n pollingInterval: env.POLLING_INTERVAL,\n});\n\nconst chainId = await publicClient.getChainId();\nconst database = drizzle(postgres(env.DATABASE_URL, { prepare: false }));\n\nif (await shouldCleanDatabase(database, chainId)) {\n console.log(\"outdated database detected, clearing data to start fresh\");\n await cleanDatabase(database);\n}\n\nconst { storageAdapter, tables } = await createStorageAdapter({ database, publicClient });\n\nlet startBlock = env.START_BLOCK;\n\n//
|
1
|
+
{"version":3,"sources":["../../bin/postgres-indexer.ts"],"sourcesContent":["#!/usr/bin/env node\nimport \"dotenv/config\";\nimport { z } from \"zod\";\nimport { eq } from \"drizzle-orm\";\nimport { createPublicClient, fallback, webSocket, http, Transport } from \"viem\";\nimport { isDefined } from \"@latticexyz/common/utils\";\nimport { combineLatest, filter, first } from \"rxjs\";\nimport { drizzle } from \"drizzle-orm/postgres-js\";\nimport postgres from \"postgres\";\nimport { cleanDatabase, createStorageAdapter, shouldCleanDatabase } from \"@latticexyz/store-sync/postgres\";\nimport { createStoreSync } from \"@latticexyz/store-sync\";\nimport { indexerEnvSchema, parseEnv } from \"./parseEnv\";\n\nconst env = parseEnv(\n z.intersection(\n indexerEnvSchema,\n z.object({\n DATABASE_URL: z.string(),\n HEALTHCHECK_HOST: z.string().optional(),\n HEALTHCHECK_PORT: z.coerce.number().optional(),\n }),\n ),\n);\n\nconst transports: Transport[] = [\n // prefer WS when specified\n env.RPC_WS_URL ? webSocket(env.RPC_WS_URL) : undefined,\n // otherwise use or fallback to HTTP\n env.RPC_HTTP_URL ? http(env.RPC_HTTP_URL) : undefined,\n].filter(isDefined);\n\nconst publicClient = createPublicClient({\n transport: fallback(transports),\n pollingInterval: env.POLLING_INTERVAL,\n});\n\nconst chainId = await publicClient.getChainId();\nconst database = drizzle(postgres(env.DATABASE_URL, { prepare: false }));\n\nif (await shouldCleanDatabase(database, chainId)) {\n console.log(\"outdated database detected, clearing data to start fresh\");\n await cleanDatabase(database);\n}\n\nconst { storageAdapter, tables } = await createStorageAdapter({ database, publicClient });\n\nlet startBlock = env.START_BLOCK;\n\nasync function getLatestStoredBlockNumber(): Promise<bigint | undefined> {\n // Fetch latest block stored in DB. This will throw if the DB doesn't exist yet, so we wrap in a try/catch and ignore the error.\n // TODO: query if the DB exists instead of try/catch\n try {\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\n return chainState?.blockNumber;\n } catch (error) {\n // ignore errors for now\n }\n}\n\nconst latestStoredBlockNumber = await getLatestStoredBlockNumber();\nif (latestStoredBlockNumber != null) {\n startBlock = latestStoredBlockNumber + 1n;\n console.log(\"resuming from block number\", startBlock);\n}\n\nconst { latestBlockNumber$, storedBlockLogs$ } = await createStoreSync({\n storageAdapter,\n publicClient,\n followBlockTag: env.FOLLOW_BLOCK_TAG,\n startBlock,\n maxBlockRange: env.MAX_BLOCK_RANGE,\n address: env.STORE_ADDRESS,\n});\n\nstoredBlockLogs$.subscribe();\n\nlet isCaughtUp = false;\ncombineLatest([latestBlockNumber$, storedBlockLogs$])\n .pipe(\n filter(\n ([latestBlockNumber, { blockNumber: lastBlockNumberProcessed }]) =>\n latestBlockNumber === lastBlockNumberProcessed,\n ),\n first(),\n )\n .subscribe(() => {\n isCaughtUp = true;\n console.log(\"all caught up\");\n });\n\nif (env.HEALTHCHECK_HOST != null || env.HEALTHCHECK_PORT != null) {\n const { default: Koa } = await import(\"koa\");\n const { default: cors } = await import(\"@koa/cors\");\n const { healthcheck } = await import(\"../src/koa-middleware/healthcheck\");\n const { metrics } = await import(\"../src/koa-middleware/metrics\");\n const { helloWorld } = await import(\"../src/koa-middleware/helloWorld\");\n\n const server = new Koa();\n\n server.use(cors());\n server.use(\n healthcheck({\n isReady: () => isCaughtUp,\n }),\n );\n server.use(\n metrics({\n isHealthy: () => true,\n isReady: () => isCaughtUp,\n getLatestStoredBlockNumber,\n followBlockTag: env.FOLLOW_BLOCK_TAG,\n }),\n );\n server.use(helloWorld());\n\n server.listen({ host: env.HEALTHCHECK_HOST, port: env.HEALTHCHECK_PORT });\n console.log(\n `postgres indexer healthcheck server listening on http://${env.HEALTHCHECK_HOST}:${env.HEALTHCHECK_PORT}`,\n );\n}\n"],"mappings":";gDACA,MAAO,gBACP,OAAS,KAAAA,MAAS,MAClB,OAAS,MAAAC,MAAU,cACnB,OAAS,sBAAAC,EAAoB,YAAAC,EAAU,aAAAC,EAAW,QAAAC,MAAuB,OACzE,OAAS,aAAAC,MAAiB,2BAC1B,OAAS,iBAAAC,EAAe,UAAAC,EAAQ,SAAAC,MAAa,OAC7C,OAAS,WAAAC,MAAe,0BACxB,OAAOC,MAAc,WACrB,OAAS,iBAAAC,EAAe,wBAAAC,EAAsB,uBAAAC,MAA2B,kCACzE,OAAS,mBAAAC,MAAuB,yBAGhC,IAAMC,EAAMC,EACVC,EAAE,aACAC,EACAD,EAAE,OAAO,CACP,aAAcA,EAAE,OAAO,EACvB,iBAAkBA,EAAE,OAAO,EAAE,SAAS,EACtC,iBAAkBA,EAAE,OAAO,OAAO,EAAE,SAAS,CAC/C,CAAC,CACH,CACF,EAEME,EAA0B,CAE9BJ,EAAI,WAAaK,EAAUL,EAAI,UAAU,EAAI,OAE7CA,EAAI,aAAeM,EAAKN,EAAI,YAAY,EAAI,MAC9C,EAAE,OAAOO,CAAS,EAEZC,EAAeC,EAAmB,CACtC,UAAWC,EAASN,CAAU,EAC9B,gBAAiBJ,EAAI,gBACvB,CAAC,EAEKW,EAAU,MAAMH,EAAa,WAAW,EACxCI,EAAWC,EAAQC,EAASd,EAAI,aAAc,CAAE,QAAS,EAAM,CAAC,CAAC,EAEnE,MAAMe,EAAoBH,EAAUD,CAAO,IAC7C,QAAQ,IAAI,0DAA0D,EACtE,MAAMK,EAAcJ,CAAQ,GAG9B,GAAM,CAAE,eAAAK,EAAgB,OAAAC,CAAO,EAAI,MAAMC,EAAqB,CAAE,SAAAP,EAAU,aAAAJ,CAAa,CAAC,EAEpFY,E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,CAAC,CACH,EACAW,EAAO,IACLF,EAAQ,CACN,UAAW,IAAM,GACjB,QAAS,IAAMT,EACf,2BAAAP,EACA,eAAgBrB,EAAI,gBACtB,CAAC,CACH,EACAuC,EAAO,IAAID,EAAW,CAAC,EAEvBC,EAAO,OAAO,CAAE,KAAMvC,EAAI,iBAAkB,KAAMA,EAAI,gBAAiB,CAAC,EACxE,QAAQ,IACN,2DAA2DA,EAAI,oBAAoBA,EAAI,kBACzF","names":["z","eq","createPublicClient","fallback","webSocket","http","isDefined","combineLatest","filter","first","drizzle","postgres","cleanDatabase","createStorageAdapter","shouldCleanDatabase","createStoreSync","env","parseEnv","z","indexerEnvSchema","transports","webSocket","http","isDefined","publicClient","createPublicClient","fallback","chainId","database","drizzle","postgres","shouldCleanDatabase","cleanDatabase","storageAdapter","tables","createStorageAdapter","startBlock","getLatestStoredBlockNumber","eq","rows","latestStoredBlockNumber","latestBlockNumber$","storedBlockLogs$","createStoreSync","isCaughtUp","combineLatest","filter","latestBlockNumber","lastBlockNumberProcessed","first","Koa","cors","healthcheck","metrics","helloWorld","server"]}
|
@@ -1,3 +1,3 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import{a as
|
2
|
+
import{a as S,c as _}from"../chunk-ZS3IQEZ4.js";import{a as B}from"../chunk-VCBWGHIO.js";import{a as R,b as L,c as N}from"../chunk-NHP2EYE7.js";import{a as C}from"../chunk-KDDXIBYJ.js";import{a as E}from"../chunk-OUZYPRYF.js";import{a as I}from"../chunk-WOLC7XUT.js";import"dotenv/config";import X from"node:fs";import{z as p}from"zod";import{eq as Z}from"drizzle-orm";import{drizzle as ee}from"drizzle-orm/better-sqlite3";import te from"better-sqlite3";import{createPublicClient as re,fallback as oe,webSocket as ae,http as se}from"viem";import ne from"koa";import ie from"@koa/cors";import{createKoaMiddleware as le}from"trpc-koa-adapter";import{createAppRouter as ce}from"@latticexyz/store-sync/trpc-indexer";import{chainState as P,schemaVersion as W,syncToSqlite as me}from"@latticexyz/store-sync/sqlite";import{asc as F,eq as O}from"drizzle-orm";import{buildTable as H,chainState as w,getTables as K}from"@latticexyz/store-sync/sqlite";import{getAddress as A}from"viem";import{decodeDynamicField as j}from"@latticexyz/protocol-parser/internal";function u(r,{chainId:s,address:t,filters:n=[]}){let i=r.select().from(w).where(O(w.chainId,s)).limit(1).all().find(()=>!0),o=Array.from(new Set(n.map(a=>a.tableId))),y=K(r).filter(a=>t==null||A(t)===A(a.address)).filter(a=>!o.length||o.includes(a.tableId)).map(a=>{let h=H(a),k=r.select().from(h).where(O(h.__isDeleted,!1)).orderBy(F(h.__lastUpdatedBlockNumber)).all(),M=n.length?k.filter(f=>{let l=j("bytes32[]",f.__key);return n.some(d=>d.tableId===a.tableId&&(d.key0==null||d.key0===l[0])&&(d.key1==null||d.key1===l[1]))}):k;return{...a,records:M.map(f=>({key:Object.fromEntries(Object.entries(a.keySchema).map(([l])=>[l,f[l]])),value:Object.fromEntries(Object.entries(a.valueSchema).map(([l])=>[l,f[l]]))}))}});return{blockNumber:i?.lastUpdatedBlockNumber??null,tables:y}}import{tablesWithRecordsToLogs as V}from"@latticexyz/store-sync";async function D(r){return{async getLogs(t){let{blockNumber:n,tables:i}=u(r,t),o=V(i);return{blockNumber:n??0n,logs:o}},async findAll(t){return u(r,t)}}}import{isDefined as de}from"@latticexyz/common/utils";import{combineLatest as ue,filter as pe,first as fe}from"rxjs";import x from"@koa/router";import G from"koa-compose";import{input as J}from"@latticexyz/store-sync/indexer-client";import{storeTables as $,tablesWithRecordsToLogs as z}from"@latticexyz/store-sync";import{createBenchmark as Y}from"@latticexyz/common";function Q(r){let s=new x;return s.get("/api/logs",_(),async t=>{let n=Y("sqlite:logs"),i;try{i=J.parse(typeof t.query.input=="string"?JSON.parse(t.query.input):{})}catch(o){t.status=400,t.body=JSON.stringify(o),S(o);return}try{i.filters=i.filters.length>0?[...i.filters,{tableId:$.Tables.tableId}]:[],n("parse config");let{blockNumber:o,tables:T}=u(r,i);n("query tables with records");let y=z(T);n("convert records to logs"),t.body=JSON.stringify({blockNumber:o?.toString()??"-1",logs:y}),t.status=200}catch(o){t.status=500,t.body=JSON.stringify(o),S(o)}}),G([s.routes(),s.allowedMethods()])}var e=N(p.intersection(p.intersection(L,R),p.object({SQLITE_FILENAME:p.string().default("indexer.db"),SENTRY_DSN:p.string().optional()}))),be=[e.RPC_WS_URL?ae(e.RPC_WS_URL):void 0,e.RPC_HTTP_URL?se(e.RPC_HTTP_URL):void 0].filter(de),U=re({transport:oe(be),pollingInterval:e.POLLING_INTERVAL}),ye=await U.getChainId(),b=ee(new te(e.SQLITE_FILENAME)),v=e.START_BLOCK;async function q(){try{return b.select().from(P).where(Z(P.chainId,ye)).all()[0]}catch{}}async function he(){return(await q())?.lastUpdatedBlockNumber??void 0}var m=await q();m&&(m.schemaVersion!=W?(console.log("schema version changed from",m.schemaVersion,"to",W,"recreating database"),X.truncateSync(e.SQLITE_FILENAME)):m.lastUpdatedBlockNumber!=null&&(console.log("resuming from block number",m.lastUpdatedBlockNumber+1n),v=m.lastUpdatedBlockNumber+1n));var{latestBlockNumber$:Se,storedBlockLogs$:ge}=await me({database:b,publicClient:U,followBlockTag:e.FOLLOW_BLOCK_TAG,startBlock:v,maxBlockRange:e.MAX_BLOCK_RANGE,address:e.STORE_ADDRESS}),g=!1;ue([Se,ge]).pipe(pe(([r,{blockNumber:s}])=>r===s),fe()).subscribe(()=>{g=!0,console.log("all caught up")});var c=new ne;e.SENTRY_DSN&&c.use(B(e.SENTRY_DSN));c.use(ie());c.use(C({isReady:()=>g}));c.use(I({isHealthy:()=>!0,isReady:()=>g,getLatestStoredBlockNumber:he,followBlockTag:e.FOLLOW_BLOCK_TAG}));c.use(E());c.use(Q(b));c.use(le({prefix:"/trpc",router:ce(),createContext:async()=>({queryAdapter:await D(b)})}));c.listen({host:e.HOST,port:e.PORT});console.log(`sqlite indexer frontend listening on http://${e.HOST}:${e.PORT}`);
|
3
3
|
//# sourceMappingURL=sqlite-indexer.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../bin/sqlite-indexer.ts","../../src/sqlite/getTablesWithRecords.ts","../../src/sqlite/createQueryAdapter.ts","../../src/sqlite/apiRoutes.ts"],"sourcesContent":["#!/usr/bin/env node\nimport \"dotenv/config\";\nimport fs from \"node:fs\";\nimport { z } from \"zod\";\nimport { eq } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport Database from \"better-sqlite3\";\nimport { createPublicClient, fallback, webSocket, http, Transport } from \"viem\";\nimport Koa from \"koa\";\nimport cors from \"@koa/cors\";\nimport { createKoaMiddleware } from \"trpc-koa-adapter\";\nimport { createAppRouter } from \"@latticexyz/store-sync/trpc-indexer\";\nimport { chainState, schemaVersion, syncToSqlite } from \"@latticexyz/store-sync/sqlite\";\nimport { createQueryAdapter } from \"../src/sqlite/createQueryAdapter\";\nimport { isDefined } from \"@latticexyz/common/utils\";\nimport { combineLatest, filter, first } from \"rxjs\";\nimport { frontendEnvSchema, indexerEnvSchema, parseEnv } from \"./parseEnv\";\nimport { healthcheck } from \"../src/koa-middleware/healthcheck\";\nimport { helloWorld } from \"../src/koa-middleware/helloWorld\";\nimport { apiRoutes } from \"../src/sqlite/apiRoutes\";\nimport { sentry } from \"../src/koa-middleware/sentry\";\n\nconst env = parseEnv(\n z.intersection(\n z.intersection(indexerEnvSchema, frontendEnvSchema),\n z.object({\n SQLITE_FILENAME: z.string().default(\"indexer.db\"),\n SENTRY_DSN: z.string().optional(),\n }),\n ),\n);\n\nconst transports: Transport[] = [\n // prefer WS when specified\n env.RPC_WS_URL ? webSocket(env.RPC_WS_URL) : undefined,\n // otherwise use or fallback to HTTP\n env.RPC_HTTP_URL ? http(env.RPC_HTTP_URL) : undefined,\n].filter(isDefined);\n\nconst publicClient = createPublicClient({\n transport: fallback(transports),\n pollingInterval: env.POLLING_INTERVAL,\n});\n\nconst chainId = await publicClient.getChainId();\nconst database = drizzle(new Database(env.SQLITE_FILENAME));\n\nlet startBlock = env.START_BLOCK;\n\n// Resume from latest block stored in DB. This will throw if the DB doesn't exist yet, so we wrap in a try/catch and ignore the error.\ntry {\n const currentChainStates = database.select().from(chainState).where(eq(chainState.chainId, chainId)).all();\n // TODO: replace this type workaround with `noUncheckedIndexedAccess: true` when we can fix all the issues related (https://github.com/latticexyz/mud/issues/1212)\n const currentChainState: (typeof currentChainStates)[number] | undefined = currentChainStates[0];\n\n if (currentChainState != null) {\n if (currentChainState.schemaVersion != schemaVersion) {\n console.log(\n \"schema version changed from\",\n currentChainState.schemaVersion,\n \"to\",\n schemaVersion,\n \"recreating database\",\n );\n fs.truncateSync(env.SQLITE_FILENAME);\n } else if (currentChainState.lastUpdatedBlockNumber != null) {\n console.log(\"resuming from block number\", currentChainState.lastUpdatedBlockNumber + 1n);\n startBlock = currentChainState.lastUpdatedBlockNumber + 1n;\n }\n }\n} catch (error) {\n // ignore errors, this is optional\n}\n\nconst { latestBlockNumber$, storedBlockLogs$ } = await syncToSqlite({\n database,\n publicClient,\n followBlockTag: env.FOLLOW_BLOCK_TAG,\n startBlock,\n maxBlockRange: env.MAX_BLOCK_RANGE,\n address: env.STORE_ADDRESS,\n});\n\nlet isCaughtUp = false;\ncombineLatest([latestBlockNumber$, storedBlockLogs$])\n .pipe(\n filter(\n ([latestBlockNumber, { blockNumber: lastBlockNumberProcessed }]) =>\n latestBlockNumber === lastBlockNumberProcessed,\n ),\n first(),\n )\n .subscribe(() => {\n isCaughtUp = true;\n console.log(\"all caught up\");\n });\n\nconst server = new Koa();\n\nif (env.SENTRY_DSN) {\n server.use(sentry(env.SENTRY_DSN));\n}\n\nserver.use(cors());\nserver.use(\n healthcheck({\n isReady: () => isCaughtUp,\n }),\n);\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(database),\n }),\n }),\n);\n\nserver.listen({ host: env.HOST, port: env.PORT });\nconsole.log(`sqlite indexer frontend listening on http://${env.HOST}:${env.PORT}`);\n","import { asc, eq } from \"drizzle-orm\";\nimport { BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\nimport { buildTable, chainState, getTables } from \"@latticexyz/store-sync/sqlite\";\nimport { Hex, getAddress } from \"viem\";\nimport { decodeDynamicField } from \"@latticexyz/protocol-parser/internal\";\nimport { SyncFilter, TableWithRecords } from \"@latticexyz/store-sync\";\n\n// TODO: refactor sqlite and replace this with getLogs to match postgres (https://github.com/latticexyz/mud/issues/1970)\n\n/**\n * @deprecated\n * */\nexport function getTablesWithRecords(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n database: BaseSQLiteDatabase<\"sync\", any>,\n {\n chainId,\n address,\n filters = [],\n }: {\n readonly chainId: number;\n readonly address?: Hex;\n readonly filters?: readonly SyncFilter[];\n },\n): { blockNumber: bigint | null; tables: readonly TableWithRecords[] } {\n const metadata = database\n .select()\n .from(chainState)\n .where(eq(chainState.chainId, chainId))\n .limit(1)\n .all()\n .find(() => true);\n\n // If _any_ filter has a table ID, this will filter down all data to just those tables. Which mean we can't yet mix table filters with key-only filters.\n // TODO: improve this so we can express this in the query (need to be able to query data across tables more easily)\n const tableIds = Array.from(new Set(filters.map((filter) => filter.tableId)));\n const tables = getTables(database)\n .filter((table) => address == null || getAddress(address) === getAddress(table.address))\n .filter((table) => !tableIds.length || tableIds.includes(table.tableId));\n\n const tablesWithRecords = tables.map((table) => {\n const sqliteTable = buildTable(table);\n const records = database\n .select()\n .from(sqliteTable)\n .where(eq(sqliteTable.__isDeleted, false))\n .orderBy(\n asc(sqliteTable.__lastUpdatedBlockNumber),\n // TODO: add logIndex (https://github.com/latticexyz/mud/issues/1979)\n )\n .all();\n const filteredRecords = !filters.length\n ? records\n : records.filter((record) => {\n const keyTuple = decodeDynamicField(\"bytes32[]\", record.__key);\n return filters.some(\n (filter) =>\n filter.tableId === table.tableId &&\n (filter.key0 == null || filter.key0 === keyTuple[0]) &&\n (filter.key1 == null || filter.key1 === keyTuple[1]),\n );\n });\n return {\n ...table,\n records: filteredRecords.map((record) => ({\n key: Object.fromEntries(Object.entries(table.keySchema).map(([name]) => [name, record[name]])),\n value: Object.fromEntries(Object.entries(table.valueSchema).map(([name]) => [name, record[name]])),\n })),\n };\n });\n\n return {\n blockNumber: metadata?.lastUpdatedBlockNumber ?? null,\n tables: tablesWithRecords,\n };\n}\n","import { BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\nimport { QueryAdapter } from \"@latticexyz/store-sync/trpc-indexer\";\nimport { getTablesWithRecords } from \"./getTablesWithRecords\";\nimport { tablesWithRecordsToLogs } from \"@latticexyz/store-sync\";\n\n/**\n * Creates a storage adapter for the tRPC server/client to query data from SQLite.\n *\n * @param {BaseSQLiteDatabase<\"sync\", any>} database SQLite database object from Drizzle\n * @returns {Promise<QueryAdapter>} A set of methods used by tRPC endpoints.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function createQueryAdapter(database: BaseSQLiteDatabase<\"sync\", any>): Promise<QueryAdapter> {\n const adapter: QueryAdapter = {\n async getLogs(opts) {\n const { blockNumber, tables } = getTablesWithRecords(database, opts);\n const logs = tablesWithRecordsToLogs(tables);\n return { blockNumber: blockNumber ?? 0n, logs };\n },\n async findAll(opts) {\n return getTablesWithRecords(database, opts);\n },\n };\n return adapter;\n}\n","import { Middleware } from \"koa\";\nimport Router from \"@koa/router\";\nimport compose from \"koa-compose\";\nimport { input } from \"@latticexyz/store-sync/indexer-client\";\nimport { storeTables, tablesWithRecordsToLogs } from \"@latticexyz/store-sync\";\nimport { debug } from \"../debug\";\nimport { createBenchmark } from \"@latticexyz/common\";\nimport { compress } from \"../koa-middleware/compress\";\nimport { getTablesWithRecords } from \"./getTablesWithRecords\";\nimport { BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function apiRoutes(database: BaseSQLiteDatabase<\"sync\", any>): Middleware {\n const router = new Router();\n\n router.get(\"/api/logs\", compress(), async (ctx) => {\n const benchmark = createBenchmark(\"sqlite:logs\");\n\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 (error) {\n ctx.status = 400;\n ctx.body = JSON.stringify(error);\n debug(error);\n return;\n }\n\n try {\n options.filters = options.filters.length > 0 ? [...options.filters, { tableId: storeTables.Tables.tableId }] : [];\n benchmark(\"parse config\");\n const { blockNumber, tables } = getTablesWithRecords(database, options);\n benchmark(\"query tables with records\");\n const logs = tablesWithRecordsToLogs(tables);\n benchmark(\"convert records to logs\");\n\n ctx.body = JSON.stringify({ blockNumber: blockNumber?.toString() ?? \"-1\", logs });\n ctx.status = 200;\n } catch (error) {\n ctx.status = 500;\n ctx.body = JSON.stringify(error);\n debug(error);\n }\n });\n\n return compose([router.routes(), router.allowedMethods()]) as Middleware;\n}\n"],"mappings":";kOACA,MAAO,gBACP,OAAOA,MAAQ,UACf,OAAS,KAAAC,MAAS,MAClB,OAAS,MAAAC,MAAU,cACnB,OAAS,WAAAC,MAAe,6BACxB,OAAOC,MAAc,iBACrB,OAAS,sBAAAC,EAAoB,YAAAC,GAAU,aAAAC,GAAW,QAAAC,OAAuB,OACzE,OAAOC,OAAS,MAChB,OAAOC,OAAU,YACjB,OAAS,uBAAAC,OAA2B,mBACpC,OAAS,mBAAAC,OAAuB,sCAChC,OAAS,cAAAC,EAAY,iBAAAC,EAAe,gBAAAC,OAAoB,gCCZxD,OAAS,OAAAC,EAAK,MAAAC,MAAU,cAExB,OAAS,cAAAC,EAAY,cAAAC,EAAY,aAAAC,MAAiB,gCAClD,OAAc,cAAAC,MAAkB,OAChC,OAAS,sBAAAC,MAA0B,uCAQ5B,SAASC,EAEdC,EACA,CACE,QAAAC,EACA,QAAAC,EACA,QAAAC,EAAU,CAAC,CACb,EAKqE,CACrE,IAAMC,EAAWJ,EACd,OAAO,EACP,KAAKL,CA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CAEF,CAEA,GAAM,CAAE,mBAAAK,GAAoB,iBAAAC,EAAiB,EAAI,MAAMC,GAAa,CAClE,SAAAX,EACA,aAAAJ,EACA,eAAgBT,EAAI,iBACpB,WAAAgB,EACA,cAAehB,EAAI,gBACnB,QAASA,EAAI,aACf,CAAC,EAEGyB,EAAa,GACjBC,GAAc,CAACJ,GAAoBC,EAAgB,CAAC,EACjD,KACCI,GACE,CAAC,CAACC,EAAmB,CAAE,YAAaC,CAAyB,CAAC,IAC5DD,IAAsBC,CAC1B,EACAC,GAAM,CACR,EACC,UAAU,IAAM,CACfL,EAAa,GACb,QAAQ,IAAI,eAAe,CAC7B,CAAC,EAEH,IAAMM,EAAS,IAAIC,GAEfhC,EAAI,YACN+B,EAAO,IAAIE,EAAOjC,EAAI,UAAU,CAAC,EAGnC+B,EAAO,IAAIG,GAAK,CAAC,EACjBH,EAAO,IACLI,EAAY,CACV,QAAS,IAAMV,CACjB,CAAC,CACH,EACAM,EAAO,IAAIK,EAAW,CAAC,EACvBL,EAAO,IAAIM,EAAUxB,CAAQ,CAAC,EAE9BkB,EAAO,IACLO,GAAoB,CAClB,OAAQ,QACR,OAAQC,GAAgB,EACxB,cAAe,UAAa,CAC1B,aAAc,MAAMC,EAAmB3B,CAAQ,CACjD,EACF,CAAC,CACH,EAEAkB,EAAO,OAAO,CAAE,KAAM/B,EAAI,KAAM,KAAMA,EAAI,IAAK,CAAC,EAChD,QAAQ,IAAI,+CAA+CA,EAAI,QAAQA,EAAI,MAAM","names":["fs","z","eq","drizzle","Database","createPublicClient","fallback","webSocket","http","Koa","cors","createKoaMiddleware","createAppRouter","chainState","schemaVersion","syncToSqlite","asc","eq","buildTable","chainState","getTables","getAddress","decodeDynamicField","getTablesWithRecords","database","chainId","address","filters","metadata","tableIds","filter","tablesWithRecords","table","sqliteTable","records","filteredRecords","record","keyTuple","name","tablesWithRecordsToLogs","createQueryAdapter","database","opts","blockNumber","tables","getTablesWithRecords","logs","isDefined","combineLatest","filter","first","Router","compose","input","storeTables","tablesWithRecordsToLogs","createBenchmark","apiRoutes","database","router","Router","compress","ctx","benchmark","createBenchmark","options","input","error","debug","storeTables","blockNumber","tables","getTablesWithRecords","logs","tablesWithRecordsToLogs","compose","env","parseEnv","z","indexerEnvSchema","frontendEnvSchema","transports","webSocket","http","isDefined","publicClient","createPublicClient","fallback","chainId","database","drizzle","Database","startBlock","currentChainState","chainState","eq","schemaVersion","fs","latestBlockNumber$","storedBlockLogs$","syncToSqlite","isCaughtUp","combineLatest","filter","latestBlockNumber","lastBlockNumberProcessed","first","server","Koa","sentry","cors","healthcheck","helloWorld","apiRoutes","createKoaMiddleware","createAppRouter","createQueryAdapter"]}
|
1
|
+
{"version":3,"sources":["../../bin/sqlite-indexer.ts","../../src/sqlite/getTablesWithRecords.ts","../../src/sqlite/createQueryAdapter.ts","../../src/sqlite/apiRoutes.ts"],"sourcesContent":["#!/usr/bin/env node\nimport \"dotenv/config\";\nimport fs from \"node:fs\";\nimport { z } from \"zod\";\nimport { eq } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport Database from \"better-sqlite3\";\nimport { createPublicClient, fallback, webSocket, http, Transport } from \"viem\";\nimport Koa from \"koa\";\nimport cors from \"@koa/cors\";\nimport { createKoaMiddleware } from \"trpc-koa-adapter\";\nimport { createAppRouter } from \"@latticexyz/store-sync/trpc-indexer\";\nimport { chainState, schemaVersion, syncToSqlite } from \"@latticexyz/store-sync/sqlite\";\nimport { createQueryAdapter } from \"../src/sqlite/createQueryAdapter\";\nimport { isDefined } from \"@latticexyz/common/utils\";\nimport { combineLatest, filter, first } from \"rxjs\";\nimport { frontendEnvSchema, indexerEnvSchema, parseEnv } from \"./parseEnv\";\nimport { healthcheck } from \"../src/koa-middleware/healthcheck\";\nimport { helloWorld } from \"../src/koa-middleware/helloWorld\";\nimport { apiRoutes } from \"../src/sqlite/apiRoutes\";\nimport { sentry } from \"../src/koa-middleware/sentry\";\nimport { metrics } from \"../src/koa-middleware/metrics\";\n\nconst env = parseEnv(\n z.intersection(\n z.intersection(indexerEnvSchema, frontendEnvSchema),\n z.object({\n SQLITE_FILENAME: z.string().default(\"indexer.db\"),\n SENTRY_DSN: z.string().optional(),\n }),\n ),\n);\n\nconst transports: Transport[] = [\n // prefer WS when specified\n env.RPC_WS_URL ? webSocket(env.RPC_WS_URL) : undefined,\n // otherwise use or fallback to HTTP\n env.RPC_HTTP_URL ? http(env.RPC_HTTP_URL) : undefined,\n].filter(isDefined);\n\nconst publicClient = createPublicClient({\n transport: fallback(transports),\n pollingInterval: env.POLLING_INTERVAL,\n});\n\nconst chainId = await publicClient.getChainId();\nconst database = drizzle(new Database(env.SQLITE_FILENAME));\n\nlet startBlock = env.START_BLOCK;\n\nasync function getCurrentChainState(): Promise<\n | {\n schemaVersion: number;\n chainId: number;\n lastUpdatedBlockNumber: bigint | null;\n lastError: string | null;\n }\n | undefined\n> {\n // This will throw if the DB doesn't exist yet, so we wrap in a try/catch and ignore the error.\n try {\n const currentChainStates = database.select().from(chainState).where(eq(chainState.chainId, chainId)).all();\n // TODO: replace this type workaround with `noUncheckedIndexedAccess: true` when we can fix all the issues related (https://github.com/latticexyz/mud/issues/1212)\n const currentChainState: (typeof currentChainStates)[number] | undefined = currentChainStates[0];\n return currentChainState;\n } catch (error) {\n // ignore errors, this is optional\n }\n}\n\nasync function getLatestStoredBlockNumber(): Promise<bigint | undefined> {\n const currentChainState = await getCurrentChainState();\n return currentChainState?.lastUpdatedBlockNumber ?? undefined;\n}\n\nconst currentChainState = await getCurrentChainState();\nif (currentChainState) {\n // Reset the db if the version changed\n if (currentChainState.schemaVersion != schemaVersion) {\n console.log(\n \"schema version changed from\",\n currentChainState.schemaVersion,\n \"to\",\n schemaVersion,\n \"recreating database\",\n );\n fs.truncateSync(env.SQLITE_FILENAME);\n } else if (currentChainState.lastUpdatedBlockNumber != null) {\n // Resume from latest block stored in DB. This will throw if the DB doesn't exist yet, so we wrap in a try/catch and ignore the error.\n console.log(\"resuming from block number\", currentChainState.lastUpdatedBlockNumber + 1n);\n startBlock = currentChainState.lastUpdatedBlockNumber + 1n;\n }\n}\n\nconst { latestBlockNumber$, storedBlockLogs$ } = await syncToSqlite({\n database,\n publicClient,\n followBlockTag: env.FOLLOW_BLOCK_TAG,\n startBlock,\n maxBlockRange: env.MAX_BLOCK_RANGE,\n address: env.STORE_ADDRESS,\n});\n\nlet isCaughtUp = false;\ncombineLatest([latestBlockNumber$, storedBlockLogs$])\n .pipe(\n filter(\n ([latestBlockNumber, { blockNumber: lastBlockNumberProcessed }]) =>\n latestBlockNumber === lastBlockNumberProcessed,\n ),\n first(),\n )\n .subscribe(() => {\n isCaughtUp = true;\n console.log(\"all caught up\");\n });\n\nconst server = new Koa();\n\nif (env.SENTRY_DSN) {\n server.use(sentry(env.SENTRY_DSN));\n}\n\nserver.use(cors());\nserver.use(\n healthcheck({\n isReady: () => isCaughtUp,\n }),\n);\nserver.use(\n metrics({\n isHealthy: () => true,\n isReady: () => isCaughtUp,\n getLatestStoredBlockNumber,\n followBlockTag: env.FOLLOW_BLOCK_TAG,\n }),\n);\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(database),\n }),\n }),\n);\n\nserver.listen({ host: env.HOST, port: env.PORT });\nconsole.log(`sqlite indexer frontend listening on http://${env.HOST}:${env.PORT}`);\n","import { asc, eq } from \"drizzle-orm\";\nimport { BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\nimport { buildTable, chainState, getTables } from \"@latticexyz/store-sync/sqlite\";\nimport { Hex, getAddress } from \"viem\";\nimport { decodeDynamicField } from \"@latticexyz/protocol-parser/internal\";\nimport { SyncFilter, TableWithRecords } from \"@latticexyz/store-sync\";\n\n// TODO: refactor sqlite and replace this with getLogs to match postgres (https://github.com/latticexyz/mud/issues/1970)\n\n/**\n * @deprecated\n * */\nexport function getTablesWithRecords(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n database: BaseSQLiteDatabase<\"sync\", any>,\n {\n chainId,\n address,\n filters = [],\n }: {\n readonly chainId: number;\n readonly address?: Hex;\n readonly filters?: readonly SyncFilter[];\n },\n): { blockNumber: bigint | null; tables: readonly TableWithRecords[] } {\n const metadata = database\n .select()\n .from(chainState)\n .where(eq(chainState.chainId, chainId))\n .limit(1)\n .all()\n .find(() => true);\n\n // If _any_ filter has a table ID, this will filter down all data to just those tables. Which mean we can't yet mix table filters with key-only filters.\n // TODO: improve this so we can express this in the query (need to be able to query data across tables more easily)\n const tableIds = Array.from(new Set(filters.map((filter) => filter.tableId)));\n const tables = getTables(database)\n .filter((table) => address == null || getAddress(address) === getAddress(table.address))\n .filter((table) => !tableIds.length || tableIds.includes(table.tableId));\n\n const tablesWithRecords = tables.map((table) => {\n const sqliteTable = buildTable(table);\n const records = database\n .select()\n .from(sqliteTable)\n .where(eq(sqliteTable.__isDeleted, false))\n .orderBy(\n asc(sqliteTable.__lastUpdatedBlockNumber),\n // TODO: add logIndex (https://github.com/latticexyz/mud/issues/1979)\n )\n .all();\n const filteredRecords = !filters.length\n ? records\n : records.filter((record) => {\n const keyTuple = decodeDynamicField(\"bytes32[]\", record.__key);\n return filters.some(\n (filter) =>\n filter.tableId === table.tableId &&\n (filter.key0 == null || filter.key0 === keyTuple[0]) &&\n (filter.key1 == null || filter.key1 === keyTuple[1]),\n );\n });\n return {\n ...table,\n records: filteredRecords.map((record) => ({\n key: Object.fromEntries(Object.entries(table.keySchema).map(([name]) => [name, record[name]])),\n value: Object.fromEntries(Object.entries(table.valueSchema).map(([name]) => [name, record[name]])),\n })),\n };\n });\n\n return {\n blockNumber: metadata?.lastUpdatedBlockNumber ?? null,\n tables: tablesWithRecords,\n };\n}\n","import { BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\nimport { QueryAdapter } from \"@latticexyz/store-sync/trpc-indexer\";\nimport { getTablesWithRecords } from \"./getTablesWithRecords\";\nimport { tablesWithRecordsToLogs } from \"@latticexyz/store-sync\";\n\n/**\n * Creates a storage adapter for the tRPC server/client to query data from SQLite.\n *\n * @param {BaseSQLiteDatabase<\"sync\", any>} database SQLite database object from Drizzle\n * @returns {Promise<QueryAdapter>} A set of methods used by tRPC endpoints.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function createQueryAdapter(database: BaseSQLiteDatabase<\"sync\", any>): Promise<QueryAdapter> {\n const adapter: QueryAdapter = {\n async getLogs(opts) {\n const { blockNumber, tables } = getTablesWithRecords(database, opts);\n const logs = tablesWithRecordsToLogs(tables);\n return { blockNumber: blockNumber ?? 0n, logs };\n },\n async findAll(opts) {\n return getTablesWithRecords(database, opts);\n },\n };\n return adapter;\n}\n","import { Middleware } from \"koa\";\nimport Router from \"@koa/router\";\nimport compose from \"koa-compose\";\nimport { input } from \"@latticexyz/store-sync/indexer-client\";\nimport { storeTables, tablesWithRecordsToLogs } from \"@latticexyz/store-sync\";\nimport { debug } from \"../debug\";\nimport { createBenchmark } from \"@latticexyz/common\";\nimport { compress } from \"../koa-middleware/compress\";\nimport { getTablesWithRecords } from \"./getTablesWithRecords\";\nimport { BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function apiRoutes(database: BaseSQLiteDatabase<\"sync\", any>): Middleware {\n const router = new Router();\n\n router.get(\"/api/logs\", compress(), async (ctx) => {\n const benchmark = createBenchmark(\"sqlite:logs\");\n\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 (error) {\n ctx.status = 400;\n ctx.body = JSON.stringify(error);\n debug(error);\n return;\n }\n\n try {\n options.filters = options.filters.length > 0 ? [...options.filters, { tableId: storeTables.Tables.tableId }] : [];\n benchmark(\"parse config\");\n const { blockNumber, tables } = getTablesWithRecords(database, options);\n benchmark(\"query tables with records\");\n const logs = tablesWithRecordsToLogs(tables);\n benchmark(\"convert records to logs\");\n\n ctx.body = JSON.stringify({ blockNumber: blockNumber?.toString() ?? \"-1\", logs });\n ctx.status = 200;\n } catch (error) {\n ctx.status = 500;\n ctx.body = JSON.stringify(error);\n debug(error);\n }\n });\n\n return compose([router.routes(), router.allowedMethods()]) as Middleware;\n}\n"],"mappings":";2QACA,MAAO,gBACP,OAAOA,MAAQ,UACf,OAAS,KAAAC,MAAS,MAClB,OAAS,MAAAC,MAAU,cACnB,OAAS,WAAAC,OAAe,6BACxB,OAAOC,OAAc,iBACrB,OAAS,sBAAAC,GAAoB,YAAAC,GAAU,aAAAC,GAAW,QAAAC,OAAuB,OACzE,OAAOC,OAAS,MAChB,OAAOC,OAAU,YACjB,OAAS,uBAAAC,OAA2B,mBACpC,OAAS,mBAAAC,OAAuB,sCAChC,OAAS,cAAAC,EAAY,iBAAAC,EAAe,gBAAAC,OAAoB,gCCZxD,OAAS,OAAAC,EAAK,MAAAC,MAAU,cAExB,OAAS,cAAAC,EAAY,cAAAC,EAAY,aAAAC,MAAiB,gCAClD,OAAc,cAAAC,MAAkB,OAChC,OAAS,sBAAAC,MAA0B,uCAQ5B,SAASC,EAEdC,EACA,CACE,QAAAC,EACA,QAAAC,EACA,QAAAC,EAAU,CAAC,CACb,EAKqE,CACrE,IAAMC,EAAWJ,EACd,OAAO,EACP,KAAKL,CAAU,EACf,MAAMF,EAAGE,EAAW,QAASM,CAAO,CAAC,EACrC,MAAM,CAAC,EACP,IAAI,EACJ,KAAK,IAAM,EAAI,EAIZI,EAAW,MAAM,KAAK,IAAI,IAAIF,EAAQ,IAAKG,GAAWA,EAAO,OAAO,CAAC,CAAC,EAKtEC,EAJSX,EAAUI,CAAQ,EAC9B,OAAQQ,GAAUN,GAAW,MAAQL,EAAWK,CAAO,IAAML,EAAWW,EAAM,OAAO,CAAC,EACtF,OAAQA,GAAU,CAACH,EAAS,QAAUA,EAAS,SAASG,EAAM,OAAO,CAAC,EAExC,IAA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,CAAC,CAACC,EAAmB,CAAE,YAAaC,CAAyB,CAAC,IAC5DD,IAAsBC,CAC1B,EACAC,GAAM,CACR,EACC,UAAU,IAAM,CACfL,EAAa,GACb,QAAQ,IAAI,eAAe,CAC7B,CAAC,EAEH,IAAMM,EAAS,IAAIC,GAEflC,EAAI,YACNiC,EAAO,IAAIE,EAAOnC,EAAI,UAAU,CAAC,EAGnCiC,EAAO,IAAIG,GAAK,CAAC,EACjBH,EAAO,IACLI,EAAY,CACV,QAAS,IAAMV,CACjB,CAAC,CACH,EACAM,EAAO,IACLK,EAAQ,CACN,UAAW,IAAM,GACjB,QAAS,IAAMX,EACf,2BAAAP,GACA,eAAgBpB,EAAI,gBACtB,CAAC,CACH,EACAiC,EAAO,IAAIM,EAAW,CAAC,EACvBN,EAAO,IAAIO,EAAU3B,CAAQ,CAAC,EAE9BoB,EAAO,IACLQ,GAAoB,CAClB,OAAQ,QACR,OAAQC,GAAgB,EACxB,cAAe,UAAa,CAC1B,aAAc,MAAMC,EAAmB9B,CAAQ,CACjD,EACF,CAAC,CACH,EAEAoB,EAAO,OAAO,CAAE,KAAMjC,EAAI,KAAM,KAAMA,EAAI,IAAK,CAAC,EAChD,QAAQ,IAAI,+CAA+CA,EAAI,QAAQA,EAAI,MAAM","names":["fs","z","eq","drizzle","Database","createPublicClient","fallback","webSocket","http","Koa","cors","createKoaMiddleware","createAppRouter","chainState","schemaVersion","syncToSqlite","asc","eq","buildTable","chainState","getTables","getAddress","decodeDynamicField","getTablesWithRecords","database","chainId","address","filters","metadata","tableIds","filter","tablesWithRecords","table","sqliteTable","records","filteredRecords","record","keyTuple","name","tablesWithRecordsToLogs","createQueryAdapter","database","opts","blockNumber","tables","getTablesWithRecords","logs","isDefined","combineLatest","filter","first","Router","compose","input","storeTables","tablesWithRecordsToLogs","createBenchmark","apiRoutes","database","router","Router","compress","ctx","benchmark","createBenchmark","options","input","error","debug","storeTables","blockNumber","tables","getTablesWithRecords","logs","tablesWithRecordsToLogs","compose","env","parseEnv","z","indexerEnvSchema","frontendEnvSchema","transports","webSocket","http","isDefined","publicClient","createPublicClient","fallback","chainId","database","drizzle","Database","startBlock","getCurrentChainState","chainState","eq","getLatestStoredBlockNumber","currentChainState","schemaVersion","fs","latestBlockNumber$","storedBlockLogs$","syncToSqlite","isCaughtUp","combineLatest","filter","latestBlockNumber","lastBlockNumberProcessed","first","server","Koa","sentry","cors","healthcheck","metrics","helloWorld","apiRoutes","createKoaMiddleware","createAppRouter","createQueryAdapter"]}
|
@@ -0,0 +1,2 @@
|
|
1
|
+
import e from"prom-client";function u({isHealthy:a,isReady:i,getLatestStoredBlockNumber:s,followBlockTag:l}={}){if(e.collectDefaultMetrics(),a!=null&&new e.Gauge({name:"health_status",help:"Health status (0 = unhealthy, 1 = healthy)",collect(){this.set(Number(a()))}}),i!=null&&new e.Gauge({name:"readiness_status",help:"Readiness status (whether the service is ready to receive requests, 0 = not ready, 1 = ready)",collect(){this.set(Number(i()))}}),s!=null&&new e.Gauge({name:"latest_stored_block_number",help:"Latest block number stored in the database",async collect(){this.set(Number(await s()))}}),l!=null){let o=new e.Gauge({name:"follow_block_tag",help:"Block tag the indexer is following (0 = finalized, 1 = safe, 2 = latest)"}),t={finalized:0,safe:1,latest:2};o.set(t[l])}return async function(t,n){if(t.path==="/metrics"){t.status=200,t.body=await e.register.metrics();return}await n()}}export{u as a};
|
2
|
+
//# sourceMappingURL=chunk-WOLC7XUT.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/koa-middleware/metrics.ts"],"sourcesContent":["import { Middleware } from \"koa\";\nimport promClient from \"prom-client\";\n\ntype MetricsOptions = {\n isHealthy?: () => boolean;\n isReady?: () => boolean;\n getLatestStoredBlockNumber?: () => Promise<bigint | undefined>;\n followBlockTag?: \"latest\" | \"safe\" | \"finalized\";\n};\n\n/**\n * Middleware to add Prometheus metrics endpoints\n */\nexport function metrics({\n isHealthy,\n isReady,\n getLatestStoredBlockNumber,\n followBlockTag,\n}: MetricsOptions = {}): Middleware {\n promClient.collectDefaultMetrics();\n if (isHealthy != null) {\n new promClient.Gauge({\n name: \"health_status\",\n help: \"Health status (0 = unhealthy, 1 = healthy)\",\n collect(): void {\n this.set(Number(isHealthy()));\n },\n });\n }\n\n if (isReady != null) {\n new promClient.Gauge({\n name: \"readiness_status\",\n help: \"Readiness status (whether the service is ready to receive requests, 0 = not ready, 1 = ready)\",\n collect(): void {\n this.set(Number(isReady()));\n },\n });\n }\n\n if (getLatestStoredBlockNumber != null) {\n new promClient.Gauge({\n name: \"latest_stored_block_number\",\n help: \"Latest block number stored in the database\",\n async collect(): Promise<void> {\n this.set(Number(await getLatestStoredBlockNumber()));\n },\n });\n }\n\n if (followBlockTag != null) {\n const blockTagGauge = new promClient.Gauge({\n name: \"follow_block_tag\",\n help: \"Block tag the indexer is following (0 = finalized, 1 = safe, 2 = latest)\",\n });\n const blockTagToValue = {\n finalized: 0,\n safe: 1,\n latest: 2,\n };\n blockTagGauge.set(blockTagToValue[followBlockTag]);\n }\n\n return async function metricsMiddleware(ctx, next): Promise<void> {\n if (ctx.path === \"/metrics\") {\n ctx.status = 200;\n ctx.body = await promClient.register.metrics();\n return;\n }\n\n await next();\n };\n}\n"],"mappings":"AACA,OAAOA,MAAgB,cAYhB,SAASC,EAAQ,CACtB,UAAAC,EACA,QAAAC,EACA,2BAAAC,EACA,eAAAC,CACF,EAAoB,CAAC,EAAe,CAgClC,GA/BAL,EAAW,sBAAsB,EAC7BE,GAAa,MACf,IAAIF,EAAW,MAAM,CACnB,KAAM,gBACN,KAAM,6CACN,SAAgB,CACd,KAAK,IAAI,OAAOE,EAAU,CAAC,CAAC,CAC9B,CACF,CAAC,EAGCC,GAAW,MACb,IAAIH,EAAW,MAAM,CACnB,KAAM,mBACN,KAAM,gGACN,SAAgB,CACd,KAAK,IAAI,OAAOG,EAAQ,CAAC,CAAC,CAC5B,CACF,CAAC,EAGCC,GAA8B,MAChC,IAAIJ,EAAW,MAAM,CACnB,KAAM,6BACN,KAAM,6CACN,MAAM,SAAyB,CAC7B,KAAK,IAAI,OAAO,MAAMI,EAA2B,CAAC,CAAC,CACrD,CACF,CAAC,EAGCC,GAAkB,KAAM,CAC1B,IAAMC,EAAgB,IAAIN,EAAW,MAAM,CACzC,KAAM,mBACN,KAAM,0EACR,CAAC,EACKO,EAAkB,CACtB,UAAW,EACX,KAAM,EACN,OAAQ,CACV,EACAD,EAAc,IAAIC,EAAgBF,CAAc,CAAC,EAGnD,OAAO,eAAiCG,EAAKC,EAAqB,CAChE,GAAID,EAAI,OAAS,WAAY,CAC3BA,EAAI,OAAS,IACbA,EAAI,KAAO,MAAMR,EAAW,SAAS,QAAQ,EAC7C,OAGF,MAAMS,EAAK,CACb,CACF","names":["promClient","metrics","isHealthy","isReady","getLatestStoredBlockNumber","followBlockTag","blockTagGauge","blockTagToValue","ctx","next"]}
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@latticexyz/store-indexer",
|
3
|
-
"version": "2.0.7-main-
|
3
|
+
"version": "2.0.7-main-7dfb82f7",
|
4
4
|
"description": "Minimal Typescript indexer for Store",
|
5
5
|
"repository": {
|
6
6
|
"type": "git",
|
@@ -35,16 +35,17 @@
|
|
35
35
|
"koa": "^2.14.2",
|
36
36
|
"koa-compose": "^4.1.0",
|
37
37
|
"postgres": "3.3.5",
|
38
|
+
"prom-client": "^15.1.2",
|
38
39
|
"rxjs": "7.5.5",
|
39
40
|
"superjson": "^1.12.4",
|
40
41
|
"trpc-koa-adapter": "^1.1.3",
|
41
42
|
"viem": "2.9.20",
|
42
43
|
"zod": "^3.21.4",
|
43
|
-
"@latticexyz/block-logs-stream": "2.0.7-main-
|
44
|
-
"@latticexyz/common": "2.0.7-main-
|
45
|
-
"@latticexyz/protocol-parser": "2.0.7-main-
|
46
|
-
"@latticexyz/store": "2.0.7-main-
|
47
|
-
"@latticexyz/store-sync": "2.0.7-main-
|
44
|
+
"@latticexyz/block-logs-stream": "2.0.7-main-7dfb82f7",
|
45
|
+
"@latticexyz/common": "2.0.7-main-7dfb82f7",
|
46
|
+
"@latticexyz/protocol-parser": "2.0.7-main-7dfb82f7",
|
47
|
+
"@latticexyz/store": "2.0.7-main-7dfb82f7",
|
48
|
+
"@latticexyz/store-sync": "2.0.7-main-7dfb82f7"
|
48
49
|
},
|
49
50
|
"devDependencies": {
|
50
51
|
"@types/accepts": "^1.3.7",
|
@@ -0,0 +1,73 @@
|
|
1
|
+
import { Middleware } from "koa";
|
2
|
+
import promClient from "prom-client";
|
3
|
+
|
4
|
+
type MetricsOptions = {
|
5
|
+
isHealthy?: () => boolean;
|
6
|
+
isReady?: () => boolean;
|
7
|
+
getLatestStoredBlockNumber?: () => Promise<bigint | undefined>;
|
8
|
+
followBlockTag?: "latest" | "safe" | "finalized";
|
9
|
+
};
|
10
|
+
|
11
|
+
/**
|
12
|
+
* Middleware to add Prometheus metrics endpoints
|
13
|
+
*/
|
14
|
+
export function metrics({
|
15
|
+
isHealthy,
|
16
|
+
isReady,
|
17
|
+
getLatestStoredBlockNumber,
|
18
|
+
followBlockTag,
|
19
|
+
}: MetricsOptions = {}): Middleware {
|
20
|
+
promClient.collectDefaultMetrics();
|
21
|
+
if (isHealthy != null) {
|
22
|
+
new promClient.Gauge({
|
23
|
+
name: "health_status",
|
24
|
+
help: "Health status (0 = unhealthy, 1 = healthy)",
|
25
|
+
collect(): void {
|
26
|
+
this.set(Number(isHealthy()));
|
27
|
+
},
|
28
|
+
});
|
29
|
+
}
|
30
|
+
|
31
|
+
if (isReady != null) {
|
32
|
+
new promClient.Gauge({
|
33
|
+
name: "readiness_status",
|
34
|
+
help: "Readiness status (whether the service is ready to receive requests, 0 = not ready, 1 = ready)",
|
35
|
+
collect(): void {
|
36
|
+
this.set(Number(isReady()));
|
37
|
+
},
|
38
|
+
});
|
39
|
+
}
|
40
|
+
|
41
|
+
if (getLatestStoredBlockNumber != null) {
|
42
|
+
new promClient.Gauge({
|
43
|
+
name: "latest_stored_block_number",
|
44
|
+
help: "Latest block number stored in the database",
|
45
|
+
async collect(): Promise<void> {
|
46
|
+
this.set(Number(await getLatestStoredBlockNumber()));
|
47
|
+
},
|
48
|
+
});
|
49
|
+
}
|
50
|
+
|
51
|
+
if (followBlockTag != null) {
|
52
|
+
const blockTagGauge = new promClient.Gauge({
|
53
|
+
name: "follow_block_tag",
|
54
|
+
help: "Block tag the indexer is following (0 = finalized, 1 = safe, 2 = latest)",
|
55
|
+
});
|
56
|
+
const blockTagToValue = {
|
57
|
+
finalized: 0,
|
58
|
+
safe: 1,
|
59
|
+
latest: 2,
|
60
|
+
};
|
61
|
+
blockTagGauge.set(blockTagToValue[followBlockTag]);
|
62
|
+
}
|
63
|
+
|
64
|
+
return async function metricsMiddleware(ctx, next): Promise<void> {
|
65
|
+
if (ctx.path === "/metrics") {
|
66
|
+
ctx.status = 200;
|
67
|
+
ctx.body = await promClient.register.metrics();
|
68
|
+
return;
|
69
|
+
}
|
70
|
+
|
71
|
+
await next();
|
72
|
+
};
|
73
|
+
}
|