@secondlayer/subgraphs 0.5.0
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/src/index.d.ts +219 -0
- package/dist/src/index.js +956 -0
- package/dist/src/index.js.map +22 -0
- package/dist/src/runtime/block-processor.d.ts +100 -0
- package/dist/src/runtime/block-processor.js +501 -0
- package/dist/src/runtime/block-processor.js.map +16 -0
- package/dist/src/runtime/catchup.d.ts +78 -0
- package/dist/src/runtime/catchup.js +630 -0
- package/dist/src/runtime/catchup.js.map +18 -0
- package/dist/src/runtime/clarity.d.ts +15 -0
- package/dist/src/runtime/clarity.js +41 -0
- package/dist/src/runtime/clarity.js.map +10 -0
- package/dist/src/runtime/context.d.ts +69 -0
- package/dist/src/runtime/context.js +177 -0
- package/dist/src/runtime/context.js.map +10 -0
- package/dist/src/runtime/processor.d.ts +8 -0
- package/dist/src/runtime/processor.js +770 -0
- package/dist/src/runtime/processor.js.map +20 -0
- package/dist/src/runtime/reindex.d.ts +84 -0
- package/dist/src/runtime/reindex.js +738 -0
- package/dist/src/runtime/reindex.js.map +19 -0
- package/dist/src/runtime/reorg.d.ts +78 -0
- package/dist/src/runtime/reorg.js +536 -0
- package/dist/src/runtime/reorg.js.map +17 -0
- package/dist/src/runtime/runner.d.ts +147 -0
- package/dist/src/runtime/runner.js +130 -0
- package/dist/src/runtime/runner.js.map +11 -0
- package/dist/src/runtime/source-matcher.d.ts +53 -0
- package/dist/src/runtime/source-matcher.js +111 -0
- package/dist/src/runtime/source-matcher.js.map +11 -0
- package/dist/src/runtime/stats.d.ts +24 -0
- package/dist/src/runtime/stats.js +75 -0
- package/dist/src/runtime/stats.js.map +10 -0
- package/dist/src/schema/index.d.ts +117 -0
- package/dist/src/schema/index.js +305 -0
- package/dist/src/schema/index.js.map +13 -0
- package/dist/src/service.d.ts +0 -0
- package/dist/src/service.js +780 -0
- package/dist/src/service.js.map +21 -0
- package/dist/src/types.d.ts +80 -0
- package/dist/src/types.js +22 -0
- package/dist/src/types.js.map +10 -0
- package/dist/src/validate.d.ts +84 -0
- package/dist/src/validate.js +59 -0
- package/dist/src/validate.js.map +10 -0
- package/package.json +49 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/types.ts", "../src/runtime/context.ts", "../src/runtime/source-matcher.ts", "../src/runtime/clarity.ts", "../src/runtime/runner.ts", "../src/runtime/block-processor.ts", "../src/schema/utils.ts", "../src/runtime/stats.ts", "../src/runtime/catchup.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/** Supported column types for subgraph schemas */\nexport type ColumnType =\n | \"text\"\n | \"uint\"\n | \"int\"\n | \"principal\"\n | \"boolean\"\n | \"timestamp\"\n | \"jsonb\";\n\n/** Column definition in a subgraph table */\nexport interface SubgraphColumn {\n type: ColumnType;\n nullable?: boolean;\n indexed?: boolean;\n search?: boolean;\n default?: string | number | boolean;\n}\n\n/** Table definition within a subgraph schema */\nexport interface SubgraphTable {\n columns: Record<string, SubgraphColumn>;\n /** Composite indexes (each entry is an array of column names) */\n indexes?: string[][];\n /** Unique key constraints (each entry is an array of column names). Required for upsert. */\n uniqueKeys?: string[][];\n}\n\n/** Subgraph schema — maps table names to table definitions */\nexport type SubgraphSchema = Record<string, SubgraphTable>;\n\n/** Source filter for what blockchain data this subgraph processes */\nexport interface SubgraphSource {\n /** Contract principal (e.g., SP000...::contract-name). Supports * wildcards. */\n contract?: string;\n /** Event name/topic to filter on */\n event?: string;\n /** Function name to filter on */\n function?: string;\n /** Transaction type filter (e.g., \"stx_transfer\", \"contract_call\") */\n type?: string;\n /** Minimum amount filter (for stx_transfer sources) */\n minAmount?: bigint;\n}\n\n/** Context passed to subgraph handlers during event processing */\nexport interface SubgraphContext {\n block: { height: number; hash: string; timestamp: number; burnBlockHeight: number };\n tx: { txId: string; sender: string; type: string; status: string };\n insert(table: string, row: Record<string, unknown>): void;\n update(table: string, where: Record<string, unknown>, set: Record<string, unknown>): void;\n upsert(table: string, key: Record<string, unknown>, row: Record<string, unknown>): void;\n delete(table: string, where: Record<string, unknown>): void;\n findOne(table: string, where: Record<string, unknown>): Promise<Record<string, unknown> | null>;\n findMany(table: string, where: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n}\n\n/** Handler function that processes events and writes to the subgraph */\nexport type SubgraphHandler = (\n event: Record<string, unknown>,\n ctx: SubgraphContext,\n) => Promise<void> | void;\n\n/**\n * Derive the source key used to look up handlers.\n * - { contract: \"SP123.market\", function: \"list\" } → \"SP123.market::list\"\n * - { contract: \"SP123.market\", event: \"sale\" } → \"SP123.market::sale\"\n * - { contract: \"SP123.market\" } → \"SP123.market\"\n * - { type: \"stx_transfer\" } → \"stx_transfer\"\n */\nexport function sourceKey(source: SubgraphSource): string {\n if (source.contract) {\n if (source.function) return `${source.contract}::${source.function}`;\n if (source.event) return `${source.contract}::${source.event}`;\n return source.contract;\n }\n if (source.type) return source.type;\n return \"*\";\n}\n\n/** Complete subgraph definition */\nexport interface SubgraphDefinition {\n /** Unique subgraph name (lowercase, alphanumeric + hyphens) */\n name: string;\n /** Semantic version */\n version?: string;\n /** Human description */\n description?: string;\n /** What blockchain data to process — one or more source filters */\n sources: SubgraphSource[];\n /** Tables in this subgraph */\n schema: SubgraphSchema;\n /** Keyed handler functions — keys match sourceKey() output, \"*\" is catch-all */\n handlers: Record<string, SubgraphHandler>;\n}\n",
|
|
6
|
+
"import { sql, type Kysely, type Transaction } from \"kysely\";\nimport type { Database } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { SubgraphSchema } from \"../types.ts\";\n\ntype AnyDb = Kysely<Database> | Transaction<Database>;\n\ninterface WriteOp {\n kind: \"insert\" | \"update\" | \"delete\";\n table: string;\n data: Record<string, unknown>;\n /** For update: SET clause */\n set?: Record<string, unknown>;\n}\n\nexport interface BlockMeta {\n height: number;\n hash: string;\n timestamp: number;\n burnBlockHeight: number;\n}\n\nexport interface TxMeta {\n txId: string;\n sender: string;\n type: string;\n status: string;\n}\n\n/** Validate that a column name is safe for SQL identifiers */\nfunction validateColumnName(name: string): void {\n if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {\n throw new Error(`Invalid column name: ${name}`);\n }\n}\n\n/**\n * Runtime context passed to subgraph handlers.\n * Batches writes and flushes them atomically at the end of a block.\n * Reads execute immediately against the DB (pre-flush state).\n */\nexport class SubgraphContext {\n readonly block: BlockMeta;\n private _tx: TxMeta;\n private readonly db: AnyDb;\n private readonly pgSchemaName: string;\n private readonly subgraphSchema: SubgraphSchema;\n private readonly ops: WriteOp[] = [];\n\n constructor(\n db: AnyDb,\n pgSchemaName: string,\n subgraphSchema: SubgraphSchema,\n block: BlockMeta,\n tx: TxMeta,\n ) {\n this.db = db;\n this.pgSchemaName = pgSchemaName;\n this.subgraphSchema = subgraphSchema;\n this.block = block;\n this._tx = tx;\n }\n\n get tx(): TxMeta {\n return this._tx;\n }\n\n /** Update the current transaction context (used by runner between events) */\n setTx(tx: TxMeta): void {\n this._tx = tx;\n }\n\n // --- Write operations (batched) ---\n\n insert(table: string, row: Record<string, unknown>): void {\n this.validateTable(table);\n this.ops.push({ kind: \"insert\", table, data: row });\n }\n\n update(\n table: string,\n where: Record<string, unknown>,\n set: Record<string, unknown>,\n ): void {\n this.validateTable(table);\n this.ops.push({ kind: \"update\", table, data: where, set });\n }\n\n upsert(\n table: string,\n key: Record<string, unknown>,\n row: Record<string, unknown>,\n ): void {\n this.validateTable(table);\n const tableDef = this.subgraphSchema[table]!;\n const keyColumns = Object.keys(key);\n\n // Check if there's a matching uniqueKeys constraint\n const hasUniqueConstraint = tableDef.uniqueKeys?.some(\n (uk) => uk.length === keyColumns.length && uk.every((c) => keyColumns.includes(c)),\n );\n\n if (hasUniqueConstraint) {\n // Use ON CONFLICT for proper upsert\n this.ops.push({ kind: \"insert\", table, data: { ...key, ...row, _upsert_keys: keyColumns } });\n } else {\n // Fallback: log warning, use findOne + conditional insert/update\n logger.warn(\"upsert called without matching uniqueKeys constraint, using fallback\", {\n table,\n keys: keyColumns,\n });\n this.ops.push({ kind: \"insert\", table, data: { ...key, ...row, _upsert_fallback_keys: keyColumns, _upsert_fallback_set: row } });\n }\n }\n\n delete(table: string, where: Record<string, unknown>): void {\n this.validateTable(table);\n this.ops.push({ kind: \"delete\", table, data: where });\n }\n\n // --- Read operations (immediate) ---\n\n async findOne(\n table: string,\n where: Record<string, unknown>,\n ): Promise<Record<string, unknown> | null> {\n this.validateTable(table);\n const qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n const { clause } = buildWhereClause(where);\n const query = `SELECT * FROM ${qualifiedTable} WHERE ${clause} LIMIT 1`;\n const { rows } = await sql.raw(query).execute(this.db);\n return (rows as Record<string, unknown>[])[0] ?? null;\n }\n\n async findMany(\n table: string,\n where: Record<string, unknown>,\n ): Promise<Record<string, unknown>[]> {\n this.validateTable(table);\n const qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n const { clause } = buildWhereClause(where);\n const query = `SELECT * FROM ${qualifiedTable} WHERE ${clause}`;\n const { rows } = await sql.raw(query).execute(this.db);\n return rows as Record<string, unknown>[];\n }\n\n // --- Flush ---\n\n /** Number of pending write operations */\n get pendingOps(): number {\n return this.ops.length;\n }\n\n /**\n * Execute all batched writes in a single transaction.\n * Auto-populates _block_height, _tx_id, _created_at on inserts.\n */\n async flush(): Promise<number> {\n if (this.ops.length === 0) return 0;\n\n const opsToFlush = [...this.ops];\n this.ops.length = 0;\n\n const statements = this.buildStatements(opsToFlush);\n\n // If db is already a transaction, execute directly\n if (\"isTransaction\" in this.db) {\n for (const stmt of statements) {\n await sql.raw(stmt).execute(this.db);\n }\n } else {\n await (this.db as Kysely<Database>).transaction().execute(async (tx) => {\n for (const stmt of statements) {\n await sql.raw(stmt).execute(tx);\n }\n });\n }\n\n return opsToFlush.length;\n }\n\n /** Build SQL statements from write ops */\n private buildStatements(ops: WriteOp[]): string[] {\n const statements: string[] = [];\n\n for (const op of ops) {\n const qualifiedTable = `\"${this.pgSchemaName}\".\"${op.table}\"`;\n\n switch (op.kind) {\n case \"insert\": {\n const upsertKeys = op.data._upsert_keys as string[] | undefined;\n const fallbackKeys = op.data._upsert_fallback_keys as string[] | undefined;\n const fallbackSet = op.data._upsert_fallback_set as Record<string, unknown> | undefined;\n const data = { ...op.data };\n delete data._upsert_keys;\n delete data._upsert_fallback_keys;\n delete data._upsert_fallback_set;\n\n // Auto-populate meta columns\n data._block_height = this.block.height;\n data._tx_id = this._tx.txId;\n data._created_at = \"NOW()\";\n\n const cols = Object.keys(data);\n cols.forEach(validateColumnName);\n const vals = cols.map((c) =>\n data[c] === \"NOW()\" ? \"NOW()\" : escapeLiteral(data[c]),\n );\n let stmt = `INSERT INTO ${qualifiedTable} (${cols.map((c) => `\"${c}\"`).join(\", \")}) VALUES (${vals.join(\", \")})`;\n\n if (upsertKeys && upsertKeys.length > 0) {\n const updateCols = cols.filter((c) => !upsertKeys.includes(c) && !c.startsWith(\"_\"));\n if (updateCols.length > 0) {\n const setClauses = updateCols.map((c) => `\"${c}\" = EXCLUDED.\"${c}\"`);\n stmt += ` ON CONFLICT (${upsertKeys.map((k) => `\"${k}\"`).join(\", \")}) DO UPDATE SET ${setClauses.join(\", \")}`;\n } else {\n stmt += ` ON CONFLICT (${upsertKeys.map((k) => `\"${k}\"`).join(\", \")}) DO NOTHING`;\n }\n } else if (fallbackKeys && fallbackSet) {\n // Fallback upsert: use ON CONFLICT DO UPDATE but without a declared constraint\n // This will just be a plain INSERT — if it conflicts, PG will raise an error.\n // The caller was already warned. This is the best we can do without a unique constraint.\n }\n\n statements.push(stmt);\n break;\n }\n case \"update\": {\n const setEntries = Object.entries(op.set!);\n setEntries.forEach(([k]) => validateColumnName(k));\n const setClauses = setEntries.map(\n ([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`,\n );\n const { clause } = buildWhereClause(op.data);\n statements.push(\n `UPDATE ${qualifiedTable} SET ${setClauses.join(\", \")} WHERE ${clause}`,\n );\n break;\n }\n case \"delete\": {\n const { clause } = buildWhereClause(op.data);\n statements.push(`DELETE FROM ${qualifiedTable} WHERE ${clause}`);\n break;\n }\n }\n }\n\n return statements;\n }\n\n private validateTable(table: string): void {\n if (!this.subgraphSchema[table]) {\n throw new Error(\n `Table \"${table}\" not found in subgraph schema. Available: [${Object.keys(this.subgraphSchema).join(\", \")}]`,\n );\n }\n }\n}\n\n// --- Helpers ---\n\nfunction escapeLiteral(value: unknown): string {\n if (value === null || value === undefined) return \"NULL\";\n if (typeof value === \"number\" || typeof value === \"bigint\") return String(value);\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n if (typeof value === \"object\") return `'${JSON.stringify(value).replace(/'/g, \"''\")}'::jsonb`;\n // String — escape single quotes\n return `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\nfunction buildWhereClause(where: Record<string, unknown>): {\n clause: string;\n values: unknown[];\n} {\n const entries = Object.entries(where);\n if (entries.length === 0) return { clause: \"TRUE\", values: [] };\n\n entries.forEach(([k]) => validateColumnName(k));\n const parts = entries.map(([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`);\n return { clause: parts.join(\" AND \"), values: [] };\n}\n",
|
|
7
|
+
"import { type SubgraphSource, sourceKey } from \"../types.ts\";\n\nexport interface MatchedTx {\n tx: { tx_id: string; type: string; sender: string; status: string; contract_id?: string | null; function_name?: string | null };\n events: { id: string; tx_id: string; type: string; event_index: number; data: unknown }[];\n /** Which source produced this match — used for handler dispatch */\n sourceKey: string;\n}\n\n/**\n * Check if a string matches a pattern with `*` wildcard support.\n */\nfunction matchPattern(value: string, pattern: string): boolean {\n if (!pattern.includes(\"*\")) return value === pattern;\n const regex = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*/g, \".*\");\n return new RegExp(`^${regex}$`).test(value);\n}\n\ntype TxRecord = { tx_id: string; type: string; sender: string; status: string; contract_id?: string | null; function_name?: string | null };\ntype EventRecord = { id: string; tx_id: string; type: string; event_index: number; data: unknown };\n\n/**\n * Match a single source against transactions and events.\n */\nfunction matchSource(\n source: SubgraphSource,\n transactions: TxRecord[],\n eventsByTx: Map<string, EventRecord[]>,\n): MatchedTx[] {\n const results: MatchedTx[] = [];\n const key = sourceKey(source);\n\n for (const tx of transactions) {\n // Type-based matching (e.g., token_transfer → matches tx.type)\n if (source.type) {\n if (!matchPattern(tx.type, source.type)) continue;\n\n const txEvents = eventsByTx.get(tx.tx_id) ?? [];\n\n // Collect all events for this tx (type-based sources match the whole tx)\n let matchedEvents = txEvents;\n\n // minAmount filter — check events with an amount field\n if (source.minAmount !== undefined) {\n const amountEvents = matchedEvents.filter((e) => {\n const data = e.data as Record<string, unknown> | null;\n const rawAmount = data?.amount as string | number | undefined;\n if (rawAmount === undefined) return false;\n const amount = BigInt(rawAmount);\n return amount >= source.minAmount!;\n });\n if (amountEvents.length === 0) continue;\n matchedEvents = amountEvents;\n }\n\n results.push({ tx, events: matchedEvents, sourceKey: key });\n continue;\n }\n\n // Contract-based matching\n if (source.contract) {\n const txContractMatch = tx.contract_id && matchPattern(tx.contract_id, source.contract);\n\n // Function filter\n if (source.function && tx.function_name) {\n if (!matchPattern(tx.function_name, source.function)) continue;\n } else if (source.function && !tx.function_name) {\n continue;\n }\n\n const txEvents = eventsByTx.get(tx.tx_id) ?? [];\n let matchedEvents = txEvents;\n\n if (!txContractMatch) {\n // Check if any events match the contract\n matchedEvents = txEvents.filter((e) => {\n const data = e.data as Record<string, unknown> | null;\n const contractIdentifier = data?.contract_identifier as string | undefined;\n return contractIdentifier && matchPattern(contractIdentifier, source.contract!);\n });\n if (matchedEvents.length === 0) continue;\n }\n\n // Event type / topic filter\n if (source.event) {\n matchedEvents = matchedEvents.filter((e) => {\n if (matchPattern(e.type, source.event!)) return true;\n const data = e.data as Record<string, unknown> | null;\n const topic = data?.topic as string | undefined;\n return topic ? matchPattern(topic, source.event!) : false;\n });\n }\n\n if (txContractMatch || matchedEvents.length > 0) {\n results.push({ tx, events: matchedEvents, sourceKey: key });\n }\n }\n }\n\n return results;\n}\n\n/**\n * Match all sources against a block's transactions and events.\n * Deduplicates by (txId, sourceKey) — each handler key fires at most once per tx.\n */\nexport function matchSources(\n sources: SubgraphSource[],\n transactions: TxRecord[],\n events: EventRecord[],\n): MatchedTx[] {\n // Index events by txId\n const eventsByTx = new Map<string, EventRecord[]>();\n for (const event of events) {\n const list = eventsByTx.get(event.tx_id) ?? [];\n list.push(event);\n eventsByTx.set(event.tx_id, list);\n }\n\n const seen = new Set<string>();\n const results: MatchedTx[] = [];\n\n for (const source of sources) {\n const matches = matchSource(source, transactions, eventsByTx);\n for (const match of matches) {\n const dedupeKey = `${match.tx.tx_id}:${match.sourceKey}`;\n if (!seen.has(dedupeKey)) {\n seen.add(dedupeKey);\n results.push(match);\n }\n }\n }\n\n return results;\n}\n",
|
|
8
|
+
"import { cvToJSON, deserializeCV } from \"@secondlayer/stacks/clarity\";\n\n/**\n * Decode a hex-encoded Clarity value to a JS object.\n * Returns original value on failure.\n */\nexport function decodeClarityValue(hex: string): unknown {\n try {\n const cleanHex = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n const cv = deserializeCV(cleanHex);\n return cvToJSON(cv);\n } catch {\n return hex;\n }\n}\n\n/**\n * Recursively decode all hex-encoded Clarity values in an object.\n * Any string starting with \"0x\" and longer than 10 chars is attempted.\n */\nexport function decodeEventData(data: unknown): unknown {\n if (typeof data === \"string\" && data.startsWith(\"0x\") && data.length > 10) {\n return decodeClarityValue(data);\n }\n\n if (Array.isArray(data)) {\n return data.map(decodeEventData);\n }\n\n if (typeof data === \"object\" && data !== null) {\n const decoded: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n decoded[key] = decodeEventData(value);\n }\n return decoded;\n }\n\n return data;\n}\n\n/**\n * Decode function args array (hex-encoded Clarity values).\n */\nexport function decodeFunctionArgs(args: string[]): unknown[] {\n return args.map(decodeClarityValue);\n}\n",
|
|
9
|
+
"import { logger } from \"@secondlayer/shared/logger\";\nimport { getErrorMessage } from \"@secondlayer/shared\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport type { SubgraphContext } from \"./context.ts\";\nimport type { MatchedTx } from \"./source-matcher.ts\";\nimport { decodeEventData } from \"./clarity.ts\";\n\n/** Max consecutive handler errors before marking subgraph as error */\nconst DEFAULT_ERROR_THRESHOLD = 50;\n\nexport interface RunResult {\n processed: number;\n errors: number;\n}\n\n/**\n * Resolve the handler for a matched tx.\n * Looks up by sourceKey first, then falls back to \"*\" catch-all.\n */\nfunction resolveHandler(handlers: SubgraphDefinition[\"handlers\"], key: string) {\n return handlers[key] ?? handlers[\"*\"] ?? null;\n}\n\n/**\n * Run a subgraph's keyed handlers against all matched transactions/events.\n *\n * Each MatchedTx carries a sourceKey from the matcher. The runner looks up\n * the corresponding handler in subgraph.handlers, falling back to \"*\".\n *\n * Does NOT flush — caller is responsible for flushing ctx after run.\n */\nexport async function runHandlers(\n subgraph: SubgraphDefinition,\n matched: MatchedTx[],\n ctx: SubgraphContext,\n opts?: { errorThreshold?: number },\n): Promise<RunResult> {\n let processed = 0;\n let errors = 0;\n const threshold = opts?.errorThreshold ?? DEFAULT_ERROR_THRESHOLD;\n\n for (const { tx, events, sourceKey } of matched) {\n const handler = resolveHandler(subgraph.handlers, sourceKey);\n if (!handler) {\n logger.warn(\"No handler found for source key\", { subgraph: subgraph.name, sourceKey, txId: tx.tx_id });\n continue;\n }\n\n ctx.setTx({\n txId: tx.tx_id,\n sender: tx.sender,\n type: tx.type,\n status: tx.status,\n });\n\n // If no events but tx matched, call handler with tx-level data\n if (events.length === 0) {\n try {\n const txPayload: Record<string, unknown> = {\n tx: {\n txId: tx.tx_id,\n sender: tx.sender,\n type: tx.type,\n status: tx.status,\n contractId: tx.contract_id,\n functionName: tx.function_name,\n },\n };\n await handler(txPayload, ctx);\n processed++;\n } catch (err) {\n errors++;\n logger.error(\"Subgraph handler error\", {\n subgraph: subgraph.name,\n sourceKey,\n txId: tx.tx_id,\n error: getErrorMessage(err),\n });\n }\n continue;\n }\n\n for (const event of events) {\n if (errors >= threshold) {\n logger.error(\"Subgraph error threshold reached, skipping remaining events\", {\n subgraph: subgraph.name,\n errors,\n threshold,\n });\n return { processed, errors };\n }\n\n try {\n const decoded = decodeEventData(event.data) as Record<string, unknown>;\n const eventPayload: Record<string, unknown> = {\n ...decoded,\n _eventId: event.id,\n _eventType: event.type,\n _eventIndex: event.event_index,\n tx: {\n txId: tx.tx_id,\n sender: tx.sender,\n type: tx.type,\n status: tx.status,\n contractId: tx.contract_id,\n functionName: tx.function_name,\n },\n };\n\n await handler(eventPayload, ctx);\n processed++;\n } catch (err) {\n errors++;\n logger.error(\"Subgraph handler error\", {\n subgraph: subgraph.name,\n sourceKey,\n txId: tx.tx_id,\n eventId: event.id,\n eventType: event.type,\n error: getErrorMessage(err),\n });\n }\n }\n }\n\n return { processed, errors };\n}\n",
|
|
10
|
+
"import { sql, type Transaction } from \"kysely\";\nimport { getDb, type Database } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { updateSubgraphStatus, recordSubgraphProcessed } from \"@secondlayer/shared/db/queries/subgraphs\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport { pgSchemaName } from \"../schema/utils.ts\";\nimport { SubgraphContext, type BlockMeta, type TxMeta } from \"./context.ts\";\nimport { matchSources } from \"./source-matcher.ts\";\nimport { runHandlers } from \"./runner.ts\";\n\nexport interface ProcessBlockTiming {\n totalMs: number;\n handlerMs: number;\n flushMs: number;\n}\n\nexport interface ProcessBlockResult {\n blockHeight: number;\n matched: number;\n processed: number;\n errors: number;\n skipped: boolean;\n timing?: ProcessBlockTiming;\n}\n\n/**\n * Process a single block through a single subgraph's pipeline.\n *\n * Flow:\n * 1. Load block + txs + events from DB\n * 2. Run source matcher\n * 3. Run handlers with SubgraphContext\n * 4. Flush context (commit writes atomically)\n * 5. Update subgraph.last_processed_block\n */\nexport interface ProcessBlockOptions {\n /** Skip updating last_processed_block in DB (reindex batches this externally). */\n skipProgressUpdate?: boolean;\n}\n\nexport async function processBlock(\n subgraph: SubgraphDefinition,\n subgraphName: string,\n blockHeight: number,\n opts?: ProcessBlockOptions,\n): Promise<ProcessBlockResult> {\n const db = getDb();\n const blockStart = performance.now();\n const result: ProcessBlockResult = {\n blockHeight,\n matched: 0,\n processed: 0,\n errors: 0,\n skipped: false,\n };\n\n // 1. Load block\n const block = await db\n .selectFrom(\"blocks\")\n .selectAll()\n .where(\"height\", \"=\", blockHeight)\n .executeTakeFirst();\n\n if (!block) {\n logger.warn(\"Block not found for subgraph processing\", { subgraph: subgraphName, blockHeight });\n result.skipped = true;\n return result;\n }\n\n if (!block.canonical) {\n logger.debug(\"Skipping non-canonical block\", { subgraph: subgraphName, blockHeight });\n result.skipped = true;\n return result;\n }\n\n // 2. Load txs + events\n const txs = await db\n .selectFrom(\"transactions\")\n .selectAll()\n .where(\"block_height\", \"=\", blockHeight)\n .execute();\n\n const evts = await db\n .selectFrom(\"events\")\n .selectAll()\n .where(\"block_height\", \"=\", blockHeight)\n .execute();\n\n // 3. Match source\n const matched = matchSources(subgraph.sources, txs, evts);\n result.matched = matched.length;\n\n if (matched.length === 0) {\n if (!opts?.skipProgressUpdate) {\n await updateSubgraphStatus(db, subgraphName, \"active\", blockHeight);\n }\n return result;\n }\n\n // 4. Create context and run handlers\n // Use stored schema_name from DB if available, otherwise compute\n const subgraphRecord = await db\n .selectFrom(\"subgraphs\")\n .select(\"schema_name\")\n .where(\"name\", \"=\", subgraphName)\n .executeTakeFirst();\n const schemaName = subgraphRecord?.schema_name ?? pgSchemaName(subgraphName);\n const blockMeta: BlockMeta = {\n height: block.height,\n hash: block.hash,\n timestamp: block.timestamp,\n burnBlockHeight: block.burn_block_height,\n };\n const initialTx: TxMeta = {\n txId: \"\",\n sender: \"\",\n type: \"\",\n status: \"\",\n };\n\n // Wrap entire block processing in a single transaction\n let handlerMs = 0;\n let flushMs = 0;\n\n await db.transaction().execute(async (tx: Transaction<Database>) => {\n const ctx = new SubgraphContext(tx, schemaName, subgraph.schema, blockMeta, initialTx);\n\n const handlerStart = performance.now();\n const runResult = await runHandlers(subgraph, matched, ctx);\n handlerMs = performance.now() - handlerStart;\n\n result.processed = runResult.processed;\n result.errors = runResult.errors;\n\n // 5. Flush writes\n if (ctx.pendingOps > 0) {\n const flushStart = performance.now();\n await ctx.flush();\n flushMs = performance.now() - flushStart;\n }\n\n // 6. Update progress + health metrics (same transaction)\n if (!opts?.skipProgressUpdate) {\n const status = runResult.errors > 0 && runResult.processed === 0 ? \"error\" : \"active\";\n await updateSubgraphStatus(tx, subgraphName, status, blockHeight);\n }\n\n if (!opts?.skipProgressUpdate && (runResult.processed > 0 || runResult.errors > 0)) {\n const lastError = runResult.errors > 0\n ? `${runResult.errors} error(s) at block ${blockHeight}`\n : undefined;\n await recordSubgraphProcessed(tx, subgraphName, runResult.processed, runResult.errors, lastError);\n }\n });\n\n const totalMs = performance.now() - blockStart;\n result.timing = {\n totalMs: Math.round(totalMs),\n handlerMs: Math.round(handlerMs),\n flushMs: Math.round(flushMs),\n };\n\n // 7. Row count warning — sample every 1000 blocks\n if (blockHeight % 1000 === 0) {\n try {\n const tables = Object.keys(subgraph.schema);\n for (const table of tables) {\n const { rows } = await sql.raw(\n `SELECT COUNT(*) as count FROM \"${schemaName}\".\"${table}\"`,\n ).execute(db);\n const count = Number((rows[0] as Record<string, unknown>).count);\n if (count >= 10_000_000) {\n logger.warn(\"Subgraph table exceeds 10M rows\", { subgraph: subgraphName, table, count });\n }\n }\n } catch {\n // Table may not exist yet\n }\n }\n\n return result;\n}\n",
|
|
11
|
+
"// Re-export canonical pgSchemaName from shared\nexport { pgSchemaName } from \"@secondlayer/shared/db/queries/subgraphs\";\n",
|
|
12
|
+
"import type { Kysely } from \"kysely\";\nimport type { Database } from \"@secondlayer/shared/db\";\nimport type { ProcessBlockTiming } from \"./block-processor.ts\";\n\ninterface StatsEntry {\n subgraphName: string;\n apiKeyId: string | null;\n bucketStart: Date;\n blocksProcessed: number;\n totalTimeMs: number;\n handlerTimeMs: number;\n flushTimeMs: number;\n maxBlockTimeMs: number;\n maxHandlerTimeMs: number;\n totalOps: number;\n isCatchup: boolean;\n}\n\nconst FLUSH_INTERVAL_BLOCKS = 100;\nconst FLUSH_INTERVAL_MS = 60_000;\n\n/**\n * Accumulates per-block timing stats and flushes to DB periodically.\n * One instance per subgraph during catchup/reindex/live processing.\n */\nexport class StatsAccumulator {\n private current: StatsEntry;\n private lastFlush = Date.now();\n\n constructor(\n private subgraphName: string,\n private apiKeyId: string | null,\n private isCatchup: boolean,\n ) {\n this.current = this.newEntry();\n }\n\n record(timing: ProcessBlockTiming, opsCount: number): void {\n this.current.blocksProcessed++;\n this.current.totalTimeMs += timing.totalMs;\n this.current.handlerTimeMs += timing.handlerMs;\n this.current.flushTimeMs += timing.flushMs;\n this.current.maxBlockTimeMs = Math.max(this.current.maxBlockTimeMs, timing.totalMs);\n this.current.maxHandlerTimeMs = Math.max(this.current.maxHandlerTimeMs, timing.handlerMs);\n this.current.totalOps += opsCount;\n }\n\n shouldFlush(): boolean {\n return (\n this.current.blocksProcessed >= FLUSH_INTERVAL_BLOCKS ||\n Date.now() - this.lastFlush >= FLUSH_INTERVAL_MS\n );\n }\n\n async flush(db: Kysely<Database>): Promise<void> {\n if (this.current.blocksProcessed === 0) return;\n\n const entry = this.current;\n this.current = this.newEntry();\n this.lastFlush = Date.now();\n\n const avgOpsPerBlock = entry.blocksProcessed > 0\n ? entry.totalOps / entry.blocksProcessed\n : 0;\n\n await db\n .insertInto(\"subgraph_processing_stats\")\n .values({\n subgraph_name: entry.subgraphName,\n api_key_id: entry.apiKeyId,\n bucket_start: entry.bucketStart,\n bucket_end: new Date(),\n blocks_processed: entry.blocksProcessed,\n total_time_ms: Math.round(entry.totalTimeMs),\n handler_time_ms: Math.round(entry.handlerTimeMs),\n flush_time_ms: Math.round(entry.flushTimeMs),\n max_block_time_ms: Math.round(entry.maxBlockTimeMs),\n max_handler_time_ms: Math.round(entry.maxHandlerTimeMs),\n avg_ops_per_block: parseFloat(avgOpsPerBlock.toFixed(2)),\n is_catchup: entry.isCatchup,\n })\n .execute();\n }\n\n private newEntry(): StatsEntry {\n return {\n subgraphName: this.subgraphName,\n apiKeyId: this.apiKeyId,\n bucketStart: new Date(),\n blocksProcessed: 0,\n totalTimeMs: 0,\n handlerTimeMs: 0,\n flushTimeMs: 0,\n maxBlockTimeMs: 0,\n maxHandlerTimeMs: 0,\n totalOps: 0,\n isCatchup: this.isCatchup,\n };\n }\n}\n",
|
|
13
|
+
"import { getDb } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport { getSubgraph } from \"@secondlayer/shared/db/queries/subgraphs\";\nimport type { SubgraphDefinition } from \"../types.ts\";\nimport { processBlock } from \"./block-processor.ts\";\nimport { StatsAccumulator } from \"./stats.ts\";\n\nconst LOG_INTERVAL = 1000;\n\nconst catchingUp = new Set<string>();\n\n/**\n * Catch a subgraph up from its last_processed_block to the chain tip.\n * Re-reads lastProcessedBlock from DB to avoid stale values.\n * Skips if a catch-up is already in progress for this subgraph.\n */\nexport async function catchUpSubgraph(\n subgraph: SubgraphDefinition,\n subgraphName: string,\n): Promise<number> {\n if (catchingUp.has(subgraphName)) return 0;\n catchingUp.add(subgraphName);\n\n try {\n const db = getDb();\n\n // Re-read from DB to avoid stale lastProcessedBlock\n const subgraphRow = await getSubgraph(db, subgraphName);\n if (!subgraphRow) return 0;\n const lastProcessedBlock = Number(subgraphRow.last_processed_block);\n\n // Get chain tip from indexProgress\n const progress = await db\n .selectFrom(\"index_progress\")\n .selectAll()\n .where(\"network\", \"=\", process.env.NETWORK ?? \"mainnet\")\n .executeTakeFirst();\n\n if (!progress) return 0;\n\n const chainTip = Number(progress.last_contiguous_block);\n if (lastProcessedBlock >= chainTip) return 0;\n\n const startBlock = lastProcessedBlock + 1;\n const totalBlocks = chainTip - lastProcessedBlock;\n\n logger.info(\"Subgraph catch-up starting\", {\n subgraph: subgraphName,\n from: startBlock,\n to: chainTip,\n blocks: totalBlocks,\n });\n\n const stats = new StatsAccumulator(subgraphName, subgraphRow.api_key_id, true);\n let processed = 0;\n\n for (let height = startBlock; height <= chainTip; height++) {\n const result = await processBlock(subgraph, subgraphName, height);\n processed++;\n\n if (result.timing) {\n stats.record(result.timing, result.processed);\n if (stats.shouldFlush()) {\n await stats.flush(db);\n }\n }\n\n if (processed % LOG_INTERVAL === 0) {\n logger.info(\"Subgraph catch-up progress\", {\n subgraph: subgraphName,\n processed,\n total: totalBlocks,\n currentBlock: height,\n pct: Math.round((processed / totalBlocks) * 100),\n });\n }\n }\n\n // Flush remaining stats\n await stats.flush(db);\n\n logger.info(\"Subgraph catch-up complete\", {\n subgraph: subgraphName,\n processed,\n });\n\n return processed;\n } finally {\n catchingUp.delete(subgraphName);\n }\n}\n"
|
|
14
|
+
],
|
|
15
|
+
"mappings": ";;;;AAsEO,SAAS,SAAS,CAAC,QAAgC;AAAA,EACxD,IAAI,OAAO,UAAU;AAAA,IACnB,IAAI,OAAO;AAAA,MAAU,OAAO,GAAG,OAAO,aAAa,OAAO;AAAA,IAC1D,IAAI,OAAO;AAAA,MAAO,OAAO,GAAG,OAAO,aAAa,OAAO;AAAA,IACvD,OAAO,OAAO;AAAA,EAChB;AAAA,EACA,IAAI,OAAO;AAAA,IAAM,OAAO,OAAO;AAAA,EAC/B,OAAO;AAAA;;;AC7ET;AAEA;AA4BA,SAAS,kBAAkB,CAAC,MAAoB;AAAA,EAC9C,IAAI,CAAC,sBAAsB,KAAK,IAAI,GAAG;AAAA,IACrC,MAAM,IAAI,MAAM,wBAAwB,MAAM;AAAA,EAChD;AAAA;AAAA;AAQK,MAAM,gBAAgB;AAAA,EAClB;AAAA,EACD;AAAA,EACS;AAAA,EACA;AAAA,EACA;AAAA,EACA,MAAiB,CAAC;AAAA,EAEnC,WAAW,CACT,IACA,cACA,gBACA,OACA,IACA;AAAA,IACA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AClC,QAAO,KAAK,8BAA8B;AAAA,UACxC,UAAU;AAAA,UACV;AAAA,UACA,OAAO;AAAA,UACP,cAAc;AAAA,UACd,KAAK,KAAK,MAAO,YAAY,cAAe,GAAG;AAAA,QACjD,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IAGA,MAAM,MAAM,MAAM,EAAE;AAAA,IAEpB,QAAO,KAAK,8BAA8B;AAAA,MACxC,UAAU;AAAA,MACV;AAAA,IACF,CAAC;AAAA,IAED,OAAO;AAAA,YACP;AAAA,IACA,WAAW,OAAO,YAAY;AAAA;AAAA;",
|
|
16
|
+
"debugId": "742E9B8ABE1F7B4364756E2164756E21",
|
|
17
|
+
"names": []
|
|
18
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decode a hex-encoded Clarity value to a JS object.
|
|
3
|
+
* Returns original value on failure.
|
|
4
|
+
*/
|
|
5
|
+
declare function decodeClarityValue(hex: string): unknown;
|
|
6
|
+
/**
|
|
7
|
+
* Recursively decode all hex-encoded Clarity values in an object.
|
|
8
|
+
* Any string starting with "0x" and longer than 10 chars is attempted.
|
|
9
|
+
*/
|
|
10
|
+
declare function decodeEventData(data: unknown): unknown;
|
|
11
|
+
/**
|
|
12
|
+
* Decode function args array (hex-encoded Clarity values).
|
|
13
|
+
*/
|
|
14
|
+
declare function decodeFunctionArgs(args: string[]): unknown[];
|
|
15
|
+
export { decodeFunctionArgs, decodeEventData, decodeClarityValue };
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
// src/runtime/clarity.ts
|
|
5
|
+
import { cvToJSON, deserializeCV } from "@secondlayer/stacks/clarity";
|
|
6
|
+
function decodeClarityValue(hex) {
|
|
7
|
+
try {
|
|
8
|
+
const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
|
|
9
|
+
const cv = deserializeCV(cleanHex);
|
|
10
|
+
return cvToJSON(cv);
|
|
11
|
+
} catch {
|
|
12
|
+
return hex;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function decodeEventData(data) {
|
|
16
|
+
if (typeof data === "string" && data.startsWith("0x") && data.length > 10) {
|
|
17
|
+
return decodeClarityValue(data);
|
|
18
|
+
}
|
|
19
|
+
if (Array.isArray(data)) {
|
|
20
|
+
return data.map(decodeEventData);
|
|
21
|
+
}
|
|
22
|
+
if (typeof data === "object" && data !== null) {
|
|
23
|
+
const decoded = {};
|
|
24
|
+
for (const [key, value] of Object.entries(data)) {
|
|
25
|
+
decoded[key] = decodeEventData(value);
|
|
26
|
+
}
|
|
27
|
+
return decoded;
|
|
28
|
+
}
|
|
29
|
+
return data;
|
|
30
|
+
}
|
|
31
|
+
function decodeFunctionArgs(args) {
|
|
32
|
+
return args.map(decodeClarityValue);
|
|
33
|
+
}
|
|
34
|
+
export {
|
|
35
|
+
decodeFunctionArgs,
|
|
36
|
+
decodeEventData,
|
|
37
|
+
decodeClarityValue
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
//# debugId=E1B0DFCE065915FC64756E2164756E21
|
|
41
|
+
//# sourceMappingURL=clarity.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/runtime/clarity.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { cvToJSON, deserializeCV } from \"@secondlayer/stacks/clarity\";\n\n/**\n * Decode a hex-encoded Clarity value to a JS object.\n * Returns original value on failure.\n */\nexport function decodeClarityValue(hex: string): unknown {\n try {\n const cleanHex = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n const cv = deserializeCV(cleanHex);\n return cvToJSON(cv);\n } catch {\n return hex;\n }\n}\n\n/**\n * Recursively decode all hex-encoded Clarity values in an object.\n * Any string starting with \"0x\" and longer than 10 chars is attempted.\n */\nexport function decodeEventData(data: unknown): unknown {\n if (typeof data === \"string\" && data.startsWith(\"0x\") && data.length > 10) {\n return decodeClarityValue(data);\n }\n\n if (Array.isArray(data)) {\n return data.map(decodeEventData);\n }\n\n if (typeof data === \"object\" && data !== null) {\n const decoded: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n decoded[key] = decodeEventData(value);\n }\n return decoded;\n }\n\n return data;\n}\n\n/**\n * Decode function args array (hex-encoded Clarity values).\n */\nexport function decodeFunctionArgs(args: string[]): unknown[] {\n return args.map(decodeClarityValue);\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";;;;AAAA;AAMO,SAAS,kBAAkB,CAAC,KAAsB;AAAA,EACvD,IAAI;AAAA,IACF,MAAM,WAAW,IAAI,WAAW,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI;AAAA,IACvD,MAAM,KAAK,cAAc,QAAQ;AAAA,IACjC,OAAO,SAAS,EAAE;AAAA,IAClB,MAAM;AAAA,IACN,OAAO;AAAA;AAAA;AAQJ,SAAS,eAAe,CAAC,MAAwB;AAAA,EACtD,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,IAAI,KAAK,KAAK,SAAS,IAAI;AAAA,IACzE,OAAO,mBAAmB,IAAI;AAAA,EAChC;AAAA,EAEA,IAAI,MAAM,QAAQ,IAAI,GAAG;AAAA,IACvB,OAAO,KAAK,IAAI,eAAe;AAAA,EACjC;AAAA,EAEA,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM;AAAA,IAC7C,MAAM,UAAmC,CAAC;AAAA,IAC1C,YAAY,KAAK,UAAU,OAAO,QAAQ,IAAI,GAAG;AAAA,MAC/C,QAAQ,OAAO,gBAAgB,KAAK;AAAA,IACtC;AAAA,IACA,OAAO;AAAA,EACT;AAAA,EAEA,OAAO;AAAA;AAMF,SAAS,kBAAkB,CAAC,MAA2B;AAAA,EAC5D,OAAO,KAAK,IAAI,kBAAkB;AAAA;",
|
|
8
|
+
"debugId": "E1B0DFCE065915FC64756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Supported column types for subgraph schemas */
|
|
2
|
+
type ColumnType = "text" | "uint" | "int" | "principal" | "boolean" | "timestamp" | "jsonb";
|
|
3
|
+
/** Column definition in a subgraph table */
|
|
4
|
+
interface SubgraphColumn {
|
|
5
|
+
type: ColumnType;
|
|
6
|
+
nullable?: boolean;
|
|
7
|
+
indexed?: boolean;
|
|
8
|
+
search?: boolean;
|
|
9
|
+
default?: string | number | boolean;
|
|
10
|
+
}
|
|
11
|
+
/** Table definition within a subgraph schema */
|
|
12
|
+
interface SubgraphTable {
|
|
13
|
+
columns: Record<string, SubgraphColumn>;
|
|
14
|
+
/** Composite indexes (each entry is an array of column names) */
|
|
15
|
+
indexes?: string[][];
|
|
16
|
+
/** Unique key constraints (each entry is an array of column names). Required for upsert. */
|
|
17
|
+
uniqueKeys?: string[][];
|
|
18
|
+
}
|
|
19
|
+
/** Subgraph schema — maps table names to table definitions */
|
|
20
|
+
type SubgraphSchema = Record<string, SubgraphTable>;
|
|
21
|
+
import { Kysely, Transaction } from "kysely";
|
|
22
|
+
import { Database } from "@secondlayer/shared/db";
|
|
23
|
+
type AnyDb = Kysely<Database> | Transaction<Database>;
|
|
24
|
+
interface BlockMeta {
|
|
25
|
+
height: number;
|
|
26
|
+
hash: string;
|
|
27
|
+
timestamp: number;
|
|
28
|
+
burnBlockHeight: number;
|
|
29
|
+
}
|
|
30
|
+
interface TxMeta {
|
|
31
|
+
txId: string;
|
|
32
|
+
sender: string;
|
|
33
|
+
type: string;
|
|
34
|
+
status: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Runtime context passed to subgraph handlers.
|
|
38
|
+
* Batches writes and flushes them atomically at the end of a block.
|
|
39
|
+
* Reads execute immediately against the DB (pre-flush state).
|
|
40
|
+
*/
|
|
41
|
+
declare class SubgraphContext2 {
|
|
42
|
+
readonly block: BlockMeta;
|
|
43
|
+
private _tx;
|
|
44
|
+
private readonly db;
|
|
45
|
+
private readonly pgSchemaName;
|
|
46
|
+
private readonly subgraphSchema;
|
|
47
|
+
private readonly ops;
|
|
48
|
+
constructor(db: AnyDb, pgSchemaName: string, subgraphSchema: SubgraphSchema, block: BlockMeta, tx: TxMeta);
|
|
49
|
+
get tx(): TxMeta;
|
|
50
|
+
/** Update the current transaction context (used by runner between events) */
|
|
51
|
+
setTx(tx: TxMeta): void;
|
|
52
|
+
insert(table: string, row: Record<string, unknown>): void;
|
|
53
|
+
update(table: string, where: Record<string, unknown>, set: Record<string, unknown>): void;
|
|
54
|
+
upsert(table: string, key: Record<string, unknown>, row: Record<string, unknown>): void;
|
|
55
|
+
delete(table: string, where: Record<string, unknown>): void;
|
|
56
|
+
findOne(table: string, where: Record<string, unknown>): Promise<Record<string, unknown> | null>;
|
|
57
|
+
findMany(table: string, where: Record<string, unknown>): Promise<Record<string, unknown>[]>;
|
|
58
|
+
/** Number of pending write operations */
|
|
59
|
+
get pendingOps(): number;
|
|
60
|
+
/**
|
|
61
|
+
* Execute all batched writes in a single transaction.
|
|
62
|
+
* Auto-populates _block_height, _tx_id, _created_at on inserts.
|
|
63
|
+
*/
|
|
64
|
+
flush(): Promise<number>;
|
|
65
|
+
/** Build SQL statements from write ops */
|
|
66
|
+
private buildStatements;
|
|
67
|
+
private validateTable;
|
|
68
|
+
}
|
|
69
|
+
export { TxMeta, SubgraphContext2 as SubgraphContext, BlockMeta };
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
// src/runtime/context.ts
|
|
5
|
+
import { sql } from "kysely";
|
|
6
|
+
import { logger } from "@secondlayer/shared/logger";
|
|
7
|
+
function validateColumnName(name) {
|
|
8
|
+
if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {
|
|
9
|
+
throw new Error(`Invalid column name: ${name}`);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
class SubgraphContext {
|
|
14
|
+
block;
|
|
15
|
+
_tx;
|
|
16
|
+
db;
|
|
17
|
+
pgSchemaName;
|
|
18
|
+
subgraphSchema;
|
|
19
|
+
ops = [];
|
|
20
|
+
constructor(db, pgSchemaName, subgraphSchema, block, tx) {
|
|
21
|
+
this.db = db;
|
|
22
|
+
this.pgSchemaName = pgSchemaName;
|
|
23
|
+
this.subgraphSchema = subgraphSchema;
|
|
24
|
+
this.block = block;
|
|
25
|
+
this._tx = tx;
|
|
26
|
+
}
|
|
27
|
+
get tx() {
|
|
28
|
+
return this._tx;
|
|
29
|
+
}
|
|
30
|
+
setTx(tx) {
|
|
31
|
+
this._tx = tx;
|
|
32
|
+
}
|
|
33
|
+
insert(table, row) {
|
|
34
|
+
this.validateTable(table);
|
|
35
|
+
this.ops.push({ kind: "insert", table, data: row });
|
|
36
|
+
}
|
|
37
|
+
update(table, where, set) {
|
|
38
|
+
this.validateTable(table);
|
|
39
|
+
this.ops.push({ kind: "update", table, data: where, set });
|
|
40
|
+
}
|
|
41
|
+
upsert(table, key, row) {
|
|
42
|
+
this.validateTable(table);
|
|
43
|
+
const tableDef = this.subgraphSchema[table];
|
|
44
|
+
const keyColumns = Object.keys(key);
|
|
45
|
+
const hasUniqueConstraint = tableDef.uniqueKeys?.some((uk) => uk.length === keyColumns.length && uk.every((c) => keyColumns.includes(c)));
|
|
46
|
+
if (hasUniqueConstraint) {
|
|
47
|
+
this.ops.push({ kind: "insert", table, data: { ...key, ...row, _upsert_keys: keyColumns } });
|
|
48
|
+
} else {
|
|
49
|
+
logger.warn("upsert called without matching uniqueKeys constraint, using fallback", {
|
|
50
|
+
table,
|
|
51
|
+
keys: keyColumns
|
|
52
|
+
});
|
|
53
|
+
this.ops.push({ kind: "insert", table, data: { ...key, ...row, _upsert_fallback_keys: keyColumns, _upsert_fallback_set: row } });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
delete(table, where) {
|
|
57
|
+
this.validateTable(table);
|
|
58
|
+
this.ops.push({ kind: "delete", table, data: where });
|
|
59
|
+
}
|
|
60
|
+
async findOne(table, where) {
|
|
61
|
+
this.validateTable(table);
|
|
62
|
+
const qualifiedTable = `"${this.pgSchemaName}"."${table}"`;
|
|
63
|
+
const { clause } = buildWhereClause(where);
|
|
64
|
+
const query = `SELECT * FROM ${qualifiedTable} WHERE ${clause} LIMIT 1`;
|
|
65
|
+
const { rows } = await sql.raw(query).execute(this.db);
|
|
66
|
+
return rows[0] ?? null;
|
|
67
|
+
}
|
|
68
|
+
async findMany(table, where) {
|
|
69
|
+
this.validateTable(table);
|
|
70
|
+
const qualifiedTable = `"${this.pgSchemaName}"."${table}"`;
|
|
71
|
+
const { clause } = buildWhereClause(where);
|
|
72
|
+
const query = `SELECT * FROM ${qualifiedTable} WHERE ${clause}`;
|
|
73
|
+
const { rows } = await sql.raw(query).execute(this.db);
|
|
74
|
+
return rows;
|
|
75
|
+
}
|
|
76
|
+
get pendingOps() {
|
|
77
|
+
return this.ops.length;
|
|
78
|
+
}
|
|
79
|
+
async flush() {
|
|
80
|
+
if (this.ops.length === 0)
|
|
81
|
+
return 0;
|
|
82
|
+
const opsToFlush = [...this.ops];
|
|
83
|
+
this.ops.length = 0;
|
|
84
|
+
const statements = this.buildStatements(opsToFlush);
|
|
85
|
+
if ("isTransaction" in this.db) {
|
|
86
|
+
for (const stmt of statements) {
|
|
87
|
+
await sql.raw(stmt).execute(this.db);
|
|
88
|
+
}
|
|
89
|
+
} else {
|
|
90
|
+
await this.db.transaction().execute(async (tx) => {
|
|
91
|
+
for (const stmt of statements) {
|
|
92
|
+
await sql.raw(stmt).execute(tx);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
return opsToFlush.length;
|
|
97
|
+
}
|
|
98
|
+
buildStatements(ops) {
|
|
99
|
+
const statements = [];
|
|
100
|
+
for (const op of ops) {
|
|
101
|
+
const qualifiedTable = `"${this.pgSchemaName}"."${op.table}"`;
|
|
102
|
+
switch (op.kind) {
|
|
103
|
+
case "insert": {
|
|
104
|
+
const upsertKeys = op.data._upsert_keys;
|
|
105
|
+
const fallbackKeys = op.data._upsert_fallback_keys;
|
|
106
|
+
const fallbackSet = op.data._upsert_fallback_set;
|
|
107
|
+
const data = { ...op.data };
|
|
108
|
+
delete data._upsert_keys;
|
|
109
|
+
delete data._upsert_fallback_keys;
|
|
110
|
+
delete data._upsert_fallback_set;
|
|
111
|
+
data._block_height = this.block.height;
|
|
112
|
+
data._tx_id = this._tx.txId;
|
|
113
|
+
data._created_at = "NOW()";
|
|
114
|
+
const cols = Object.keys(data);
|
|
115
|
+
cols.forEach(validateColumnName);
|
|
116
|
+
const vals = cols.map((c) => data[c] === "NOW()" ? "NOW()" : escapeLiteral(data[c]));
|
|
117
|
+
let stmt = `INSERT INTO ${qualifiedTable} (${cols.map((c) => `"${c}"`).join(", ")}) VALUES (${vals.join(", ")})`;
|
|
118
|
+
if (upsertKeys && upsertKeys.length > 0) {
|
|
119
|
+
const updateCols = cols.filter((c) => !upsertKeys.includes(c) && !c.startsWith("_"));
|
|
120
|
+
if (updateCols.length > 0) {
|
|
121
|
+
const setClauses = updateCols.map((c) => `"${c}" = EXCLUDED."${c}"`);
|
|
122
|
+
stmt += ` ON CONFLICT (${upsertKeys.map((k) => `"${k}"`).join(", ")}) DO UPDATE SET ${setClauses.join(", ")}`;
|
|
123
|
+
} else {
|
|
124
|
+
stmt += ` ON CONFLICT (${upsertKeys.map((k) => `"${k}"`).join(", ")}) DO NOTHING`;
|
|
125
|
+
}
|
|
126
|
+
} else if (fallbackKeys && fallbackSet) {}
|
|
127
|
+
statements.push(stmt);
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
case "update": {
|
|
131
|
+
const setEntries = Object.entries(op.set);
|
|
132
|
+
setEntries.forEach(([k]) => validateColumnName(k));
|
|
133
|
+
const setClauses = setEntries.map(([k, v]) => `"${k}" = ${escapeLiteral(v)}`);
|
|
134
|
+
const { clause } = buildWhereClause(op.data);
|
|
135
|
+
statements.push(`UPDATE ${qualifiedTable} SET ${setClauses.join(", ")} WHERE ${clause}`);
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
case "delete": {
|
|
139
|
+
const { clause } = buildWhereClause(op.data);
|
|
140
|
+
statements.push(`DELETE FROM ${qualifiedTable} WHERE ${clause}`);
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return statements;
|
|
146
|
+
}
|
|
147
|
+
validateTable(table) {
|
|
148
|
+
if (!this.subgraphSchema[table]) {
|
|
149
|
+
throw new Error(`Table "${table}" not found in subgraph schema. Available: [${Object.keys(this.subgraphSchema).join(", ")}]`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function escapeLiteral(value) {
|
|
154
|
+
if (value === null || value === undefined)
|
|
155
|
+
return "NULL";
|
|
156
|
+
if (typeof value === "number" || typeof value === "bigint")
|
|
157
|
+
return String(value);
|
|
158
|
+
if (typeof value === "boolean")
|
|
159
|
+
return value ? "TRUE" : "FALSE";
|
|
160
|
+
if (typeof value === "object")
|
|
161
|
+
return `'${JSON.stringify(value).replace(/'/g, "''")}'::jsonb`;
|
|
162
|
+
return `'${String(value).replace(/'/g, "''")}'`;
|
|
163
|
+
}
|
|
164
|
+
function buildWhereClause(where) {
|
|
165
|
+
const entries = Object.entries(where);
|
|
166
|
+
if (entries.length === 0)
|
|
167
|
+
return { clause: "TRUE", values: [] };
|
|
168
|
+
entries.forEach(([k]) => validateColumnName(k));
|
|
169
|
+
const parts = entries.map(([k, v]) => `"${k}" = ${escapeLiteral(v)}`);
|
|
170
|
+
return { clause: parts.join(" AND "), values: [] };
|
|
171
|
+
}
|
|
172
|
+
export {
|
|
173
|
+
SubgraphContext
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
//# debugId=05A07F5B9890D95264756E2164756E21
|
|
177
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/runtime/context.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { sql, type Kysely, type Transaction } from \"kysely\";\nimport type { Database } from \"@secondlayer/shared/db\";\nimport { logger } from \"@secondlayer/shared/logger\";\nimport type { SubgraphSchema } from \"../types.ts\";\n\ntype AnyDb = Kysely<Database> | Transaction<Database>;\n\ninterface WriteOp {\n kind: \"insert\" | \"update\" | \"delete\";\n table: string;\n data: Record<string, unknown>;\n /** For update: SET clause */\n set?: Record<string, unknown>;\n}\n\nexport interface BlockMeta {\n height: number;\n hash: string;\n timestamp: number;\n burnBlockHeight: number;\n}\n\nexport interface TxMeta {\n txId: string;\n sender: string;\n type: string;\n status: string;\n}\n\n/** Validate that a column name is safe for SQL identifiers */\nfunction validateColumnName(name: string): void {\n if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {\n throw new Error(`Invalid column name: ${name}`);\n }\n}\n\n/**\n * Runtime context passed to subgraph handlers.\n * Batches writes and flushes them atomically at the end of a block.\n * Reads execute immediately against the DB (pre-flush state).\n */\nexport class SubgraphContext {\n readonly block: BlockMeta;\n private _tx: TxMeta;\n private readonly db: AnyDb;\n private readonly pgSchemaName: string;\n private readonly subgraphSchema: SubgraphSchema;\n private readonly ops: WriteOp[] = [];\n\n constructor(\n db: AnyDb,\n pgSchemaName: string,\n subgraphSchema: SubgraphSchema,\n block: BlockMeta,\n tx: TxMeta,\n ) {\n this.db = db;\n this.pgSchemaName = pgSchemaName;\n this.subgraphSchema = subgraphSchema;\n this.block = block;\n this._tx = tx;\n }\n\n get tx(): TxMeta {\n return this._tx;\n }\n\n /** Update the current transaction context (used by runner between events) */\n setTx(tx: TxMeta): void {\n this._tx = tx;\n }\n\n // --- Write operations (batched) ---\n\n insert(table: string, row: Record<string, unknown>): void {\n this.validateTable(table);\n this.ops.push({ kind: \"insert\", table, data: row });\n }\n\n update(\n table: string,\n where: Record<string, unknown>,\n set: Record<string, unknown>,\n ): void {\n this.validateTable(table);\n this.ops.push({ kind: \"update\", table, data: where, set });\n }\n\n upsert(\n table: string,\n key: Record<string, unknown>,\n row: Record<string, unknown>,\n ): void {\n this.validateTable(table);\n const tableDef = this.subgraphSchema[table]!;\n const keyColumns = Object.keys(key);\n\n // Check if there's a matching uniqueKeys constraint\n const hasUniqueConstraint = tableDef.uniqueKeys?.some(\n (uk) => uk.length === keyColumns.length && uk.every((c) => keyColumns.includes(c)),\n );\n\n if (hasUniqueConstraint) {\n // Use ON CONFLICT for proper upsert\n this.ops.push({ kind: \"insert\", table, data: { ...key, ...row, _upsert_keys: keyColumns } });\n } else {\n // Fallback: log warning, use findOne + conditional insert/update\n logger.warn(\"upsert called without matching uniqueKeys constraint, using fallback\", {\n table,\n keys: keyColumns,\n });\n this.ops.push({ kind: \"insert\", table, data: { ...key, ...row, _upsert_fallback_keys: keyColumns, _upsert_fallback_set: row } });\n }\n }\n\n delete(table: string, where: Record<string, unknown>): void {\n this.validateTable(table);\n this.ops.push({ kind: \"delete\", table, data: where });\n }\n\n // --- Read operations (immediate) ---\n\n async findOne(\n table: string,\n where: Record<string, unknown>,\n ): Promise<Record<string, unknown> | null> {\n this.validateTable(table);\n const qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n const { clause } = buildWhereClause(where);\n const query = `SELECT * FROM ${qualifiedTable} WHERE ${clause} LIMIT 1`;\n const { rows } = await sql.raw(query).execute(this.db);\n return (rows as Record<string, unknown>[])[0] ?? null;\n }\n\n async findMany(\n table: string,\n where: Record<string, unknown>,\n ): Promise<Record<string, unknown>[]> {\n this.validateTable(table);\n const qualifiedTable = `\"${this.pgSchemaName}\".\"${table}\"`;\n const { clause } = buildWhereClause(where);\n const query = `SELECT * FROM ${qualifiedTable} WHERE ${clause}`;\n const { rows } = await sql.raw(query).execute(this.db);\n return rows as Record<string, unknown>[];\n }\n\n // --- Flush ---\n\n /** Number of pending write operations */\n get pendingOps(): number {\n return this.ops.length;\n }\n\n /**\n * Execute all batched writes in a single transaction.\n * Auto-populates _block_height, _tx_id, _created_at on inserts.\n */\n async flush(): Promise<number> {\n if (this.ops.length === 0) return 0;\n\n const opsToFlush = [...this.ops];\n this.ops.length = 0;\n\n const statements = this.buildStatements(opsToFlush);\n\n // If db is already a transaction, execute directly\n if (\"isTransaction\" in this.db) {\n for (const stmt of statements) {\n await sql.raw(stmt).execute(this.db);\n }\n } else {\n await (this.db as Kysely<Database>).transaction().execute(async (tx) => {\n for (const stmt of statements) {\n await sql.raw(stmt).execute(tx);\n }\n });\n }\n\n return opsToFlush.length;\n }\n\n /** Build SQL statements from write ops */\n private buildStatements(ops: WriteOp[]): string[] {\n const statements: string[] = [];\n\n for (const op of ops) {\n const qualifiedTable = `\"${this.pgSchemaName}\".\"${op.table}\"`;\n\n switch (op.kind) {\n case \"insert\": {\n const upsertKeys = op.data._upsert_keys as string[] | undefined;\n const fallbackKeys = op.data._upsert_fallback_keys as string[] | undefined;\n const fallbackSet = op.data._upsert_fallback_set as Record<string, unknown> | undefined;\n const data = { ...op.data };\n delete data._upsert_keys;\n delete data._upsert_fallback_keys;\n delete data._upsert_fallback_set;\n\n // Auto-populate meta columns\n data._block_height = this.block.height;\n data._tx_id = this._tx.txId;\n data._created_at = \"NOW()\";\n\n const cols = Object.keys(data);\n cols.forEach(validateColumnName);\n const vals = cols.map((c) =>\n data[c] === \"NOW()\" ? \"NOW()\" : escapeLiteral(data[c]),\n );\n let stmt = `INSERT INTO ${qualifiedTable} (${cols.map((c) => `\"${c}\"`).join(\", \")}) VALUES (${vals.join(\", \")})`;\n\n if (upsertKeys && upsertKeys.length > 0) {\n const updateCols = cols.filter((c) => !upsertKeys.includes(c) && !c.startsWith(\"_\"));\n if (updateCols.length > 0) {\n const setClauses = updateCols.map((c) => `\"${c}\" = EXCLUDED.\"${c}\"`);\n stmt += ` ON CONFLICT (${upsertKeys.map((k) => `\"${k}\"`).join(\", \")}) DO UPDATE SET ${setClauses.join(\", \")}`;\n } else {\n stmt += ` ON CONFLICT (${upsertKeys.map((k) => `\"${k}\"`).join(\", \")}) DO NOTHING`;\n }\n } else if (fallbackKeys && fallbackSet) {\n // Fallback upsert: use ON CONFLICT DO UPDATE but without a declared constraint\n // This will just be a plain INSERT — if it conflicts, PG will raise an error.\n // The caller was already warned. This is the best we can do without a unique constraint.\n }\n\n statements.push(stmt);\n break;\n }\n case \"update\": {\n const setEntries = Object.entries(op.set!);\n setEntries.forEach(([k]) => validateColumnName(k));\n const setClauses = setEntries.map(\n ([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`,\n );\n const { clause } = buildWhereClause(op.data);\n statements.push(\n `UPDATE ${qualifiedTable} SET ${setClauses.join(\", \")} WHERE ${clause}`,\n );\n break;\n }\n case \"delete\": {\n const { clause } = buildWhereClause(op.data);\n statements.push(`DELETE FROM ${qualifiedTable} WHERE ${clause}`);\n break;\n }\n }\n }\n\n return statements;\n }\n\n private validateTable(table: string): void {\n if (!this.subgraphSchema[table]) {\n throw new Error(\n `Table \"${table}\" not found in subgraph schema. Available: [${Object.keys(this.subgraphSchema).join(\", \")}]`,\n );\n }\n }\n}\n\n// --- Helpers ---\n\nfunction escapeLiteral(value: unknown): string {\n if (value === null || value === undefined) return \"NULL\";\n if (typeof value === \"number\" || typeof value === \"bigint\") return String(value);\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n if (typeof value === \"object\") return `'${JSON.stringify(value).replace(/'/g, \"''\")}'::jsonb`;\n // String — escape single quotes\n return `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\nfunction buildWhereClause(where: Record<string, unknown>): {\n clause: string;\n values: unknown[];\n} {\n const entries = Object.entries(where);\n if (entries.length === 0) return { clause: \"TRUE\", values: [] };\n\n entries.forEach(([k]) => validateColumnName(k));\n const parts = entries.map(([k, v]) => `\"${k}\" = ${escapeLiteral(v)}`);\n return { clause: parts.join(\" AND \"), values: [] };\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ACR,UAAU,oDAAoD,OAAO,KAAK,KAAK,cAAc,EAAE,KAAK,IAAI,IAC1G;AAAA,IACF;AAAA;AAEJ;AAIA,SAAS,aAAa,CAAC,OAAwB;AAAA,EAC7C,IAAI,UAAU,QAAQ,UAAU;AAAA,IAAW,OAAO;AAAA,EAClD,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU;AAAA,IAAU,OAAO,OAAO,KAAK;AAAA,EAC/E,IAAI,OAAO,UAAU;AAAA,IAAW,OAAO,QAAQ,SAAS;AAAA,EACxD,IAAI,OAAO,UAAU;AAAA,IAAU,OAAO,IAAI,KAAK,UAAU,KAAK,EAAE,QAAQ,MAAM,IAAI;AAAA,EAElF,OAAO,IAAI,OAAO,KAAK,EAAE,QAAQ,MAAM,IAAI;AAAA;AAG7C,SAAS,gBAAgB,CAAC,OAGxB;AAAA,EACA,MAAM,UAAU,OAAO,QAAQ,KAAK;AAAA,EACpC,IAAI,QAAQ,WAAW;AAAA,IAAG,OAAO,EAAE,QAAQ,QAAQ,QAAQ,CAAC,EAAE;AAAA,EAE9D,QAAQ,QAAQ,EAAE,OAAO,mBAAmB,CAAC,CAAC;AAAA,EAC9C,MAAM,QAAQ,QAAQ,IAAI,EAAE,GAAG,OAAO,IAAI,QAAQ,cAAc,CAAC,GAAG;AAAA,EACpE,OAAO,EAAE,QAAQ,MAAM,KAAK,OAAO,GAAG,QAAQ,CAAC,EAAE;AAAA;",
|
|
8
|
+
"debugId": "05A07F5B9890D95264756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Start the subgraph processor service.
|
|
3
|
+
* Listens for new blocks via NOTIFY and processes them through all active subgraphs.
|
|
4
|
+
*/
|
|
5
|
+
declare function startSubgraphProcessor(opts?: {
|
|
6
|
+
concurrency?: number
|
|
7
|
+
}): Promise<() => Promise<void>>;
|
|
8
|
+
export { startSubgraphProcessor };
|