@substrat-run/kernel 0.206.0 → 0.208.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.
@@ -7,6 +7,7 @@ import { METER_DAYS_PRUNE_BATCH, METER_SNAPSHOT_TIMEOUT_MS } from './meter-days.
7
7
  import { REQUEST_ROLLUP_DAYS_PER_PASS, REQUEST_ROLLUP_LOOKBACK_DAYS, REQUEST_ROLLUP_MAX_LOOKBACK_DAYS, REQUEST_ROLLUP_PRUNE_BATCH, REQUEST_ROLLUP_READ_TIMEOUT_MS, REQUEST_ROLLUP_RETRY_MS, REQUEST_ROLLUP_SETTLE_MS, isRequestRollupSaturated, requestRollupDueDays, } from './request-rollup.js';
8
8
  import { COST_ROLLUP_DAYS_PER_PASS, COST_ROLLUP_LOOKBACK_DAYS, COST_ROLLUP_MAX_LOOKBACK_DAYS, COST_ROLLUP_PRUNE_BATCH, COST_ROLLUP_READ_TIMEOUT_MS, COST_ROLLUP_RETRY_MS, COST_ROLLUP_SETTLE_MS, SCOPE_OBJECT_RETRY_MS, SCOPE_OBJECTS_PER_PASS, } from './cost-rollup.js';
9
9
  import { backoffAt, fetchLikeOf } from './connector-transport.js';
10
+ import { budgetedFetch, CONNECTOR_SWEEP_MAX_BYTES, CONNECTOR_SWEEP_MAX_MS } from './sweep-budget.js';
10
11
  import { assertRowLimit, TELEMETRY_PRUNE_BATCH } from './retention.js';
11
12
  import { MIGRATION_FLAG_THRESHOLD, migrationFleet, migrationProgress, scopeMigrationState } from './migration-progress.js';
12
13
  import { UNDRAINED_SKIPPED_IDS } from './outbox-event.js';
@@ -364,6 +365,7 @@ function scopeReaderFor(admin, actor, report) {
364
365
  }
365
366
  export async function runPlatformSweep(host, options) {
366
367
  assertSweepBatches(options);
368
+ assertConnectorSweepOptions(options);
367
369
  const concurrency = options.concurrency ?? 8;
368
370
  const report = {
369
371
  scopesDrained: 0,
@@ -371,6 +373,8 @@ export async function runPlatformSweep(host, options) {
371
373
  connectionsSwept: 0,
372
374
  connectionLandings: options.connectionLandings ? { granted: 0, bound: 0, failed: 0 } : null,
373
375
  connectionsSkipped: 0,
376
+ connectionsPaused: 0,
377
+ connectionsBackingOff: 0,
374
378
  snapshotsReaped: 0,
375
379
  archivedScopesReaped: 0,
376
380
  tenantsReaped: 0,
@@ -884,156 +888,12 @@ export async function runPlatformSweep(host, options) {
884
888
  }
885
889
  });
886
890
  }
887
- const connections = await host.admin.listConnections(options.actor, {});
888
- const landings = options.connectionLandings ? new LandingPass(host, options.actor, options.connectionLandings, concurrency, listScopes) : null;
889
- await mapBounded(connections, concurrency, async (c) => {
890
- // #1232: the connection's durable sweep record. A connection row carries no
891
- // scope (a connection spans scopes by construction) and no version.
892
- const record = (outcome, extra) => options.recordSweepRun?.({
893
- kind: 'connector',
894
- unit: c.id,
895
- outcome,
896
- tenantId: c.tenantId,
897
- vertical: c.vertical,
898
- operation: `sweep.connector:${c.provider}`,
899
- connectionId: c.id,
900
- ...extra,
901
- });
902
- if (c.revokedAt !== null) {
903
- // Terminal — nothing to reconcile through it, and deliberately unrecorded:
904
- // a revoked connection is not "waiting to be swept", and a skipped row per
905
- // pass forever would be noise every strip has to filter back out.
906
- report.connectionsSkipped += 1;
907
- return;
908
- }
909
- const sweeper = options.sweepers[c.provider] ?? options.sweeperFor?.(c);
910
- if (!sweeper) {
911
- report.connectionsSkipped += 1;
912
- // Recorded, unlike the revoked case: "bound but no sweeper registered" is a
913
- // live connection nothing will ever poll — exactly the declared-vs-observed
914
- // finding the signals views exist to surface.
915
- record('skipped');
916
- return;
917
- }
918
- const started = Date.now();
919
- // #2316: what the running versions declare, granted and bound before the poll reads bindings.
920
- // Never sinks the sweep: its failures join the poll's on the connection's row.
921
- const landed = landings ? await landings.apply(c).catch((err) => ({ granted: [], bound: [], failed: [{ scopeId: '*', error: message(err) }] })) : null;
922
- if (landed && report.connectionLandings) {
923
- report.connectionLandings.granted += landed.granted.length;
924
- report.connectionLandings.bound += landed.bound.length;
925
- report.connectionLandings.failed += landed.failed.length;
926
- }
927
- const landingFailed = landed?.failed ?? [];
928
- // #2316: the row is the connection's tenant's to read, so it says what became of the sweep, in
929
- // the platform's words with counts, under one reference; the text (a provider's answer, a landing
930
- // refusal) is staff's row under the same reference, or the report's when nothing files one.
931
- //
932
- // #3235: a failure that names the scope it belongs to is filed as a PAIR under that reference: a
933
- // row for the connection's tenant, carrying the scope, so that app's Failures view and fleet
934
- // health count it, saying in the platform's words what became of that binding (with the
935
- // connector's `said` when it gave one); and staff's row with the failure's own text. Only a
936
- // failure with no scope (a sweep that threw, a landing pass that could not start) stays staff's
937
- // alone, as before.
938
- const fail = (said, failures, neutralDetail) => {
939
- const reference = ulid();
940
- if (options.recordFailure) {
941
- const operation = `sweep.connector:${c.provider}`;
942
- const opening = `connection ${c.id} of tenant ${c.tenantId}: `;
943
- const unscoped = [];
944
- // One pair per scope: a scope can fail twice in one pass (a declared landing, then its
945
- // poll), and two pairs sharing the reference, the operation and the scope could not be told
946
- // apart by a reader that pairs them.
947
- const byScope = new Map();
948
- for (const f of failures) {
949
- const scope = f.scopeId === undefined ? undefined : scopeIdSchema.safeParse(f.scopeId);
950
- if (!scope?.success) {
951
- unscoped.push(f.scopeId === undefined ? f.error : `scope ${f.scopeId}: ${f.error}`);
952
- continue;
953
- }
954
- byScope.set(scope.data, [...(byScope.get(scope.data) ?? []), f]);
955
- }
956
- for (const [scope, fs] of byScope) {
957
- options.recordFailure(withheldOpsFailure({ operation, stage: 'sweep', tenantId: c.tenantId, scopeId: scope, vertical: c.vertical }, fs.map((f) => f.error).join('; '), (ref) => `${[...new Set(fs.map((f) => tenantSentence(c.provider, f)))].join('; ')} (reference ${ref})`, reference, `${opening}scope ${scope}: `));
958
- }
959
- if (unscoped.length > 0) {
960
- options.recordFailure(withheldStaffFailure({ operation, stage: 'sweep', vertical: c.vertical }, unscoped.join('; '), reference, opening));
961
- }
962
- }
963
- else {
964
- for (const f of failures)
965
- report.errors.push({ kind: 'sweep', id: c.id, error: f.scopeId === undefined ? f.error : `scope ${f.scopeId}: ${f.error}` });
966
- }
967
- const failureText = `${said.join('; ')} (reference ${reference})`;
968
- record('failed', { error: neutralDetail ? `Unsupported bindings: ${neutralDetail}\n${failureText}` : failureText, elapsedMs: Date.now() - started });
969
- };
970
- const landingSaid = landingFailed.length > 0 ? [`${counted(landingFailed.length, 'declared landing')} could not be granted or bound`] : [];
971
- const landingFailures = landingFailed.map((f) => ({ ...f, landing: true }));
972
- const everyMinutes = options.sweepEveryMinutes?.[c.provider];
973
- if (everyMinutes) {
974
- try {
975
- const [ok, failed, unsupported] = await Promise.all([
976
- host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'ok', limit: 1 }),
977
- host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'failed', limit: 1 }),
978
- host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'unsupported', limit: 1 }),
979
- ]);
980
- // Ignore skipped rows and future-dated receipts: neither proves a poll inside this interval.
981
- const now = Date.now();
982
- const lastAttempt = Math.max(0, ...[ok[0], failed[0], unsupported[0]].filter((row) => row !== undefined).map((row) => Date.parse(row.at)).filter((at) => at <= now));
983
- if (now - lastAttempt < everyMinutes * 60_000) {
984
- if (landingFailed.length > 0)
985
- fail(landingSaid, landingFailures);
986
- report.connectionsSkipped += 1;
987
- return;
988
- }
989
- }
990
- catch (err) {
991
- // Without the ledger's clock, do not risk spending the provider's daily allowance.
992
- if (landingFailed.length > 0)
993
- fail(landingSaid, landingFailures);
994
- report.errors.push({ kind: 'sweep', id: c.id, error: `cannot read connector cadence: ${message(err)}` });
995
- report.connectionsSkipped += 1;
996
- return;
997
- }
998
- }
999
- let result;
1000
- try {
1001
- // #2498: a sized stream body the connector sends reaches the injected fetch converted.
1002
- result = await sweeper(host, c.id, { fetch: fetchLikeOf(options.fetch) });
1003
- }
1004
- catch (err) {
1005
- // The landing step's failures, if any, belong on the same row as the poll's throw.
1006
- fail([...landingSaid, 'the sweep did not complete'], [...landingFailures, { error: message(err) }]);
1007
- return;
1008
- }
1009
- const answer = options.connectionLandings && binderOf(options.connectionLandings, c) ? connectorSweepAnswerOf(result) : null;
1010
- // Skipped only when the row below is `unsupported`: a failed landing makes it `failed`, and swept.
1011
- if (answer && answer.found > 0 && answer.unsupported?.length === answer.found && answer.failed.length === 0 && landingFailed.length === 0) {
1012
- report.connectionsSkipped += 1;
1013
- }
1014
- else {
1015
- report.connectionsSwept += 1;
1016
- }
1017
- // #2316: a resolved sweep is not a landed one. A binding the connector could not land, or a
1018
- // landing the platform could not seat, fails the row; a poll that found nothing to poll is
1019
- // `skipped`, which a console reads as "nothing polls this connection". A mixed connection
1020
- // records the result of its polled bindings and keeps unsupported bindings in the detail.
1021
- const pollFailed = answer?.failed ?? [];
1022
- const unsupported = answer?.unsupported ?? [];
1023
- const unsupportedDetail = unsupported.map((u) => `scope ${u.scopeId}: ${u.reason}`).join('; ');
1024
- if (landingFailed.length > 0 || pollFailed.length > 0) {
1025
- fail([...landingSaid, ...(pollFailed.length > 0 ? [`${pollFailed.length} of ${counted(answer.found, 'binding')} did not land${saidOf(pollFailed)}`] : [])], [...landingFailures, ...pollFailed], unsupportedDetail || undefined);
1026
- }
1027
- else if (answer && answer.found === 0) {
1028
- record('skipped', { error: NO_BINDING, elapsedMs: Date.now() - started });
1029
- }
1030
- else if (unsupported.length > 0 && answer?.found === unsupported.length) {
1031
- record('unsupported', { error: unsupportedDetail, elapsedMs: Date.now() - started });
1032
- }
1033
- else {
1034
- record('ok', { ...(unsupportedDetail ? { error: unsupportedDetail } : {}), elapsedMs: Date.now() - started });
1035
- }
1036
- });
891
+ // -- connector sweeps (#574, #3324) ------------------------------------------
892
+ // Skipped when the caller runs them itself, after everything else (`sweepConnectors: false`
893
+ // and `runConnectorSweep`): a connection's sweep reads a third party's data through this
894
+ // isolate, and a sweep that exhausts it takes every phase still to run with it.
895
+ if (options.sweepConnectors !== false)
896
+ await sweepConnections(host, options, report, listScopes, concurrency);
1037
897
  // -- cross-vertical event delivery (#1705) ------------------------------------
1038
898
  // After the provision reconcile, so a peer grant a new version declares is seated before
1039
899
  // the edge that needs it is read. Before the Tier-2 drain, which only ships each scope's
@@ -2441,4 +2301,286 @@ async function sweepOrphanAttachmentWindow(host, options, phase, scopes, report)
2441
2301
  });
2442
2302
  return out;
2443
2303
  }
2304
+ /** The `error` of a paused connection's `skipped` row (#3324). */
2305
+ export const CONNECTOR_SWEEP_PAUSED = 'paused by an operator: this connection is not swept until the pause is lifted';
2306
+ /**
2307
+ * How long a connection whose sweep the pass died in is waited out (#3324): `baseDelayMs` after the
2308
+ * first, doubling with each attempt in a row that did not finish, never more than `maxDelayMs`.
2309
+ * 30 minutes, then an hour, two, …, a day. Jittered by `backoffAt`.
2310
+ */
2311
+ export const CONNECTOR_CRASH_BACKOFF = { baseDelayMs: 30 * 60_000, maxDelayMs: 24 * 3_600_000 };
2312
+ /** Attempts read back to count a run of unfinished ones; past this many the delay is at its cap anyway. */
2313
+ const CRASH_STREAK_WINDOW = 8;
2314
+ /**
2315
+ * The connection's attempts newer than its newest `connector` row: each is a sweep that started and
2316
+ * recorded no outcome, so the pass running it ended inside it. Null when the newest attempt has an
2317
+ * outcome after it (or there is none).
2318
+ */
2319
+ async function crashedAttemptsOf(host, actor, unit) {
2320
+ const [attempts, outcomes] = await Promise.all([
2321
+ host.admin.listSweepRuns(actor, { kind: 'connector-attempt', unit, limit: CRASH_STREAK_WINDOW }),
2322
+ host.admin.listSweepRuns(actor, { kind: 'connector', unit, limit: 1 }),
2323
+ ]);
2324
+ const last = outcomes[0];
2325
+ let streak = 0;
2326
+ for (const a of attempts) {
2327
+ if (last !== undefined && (a.at < last.at || (a.at === last.at && a.id < last.id)))
2328
+ break;
2329
+ streak += 1;
2330
+ }
2331
+ return streak === 0 ? null : { streak, lastAt: attempts[0].at };
2332
+ }
2333
+ /**
2334
+ * The connector sweep alone (#3324), for a caller that runs it after every other phase of its pass
2335
+ * (`runPlatformSweep` with `sweepConnectors: false`). A connection's sweep reads a third party's
2336
+ * data through the calling isolate; run last, one that exhausts it ends a pass with nothing left
2337
+ * to lose but the connections still in flight.
2338
+ */
2339
+ export async function runConnectorSweep(host, options) {
2340
+ assertConnectorSweepOptions(options);
2341
+ const report = {
2342
+ connectionsSwept: 0,
2343
+ connectionsSkipped: 0,
2344
+ connectionsPaused: 0,
2345
+ connectionsBackingOff: 0,
2346
+ connectionLandings: options.connectionLandings ? { granted: 0, bound: 0, failed: 0 } : null,
2347
+ errors: [],
2348
+ };
2349
+ await sweepConnections(host, options, report, scopeReaderFor(host.admin, options.actor, report), options.concurrency ?? 8);
2350
+ return report;
2351
+ }
2352
+ /** The budget and backoff options, refused when they could not bound anything. */
2353
+ function assertConnectorSweepOptions(options) {
2354
+ const budget = options.connectorBudget;
2355
+ if (budget?.maxBytes !== undefined && !(Number.isInteger(budget.maxBytes) && budget.maxBytes > 0)) {
2356
+ throw substratError('validation_failed', `connectorBudget.maxBytes must be a positive whole number of bytes, got ${String(budget.maxBytes)}`);
2357
+ }
2358
+ if (budget?.maxMs !== undefined)
2359
+ assertPositiveMs('connectorBudget.maxMs', budget.maxMs);
2360
+ for (const name of ['baseDelayMs', 'maxDelayMs']) {
2361
+ const ms = options.connectorCrashBackoff?.[name];
2362
+ if (ms !== undefined)
2363
+ assertPositiveMs(`connectorCrashBackoff.${name}`, ms);
2364
+ }
2365
+ }
2366
+ async function sweepConnections(host, options, report, listScopes, concurrency) {
2367
+ const clock = options.clock ?? Date.now;
2368
+ const budget = {
2369
+ maxBytes: options.connectorBudget?.maxBytes ?? CONNECTOR_SWEEP_MAX_BYTES,
2370
+ maxMs: options.connectorBudget?.maxMs ?? CONNECTOR_SWEEP_MAX_MS,
2371
+ };
2372
+ const crashBackoff = {
2373
+ maxAttempts: Number.MAX_SAFE_INTEGER,
2374
+ baseDelayMs: options.connectorCrashBackoff?.baseDelayMs ?? CONNECTOR_CRASH_BACKOFF.baseDelayMs,
2375
+ maxDelayMs: options.connectorCrashBackoff?.maxDelayMs ?? CONNECTOR_CRASH_BACKOFF.maxDelayMs,
2376
+ };
2377
+ const connections = await host.admin.listConnections(options.actor, {});
2378
+ const landings = options.connectionLandings ? new LandingPass(host, options.actor, options.connectionLandings, concurrency, listScopes) : null;
2379
+ await mapBounded(connections, concurrency, async (c) => {
2380
+ // #1232: the connection's durable sweep record. A connection row carries no
2381
+ // scope (a connection spans scopes by construction) and no version.
2382
+ const record = (outcome, extra) => options.recordSweepRun?.({
2383
+ kind: 'connector',
2384
+ unit: c.id,
2385
+ outcome,
2386
+ tenantId: c.tenantId,
2387
+ vertical: c.vertical,
2388
+ operation: `sweep.connector:${c.provider}`,
2389
+ connectionId: c.id,
2390
+ ...extra,
2391
+ });
2392
+ if (c.revokedAt !== null) {
2393
+ // Terminal — nothing to reconcile through it, and deliberately unrecorded:
2394
+ // a revoked connection is not "waiting to be swept", and a skipped row per
2395
+ // pass forever would be noise every strip has to filter back out.
2396
+ report.connectionsSkipped += 1;
2397
+ return;
2398
+ }
2399
+ // #3324: an operator's pause. Recorded, unlike a revoke: the connection is live and nothing
2400
+ // polls it, which is what a reader of its row should see, pass after pass, until it is lifted.
2401
+ if (options.pausedConnections?.has(c.id)) {
2402
+ report.connectionsPaused += 1;
2403
+ report.connectionsSkipped += 1;
2404
+ record('skipped', { error: CONNECTOR_SWEEP_PAUSED });
2405
+ return;
2406
+ }
2407
+ const sweeper = options.sweepers[c.provider] ?? options.sweeperFor?.(c);
2408
+ if (!sweeper) {
2409
+ report.connectionsSkipped += 1;
2410
+ // Recorded, unlike the revoked case: "bound but no sweeper registered" is a
2411
+ // live connection nothing will ever poll — exactly the declared-vs-observed
2412
+ // finding the signals views exist to surface.
2413
+ record('skipped');
2414
+ return;
2415
+ }
2416
+ // #3324: a sweep the pass died in left its attempt and no outcome. Waited out, exponentially and
2417
+ // capped, rather than run again on the next pass: run on every pass, it was every pass that died.
2418
+ if (options.recordSweepAttempt) {
2419
+ let crashed;
2420
+ try {
2421
+ crashed = await crashedAttemptsOf(host, options.actor, c.id);
2422
+ }
2423
+ catch (err) {
2424
+ // Without the record, a sweep that kills its pass would be run again on every one.
2425
+ report.errors.push({ kind: 'sweep', id: c.id, error: `cannot read the connection's sweep attempts: ${message(err)}` });
2426
+ report.connectionsSkipped += 1;
2427
+ return;
2428
+ }
2429
+ if (crashed) {
2430
+ const retryAt = Date.parse(backoffAt(crashed.streak, crashBackoff, new Date(crashed.lastAt)));
2431
+ const said = `the last ${counted(crashed.streak, 'sweep')} of connection ${c.id} did not finish: the pass running ${crashed.streak === 1 ? 'it' : 'them'} ended first`;
2432
+ if (clock() < retryAt) {
2433
+ report.connectionsBackingOff += 1;
2434
+ report.connectionsSkipped += 1;
2435
+ report.errors.push({ kind: 'sweep', id: c.id, error: `${said}; next attempt after ${new Date(retryAt).toISOString()}` });
2436
+ return;
2437
+ }
2438
+ // Filed once per retry, so the failure digest names a connection whose sweeps keep dying.
2439
+ options.recordFailure?.(withheldStaffFailure({ operation: `sweep.connector:${c.provider}`, stage: 'sweep', vertical: c.vertical }, `${said}; trying again`, ulid(), `connection ${c.id} of tenant ${c.tenantId}: `));
2440
+ }
2441
+ }
2442
+ const started = Date.now();
2443
+ // #2316: what the running versions declare, granted and bound before the poll reads bindings.
2444
+ // Never sinks the sweep: its failures join the poll's on the connection's row.
2445
+ const landed = landings ? await landings.apply(c).catch((err) => ({ granted: [], bound: [], failed: [{ scopeId: '*', error: message(err) }] })) : null;
2446
+ if (landed && report.connectionLandings) {
2447
+ report.connectionLandings.granted += landed.granted.length;
2448
+ report.connectionLandings.bound += landed.bound.length;
2449
+ report.connectionLandings.failed += landed.failed.length;
2450
+ }
2451
+ const landingFailed = landed?.failed ?? [];
2452
+ // #2316: the row is the connection's tenant's to read, so it says what became of the sweep, in
2453
+ // the platform's words with counts, under one reference; the text (a provider's answer, a landing
2454
+ // refusal) is staff's row under the same reference, or the report's when nothing files one.
2455
+ //
2456
+ // #3235: a failure that names the scope it belongs to is filed as a PAIR under that reference: a
2457
+ // row for the connection's tenant, carrying the scope, so that app's Failures view and fleet
2458
+ // health count it, saying in the platform's words what became of that binding (with the
2459
+ // connector's `said` when it gave one); and staff's row with the failure's own text. Only a
2460
+ // failure with no scope (a sweep that threw, a landing pass that could not start) stays staff's
2461
+ // alone, as before.
2462
+ const fail = (said, failures, neutralDetail) => {
2463
+ const reference = ulid();
2464
+ if (options.recordFailure) {
2465
+ const operation = `sweep.connector:${c.provider}`;
2466
+ const opening = `connection ${c.id} of tenant ${c.tenantId}: `;
2467
+ const unscoped = [];
2468
+ // One pair per scope: a scope can fail twice in one pass (a declared landing, then its
2469
+ // poll), and two pairs sharing the reference, the operation and the scope could not be told
2470
+ // apart by a reader that pairs them.
2471
+ const byScope = new Map();
2472
+ for (const f of failures) {
2473
+ const scope = f.scopeId === undefined ? undefined : scopeIdSchema.safeParse(f.scopeId);
2474
+ if (!scope?.success) {
2475
+ unscoped.push(f.scopeId === undefined ? f.error : `scope ${f.scopeId}: ${f.error}`);
2476
+ continue;
2477
+ }
2478
+ byScope.set(scope.data, [...(byScope.get(scope.data) ?? []), f]);
2479
+ }
2480
+ for (const [scope, fs] of byScope) {
2481
+ options.recordFailure(withheldOpsFailure({ operation, stage: 'sweep', tenantId: c.tenantId, scopeId: scope, vertical: c.vertical }, fs.map((f) => f.error).join('; '), (ref) => `${[...new Set(fs.map((f) => tenantSentence(c.provider, f)))].join('; ')} (reference ${ref})`, reference, `${opening}scope ${scope}: `));
2482
+ }
2483
+ if (unscoped.length > 0) {
2484
+ options.recordFailure(withheldStaffFailure({ operation, stage: 'sweep', vertical: c.vertical }, unscoped.join('; '), reference, opening));
2485
+ }
2486
+ }
2487
+ else {
2488
+ for (const f of failures)
2489
+ report.errors.push({ kind: 'sweep', id: c.id, error: f.scopeId === undefined ? f.error : `scope ${f.scopeId}: ${f.error}` });
2490
+ }
2491
+ const failureText = `${said.join('; ')} (reference ${reference})`;
2492
+ record('failed', { error: neutralDetail ? `Unsupported bindings: ${neutralDetail}\n${failureText}` : failureText, elapsedMs: Date.now() - started });
2493
+ };
2494
+ const landingSaid = landingFailed.length > 0 ? [`${counted(landingFailed.length, 'declared landing')} could not be granted or bound`] : [];
2495
+ const landingFailures = landingFailed.map((f) => ({ ...f, landing: true }));
2496
+ const everyMinutes = options.sweepEveryMinutes?.[c.provider];
2497
+ if (everyMinutes) {
2498
+ try {
2499
+ const [ok, failed, unsupported] = await Promise.all([
2500
+ host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'ok', limit: 1 }),
2501
+ host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'failed', limit: 1 }),
2502
+ host.admin.listSweepRuns(options.actor, { kind: 'connector', unit: c.id, outcome: 'unsupported', limit: 1 }),
2503
+ ]);
2504
+ // Ignore skipped rows and future-dated receipts: neither proves a poll inside this interval.
2505
+ const now = Date.now();
2506
+ const lastAttempt = Math.max(0, ...[ok[0], failed[0], unsupported[0]].filter((row) => row !== undefined).map((row) => Date.parse(row.at)).filter((at) => at <= now));
2507
+ if (now - lastAttempt < everyMinutes * 60_000) {
2508
+ if (landingFailed.length > 0)
2509
+ fail(landingSaid, landingFailures);
2510
+ report.connectionsSkipped += 1;
2511
+ return;
2512
+ }
2513
+ }
2514
+ catch (err) {
2515
+ // Without the ledger's clock, do not risk spending the provider's daily allowance.
2516
+ if (landingFailed.length > 0)
2517
+ fail(landingSaid, landingFailures);
2518
+ report.errors.push({ kind: 'sweep', id: c.id, error: `cannot read connector cadence: ${message(err)}` });
2519
+ report.connectionsSkipped += 1;
2520
+ return;
2521
+ }
2522
+ }
2523
+ // #3324: the attempt, noted before the work and awaited, so a pass that dies inside the sweep
2524
+ // leaves it behind. A note that cannot be written holds the sweep back a pass: without it, a
2525
+ // sweep that kills its pass would be run again on every one.
2526
+ if (options.recordSweepAttempt) {
2527
+ try {
2528
+ await options.recordSweepAttempt({
2529
+ kind: 'connector-attempt',
2530
+ unit: c.id,
2531
+ outcome: 'started',
2532
+ tenantId: null,
2533
+ vertical: c.vertical,
2534
+ operation: `sweep.connector:${c.provider}`,
2535
+ connectionId: c.id,
2536
+ });
2537
+ }
2538
+ catch (err) {
2539
+ if (landingFailed.length > 0)
2540
+ fail(landingSaid, landingFailures);
2541
+ report.errors.push({ kind: 'sweep', id: c.id, error: `cannot note the sweep's attempt, so it waits for the next pass: ${message(err)}` });
2542
+ report.connectionsSkipped += 1;
2543
+ return;
2544
+ }
2545
+ }
2546
+ let result;
2547
+ try {
2548
+ // #2498: a sized stream body the connector sends reaches the injected fetch converted.
2549
+ // #3324: and the connection reads no more than its share of the pass (`budgetedFetch`).
2550
+ result = await sweeper(host, c.id, { fetch: budgetedFetch(fetchLikeOf(options.fetch), { ...budget, clock }) });
2551
+ }
2552
+ catch (err) {
2553
+ // The landing step's failures, if any, belong on the same row as the poll's throw.
2554
+ fail([...landingSaid, 'the sweep did not complete'], [...landingFailures, { error: message(err) }]);
2555
+ return;
2556
+ }
2557
+ const answer = options.connectionLandings && binderOf(options.connectionLandings, c) ? connectorSweepAnswerOf(result) : null;
2558
+ // Skipped only when the row below is `unsupported`: a failed landing makes it `failed`, and swept.
2559
+ if (answer && answer.found > 0 && answer.unsupported?.length === answer.found && answer.failed.length === 0 && landingFailed.length === 0) {
2560
+ report.connectionsSkipped += 1;
2561
+ }
2562
+ else {
2563
+ report.connectionsSwept += 1;
2564
+ }
2565
+ // #2316: a resolved sweep is not a landed one. A binding the connector could not land, or a
2566
+ // landing the platform could not seat, fails the row; a poll that found nothing to poll is
2567
+ // `skipped`, which a console reads as "nothing polls this connection". A mixed connection
2568
+ // records the result of its polled bindings and keeps unsupported bindings in the detail.
2569
+ const pollFailed = answer?.failed ?? [];
2570
+ const unsupported = answer?.unsupported ?? [];
2571
+ const unsupportedDetail = unsupported.map((u) => `scope ${u.scopeId}: ${u.reason}`).join('; ');
2572
+ if (landingFailed.length > 0 || pollFailed.length > 0) {
2573
+ fail([...landingSaid, ...(pollFailed.length > 0 ? [`${pollFailed.length} of ${counted(answer.found, 'binding')} did not land${saidOf(pollFailed)}`] : [])], [...landingFailures, ...pollFailed], unsupportedDetail || undefined);
2574
+ }
2575
+ else if (answer && answer.found === 0) {
2576
+ record('skipped', { error: NO_BINDING, elapsedMs: Date.now() - started });
2577
+ }
2578
+ else if (unsupported.length > 0 && answer?.found === unsupported.length) {
2579
+ record('unsupported', { error: unsupportedDetail, elapsedMs: Date.now() - started });
2580
+ }
2581
+ else {
2582
+ record('ok', { ...(unsupportedDetail ? { error: unsupportedDetail } : {}), elapsedMs: Date.now() - started });
2583
+ }
2584
+ });
2585
+ }
2444
2586
  //# sourceMappingURL=platform-sweep.js.map