@substrat-run/control-plane-api 0.159.0 → 0.161.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.
Files changed (68) hide show
  1. package/dist/api.d.ts +33 -1
  2. package/dist/api.d.ts.map +1 -1
  3. package/dist/api.js +674 -63
  4. package/dist/api.js.map +1 -1
  5. package/dist/browser.d.ts +2 -2
  6. package/dist/browser.d.ts.map +1 -1
  7. package/dist/browser.js +2 -1
  8. package/dist/browser.js.map +1 -1
  9. package/dist/cf-observability.d.ts +30 -0
  10. package/dist/cf-observability.d.ts.map +1 -1
  11. package/dist/cf-observability.js +304 -99
  12. package/dist/cf-observability.js.map +1 -1
  13. package/dist/custom-hostnames.d.ts +30 -0
  14. package/dist/custom-hostnames.d.ts.map +1 -1
  15. package/dist/custom-hostnames.js +25 -2
  16. package/dist/custom-hostnames.js.map +1 -1
  17. package/dist/deploy.d.ts +3 -0
  18. package/dist/deploy.d.ts.map +1 -1
  19. package/dist/deploy.js.map +1 -1
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +3 -1
  22. package/dist/errors.js.map +1 -1
  23. package/dist/index.d.ts +7 -5
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +6 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/observability.d.ts +29 -2
  28. package/dist/observability.d.ts.map +1 -1
  29. package/dist/observability.js +8 -0
  30. package/dist/observability.js.map +1 -1
  31. package/dist/platform-drain.d.ts +26 -2
  32. package/dist/platform-drain.d.ts.map +1 -1
  33. package/dist/platform-drain.js +297 -119
  34. package/dist/platform-drain.js.map +1 -1
  35. package/dist/platform-entry.generated.d.ts +2 -2
  36. package/dist/platform-entry.generated.d.ts.map +1 -1
  37. package/dist/platform-entry.generated.js +5 -5
  38. package/dist/platform-entry.generated.js.map +1 -1
  39. package/dist/platform-wire.d.ts +51 -0
  40. package/dist/platform-wire.d.ts.map +1 -0
  41. package/dist/platform-wire.js +163 -0
  42. package/dist/platform-wire.js.map +1 -0
  43. package/dist/scope-copy-backfill.d.ts.map +1 -1
  44. package/dist/scope-copy-backfill.js +22 -9
  45. package/dist/scope-copy-backfill.js.map +1 -1
  46. package/dist/scope-copy-cleanup.js +1 -1
  47. package/dist/scope-copy-cleanup.js.map +1 -1
  48. package/dist/staff-client.d.ts +38 -2
  49. package/dist/staff-client.d.ts.map +1 -1
  50. package/dist/staff-client.js +24 -1
  51. package/dist/staff-client.js.map +1 -1
  52. package/dist/vertical-client.d.ts +116 -4
  53. package/dist/vertical-client.d.ts.map +1 -1
  54. package/dist/vertical-client.js +366 -25
  55. package/dist/vertical-client.js.map +1 -1
  56. package/dist/wire-settings.d.ts +77 -0
  57. package/dist/wire-settings.d.ts.map +1 -0
  58. package/dist/wire-settings.js +155 -0
  59. package/dist/wire-settings.js.map +1 -0
  60. package/dist/wire-upload.d.ts +100 -0
  61. package/dist/wire-upload.d.ts.map +1 -0
  62. package/dist/wire-upload.js +141 -0
  63. package/dist/wire-upload.js.map +1 -0
  64. package/dist/wire-walk.d.ts +140 -0
  65. package/dist/wire-walk.d.ts.map +1 -0
  66. package/dist/wire-walk.js +339 -0
  67. package/dist/wire-walk.js.map +1 -0
  68. package/package.json +10 -10
@@ -4,7 +4,8 @@ import { cachedSource, cutOverSource } from './aggregate-source.js';
4
4
  import { stableDeploymentRefFor } from './deploy.js';
5
5
  import { aggregateReads } from './aggregate-reads.js';
6
6
  import { serviceFamilyPattern } from './service-family.js';
7
- import { FIELD_COVERAGE_ID_FIELD, ROUTER_SCRIPT_NAMES } from '@substrat-run/contracts';
7
+ import { FIELD_COVERAGE_ID_FIELD, ROUTER_REQUEST_POINT, ROUTER_SCRIPT_NAMES, utcDay } from '@substrat-run/contracts';
8
+ import { RequestRollupSaturated } from '@substrat-run/kernel';
8
9
  import { readFieldCoverage } from './field-coverage-read.js';
9
10
  import { TENANT_METRICS_LIMIT, REQUEST_FACET_KEYS, INVOCATION_KINDS, invocationKindOf, outboundCallsOf } from './observability.js';
10
11
  /**
@@ -192,6 +193,16 @@ function requestRecordOf(e) {
192
193
  */
193
194
  const MAX_CORRELATED_INVOCATIONS = 40;
194
195
  const MAX_LINES_PER_INVOCATION = 20;
196
+ /**
197
+ * How a service-grain read (`queryEvents`) is bounded while it fills its page after the wire line
198
+ * is left out: at most this many rounds of queries (the first round is one per service), and at
199
+ * most `MAX_FILL_QUERIES` queries past that first round in all, whatever the number of services.
200
+ * A page loses at most about a third to the wire line, so one more query nearly always fills it;
201
+ * the bounds keep a window of almost nothing else, or a read across many services, from costing
202
+ * more than a few.
203
+ */
204
+ const MAX_FILL_ROUNDS = 4;
205
+ const MAX_FILL_QUERIES = 8;
195
206
  /**
196
207
  * #1877: the groups one telemetry answer carries, and how many pages of them a span may
197
208
  * take. Past the cap a span is refused rather than cached in part.
@@ -442,6 +453,38 @@ function withoutOutputFields(e) {
442
453
  const { outputFields: _report, [FIELD_COVERAGE_ID_FIELD]: _id, ...rest } = source;
443
454
  return { ...e, source: rest };
444
455
  }
456
+ /**
457
+ * The events of a telemetry `events` answer, as every reader in this module receives them.
458
+ *
459
+ * The list is unwrapped: the view has nested it one level deeper across API revisions, so
460
+ * both shapes are accepted rather than pinning whichever was current at writing. And the
461
+ * platform's wire-signing line (`substrat: 'wire'`, RFC wire-signing §8) is left out, here
462
+ * and only here, so no reader can return one: it is the platform's counter, it carries a
463
+ * refusal's reason, and it shares a request's id, which is how a tenant's view finds the
464
+ * lines it shows. No reader today needs it; one that does (the readiness report, RFC §10
465
+ * follow-on 4) is to read it through a query of its own that opts in by name.
466
+ *
467
+ * The line is left out AFTER the backend spent its `limit` on it, because no filter of the
468
+ * telemetry API is known to keep the lines that lack the key it negates. So beside the events go
469
+ * the size of what the backend returned (`fetched`) and its oldest timestamp, never a line of it:
470
+ * a reader judges a full page (more may exist) by those, and asks again for what the filter took
471
+ * (`queryEvents`, and the tenant view's per-request read).
472
+ */
473
+ function telemetryPage(result) {
474
+ const outer = result?.events;
475
+ const all = (Array.isArray(outer) ? outer : (outer?.events ?? []));
476
+ let oldest = null;
477
+ for (const e of all) {
478
+ const t = e['timestamp'];
479
+ if (typeof t === 'number' && (oldest === null || t < oldest))
480
+ oldest = t;
481
+ }
482
+ return {
483
+ events: all.filter((e) => (e['source'] ?? {})['substrat'] !== 'wire'),
484
+ fetched: all.length,
485
+ oldest,
486
+ };
487
+ }
445
488
  /**
446
489
  * One backend event → the seam's neutral `RecentLogEvent`.
447
490
  *
@@ -698,21 +741,22 @@ export function createCfObservabilityReader(opts) {
698
741
  const pending = inFlight.get(key);
699
742
  if (pending)
700
743
  return pending;
744
+ const p = ROUTER_REQUEST_POINT;
701
745
  const sql = `
702
746
  SELECT
703
- blob1 AS vertical,
704
- blob2 AS scopeId,
705
- blob3 AS surface,
706
- double2 AS status,
707
- blob6 AS operation,
708
- blob7 AS problemCode,
709
- blob8 AS principalKind,
710
- blob9 AS level,
747
+ ${p.vertical} AS vertical,
748
+ ${p.scopeId} AS scopeId,
749
+ ${p.surface} AS surface,
750
+ ${p.status} AS status,
751
+ ${p.operation} AS operation,
752
+ ${p.problemCode} AS problemCode,
753
+ ${p.principalKind} AS principalKind,
754
+ ${p.level} AS level,
711
755
  toStartOfInterval(timestamp, INTERVAL '${grainSeconds}' SECOND) AS bucket,
712
756
  sum(_sample_interval) AS requests,
713
757
  max(_sample_interval) AS maxInterval
714
758
  FROM ${aeDataset(dataset)}
715
- WHERE index1 = ${aeLiteral(tenantId)}
759
+ WHERE ${p.tenantId} = ${aeLiteral(tenantId)}
716
760
  AND timestamp >= toDateTime(${Math.floor(q.from / 1000)})
717
761
  AND timestamp < toDateTime(${Math.ceil(q.to / 1000)})
718
762
  GROUP BY vertical, scopeId, surface, status, operation, problemCode, principalKind, level, bucket
@@ -909,14 +953,7 @@ export function createCfObservabilityReader(opts) {
909
953
  // single-valued equality, and an OR across script names is not a filter this
910
954
  // API offers. The queries are independent, so they run concurrently and the
911
955
  // merge (not the backend) enforces the overall `limit`.
912
- if (services && services.length > 1) {
913
- const pages = await Promise.all(services.map((s) => queryEvents(s, level, search, hours, limit)));
914
- return pages
915
- .flat()
916
- .sort((a, b) => (b.timestamp ?? 0) - (a.timestamp ?? 0))
917
- .slice(0, limit);
918
- }
919
- return queryEvents(services?.[0], level, search, hours, limit);
956
+ return queryEvents(services && services.length > 1 ? services : [services?.[0]], level, search, hours, limit);
920
957
  },
921
958
  // Present only when the caller named the router's dataset: with no dataset there is
922
959
  // no honest answer, and the route's 501 says so. See `routerDataset`. The bucketed
@@ -1057,33 +1094,32 @@ export function createCfObservabilityReader(opts) {
1057
1094
  // would answer two rows whose p95s no caller can combine. Vertical reads null there.
1058
1095
  const byScope = input.grain === 'scope';
1059
1096
  const window = resolveObservabilityWindow(input);
1097
+ // Blob/double positions are the router's published shape, `ROUTER_REQUEST_POINT`: it only
1098
+ // ever grows, never reorders, which is what lets a reader name the ordinal it wants. The
1099
+ // connector-call dataset's ordinals are published beside these, on
1100
+ // `queryConnectorCallsSeries` below (#1691) — a different dataset, never this one.
1101
+ const p = ROUTER_REQUEST_POINT;
1060
1102
  const where = [
1061
- `index1 = ${aeLiteral(input.tenantId)}`,
1103
+ `${p.tenantId} = ${aeLiteral(input.tenantId)}`,
1062
1104
  `timestamp >= toDateTime(${Math.ceil(Date.parse(window.since) / 1000)})`,
1063
1105
  `timestamp < toDateTime(${Math.ceil(Date.parse(window.until) / 1000)})`,
1064
1106
  ];
1065
1107
  if (input.scopeId)
1066
- where.push(`blob2 = ${aeLiteral(input.scopeId)}`);
1108
+ where.push(`${p.scopeId} = ${aeLiteral(input.scopeId)}`);
1067
1109
  if (input.vertical)
1068
- where.push(`blob1 = ${aeLiteral(input.vertical)}`);
1069
- // Blob/double positions are the router's published shape (`apps/router/src/worker.ts`
1070
- // `record`): index1 tenant; blob1 vertical, blob2 scope, blob3 surface, blob4 status
1071
- // class; double1 duration ms, double2 status. That shape only ever grows, never
1072
- // reorders — which is what lets these ordinals be written down here at all. The
1073
- // connector-call dataset's ordinals are published beside these, on
1074
- // `queryConnectorCallsSeries` below (#1691) — a different dataset, never this one.
1110
+ where.push(`${p.vertical} = ${aeLiteral(input.vertical)}`);
1075
1111
  const sql = `
1076
1112
  SELECT
1077
- blob2 AS scopeId,
1078
- ${byScope ? "'' AS vertical" : 'blob1 AS vertical'},
1079
- ${byScope ? "'' AS surface" : 'blob3 AS surface'},
1113
+ ${p.scopeId} AS scopeId,
1114
+ ${byScope ? "'' AS vertical" : `${p.vertical} AS vertical`},
1115
+ ${byScope ? "'' AS surface" : `${p.surface} AS surface`},
1080
1116
  sum(_sample_interval) AS requests,
1081
- sum(if(blob4 = '5xx', _sample_interval, 0)) AS errors,
1082
- sum(if(blob4 = '2xx', _sample_interval, 0)) AS class2xx,
1083
- sum(if(blob4 = '3xx', _sample_interval, 0)) AS class3xx,
1084
- sum(if(blob4 = '4xx', _sample_interval, 0)) AS class4xx,
1085
- quantileWeighted(0.5)(double1, _sample_interval) AS durationP50,
1086
- quantileWeighted(0.95)(double1, _sample_interval) AS durationP95
1117
+ sum(if(${p.statusClass} = '5xx', _sample_interval, 0)) AS errors,
1118
+ sum(if(${p.statusClass} = '2xx', _sample_interval, 0)) AS class2xx,
1119
+ sum(if(${p.statusClass} = '3xx', _sample_interval, 0)) AS class3xx,
1120
+ sum(if(${p.statusClass} = '4xx', _sample_interval, 0)) AS class4xx,
1121
+ quantileWeighted(0.5)(${p.durationMs}, _sample_interval) AS durationP50,
1122
+ quantileWeighted(0.95)(${p.durationMs}, _sample_interval) AS durationP95
1087
1123
  FROM ${aeDataset(dataset)}
1088
1124
  WHERE ${where.join(' AND ')}
1089
1125
  GROUP BY ${byScope ? 'scopeId' : 'scopeId, vertical, surface'}
@@ -1130,22 +1166,23 @@ export function createCfObservabilityReader(opts) {
1130
1166
  const window = resolveObservabilityWindow(input);
1131
1167
  const bucketMinutes = observabilityBucketMinutes(window);
1132
1168
  const scopes = input.scopeIds.map((s) => aeLiteral(s)).join(', ');
1169
+ const p = ROUTER_REQUEST_POINT;
1133
1170
  const sql = `
1134
1171
  SELECT
1135
- blob2 AS scopeId,
1172
+ ${p.scopeId} AS scopeId,
1136
1173
  toStartOfInterval(timestamp, INTERVAL '${bucketMinutes}' MINUTE) AS start,
1137
1174
  sum(_sample_interval) AS requests,
1138
- sum(if(blob4 = '5xx', _sample_interval, 0)) AS errors,
1139
- sum(if(blob4 = '2xx', _sample_interval, 0)) AS class2xx,
1140
- sum(if(blob4 = '3xx', _sample_interval, 0)) AS class3xx,
1141
- sum(if(blob4 = '4xx', _sample_interval, 0)) AS class4xx,
1142
- quantileWeighted(0.5)(double1, _sample_interval) AS durationP50,
1143
- quantileWeighted(0.95)(double1, _sample_interval) AS durationP95
1175
+ sum(if(${p.statusClass} = '5xx', _sample_interval, 0)) AS errors,
1176
+ sum(if(${p.statusClass} = '2xx', _sample_interval, 0)) AS class2xx,
1177
+ sum(if(${p.statusClass} = '3xx', _sample_interval, 0)) AS class3xx,
1178
+ sum(if(${p.statusClass} = '4xx', _sample_interval, 0)) AS class4xx,
1179
+ quantileWeighted(0.5)(${p.durationMs}, _sample_interval) AS durationP50,
1180
+ quantileWeighted(0.95)(${p.durationMs}, _sample_interval) AS durationP95
1144
1181
  FROM ${aeDataset(dataset)}
1145
- WHERE index1 = ${aeLiteral(input.tenantId)}
1182
+ WHERE ${p.tenantId} = ${aeLiteral(input.tenantId)}
1146
1183
  AND timestamp >= toDateTime(${Math.ceil(Date.parse(window.since) / 1000)})
1147
1184
  AND timestamp < toDateTime(${Math.ceil(Date.parse(window.until) / 1000)})
1148
- AND blob2 IN (${scopes})
1185
+ AND ${p.scopeId} IN (${scopes})
1149
1186
  GROUP BY scopeId, start
1150
1187
  ORDER BY start ASC
1151
1188
  LIMIT ${SERIES_ROW_LIMIT}
@@ -1286,14 +1323,8 @@ export function createCfObservabilityReader(opts) {
1286
1323
  });
1287
1324
  }
1288
1325
  /** One Analytics Engine SQL read, returning the rows as the API shaped them. */
1289
- async function analyticsEngineSql(sql) {
1290
- const res = await fetch(`https://api.cloudflare.com/client/v4/accounts/${opts.accountId}/analytics_engine/sql`, { method: 'POST', headers: { authorization: `Bearer ${opts.apiToken}` }, body: sql });
1291
- const text = await res.text();
1292
- if (!res.ok) {
1293
- throw new Error(`Cloudflare Analytics Engine query failed: HTTP ${res.status} ${text.slice(0, 200)}`);
1294
- }
1295
- const json = JSON.parse(text);
1296
- return json.data ?? [];
1326
+ function analyticsEngineSql(sql) {
1327
+ return analyticsEngineQuery(opts, sql);
1297
1328
  }
1298
1329
  /**
1299
1330
  * One tenant's log events, in two phases (§4.3).
@@ -1330,6 +1361,23 @@ export function createCfObservabilityReader(opts) {
1330
1361
  from: input.since ? Date.parse(input.since) : to - input.hours * 3_600_000,
1331
1362
  to,
1332
1363
  };
1364
+ // #2521: set when a page of this tenant's lines came back FULL from the backend and held fewer
1365
+ // than the read wanted once a line was taken out (`telemetryPage` leaves the wire line out after
1366
+ // the backend has spent a slot on it), so lines may lie behind the cut. It is the service
1367
+ // grain's `incomplete`: a short page is then not "the window held no more". `wanted` is what the
1368
+ // read keeps of a full page: all of it, except where it over-fetched a slot to give back (the
1369
+ // per-request read, below), which a single filtered line leaves whole. Set by this tenant's own
1370
+ // queries only: an account-wide query's filtered line is not necessarily this tenant's.
1371
+ let incomplete = false;
1372
+ const noteCut = (page, asked, wanted = asked) => {
1373
+ if (page.fetched >= asked && page.events.length < wanted)
1374
+ incomplete = true;
1375
+ };
1376
+ const readTenant = async (filters, asked) => {
1377
+ const page = await queryRawPage(filters, timeframe, asked);
1378
+ noteCut(page, asked);
1379
+ return page.events;
1380
+ };
1333
1381
  const base = [
1334
1382
  { key: 'tenantId', operation: 'eq', type: 'string', value: input.tenantId },
1335
1383
  { key: 'substrat', operation: 'eq', type: 'string', value: 'invocation' },
@@ -1400,20 +1448,21 @@ export function createCfObservabilityReader(opts) {
1400
1448
  // line from another of the tenant's apps.
1401
1449
  const moduleLines = input.vertical && !input.scopeId
1402
1450
  ? Promise.resolve([])
1403
- : queryRaw([...moduleLineFilters(input), ...serviceFilter(input.services)], timeframe, input.limit);
1451
+ : readTenant([...moduleLineFilters(input), ...serviceFilter(input.services)], input.limit);
1404
1452
  // A template names `ctx.log` lines only: an invocation line has none.
1405
1453
  if (input.template !== undefined) {
1406
- return (await moduleLines)
1454
+ const lines = (await moduleLines)
1407
1455
  .map((e) => describeModuleLine(projectEvent(e)))
1408
1456
  .sort((a, b) => (b.timestamp ?? 0) - (a.timestamp ?? 0))
1409
1457
  .slice(0, input.limit);
1458
+ return { events: lines, incomplete };
1410
1459
  }
1411
1460
  const [stamped, errorLines] = isErrorRead
1412
1461
  ? await Promise.all([
1413
1462
  Promise.all([
1414
- queryRaw([...base, { key: 'status', operation: 'eq', type: 'number', value: 500 }], timeframe, phaseOneLimit),
1415
- queryRaw([...base, { key: 'status', operation: 'gte', type: 'number', value: CAPABILITY_ABSENT + 1 }], timeframe, phaseOneLimit),
1416
- queryRaw([...base, { key: 'threw', operation: 'eq', type: 'boolean', value: true }], timeframe, phaseOneLimit),
1463
+ readTenant([...base, { key: 'status', operation: 'eq', type: 'number', value: 500 }], phaseOneLimit),
1464
+ readTenant([...base, { key: 'status', operation: 'gte', type: 'number', value: CAPABILITY_ABSENT + 1 }], phaseOneLimit),
1465
+ readTenant([...base, { key: 'threw', operation: 'eq', type: 'boolean', value: true }], phaseOneLimit),
1417
1466
  // Newest first across the pages, not page order: the correlation cap is spent
1418
1467
  // in this order, and a busy `= 500` page must not crowd out a newer 502 or
1419
1468
  // escape just because its query was listed first.
@@ -1423,7 +1472,7 @@ export function createCfObservabilityReader(opts) {
1423
1472
  // and `ownsInvocation` below still admits nothing without a stamped line.
1424
1473
  [{ key: '$metadata.level', operation: 'eq', type: 'string', value: 'error' }, ...serviceFilter(input.services)], timeframe, phaseOneLimit),
1425
1474
  ])
1426
- : [await queryRaw(base, timeframe, phaseOneLimit), []];
1475
+ : [await readTenant(base, phaseOneLimit), []];
1427
1476
  const trusted = invocationIds(stamped);
1428
1477
  const trustedIds = new Set(trusted);
1429
1478
  const candidates = invocationIds(errorLines).filter((id) => !trustedIds.has(id));
@@ -1441,13 +1490,20 @@ export function createCfObservabilityReader(opts) {
1441
1490
  // `limit` (the route bounds that at 200).
1442
1491
  const linesPerInvocation = input.invocationId !== undefined ? Math.min(input.limit, 200) : MAX_LINES_PER_INVOCATION;
1443
1492
  const sibling = await Promise.all(requestIds.map(async (id) => {
1444
- const events = await queryRaw([{ key: '$metadata.requestId', operation: 'eq', type: 'string', value: id }, ...serviceFilter(input.services)], timeframe, linesPerInvocation);
1493
+ // One more than the budget, then cut to it: a request writes at most one wire line (RFC
1494
+ // wire-signing §8), which `telemetryPage` leaves out after the backend spent a slot on it.
1495
+ // So the page holds exactly the lines it would if that line did not exist.
1496
+ const page = await queryRawPage([{ key: '$metadata.requestId', operation: 'eq', type: 'string', value: id }, ...serviceFilter(input.services)], timeframe, linesPerInvocation + 1);
1497
+ const events = page.events.slice(0, linesPerInvocation);
1445
1498
  // An account-wide candidate earns its place only by producing this tenant's
1446
1499
  // stamped line. No stamped line, or somebody else's, and the whole invocation is
1447
1500
  // dropped — a line shown to the wrong tenant is exactly the leak the tenant grain
1448
1501
  // exists to prevent, so the conservative direction is the only allowed one.
1449
1502
  if (!trustedIds.has(id) && !events.some((e) => ownsInvocation(e, input)))
1450
1503
  return [];
1504
+ // Only an invocation this tenant owns can be incomplete for it. The slot over-fetched above
1505
+ // gives one filtered line back; a full page that lost more than that is short of its share.
1506
+ noteCut(page, linesPerInvocation + 1, linesPerInvocation);
1451
1507
  return events;
1452
1508
  }));
1453
1509
  // Merge, de-duplicate, drop the router's own access log, then apply the caller's
@@ -1470,7 +1526,7 @@ export function createCfObservabilityReader(opts) {
1470
1526
  const runtimeOf = foldRuntimeRecords([...byId.values()]);
1471
1527
  const level = input.level?.toLowerCase();
1472
1528
  const search = input.search;
1473
- return runtimeOf.kept
1529
+ const events = runtimeOf.kept
1474
1530
  .map((e) => withRuntimeTimings(projectEvent(e), runtimeOf.byRequest))
1475
1531
  .map((e) => describeModuleLine(describeInvocation(e)))
1476
1532
  // A plain comparison is enough only because `describeInvocation` ran first: a stamped
@@ -1483,6 +1539,7 @@ export function createCfObservabilityReader(opts) {
1483
1539
  .filter((e) => (search ? (e.message ?? '').includes(search) : true))
1484
1540
  .sort((a, b) => (b.timestamp ?? 0) - (a.timestamp ?? 0))
1485
1541
  .slice(0, input.limit);
1542
+ return { events, incomplete };
1486
1543
  }
1487
1544
  /** The de-duplicated, order-preserving request ids of a page of events. */
1488
1545
  function invocationIds(events) {
@@ -1545,6 +1602,10 @@ export function createCfObservabilityReader(opts) {
1545
1602
  // searches the same one, so this takes the instants rather than a duration it would
1546
1603
  // have to re-anchor to a `Date.now()` of its own.
1547
1604
  timeframe, limit) {
1605
+ return (await queryRawPage(filters, timeframe, limit)).events;
1606
+ }
1607
+ /** {@link queryRaw}, with the size of the page the backend returned (see `telemetryPage`). */
1608
+ async function queryRawPage(filters, timeframe, limit) {
1548
1609
  const res = await authed(`https://api.cloudflare.com/client/v4/accounts/${opts.accountId}/workers/observability/telemetry/query`, {
1549
1610
  queryId: 'substrat-tenant-logs',
1550
1611
  view: 'events',
@@ -1558,14 +1619,14 @@ export function createCfObservabilityReader(opts) {
1558
1619
  const json = JSON.parse(text);
1559
1620
  if (json.success === false)
1560
1621
  throw telemetryFailure(502, text);
1561
- const outer = json.result?.events;
1562
- return (Array.isArray(outer) ? outer : (outer?.events ?? []));
1622
+ return telemetryPage(json.result);
1563
1623
  }
1564
1624
  /** Read a complete sampled span, or refuse it; a truncated page must never mean zero fields. */
1565
1625
  async function queryAllFieldEvents(filters, timeframe, depth = 0) {
1566
- const page = await queryRaw(filters, timeframe, 2000);
1567
- if (page.length < 2000)
1568
- return page;
1626
+ // Full is judged on what the backend returned, not on what is left once a line is filtered out.
1627
+ const page = await queryRawPage(filters, timeframe, 2000);
1628
+ if (page.fetched < 2000)
1629
+ return page.events;
1569
1630
  if (depth >= 12 || timeframe.to - timeframe.from <= 1000) {
1570
1631
  throw new ControlPlaneError(503, 'field coverage window is too busy — choose a shorter window');
1571
1632
  }
@@ -1576,38 +1637,103 @@ export function createCfObservabilityReader(opts) {
1576
1637
  ]);
1577
1638
  return [...left, ...right];
1578
1639
  }
1579
- /** One telemetry query — narrowed to a single service, or to none (the fleet view). */
1580
- async function queryEvents(service, level, search, hours, limit) {
1640
+ /**
1641
+ * The service-grain read: one walk per service, or one over none (the fleet view), merged
1642
+ * newest first and cut to `limit`, and whether it stopped short (`RecentLogs.incomplete`).
1643
+ */
1644
+ async function queryEvents(services, level, search, hours, limit) {
1581
1645
  const to = Date.now();
1582
- const filters = [];
1583
- // `$metadata.service` is the script name in Workers Logs events — the field
1584
- // Cloudflare's own query examples filter on.
1585
- if (service) {
1586
- filters.push({ key: '$metadata.service', operation: 'eq', type: 'string', value: service });
1587
- }
1588
- if (level) {
1589
- filters.push({ key: '$metadata.level', operation: 'eq', type: 'string', value: level });
1590
- }
1591
- if (search) {
1592
- filters.push({ key: '$metadata.message', operation: 'includes', type: 'string', value: search });
1593
- }
1594
- const res = await authed(`https://api.cloudflare.com/client/v4/accounts/${opts.accountId}/workers/observability/telemetry/query`, {
1595
- queryId: 'substrat-recent-logs',
1596
- view: 'events',
1597
- timeframe: { from: to - hours * 3_600_000, to },
1598
- parameters: { datasets: ['cloudflare-workers'], filters, limit },
1599
- limit,
1600
- });
1601
- const json = (await res.json());
1602
- if (!res.ok || json.success === false) {
1603
- const message = json.errors?.map((e) => e.message).join('; ') || `HTTP ${res.status}`;
1604
- throw new Error(`Cloudflare telemetry query failed: ${message}`);
1646
+ const from = to - hours * 3_600_000;
1647
+ const filtersFor = (service) => {
1648
+ const filters = [];
1649
+ // `$metadata.service` is the script name in Workers Logs events — the field
1650
+ // Cloudflare's own query examples filter on.
1651
+ if (service) {
1652
+ filters.push({ key: '$metadata.service', operation: 'eq', type: 'string', value: service });
1653
+ }
1654
+ if (level) {
1655
+ filters.push({ key: '$metadata.level', operation: 'eq', type: 'string', value: level });
1656
+ }
1657
+ if (search) {
1658
+ filters.push({ key: '$metadata.message', operation: 'includes', type: 'string', value: search });
1659
+ }
1660
+ return filters;
1661
+ };
1662
+ const page = async (filters, timeframe) => {
1663
+ const res = await authed(`https://api.cloudflare.com/client/v4/accounts/${opts.accountId}/workers/observability/telemetry/query`, {
1664
+ queryId: 'substrat-recent-logs',
1665
+ view: 'events',
1666
+ timeframe,
1667
+ parameters: { datasets: ['cloudflare-workers'], filters, limit },
1668
+ limit,
1669
+ });
1670
+ const json = (await res.json());
1671
+ if (!res.ok || json.success === false) {
1672
+ const message = json.errors?.map((e) => e.message).join('; ') || `HTTP ${res.status}`;
1673
+ throw new Error(`Cloudflare telemetry query failed: ${message}`);
1674
+ }
1675
+ return telemetryPage(json.result);
1676
+ };
1677
+ // Filled to `limit` when more exist. A full page the wire line was taken out of (in `dual`,
1678
+ // up to a third of one: a request writes its runtime record, its stamp and the wire line) may
1679
+ // be followed by the page before its oldest line: its next window ends just after that oldest
1680
+ // instant, and the event id folds the overlap. A walk is read again only while its next page
1681
+ // could still reach the merged answer, so a read across many services pays for the fill only
1682
+ // where a service's page decides the answer's tail, and never more than `MAX_FILL_QUERIES`.
1683
+ //
1684
+ // A read that stops while a walk could still hold a line for the answer says so (`incomplete`):
1685
+ // a walk the bounds left unread, or a full page all of one instant, which no earlier window
1686
+ // can cut past.
1687
+ const walks = services.map((service) => ({ filters: filtersFor(service), until: to, more: false, stuck: false, oldest: 0 }));
1688
+ const kept = new Map();
1689
+ const read = async (walk) => {
1690
+ const { events, fetched, oldest } = await page(walk.filters, { from, to: walk.until });
1691
+ for (const e of events) {
1692
+ const metadata = (e['$metadata'] ?? {});
1693
+ kept.set(typeof metadata['id'] === 'string' ? metadata['id'] : JSON.stringify(e), e);
1694
+ }
1695
+ // More may exist only behind a full page, and only if an earlier window can be cut: a page
1696
+ // all of one instant cannot be, so the walk stops there, stuck rather than spent.
1697
+ walk.more = fetched >= limit && oldest !== null && oldest + 1 < walk.until;
1698
+ walk.stuck = fetched >= limit && !walk.more;
1699
+ if (oldest !== null)
1700
+ walk.oldest = oldest;
1701
+ if (walk.more)
1702
+ walk.until = oldest + 1;
1703
+ };
1704
+ const answer = () => [...kept.values()].sort((a, b) => rawTime(b) - rawTime(a)).slice(0, limit);
1705
+ // Lines older than this may have a newer one behind a walk the budget left unread.
1706
+ let floor = -Infinity;
1707
+ let incomplete = false;
1708
+ let budget = MAX_FILL_QUERIES;
1709
+ let pending = walks;
1710
+ for (let round = 0; pending.length > 0; round++) {
1711
+ await Promise.all(pending.map(read));
1712
+ const merged = answer();
1713
+ // A walk's unread lines are no newer than its oldest read one, so it can change the answer
1714
+ // only while that line is newer than the answer's last (or the answer is short). Not "as
1715
+ // new": the walk holding the answer's last line could add only lines of that same instant,
1716
+ // whose order against it is arbitrary anyway, and every full page would cost a second query.
1717
+ const cutoff = merged.length < limit ? -Infinity : rawTime(merged[merged.length - 1]);
1718
+ const reaches = (w) => w.oldest > cutoff;
1719
+ const wanted = walks.filter((w) => w.more && reaches(w)).sort((a, b) => b.oldest - a.oldest);
1720
+ const roundsLeft = round + 1 < MAX_FILL_ROUNDS;
1721
+ pending = roundsLeft ? wanted.slice(0, budget) : [];
1722
+ budget -= pending.length;
1723
+ const unread = wanted.slice(pending.length);
1724
+ // Left unread by the budget while others are read on: their older lines would sit beside
1725
+ // lines this walk may still hold, so the answer stops at its oldest and stays a true prefix.
1726
+ // A walk that ran out of rounds is not a floor: it was read as far as every other, and a
1727
+ // floor from it would let one service whose pages are all wire lines empty the answer.
1728
+ if (roundsLeft)
1729
+ for (const w of unread)
1730
+ floor = Math.max(floor, w.oldest);
1731
+ incomplete = unread.length > 0 || walks.some((w) => w.stuck && reaches(w));
1605
1732
  }
1606
- // The events view has nested the list one level deeper across API revisions —
1607
- // accept both rather than pinning to whichever shape was current at writing.
1608
- const outer = json.result?.events;
1609
- const events = (Array.isArray(outer) ? outer : (outer?.events ?? []));
1610
- return events.map((e) => projectEvent(e));
1733
+ const events = answer()
1734
+ .filter((e) => rawTime(e) >= floor)
1735
+ .map((e) => projectEvent(e));
1736
+ return { events, incomplete };
1611
1737
  }
1612
1738
  /**
1613
1739
  * Outbound `fetch` spans for one service (#859).
@@ -1651,8 +1777,7 @@ export function createCfObservabilityReader(opts) {
1651
1777
  const message = json.errors?.map((e) => e.message).join('; ') || `HTTP ${res.status}`;
1652
1778
  throw new Error(`Cloudflare span query failed: ${message}`);
1653
1779
  }
1654
- const outer = json.result?.events;
1655
- const events = (Array.isArray(outer) ? outer : (outer?.events ?? []));
1780
+ const { events, fetched } = telemetryPage(json.result);
1656
1781
  const spans = events.map((e) => {
1657
1782
  const source = (e['source'] ?? {});
1658
1783
  const metadata = (e['$metadata'] ?? {});
@@ -1682,8 +1807,88 @@ export function createCfObservabilityReader(opts) {
1682
1807
  });
1683
1808
  // Row-cap detection: a full page means there may be more. Reported rather than
1684
1809
  // swallowed — an egress report that silently drops hosts is worse than none (#859).
1685
- return { spans, truncated: events.length >= limit };
1810
+ return { spans, truncated: fetched >= limit };
1811
+ }
1812
+ }
1813
+ /** One Analytics Engine SQL read, returning the rows as the API shaped them. */
1814
+ async function analyticsEngineQuery(opts, sql) {
1815
+ const res = await fetch(`https://api.cloudflare.com/client/v4/accounts/${opts.accountId}/analytics_engine/sql`, { method: 'POST', headers: { authorization: `Bearer ${opts.apiToken}` }, body: sql });
1816
+ const text = await res.text();
1817
+ if (!res.ok) {
1818
+ throw new Error(`Cloudflare Analytics Engine query failed: HTTP ${res.status} ${text.slice(0, 200)}`);
1686
1819
  }
1820
+ const json = JSON.parse(text);
1821
+ return json.data ?? [];
1822
+ }
1823
+ /**
1824
+ * The most rows one day's rollup query may answer (#2501): one per (tenant, vertical, scope) that
1825
+ * served a request that day. A day with more is refused as `RequestRollupSaturated`, never kept as
1826
+ * a part of the day standing for the whole. The rollup records such a day as saturated and goes on
1827
+ * with the days after it; reading it would need a paged read, which this is not yet.
1828
+ */
1829
+ export const REQUEST_ROLLUP_ROW_LIMIT = 50_000;
1830
+ /**
1831
+ * The daily request rollup's reader (#2501): one closed UTC day of the router's request
1832
+ * datapoints, counted per (tenant, vertical, scope). The platform sweep's request-rollup phase
1833
+ * calls it, never a route.
1834
+ *
1835
+ * It reads EVERY tenant at once, which is why it is not a member of `ObservabilityReader`: that
1836
+ * seam answers routes, and keeps a fleet-wide read one forgotten parameter away by having no
1837
+ * all-tenants spelling. One query per day for the whole fleet is what keeps the rollup to a
1838
+ * handful of queries a pass.
1839
+ *
1840
+ * Counts are `sum(_sample_interval)`, never `count()`, for `queryTenantMetrics`'s reason: Analytics
1841
+ * Engine samples under load, so each count is an estimate and `sampled` says whether any of the
1842
+ * day's datapoints stood for more than one request. The ordinals are the router's published shape
1843
+ * (`ROUTER_REQUEST_POINT`). Beside the total it counts each status class from `statusClass` and
1844
+ * the 429s from `status`, weighted the same way, so the split is kept while the datapoints last.
1845
+ */
1846
+ export function createRouterRequestDayReader(opts) {
1847
+ return async (day) => {
1848
+ if (!utcDay.safeParse(day).success) {
1849
+ throw new Error(`request rollup: refusing a day that is not a UTC day: ${JSON.stringify(day)}`);
1850
+ }
1851
+ const from = Date.parse(`${day}T00:00:00Z`) / 1000;
1852
+ const p = ROUTER_REQUEST_POINT;
1853
+ const sql = `
1854
+ SELECT
1855
+ ${p.tenantId} AS tenantId,
1856
+ ${p.vertical} AS vertical,
1857
+ ${p.scopeId} AS scopeId,
1858
+ sum(_sample_interval) AS requests,
1859
+ sum(if(${p.statusClass} = '2xx', _sample_interval, 0)) AS class2xx,
1860
+ sum(if(${p.statusClass} = '3xx', _sample_interval, 0)) AS class3xx,
1861
+ sum(if(${p.statusClass} = '4xx', _sample_interval, 0)) AS class4xx,
1862
+ sum(if(${p.statusClass} = '5xx', _sample_interval, 0)) AS class5xx,
1863
+ sum(if(${p.status} = 429, _sample_interval, 0)) AS rateLimited,
1864
+ max(_sample_interval) AS maxInterval
1865
+ FROM ${aeDataset(opts.routerDataset)}
1866
+ WHERE timestamp >= toDateTime(${from})
1867
+ AND timestamp < toDateTime(${from + 86_400})
1868
+ GROUP BY tenantId, vertical, scopeId
1869
+ ORDER BY tenantId, vertical, scopeId
1870
+ LIMIT ${REQUEST_ROLLUP_ROW_LIMIT + 1}
1871
+ FORMAT JSON`;
1872
+ const rows = await analyticsEngineQuery(opts, sql);
1873
+ // One row past the ceiling says the day holds more than one answer carries. An answer of
1874
+ // exactly the ceiling is the whole day.
1875
+ if (rows.length > REQUEST_ROLLUP_ROW_LIMIT) {
1876
+ throw new RequestRollupSaturated(`Cloudflare Analytics Engine request rollup holds more than ${REQUEST_ROLLUP_ROW_LIMIT} groups for ${day}: the counts would be partial`);
1877
+ }
1878
+ const count = (r, key) => Math.round(aeNum(r[key]));
1879
+ return rows.map((r) => ({
1880
+ tenantId: String(r['tenantId'] ?? ''),
1881
+ vertical: blank(r['vertical']),
1882
+ scopeId: String(r['scopeId'] ?? ''),
1883
+ requests: count(r, 'requests'),
1884
+ class2xx: count(r, 'class2xx'),
1885
+ class3xx: count(r, 'class3xx'),
1886
+ class4xx: count(r, 'class4xx'),
1887
+ class5xx: count(r, 'class5xx'),
1888
+ rateLimited: count(r, 'rateLimited'),
1889
+ sampled: aeNum(r['maxInterval']) > 1,
1890
+ }));
1891
+ };
1687
1892
  }
1688
1893
  /**
1689
1894
  * The router dataset's name, checked before it is spliced into SQL. It is an IDENTIFIER,