@secondlayer/subgraphs 3.9.0 → 3.11.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/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Typed on-chain indexing for Stacks. Declare event filters + column schema with `defineSubgraph()`; the runtime decodes blocks, matches filters, runs your handlers inside a transactional context, and exposes the result as a Postgres schema you query over REST or SQL.
4
4
 
5
+ Subgraphs have a visibility: managed deploys default `visibility: public` — anon-readable at `/v1/subgraphs/<name>/<table>`, in a single global public namespace claimed on publish (409 `PUBLIC_NAME_TAKEN` if the name is taken). BYO-database deploys default private. Override with `--visibility public|private` at deploy, or flip later with `sl subgraphs publish|unpublish <name>`.
6
+
5
7
  Subgraph rows fan out to HTTP subscribers through a post-flush outbox emitter — signed Standard Webhooks POSTs with retries, circuit breaker, and replay.
6
8
 
7
9
  ## Install
@@ -114,6 +116,9 @@ reads from there. Deploy with a connection string:
114
116
  sl subgraphs deploy subgraphs/my.ts --database-url "postgres://user:pass@your-host:5432/db"
115
117
  ```
116
118
 
119
+ BYO deploys default `visibility: private` (managed deploys default public);
120
+ pass `--visibility public` or `sl subgraphs publish <name>` to open reads.
121
+
117
122
  The connection string is stored encrypted at rest (AES-GCM, keyed by
118
123
  `SECONDLAYER_SECRETS_KEY`) and never returned in API responses. The server
119
124
  verifies the connection before deploying. Once deployed, query the
@@ -130,8 +135,13 @@ script and verifies the connection — without writing anything.
130
135
  transaction, so a crash replays the block (at-least-once). `ctx.insert` and
131
136
  `ctx.upsert` (with a unique key) are safe — flush is replace-per-height. A
132
137
  deploy with non-idempotent `ctx.update` / `ctx.patchOrInsert` is rejected.
133
- - **No reindex.** Reindex would drop + rebuild the schema in your DB from a
134
- background job; instead, re-deploy to rebuild (or drop the schema yourself).
138
+ - **No reindex.** A breaking change (removed table/column, changed type, or a
139
+ forced reindex) would drop + rebuild the schema in your DB, so the deploy is
140
+ refused with HTTP `422` — nothing is touched. The refusal carries a migration
141
+ plan: the SDK throws a typed `ByoBreakingChangeError` (`details.reasons` +
142
+ `details.plan` with `dropStatement`/`statements`/`grantScript`) and the CLI
143
+ prints the exact `DROP SCHEMA … CASCADE` + rebuild DDL to run yourself, then
144
+ re-deploy. A destructive `--force` rebuild on your DB is not yet supported.
135
145
  - **Delete leaves your data.** Deleting the subgraph removes our registry row
136
146
  (and the stored connection) and pauses subscriptions, but never drops the
137
147
  schema in your database.
@@ -707,6 +707,7 @@ declare function generateIndexSchema(target: IndexCodegenTarget, opts?: IndexCod
707
707
  declare const INDEX_CODEGEN_TABLES: readonly string[];
708
708
  import { pgSchemaName } from "@secondlayer/shared/db/queries/subgraphs";
709
709
  import { Database } from "@secondlayer/shared/db";
710
+ import { ByoBreakingChangeDetails } from "@secondlayer/shared/errors";
710
711
  import { Kysely } from "kysely";
711
712
  type AnyDb = Kysely<Database>;
712
713
  interface TableDiff {
@@ -732,8 +733,28 @@ interface DeployDiff {
732
733
  addedColumns: Record<string, string[]>;
733
734
  breakingChanges: string[];
734
735
  }
736
+ interface ByoMigrationPlan {
737
+ schemaName: string;
738
+ dropStatement: string;
739
+ statements: string[];
740
+ grantScript: string;
741
+ }
742
+ /**
743
+ * Thrown when a BYO subgraph deploy is refused for a breaking schema change.
744
+ * Plain `Error` with a literal `code` (not `SecondLayerError`) so the API
745
+ * middleware matches it by code across bundle boundaries — bunup duplicates
746
+ * classes per package, breaking cross-bundle `instanceof`. The refusal stands;
747
+ * `details` carries the reviewable DROP + rebuild the user must run manually.
748
+ */
749
+ declare class ByoBreakingChangeError extends Error {
750
+ readonly code: "BYO_BREAKING_CHANGE";
751
+ readonly details: ByoBreakingChangeDetails;
752
+ constructor(reasons: string[], diff: DeployDiff, plan: ByoMigrationPlan);
753
+ }
735
754
  interface DeployPlan {
736
755
  schemaName: string;
756
+ /** `DROP SCHEMA … CASCADE` a destructive rebuild would run first (shown, never auto-run on BYO). */
757
+ dropStatement: string;
737
758
  /** DDL Secondlayer will run against your database. */
738
759
  statements: string[];
739
760
  /** Least-privilege grant script to run once, before deploying. */
@@ -773,4 +794,4 @@ declare function deploySchema(db: AnyDb, def: SubgraphDefinition, handlerPath: s
773
794
  version: string
774
795
  diff?: DeployDiff
775
796
  }>;
776
- export { validateSubgraphDefinition, resumeReindex, renderDeployPlan, reindexSubgraph, pgSchemaName, generateSubgraphSQL, generatePrismaSchema, generateKyselySchema, generateIndexSchema, generateDrizzleSchema, diffSchema, deploySchema, defineSubgraph, backfillSubgraph, WriteRow, WhereInput, TypedSubgraphDefinition, TypedSubgraphContext, TypedHandlers, TxMeta, TableDiff, SystemRow, SubscribeOptions, SubgraphTableClient, SubgraphTable, SubgraphSchema, SubgraphHandler, SubgraphFilter, SubgraphDefinition, SubgraphContext, SubgraphColumn, StxTransferPayload, StxTransferFilter, StxMintPayload, StxMintFilter, StxLockPayload, StxLockFilter, StxBurnPayload, StxBurnFilter, RowValue, ReindexOptions, PrismaGenOptions, PrintEventPayload, PrintEventFor, PrintEventFilter, NftTransferPayload, NftTransferFilter, NftMintPayload, NftMintFilter, NftBurnPayload, NftBurnFilter, KyselyGenOptions, InferTableRow, InferSubgraphClient, InferColumnType, IndexCodegenTarget, IndexCodegenOptions, INDEX_CODEGEN_TABLES, GeneratedSQL, FtTransferPayload, FtTransferFilter, FtMintPayload, FtMintFilter, FtBurnPayload, FtBurnFilter, FindManyOptions, EventForFilter, DrizzleGenOptions, DeployPlan, ContractDeployPayload, ContractDeployFilter, ContractCallPayload, ContractCallFilter, ContractCallEvent, ComputedValue, ComparisonFilter, ColumnType, ColumnToTS, ColumnDiff, AnyEvent, AggregateSpec, AggregateResult };
797
+ export { validateSubgraphDefinition, resumeReindex, renderDeployPlan, reindexSubgraph, pgSchemaName, generateSubgraphSQL, generatePrismaSchema, generateKyselySchema, generateIndexSchema, generateDrizzleSchema, diffSchema, deploySchema, defineSubgraph, backfillSubgraph, WriteRow, WhereInput, TypedSubgraphDefinition, TypedSubgraphContext, TypedHandlers, TxMeta, TableDiff, SystemRow, SubscribeOptions, SubgraphTableClient, SubgraphTable, SubgraphSchema, SubgraphHandler, SubgraphFilter, SubgraphDefinition, SubgraphContext, SubgraphColumn, StxTransferPayload, StxTransferFilter, StxMintPayload, StxMintFilter, StxLockPayload, StxLockFilter, StxBurnPayload, StxBurnFilter, RowValue, ReindexOptions, PrismaGenOptions, PrintEventPayload, PrintEventFor, PrintEventFilter, NftTransferPayload, NftTransferFilter, NftMintPayload, NftMintFilter, NftBurnPayload, NftBurnFilter, KyselyGenOptions, InferTableRow, InferSubgraphClient, InferColumnType, IndexCodegenTarget, IndexCodegenOptions, INDEX_CODEGEN_TABLES, GeneratedSQL, FtTransferPayload, FtTransferFilter, FtMintPayload, FtMintFilter, FtBurnPayload, FtBurnFilter, FindManyOptions, EventForFilter, DrizzleGenOptions, DeployPlan, DeployDiff, ContractDeployPayload, ContractDeployFilter, ContractCallPayload, ContractCallFilter, ContractCallEvent, ComputedValue, ComparisonFilter, ColumnType, ColumnToTS, ColumnDiff, ByoMigrationPlan, ByoBreakingChangeError, AnyEvent, AggregateSpec, AggregateResult };
package/dist/src/index.js CHANGED
@@ -1195,6 +1195,28 @@ function reconstructEvent(e) {
1195
1195
  }
1196
1196
 
1197
1197
  // src/runtime/block-source.ts
1198
+ function canSparseScan(subgraph) {
1199
+ if (Array.isArray(subgraph.sources))
1200
+ return false;
1201
+ const filters = sourceFilters(subgraph);
1202
+ if (filters.length === 0)
1203
+ return false;
1204
+ return filters.every((f) => Boolean(EVENT_FILTER_TO_INDEX_TYPE[f.type]));
1205
+ }
1206
+ function sparseProbeTargets(subgraph) {
1207
+ const targets = new Map;
1208
+ for (const f of sourceFilters(subgraph)) {
1209
+ const eventType = EVENT_FILTER_TO_INDEX_TYPE[f.type];
1210
+ if (!eventType)
1211
+ continue;
1212
+ const scoped = f;
1213
+ const contractId = scoped.contractId ?? scoped.assetIdentifier?.split("::")[0];
1214
+ const key = `${eventType}|${contractId ?? ""}`;
1215
+ targets.set(key, { eventType, ...contractId ? { contractId } : {} });
1216
+ }
1217
+ return [...targets.values()];
1218
+ }
1219
+
1198
1220
  class PostgresBlockSource {
1199
1221
  async getTip() {
1200
1222
  const progress = await getSourceDb().selectFrom("index_progress").selectAll().where("network", "=", process.env.NETWORK ?? "mainnet").executeTakeFirst();
@@ -1257,9 +1279,18 @@ function isStreamsIndexEligible(subgraph) {
1257
1279
  class PublicApiBlockSource {
1258
1280
  http;
1259
1281
  eventTypes;
1260
- constructor(http, eventTypes) {
1282
+ probeTargets;
1283
+ constructor(http, eventTypes, probeTargets) {
1261
1284
  this.http = http;
1262
1285
  this.eventTypes = eventTypes;
1286
+ this.probeTargets = probeTargets;
1287
+ }
1288
+ async nextDataHeight(afterHeight, untilHeight) {
1289
+ if (!this.probeTargets?.length)
1290
+ return afterHeight + 1;
1291
+ const hits = await Promise.all(this.probeTargets.map((t) => this.http.firstEventHeight(t.eventType, afterHeight + 1, untilHeight, t.contractId)));
1292
+ const found = hits.filter((h) => h !== null);
1293
+ return found.length ? Math.min(...found) : null;
1263
1294
  }
1264
1295
  getTip() {
1265
1296
  return this.http.getIndexTip();
@@ -1323,6 +1354,15 @@ class FallbackBlockSource {
1323
1354
  return this.fallback.loadBlockRange(fromHeight, toHeight);
1324
1355
  }
1325
1356
  }
1357
+ async nextDataHeight(afterHeight, untilHeight) {
1358
+ if (!this.primary.nextDataHeight)
1359
+ return afterHeight + 1;
1360
+ try {
1361
+ return await this.primary.nextDataHeight(afterHeight, untilHeight);
1362
+ } catch {
1363
+ return afterHeight + 1;
1364
+ }
1365
+ }
1326
1366
  }
1327
1367
  var postgresBlockSource = new PostgresBlockSource;
1328
1368
  function buildHttpClient() {
@@ -1335,7 +1375,7 @@ function buildHttpClient() {
1335
1375
  }
1336
1376
  function resolveBlockSource(subgraph) {
1337
1377
  if (process.env.SUBGRAPH_SOURCE === "streams-index" && subgraph && isStreamsIndexEligible(subgraph)) {
1338
- return new FallbackBlockSource(new PublicApiBlockSource(buildHttpClient(), referencedIndexEventTypes(subgraph)), postgresBlockSource);
1378
+ return new FallbackBlockSource(new PublicApiBlockSource(buildHttpClient(), referencedIndexEventTypes(subgraph), canSparseScan(subgraph) ? sparseProbeTargets(subgraph) : undefined), postgresBlockSource);
1339
1379
  }
1340
1380
  if (process.env.SUBGRAPH_SOURCE === "streams-index" && subgraph) {
1341
1381
  logger3.debug("Subgraph not streams-index eligible, using DB tap", {
@@ -2005,6 +2045,7 @@ async function processBlockRange(def, opts) {
2005
2045
  let batchSize = batchConfig.defaultBatchSize;
2006
2046
  let currentHeight = fromBlock;
2007
2047
  let aborted = false;
2048
+ const sparse = Boolean(source.nextDataHeight && canSparseScan(def));
2008
2049
  const flushHealth = async () => {
2009
2050
  if (pendingEventsProcessed === 0 && pendingErrors === 0)
2010
2051
  return;
@@ -2035,6 +2076,7 @@ async function processBlockRange(def, opts) {
2035
2076
  nextBatchPromise = source.loadBlockRange(nextStart, nextBatchEnd);
2036
2077
  }
2037
2078
  const batchFailedBlocks = [];
2079
+ let batchMatched = 0;
2038
2080
  for (let height = currentHeight;height <= batchEnd; height++) {
2039
2081
  const blockData = batch.get(height);
2040
2082
  if (!blockData) {
@@ -2064,6 +2106,7 @@ async function processBlockRange(def, opts) {
2064
2106
  continue;
2065
2107
  }
2066
2108
  blocksProcessed++;
2109
+ batchMatched += result.matched;
2067
2110
  totalEventsProcessed += result.processed;
2068
2111
  totalErrors += result.errors;
2069
2112
  pendingEventsProcessed += result.processed;
@@ -2109,6 +2152,27 @@ async function processBlockRange(def, opts) {
2109
2152
  });
2110
2153
  });
2111
2154
  }
2155
+ if (sparse && batchMatched === 0 && batchEnd < toBlock && source.nextDataHeight) {
2156
+ const next = await source.nextDataHeight(batchEnd, toBlock);
2157
+ const jumpTo = next === null ? toBlock + 1 : Math.max(next, batchEnd + 1);
2158
+ if (jumpTo > batchEnd + 1) {
2159
+ const skipped = Math.min(jumpTo, toBlock + 1) - (batchEnd + 1);
2160
+ blocksProcessed += skipped;
2161
+ await updateSubgraphStatus2(targetDb, subgraphName, status, jumpTo - 1);
2162
+ logger6.info("Sparse skip", {
2163
+ subgraph: subgraphName,
2164
+ from: batchEnd + 1,
2165
+ to: jumpTo - 1,
2166
+ skipped
2167
+ });
2168
+ currentHeight = jumpTo;
2169
+ if (currentHeight <= toBlock) {
2170
+ nextBatchEnd = Math.min(currentHeight + batchSize - 1, toBlock);
2171
+ nextBatchPromise = source.loadBlockRange(currentHeight, nextBatchEnd);
2172
+ }
2173
+ continue;
2174
+ }
2175
+ }
2112
2176
  const avg = avgEventsPerBlock(batch);
2113
2177
  if (avg > 50)
2114
2178
  batchSize = Math.max(Math.round(batchSize * 0.5), batchConfig.minBatchSize);
@@ -2961,10 +3025,29 @@ function bumpPatch(version) {
2961
3025
  const patch = Number.parseInt(parts[2] ?? "0", 10);
2962
3026
  return `${parts[0]}.${parts[1]}.${Number.isNaN(patch) ? 1 : patch + 1}`;
2963
3027
  }
3028
+
3029
+ class ByoBreakingChangeError extends Error {
3030
+ code = "BYO_BREAKING_CHANGE";
3031
+ details;
3032
+ constructor(reasons, diff, plan) {
3033
+ super("Breaking schema change on a BYO subgraph would drop data in your " + "database. Review the plan and run the DROP + rebuild DDL manually.");
3034
+ this.name = "ByoBreakingChangeError";
3035
+ this.details = { reasons, diff, plan };
3036
+ }
3037
+ }
3038
+ function toDeployDiff(diff, reasons) {
3039
+ return {
3040
+ addedTables: diff?.addedTables ?? [],
3041
+ removedTables: diff?.removedTables ?? [],
3042
+ addedColumns: diff ? Object.fromEntries(Object.entries(diff.tables).filter(([, c]) => c.added.length > 0).map(([t, c]) => [t, c.added])) : {},
3043
+ breakingChanges: reasons
3044
+ };
3045
+ }
2964
3046
  function renderDeployPlan(def, schemaName) {
2965
3047
  validateSubgraphDefinition(def);
2966
3048
  const { statements } = generateSubgraphSQL(def, schemaName);
2967
3049
  const schema = schemaName ?? pgSchemaName(def.name);
3050
+ const dropStatement = `DROP SCHEMA IF EXISTS "${schema}" CASCADE;`;
2968
3051
  const grantScript = [
2969
3052
  "-- Run once on YOUR database as an owner/superuser, replacing <role>",
2970
3053
  "-- with the role whose credentials you give Secondlayer.",
@@ -2973,7 +3056,7 @@ function renderDeployPlan(def, schemaName) {
2973
3056
  `-- (after first deploy <role> owns "${schema}"; no further grants needed)`
2974
3057
  ].join(`
2975
3058
  `);
2976
- return { schemaName: schema, statements, grantScript };
3059
+ return { schemaName: schema, dropStatement, statements, grantScript };
2977
3060
  }
2978
3061
  async function deploySchema(db, def, handlerPath, opts) {
2979
3062
  validateSubgraphDefinition(def);
@@ -2981,8 +3064,14 @@ async function deploySchema(db, def, handlerPath, opts) {
2981
3064
  const { getSubgraph, registerSubgraph } = await import("@secondlayer/shared/db/queries/subgraphs");
2982
3065
  const ddlDb = opts?.dataDb ?? db;
2983
3066
  const byo = opts?.dataDb != null;
2984
- const refuseDestructiveOnByo = (reason) => {
2985
- throw new Error(`Breaking schema change on a BYO subgraph (${reason}) would drop data in your database. Drop the schema "${opts?.schemaName ?? pgSchemaName(def.name)}" manually and re-deploy to rebuild.`);
3067
+ const refuseDestructiveOnByo = (reasons, diff) => {
3068
+ const plan = renderDeployPlan(def, opts?.schemaName);
3069
+ throw new ByoBreakingChangeError(reasons, toDeployDiff(diff, reasons), {
3070
+ schemaName: plan.schemaName,
3071
+ dropStatement: plan.dropStatement,
3072
+ statements: plan.statements,
3073
+ grantScript: plan.grantScript
3074
+ });
2986
3075
  };
2987
3076
  const existing = await getSubgraph(db, def.name, opts?.accountId);
2988
3077
  const schemaName = opts?.schemaName ?? pgSchemaName(def.name);
@@ -3037,7 +3126,7 @@ async function deploySchema(db, def, handlerPath, opts) {
3037
3126
  }
3038
3127
  if (existing.schema_hash === hash && opts?.forceReindex) {
3039
3128
  if (byo)
3040
- refuseDestructiveOnByo("force reindex");
3129
+ refuseDestructiveOnByo(["force reindex"], null);
3041
3130
  await sql4.raw(`DROP SCHEMA IF EXISTS "${schemaName}" CASCADE`).execute(ddlDb);
3042
3131
  for (const stmt of statements) {
3043
3132
  await sql4.raw(stmt).execute(ddlDb);
@@ -3050,19 +3139,14 @@ async function deploySchema(db, def, handlerPath, opts) {
3050
3139
  const { breaking, reasons } = hasBreakingChanges(diff);
3051
3140
  if (breaking || opts?.forceReindex) {
3052
3141
  if (byo) {
3053
- refuseDestructiveOnByo(reasons.length > 0 ? reasons.join("; ") : "force reindex");
3142
+ refuseDestructiveOnByo(reasons.length > 0 ? reasons : ["force reindex"], diff);
3054
3143
  }
3055
3144
  await sql4.raw(`DROP SCHEMA IF EXISTS "${schemaName}" CASCADE`).execute(ddlDb);
3056
3145
  for (const stmt of statements) {
3057
3146
  await sql4.raw(stmt).execute(ddlDb);
3058
3147
  }
3059
3148
  const sg3 = await registerSubgraph(db, regData);
3060
- const deployDiff2 = {
3061
- addedTables: diff.addedTables,
3062
- removedTables: diff.removedTables,
3063
- addedColumns: Object.fromEntries(Object.entries(diff.tables).filter(([, c]) => c.added.length > 0).map(([t, c]) => [t, c.added])),
3064
- breakingChanges: reasons
3065
- };
3149
+ const deployDiff2 = toDeployDiff(diff, reasons);
3066
3150
  return {
3067
3151
  action: "reindexed",
3068
3152
  subgraphId: sg3.id,
@@ -3167,8 +3251,9 @@ export {
3167
3251
  deploySchema,
3168
3252
  defineSubgraph,
3169
3253
  backfillSubgraph,
3170
- INDEX_CODEGEN_TABLES
3254
+ INDEX_CODEGEN_TABLES,
3255
+ ByoBreakingChangeError
3171
3256
  };
3172
3257
 
3173
- //# debugId=822BF312943996F964756E2164756E21
3258
+ //# debugId=9A94DC6E9FCF6CD964756E2164756E21
3174
3259
  //# sourceMappingURL=index.js.map