@secondlayer/shared 15.0.2 → 15.0.4

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.
@@ -27,6 +27,16 @@ type InsightEvidence = {
27
27
  columns: string[]
28
28
  rows: (string | number)[][]
29
29
  markRow?: number
30
+ /** Label/value pairs shown under the table, e.g. "+15 more since 14:02". */
31
+ facts?: [string, string][]
32
+ } | {
33
+ /** What a receiver sent back: summary pairs, a body excerpt, then timing pairs. */
34
+ kind: "response"
35
+ title: string
36
+ sent: [string, string][]
37
+ /** At most 240 characters of the response body, whitespace collapsed. */
38
+ excerpt: string | null
39
+ facts: [string, string][]
30
40
  } | {
31
41
  kind: "shapes"
32
42
  title: string
@@ -190,6 +200,8 @@ declare function utcTime(date: Date): string;
190
200
  declare function utcDateTime(date: Date): string;
191
201
  /** "Oct 15" */
192
202
  declare function utcDay(date: Date): string;
203
+ /** "1 delivery", "851 deliveries", "3 days". A consonant before a final y
204
+ * takes "ies"; pass `many` for anything irregular. */
193
205
  declare function plural(n: number, one: string, many?: string): string;
194
206
  /** The host of a URL, or the input when it does not parse. */
195
207
  declare function hostOf(url: string): string;
@@ -25,7 +25,15 @@ var InsightEvidenceSchema = z.discriminatedUnion("kind", [
25
25
  title: z.string(),
26
26
  columns: z.array(z.string()),
27
27
  rows: z.array(z.array(z.union([z.string(), z.number()]))),
28
- markRow: z.number().optional()
28
+ markRow: z.number().optional(),
29
+ facts: z.array(z.tuple([z.string(), z.string()])).optional()
30
+ }),
31
+ z.object({
32
+ kind: z.literal("response"),
33
+ title: z.string(),
34
+ sent: z.array(z.tuple([z.string(), z.string()])),
35
+ excerpt: z.string().nullable(),
36
+ facts: z.array(z.tuple([z.string(), z.string()]))
29
37
  }),
30
38
  z.object({
31
39
  kind: z.literal("shapes"),
@@ -185,7 +193,7 @@ function utcDay(date) {
185
193
  });
186
194
  return `${month} ${date.getUTCDate()}`;
187
195
  }
188
- function plural(n, one, many = `${one}s`) {
196
+ function plural(n, one, many = /[^aeiou]y$/.test(one) ? `${one.slice(0, -1)}ies` : `${one}s`) {
189
197
  return `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
190
198
  }
191
199
  function hostOf(url) {
@@ -885,7 +893,14 @@ var CAUSE_QUESTIONS = {
885
893
  };
886
894
  var defaultCache = new Map;
887
895
  function cacheKey(insight) {
888
- const codes = insight.evidence.flatMap((e) => e.kind === "shapes" ? e.shapes.map((s) => s.code) : []).sort().join(",");
896
+ const codes = insight.evidence.flatMap((e) => {
897
+ if (e.kind === "shapes")
898
+ return e.shapes.map((s) => s.code);
899
+ if (e.kind === "response") {
900
+ return e.sent.filter(([key]) => key === "Status").map(([, v]) => v);
901
+ }
902
+ return [];
903
+ }).sort().join(",");
889
904
  return `${insight.resource.kind}:${insight.resource.id}:${insight.rule}:${codes}`;
890
905
  }
891
906
  function renderState(insight) {
@@ -992,6 +1007,35 @@ function bucketHourly(snapshots, hours, now = Date.now()) {
992
1007
  // src/insights/subgraph-rules.ts
993
1008
  var HOUR_MS2 = 3600000;
994
1009
  var ERROR_GROUPS_SHOWN = 3;
1010
+ function shortTx(txId) {
1011
+ return txId.length > 14 ? `${txId.slice(0, 6)}…${txId.slice(-4)}` : txId;
1012
+ }
1013
+ function failedEventsEvidence(groups, errors, now) {
1014
+ const rows = groups.map((g) => [
1015
+ g.sampleBlockHeight === null ? "unknown" : `#${g.sampleBlockHeight.toLocaleString("en-US")}`,
1016
+ g.sampleTxId ? shortTx(g.sampleTxId) : "unknown",
1017
+ plainSnippet(g.message, 60)
1018
+ ]);
1019
+ const windowStart = now.getTime() - 24 * HOUR_MS2;
1020
+ const since = new Date(Math.max(windowStart, Math.min(...groups.map((g) => g.firstSeen.getTime()))));
1021
+ const facts = [];
1022
+ if (errors > rows.length) {
1023
+ facts.push([`+${errors - rows.length} more since`, utcTime(since)]);
1024
+ }
1025
+ const lead = groups[0];
1026
+ if (lead) {
1027
+ facts.push(["Handler", lead.sourceName]);
1028
+ if (lead.frame)
1029
+ facts.push(["Where", lead.frame]);
1030
+ }
1031
+ return {
1032
+ kind: "table",
1033
+ title: "Events that failed",
1034
+ columns: ["Block", "Transaction", "Error"],
1035
+ rows,
1036
+ facts
1037
+ };
1038
+ }
995
1039
  function subject(name) {
996
1040
  return `My Secondlayer subgraph "${name}"`;
997
1041
  }
@@ -1029,18 +1073,7 @@ var handlerErrors = {
1029
1073
  `${plural(errors, "event")} failed inside your handler in the last 24 hours, and those rows were not written.`,
1030
1074
  leader ? `The most common error is: ${leaderText}${eventTypes.length > 0 ? ` (event type ${eventTypes[0]})` : ""}.` : ""
1031
1075
  ].filter(Boolean).join(" "),
1032
- evidence: top.length > 0 ? [
1033
- {
1034
- kind: "table",
1035
- title: "Most common errors",
1036
- columns: ["Error", "Event type", "Seen"],
1037
- rows: top.map((g) => [
1038
- plainSnippet(g.message, 120),
1039
- g.eventType ?? g.sourceName,
1040
- g.count
1041
- ])
1042
- }
1043
- ] : [],
1076
+ evidence: top.length > 0 ? [failedEventsEvidence(top, errors, input.now)] : [],
1044
1077
  handoff: {
1045
1078
  prompt: handoffPrompt({
1046
1079
  subject: subject(subgraph.name),
@@ -1159,7 +1192,8 @@ async function loadSubgraphInputs(db, now) {
1159
1192
  "total_processed"
1160
1193
  ]).where("captured_at", ">=", since).orderBy("captured_at", "asc").execute();
1161
1194
  const groups = await sql3`
1162
- SELECT subgraph_name, message, event_type, source_name, count, last_seen
1195
+ SELECT subgraph_name, message, event_type, source_name, count, first_seen,
1196
+ last_seen, sample_block_height, sample_tx_id, frame
1163
1197
  FROM subgraph_error_groups
1164
1198
  WHERE last_seen > ${new Date(now.getTime() - 24 * HOUR_MS2)}
1165
1199
  ORDER BY count DESC
@@ -1173,7 +1207,11 @@ async function loadSubgraphInputs(db, now) {
1173
1207
  eventType: g.event_type,
1174
1208
  sourceName: g.source_name,
1175
1209
  count: Number(g.count),
1176
- lastSeen: g.last_seen
1210
+ firstSeen: g.first_seen,
1211
+ lastSeen: g.last_seen,
1212
+ sampleBlockHeight: g.sample_block_height === null ? null : Number(g.sample_block_height),
1213
+ sampleTxId: g.sample_tx_id,
1214
+ frame: g.frame
1177
1215
  }))
1178
1216
  }));
1179
1217
  }
@@ -1185,6 +1223,7 @@ var DAY_MS = 86400000;
1185
1223
  var BUCKET_MS = 10 * MINUTE_MS;
1186
1224
  var BUCKETS = 36;
1187
1225
  var SHAPE_BODY_MAX = 80;
1226
+ var EXCERPT_MAX = 240;
1188
1227
  var SHAPES_MAX = 4;
1189
1228
  var ATTEMPT_WINDOW = 300;
1190
1229
  var ATTEMPT_LOOKBACK_DAYS = 8;
@@ -1258,22 +1297,54 @@ function resourceOf2(input) {
1258
1297
  name: input.webhook.name
1259
1298
  };
1260
1299
  }
1261
- function throughputEvidence(input) {
1262
- const { startMs, matched, delivered } = input.throughput;
1263
- const at = (i) => utcTime(new Date(startMs + i * BUCKET_MS)).slice(0, 5);
1300
+ function formatBytes(bytes) {
1301
+ if (bytes < 1024)
1302
+ return `${bytes} B`;
1303
+ return `${(bytes / 1024).toFixed(1)} KB`;
1304
+ }
1305
+ function formatDuration(ms) {
1306
+ return ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(1)} s`;
1307
+ }
1308
+ function bodyExcerpt(text) {
1309
+ if (!text)
1310
+ return null;
1311
+ const tidy = text.replace(/\r\n?/g, `
1312
+ `).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "").replace(/[ \t]+/g, " ").replace(/\n\s*\n+/g, `
1313
+ `).trim();
1314
+ if (tidy.length === 0)
1315
+ return null;
1316
+ return tidy.length > EXCERPT_MAX ? `${tidy.slice(0, EXCERPT_MAX - 1).trimEnd()}…` : tidy;
1317
+ }
1318
+ function responseEvidence(input, latest, firstFailureAt) {
1319
+ const sent = [
1320
+ ["Status", codeLabel(latest?.statusCode ?? null)]
1321
+ ];
1322
+ const type = latest?.contentType?.split(";")[0]?.trim();
1323
+ if (type)
1324
+ sent.push(["Type", type]);
1325
+ if (latest?.sizeBytes != null) {
1326
+ sent.push(["Size", formatBytes(latest.sizeBytes)]);
1327
+ }
1328
+ if (latest?.durationMs != null) {
1329
+ sent.push(["Took", formatDuration(latest.durationMs)]);
1330
+ }
1331
+ const { lastSuccessAt } = input.webhook;
1332
+ const facts = [
1333
+ ["Last success", lastSuccessAt ? utcDateTime(lastSuccessAt) : "never"],
1334
+ ["First failure", utcDateTime(firstFailureAt)]
1335
+ ];
1336
+ if (input.nextAttemptAt) {
1337
+ facts.push([
1338
+ "Next retry",
1339
+ input.nextAttemptAt.getTime() <= input.now.getTime() ? "now" : utcDateTime(input.nextAttemptAt)
1340
+ ]);
1341
+ }
1264
1342
  return {
1265
- kind: "series",
1266
- title: "Matched and delivered, every 10 minutes",
1267
- series: [
1268
- { name: "Matched", role: "context", points: matched },
1269
- { name: "Delivered", role: "a", points: delivered }
1270
- ],
1271
- labels: [
1272
- [0, at(0)],
1273
- [Math.floor(BUCKETS / 2), at(Math.floor(BUCKETS / 2))],
1274
- [BUCKETS - 1, "now"]
1275
- ],
1276
- unit: "events"
1343
+ kind: "response",
1344
+ title: "What your endpoint sent back",
1345
+ sent,
1346
+ excerpt: bodyExcerpt(latest?.body ?? latest?.errorMessage),
1347
+ facts
1277
1348
  };
1278
1349
  }
1279
1350
  function matchedPerHour(input) {
@@ -1317,7 +1388,6 @@ var receiverDown = {
1317
1388
  const hourly = matchedPerHour(input);
1318
1389
  const queued = input.pending;
1319
1390
  const flowing = hourly > 0 ? `Chain matches are normal (about ${hourly} an hour), so the problem is the receiver.` : "";
1320
- const shapes = buildShapes(streak, input.attempts.slice(streak.length), input.now);
1321
1391
  return {
1322
1392
  rule: "receiver_down",
1323
1393
  severity: "losing",
@@ -1331,10 +1401,7 @@ var receiverDown = {
1331
1401
  queued > 0 ? `${plural(queued, "delivery")} queued to retry.` : "",
1332
1402
  flowing
1333
1403
  ].filter(Boolean).join(" "),
1334
- evidence: [
1335
- throughputEvidence(input),
1336
- { kind: "shapes", title: "What the receiver sent back", shapes }
1337
- ],
1404
+ evidence: [responseEvidence(input, streak[0], since)],
1338
1405
  handoff: {
1339
1406
  prompt: handoffPrompt({
1340
1407
  subject: subject2(webhook.name),
@@ -1392,13 +1459,7 @@ var receiverRejects = {
1392
1459
  text ? `It said: ${text}.` : "",
1393
1460
  "It is reachable, so this is usually its auth or signature check."
1394
1461
  ].filter(Boolean).join(" "),
1395
- evidence: [
1396
- {
1397
- kind: "shapes",
1398
- title: "What the receiver sent back",
1399
- shapes: buildShapes(streak, input.attempts.slice(streak.length), input.now)
1400
- }
1401
- ],
1462
+ evidence: [responseEvidence(input, streak[0], since)],
1402
1463
  handoff: {
1403
1464
  prompt: handoffPrompt({
1404
1465
  subject: subject2(webhook.name),
@@ -2016,6 +2077,12 @@ async function fetchFunctionNames(contractId, baseUrl, apiKey, deps) {
2016
2077
  }
2017
2078
  }
2018
2079
  var num = (v) => v === null ? null : Number(v);
2080
+ var sizeOf = (v) => {
2081
+ if (v === null)
2082
+ return null;
2083
+ const n = Number(v);
2084
+ return Number.isInteger(n) && n >= 0 ? n : null;
2085
+ };
2019
2086
  async function loadWebhookInputs(db, now, abiDeps) {
2020
2087
  const nowMs = now.getTime();
2021
2088
  const webhooks = await db.selectFrom("webhooks").select([
@@ -2035,12 +2102,19 @@ async function loadWebhookInputs(db, now, abiDeps) {
2035
2102
  const lookback = new Date(nowMs - ATTEMPT_LOOKBACK_DAYS * DAY_MS);
2036
2103
  const attemptRows = await sql4`
2037
2104
  SELECT webhook_id, outbox_id, status_code, duration_ms, dispatched_at,
2038
- error_message, body, content_type, server, retry_after, block_height
2105
+ error_message, body, content_type, size_bytes, server, retry_after,
2106
+ block_height
2039
2107
  FROM (
2040
2108
  SELECT d.webhook_id, d.outbox_id, d.status_code, d.duration_ms,
2041
2109
  d.dispatched_at, d.error_message,
2042
- left(d.response_body, 200) AS body,
2110
+ left(d.response_body, 240) AS body,
2043
2111
  d.response_headers ->> 'content-type' AS content_type,
2112
+ -- The stored body is cut at 8192 bytes: its length only counts when it was not.
2113
+ coalesce(
2114
+ d.response_headers ->> 'content-length',
2115
+ CASE WHEN octet_length(d.response_body) < 8192
2116
+ THEN octet_length(d.response_body)::text END
2117
+ ) AS size_bytes,
2044
2118
  d.response_headers ->> 'server' AS server,
2045
2119
  d.response_headers ->> 'retry-after' AS retry_after,
2046
2120
  o.block_height,
@@ -2071,7 +2145,8 @@ async function loadWebhookInputs(db, now, abiDeps) {
2071
2145
  GROUP BY 1, 2
2072
2146
  `.execute(db);
2073
2147
  const pendingRows = await sql4`
2074
- SELECT webhook_id, count(*) AS n FROM webhook_outbox
2148
+ SELECT webhook_id, count(*) AS n, min(next_attempt_at) AS next_attempt_at
2149
+ FROM webhook_outbox
2075
2150
  WHERE status = 'pending' GROUP BY 1
2076
2151
  `.execute(db);
2077
2152
  const dayStart = Math.floor(nowMs / DAY_MS) * DAY_MS - (SLOWING_DAYS - 1) * DAY_MS;
@@ -2107,6 +2182,7 @@ async function loadWebhookInputs(db, now, abiDeps) {
2107
2182
  errorMessage: r.error_message,
2108
2183
  body: r.body,
2109
2184
  contentType: r.content_type,
2185
+ sizeBytes: sizeOf(r.size_bytes),
2110
2186
  server: r.server,
2111
2187
  retryAfter: r.retry_after,
2112
2188
  blockHeight: num(r.block_height)
@@ -2127,6 +2203,7 @@ async function loadWebhookInputs(db, now, abiDeps) {
2127
2203
  const matchedBy = series(matchedRows.rows);
2128
2204
  const deliveredBy = series(deliveredRows.rows);
2129
2205
  const pendingBy = new Map(pendingRows.rows.map((r) => [r.webhook_id, Number(r.n)]));
2206
+ const nextAttemptBy = new Map(pendingRows.rows.map((r) => [r.webhook_id, r.next_attempt_at]));
2130
2207
  const countBy = new Map(deliveryCountRows.rows.map((r) => [r.webhook_id, Number(r.n)]));
2131
2208
  const deadBy = new Map(deadRows.rows.map((r) => [r.webhook_id, r]));
2132
2209
  const p95By = new Map;
@@ -2184,6 +2261,7 @@ async function loadWebhookInputs(db, now, abiDeps) {
2184
2261
  },
2185
2262
  attempts: attemptsBy.get(w.id) ?? [],
2186
2263
  pending: pendingBy.get(w.id) ?? 0,
2264
+ nextAttemptAt: nextAttemptBy.get(w.id) ?? null,
2187
2265
  throughput: {
2188
2266
  startMs,
2189
2267
  matched: matchedBy.get(w.id) ?? new Array(BUCKETS).fill(0),
@@ -2344,5 +2422,5 @@ export {
2344
2422
  utcTime
2345
2423
  };
2346
2424
 
2347
- //# debugId=43EF1744AA425D2F64756E2164756E21
2425
+ //# debugId=A21ED385DD61B76864756E2164756E21
2348
2426
  //# sourceMappingURL=index.js.map