@substrat-run/adapter-cloudflare 0.210.0 → 0.211.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/host.js CHANGED
@@ -1,16 +1,17 @@
1
1
  import { env as ambientEnv } from 'cloudflare:workers';
2
2
  import { isRewindRefusal, REWIND_REFUSED } from './rewind-refusal.js';
3
3
  import { isSystemDoorMoved, SYSTEM_DOOR_MOVED, SYSTEM_DOOR_REGATES } from './system-door.js';
4
- import { delegatedReadParams, operationSeriesCount, fromWireFailure, isSubstratError, exportReadInput, exportedBatch, importBatch, importResult, importState, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, exportsOfManifestJson, assertNoBindingShapeBreak, importCursorMove, importCursorMoveAt, importCursorMoved, accessLogEntry, adminLogEntry, opsFailureEntry, opsFailureFingerprint, issueEntry, findingEntry, findingRuleEntry, sweepRunEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunsPayload, modelUsageEntry, createTenantInput, identityLink, identityPool, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, registerVerticalInput, vertical as verticalSchema, verticalServingState, deploymentWireAuth, verticalChannel, verticalVersion, connection, capabilityExchange, mintedCapability, boundedBecomeMint, boundedBindLinkMint, boundedBecomeRevoke, boundedUnbind, entityRef, becomeLinkState, principalBecomeCapabilityInput, principalBindLinkInput, capabilityGrant, principalId, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchOutcome, systemScheduleEntry, systemSwitchRecord, entitlementGrant, entitlementGrantInput, capabilityFilter, instant, meterReading, scopeStorageSample, requestDay, requestRollupDay, costDay, meterDay, meterDayTake, verticalOwnerPeriod, subjectRef, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, org as orgSchema, orgMembership, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, subjectShredReceipt, subjectAccessReceipt, connectorDispatchKind, callsOfManifestJson, outboundOfManifestJson, SCOPE_GATE_REASONS, substratError, MODULE_OBJECTS_NOT_CARRIED, errorCodeOf, redrainEventsInput, coverage, peerCoverage, peerGrantsEntry, peerSwitch, peerSwitchOutcome, verticalCaller, verticalResolution, peerInstanceResolution, peerBinding as peerBindingSchema, verticalSlug, entityObjectRef, ATTACHMENT_BLOB_BINDING, blobStoreBindingName, lifecycleDelivery, scopeLifecycle, storeDriverDumpPageBytes, } from '@substrat-run/contracts';
4
+ import { delegatedReadParams, operationSeriesCount, fromWireFailure, isSubstratError, exportReadInput, exportedBatch, importBatch, importResult, importState, importsOfManifestJson, connectionLandingsOfManifestJson, connectorsOfManifestJson, exportsOfManifestJson, assertNoBindingShapeBreak, importCursorMove, importCursorMoveAt, importCursorMoved, accessLogEntry, adminLogEntry, opsFailureEntry, opsFailureFingerprint, issueEntry, findingEntry, findingRuleEntry, sweepRunEntry, FRESHNESS_HEARTBEAT_MINUTES, sweepRunsPayload, modelUsageEntry, createTenantInput, identityLink, identityPool, createOrgInput, promotionAcknowledgement, bindAcknowledgement, bindHostnameInput, channelHistoryEntry, hostnameBinding, publishVersionInput, AUTO_ADMISSION_NOTE, registerVerticalInput, vertical as verticalSchema, verticalServingState, deploymentWireAuth, verticalChannel, verticalVersion, connection, capabilityExchange, mintedCapability, boundedBecomeMint, boundedBindLinkMint, boundedBecomeRevoke, boundedUnbind, entityRef, becomeLinkState, principalBecomeCapabilityInput, principalBindLinkInput, capabilityGrant, principalId, connectionGrant, connectionRevoke, connectionGrantRecord, connectionSecret, systemGrant, systemSwitch, systemSwitchOutcome, systemScheduleEntry, systemSwitchRecord, entitlementGrant, entitlementGrantInput, capabilityFilter, instant, meterReading, scopeStorageSample, requestDay, requestRollupDay, costDay, meterDay, meterDayTake, staleScope, staleScopeTake, verticalOwnerPeriod, subjectRef, createConnectionInput, connectLinkFilter, connectLinkKey, consumeConnectLinkInput, mintConnectLinkInput, projectedConnectionGrant, projectedConnectionKey, moduleManifest, org as orgSchema, orgMembership, resolvedIdentity, identityMembership, roleDefinition, scope as scopeSchema, tenant as tenantSchema, tenantRole, delegatedReadRecord, ownerTransferAudit, memberChangeAudit, peerBindingAudit, connectionBindingAudit, copyMarkAudit, orphanSweepAudit, deliveryRedriveAudit, subjectShredReceipt, subjectAccessReceipt, connectorDispatchKind, callsOfManifestJson, outboundOfManifestJson, SCOPE_GATE_REASONS, substratError, MODULE_OBJECTS_NOT_CARRIED, errorCodeOf, redrainEventsInput, coverage, peerCoverage, peerGrantsEntry, peerSwitch, peerSwitchOutcome, verticalCaller, verticalResolution, peerInstanceResolution, peerBinding as peerBindingSchema, verticalSlug, entityObjectRef, ATTACHMENT_BLOB_BINDING, blobStoreBindingName, lifecycleDelivery, scopeLifecycle, storeDriverDumpPageBytes, } from '@substrat-run/contracts';
5
5
  import { normalizeHostname, toRouteTarget } from './route-resolver.js';
6
6
  import { prePromoteSnapshotExpiresAt } from '@substrat-run/kernel';
7
- import { markupRecordValues, markupScheduleOf, newMarkupRow, } from '@substrat-run/kernel';
7
+ import { CONNECTOR_DISPATCH_REQUESTED_BY, markupRecordValues, markupScheduleOf, newMarkupRow, } from '@substrat-run/kernel';
8
8
  import { attachmentBlobKey, normalizeUploadMediaType, redeemOrReplayUploadLink, attachmentSha256, bytesStream, isSizedByteStream, openAttachmentByteStream, putAttachmentBytes, refuseEntitlement, requiredEntitlementFor, foldMeterReading, parseValidationRecords, readableScopes, resolveScopeRecord, ulid, withheldOpsFailure, KEPT_COPY_REFUSAL, capabilityTokenHash, checkBecomeInput, assertBecomeLinkStateIds, plausibleSessionToken, foldModelUsage, backoffAt, resolveRetryPolicy, executorOutcomeOf, isDeliveryRefusal, refusalJournalText, isSecretBoxConfigured, unconfiguredSecretBox, createSubjectKeys, generateSealingKeyPair, openSealed, ImpersonationRefused, assertSessionUsable, impersonationRowValues, mapImpersonationRow, newImpersonationSession, jobRunOf, assertLeaseMs, runDueJobRuns, SYSTEM_DOOR_WAIT, startJobRun, attachmentTextJob, assertAttachmentExtractors, resolveAttachmentTextBounds, assertJobRegistrable, ATTACHMENT_TEXT_BACKFILL_JOB, ATTACHMENT_TEXT_JOB, kernelJobFor, attachmentTextBackfillJob, searchLimit, searchMatchExpression, globalFetch, fetchLikeOf, deadlineFetch, assertRedrainWindow, platformRequestOf, undrainedEventsOf, outboxSubscribersOf, pruneInputOf, inUnitMovesToAudit, staleCarryRevertRow, staleCarryReverts, recordedOffFromWire, peerSubjectRef, SWITCH_KINDS, reassertActionOf, reassertEntry, reassertOffRow, reassertOnRow, switchActionOf, switchAuditSubject, recordAuditOutcome, auditedCapabilityRevoke, auditedScopePermissionWrite, auditWarningOf, switchNotFoundMessage, recordWriteSuperseded, switchSubjectOf, switchSupersededMessage, withRecorded, systemSwitchedOffMessage, tenantSystemSwitchedOffMessage, CrossVerticalRegistry, importCursorSourceOf, exportBreaksOf, exportBreakRefusal, assertPromoteReviewCurrent, promoteRaceRefusal, servingRaceRefusal, migratesFrom, servedFromRow, rebindRaceRefusal, bindExportBreaksOf, bindExportBreakRefusal, scopeMoveOf, runningVersionOf, strandJudgmentsOf, boundShapesOfColumn, installReconciled, collectPeers, peerCallerAt, peerSeats, connectorCallRecord, noopConnectorCallRecorder, recordConnectorCall, settleConnectionUse, splitManifestMigrations, publishedMigrationDigest, migrationChangeRefusal, unknownRoleError, assertRowLimit, assertRowOffset, emptyImportResult, INERT_SCOPE_REASON, lifecycleReceipt, lifecycleRefusal, scopeNotHeldRefusal, isPrimaryScope, isPrimaryScopeRow, asyncInvocationId, asyncLinePass, assertNoCallerPurge, parseScopeDelegation, delegationCeilingOf, heldKeysOf, purgeReportOf, purgeStillDue, assertBoundOperations, registerTrashTargets, assertModuleDeclared, noteDeclaredKeys, noteReservedKeys, reservedGrantRefusal, reservedRoleRefusal, reservedRoleSetRefusal, reservedShapeRefusal, SEAT_HOLDING_SCOPE_STATUSES, dumpRoleRefusal, dumpRoleState, memberAddedAudit, shapeTopUpBatch, verticalOwnerNow, } from '@substrat-run/kernel';
9
9
  import { fenceAttachmentSweep, missingAttachmentStore, sweepOrphanAttachments, unsettledCopyRefusal } from '@substrat-run/kernel';
10
10
  import { ConnectorRevokeUnsupported } from '@substrat-run/kernel';
11
11
  import { assertWireAuthFilter, wireAuthAccessTarget, COPY_RESTORE_FENCE_LAPSED, scopeScriptCopyOf } from '@substrat-run/kernel';
12
12
  import { attributedView, isModuleErasureCounts, moduleErasurePlan, moduleRowsErased, callReservedStoreOperation, readStoreDump, writeStoreDump, callScopeStore, observeStoreCall, replayStoreErasures, scopeStoreLifecycleOf, scopeStoreRunnersOf } from '@substrat-run/kernel';
13
- import { PLATFORM_BINDING_PREFIX, PLATFORM_STORE_CODE, scopeStoreBindingName, scopeStoreObjectName, STORE_CALL_URL, storeAnswerOf, StoreError } from '@substrat-run/contracts';
13
+ import { PLATFORM_BINDING_PREFIX, PLATFORM_STORE_CODE, parseTraceparent, scopeStoreBindingName, scopeStoreObjectName, STORE_CALL_URL, storeAnswerOf, StoreError, TRACEPARENT_HEADER } from '@substrat-run/contracts';
14
+ import { currentTraceparent } from '@substrat-run/kernel/invocation-line';
14
15
  import { isOrangeToOrange, isUpgradeRequest, LIVE_PRINCIPAL_HEADER, LIVE_SCOPE_HEADER, LIVE_SUBSCRIBE_PATH, LIVE_TENANT_HEADER, LIVE_WITHIN_HEADER, LIVE_EXPIRES_HEADER, liveInstant, encodeLiveWithin, liveRefusalStatus, liveWithinOf, } from './live-reads.js';
15
16
  import { tenantStoreDatabaseName } from './d1.js';
16
17
  import { blobStoreBucketName, r2TenantBlobStore, workerdSha256 } from './r2.js';
@@ -715,7 +716,13 @@ export class CloudflareScopeHost {
715
716
  const isHeld = async () => this.cpLess
716
717
  ? this.lifecycleHeld(scopeId)
717
718
  : (await this.cp.scopeAccessRefusal(tenantId, scopeId)) !== null;
719
+ // #3365: set at the first delivery that finds the scope's routed-delivery room full. Every
720
+ // later connector delivery in this pass would meet the same answer, each a round trip that
721
+ // records nothing, so routing stops for the pass and the drain the report asks for makes room.
722
+ let roomFull = false;
718
723
  drain: for (const [id, executor] of this.executors) {
724
+ if (roomFull && executor.kind === 'connector' && this.cpLess)
725
+ continue;
719
726
  const deliveryId = `executor:${id}`;
720
727
  const { events, undecodable } = await stub.pendingExecutorDeliveries(deliveryId, executor.eventType);
721
728
  // #1636: an event the DO could not decode is dead-lettered for this executor at once,
@@ -775,7 +782,15 @@ export class CloudflareScopeHost {
775
782
  // the authority this host lacks. The intent row carries the retry
776
783
  // state from here on; the handler's own idempotency ledger absorbs
777
784
  // the at-least-once residue, as it already must in-process.
778
- await stub.routeExecutorEventToPlatform(event.id, deliveryId, connectorDispatchKind(executor.provider), JSON.stringify({ executorId: id, event }), JSON.stringify({ system: 'connector-dispatch' }), invocationId);
785
+ const routed = await stub.routeExecutorEventToPlatform(event.id, deliveryId, connectorDispatchKind(executor.provider), JSON.stringify({ executorId: id, event }), CONNECTOR_DISPATCH_REQUESTED_BY, invocationId);
786
+ if (routed === null) {
787
+ // #3365: no room. Not an attempt — nothing was journaled, so the delivery stays due
788
+ // and the first pass after a drain routes it. The attempt counted here is undone.
789
+ report.attempted -= 1;
790
+ report.awaitingRoom = (report.awaitingRoom ?? 0) + 1;
791
+ roomFull = true;
792
+ continue drain;
793
+ }
779
794
  report.routedToPlatform += 1;
780
795
  outcomeOf(event, 'routed');
781
796
  // Handed on, not run here: the platform's drain owns its attempts from now on.
@@ -959,6 +974,28 @@ export class CloudflareScopeHost {
959
974
  // Tolerant (#1588, #1637): an undecodable row comes back naming why, never throws for the list.
960
975
  return (await this.scopeStub(scopeId).pendingPlatformRequests()).map(platformRequestOf);
961
976
  }
977
+ /**
978
+ * #3365: route this scope's due deliveries now, into whatever room a drain has just made — what
979
+ * the platform's drain calls between rounds, so a backlog larger than the routed-delivery room
980
+ * keeps moving inside one drain instead of a pass at a time. `drainDue`, answered as the two
981
+ * numbers the drain reads.
982
+ */
983
+ async routeDueDeliveries(tenantId, scopeId) {
984
+ const report = await this.drainDue(tenantId, scopeId);
985
+ return { routed: report.routedToPlatform ?? 0, awaitingRoom: report.awaitingRoom ?? 0 };
986
+ }
987
+ /** #3365: re-drive one `failed` connector intent (`retryPlatformRequest`). Whether a row moved. */
988
+ async retryPlatformRequestLocal(tenantId, scopeId, id) {
989
+ await this.validateScopeAccess(tenantId, scopeId, 'retryPlatformRequest');
990
+ await this.migrateAndRecord(scopeId);
991
+ return this.scopeStub(scopeId).retryPlatformRequest(id);
992
+ }
993
+ /** #3365: re-drive one dead-lettered executor delivery (`retryExecutorDelivery`). Whether a row moved. */
994
+ async retryExecutorDeliveryLocal(tenantId, scopeId, eventId, executorId) {
995
+ await this.validateScopeAccess(tenantId, scopeId, 'retryExecutorDelivery');
996
+ await this.migrateAndRecord(scopeId);
997
+ return this.scopeStub(scopeId).retryExecutorDelivery(eventId, `executor:${executorId}`);
998
+ }
962
999
  async listPlatformRequestHistory(tenantId, scopeId, filter) {
963
1000
  await this.validateScopeAccess(tenantId, scopeId, 'listPlatformRequestHistory');
964
1001
  await this.migrateAndRecord(scopeId);
@@ -2549,9 +2586,11 @@ export class CloudflareScopeHost {
2549
2586
  // The egress hop answers with the platform's own codes too (#2815).
2550
2587
  through: 'platform',
2551
2588
  send: async (request) => {
2589
+ // #3368: the request's trace, so the call joins it through egress and the router.
2590
+ const trace = currentTraceparent();
2552
2591
  const response = await this.fetchImpl(STORE_CALL_URL, {
2553
2592
  method: 'POST',
2554
- headers: { 'content-type': 'application/json' },
2593
+ headers: { 'content-type': 'application/json', ...(parseTraceparent(trace) ? { [TRACEPARENT_HEADER]: trace } : {}) },
2555
2594
  body: JSON.stringify({ scopeId, binding, operation: request.operation, input: request.input }),
2556
2595
  });
2557
2596
  try {
@@ -3850,8 +3889,10 @@ export class CloudflareScopeHost {
3850
3889
  // Routed connector deliveries (#574 phase 3) count too: the inline drain just
3851
3890
  // turned this operation's event into a `connector:<provider>` intent, and the
3852
3891
  // kick is what collapses its dispatch latency from sweep-cadence to seconds.
3892
+ // #3365: so do deliveries left waiting for room — the drain is what makes it, and without
3893
+ // the kick nothing but the 15-minute sweep would run one.
3853
3894
  const enqueued = envelope.platformRequests + (drained.routedToPlatform ?? 0);
3854
- if (enqueued > 0)
3895
+ if (enqueued > 0 || (drained.awaitingRoom ?? 0) > 0)
3855
3896
  options?.onPlatformRequests?.(enqueued, scopeId);
3856
3897
  if ((envelope.exported ?? 0) > 0)
3857
3898
  options?.onExportedEvents?.(envelope.exported);
@@ -6226,9 +6267,11 @@ export class CloudflareScopeHost {
6226
6267
  exportDirectoryPage: async (actor, cursor, opts) => {
6227
6268
  const { copiedTables, ...page } = await this.cp.exportDumpPage(cursor, opts);
6228
6269
  // One access-log row per copy, as a whole export writes: its first page takes the copy, so
6229
- // the count is every table the copy holds, and the params say it was paged.
6230
- if (cursor === null)
6231
- await this.recordAccess(actor, 'exportDirectory', {}, { paged: true }, copiedTables ?? page.tables.length);
6270
+ // the count is every table the copy holds, and the params say it was paged, and how it carried
6271
+ // the tables it can read by reference (#3325).
6272
+ if (cursor === null) {
6273
+ await this.recordAccess(actor, 'exportDirectory', {}, { paged: true, byReference: opts?.byReference ?? 'off' }, copiedTables ?? page.tables.length);
6274
+ }
6232
6275
  return page;
6233
6276
  },
6234
6277
  restoreDirectory: async (actor, dump) => {
@@ -6917,6 +6960,11 @@ export class CloudflareScopeHost {
6917
6960
  const { tenantId, scopeId, action, ...after } = copyMarkAudit.parse(entry);
6918
6961
  await this.recordAdmin(actor, action === 'mark' ? 'markScopeCopy' : 'clearScopeCopyMark', { tenantId, scopeId }, null, after);
6919
6962
  },
6963
+ /** #3365: one staff re-drive, written after the scope's own move. */
6964
+ recordDeliveryRedrive: async (actor, entry) => {
6965
+ const { tenantId, scopeId, ...after } = deliveryRedriveAudit.parse(entry);
6966
+ await this.recordAdmin(actor, 'redriveDelivery', { tenantId, scopeId }, null, after);
6967
+ },
6920
6968
  /** #2314: one orphan-attachment pass over a scope, written after the vertical's own pass. */
6921
6969
  recordOrphanSweep: async (actor, entry) => {
6922
6970
  const { tenantId, scopeId, ...after } = orphanSweepAudit.parse(entry);
@@ -7183,6 +7231,17 @@ export class CloudflareScopeHost {
7183
7231
  return rows;
7184
7232
  },
7185
7233
  pruneMeterDays: async (_actor, limit, retentionMonths) => this.cp.pruneMeterDays(assertRowLimit('limit', limit), retentionMonths),
7234
+ recordStaleScopes: async (_actor, input) => this.cp.recordStaleScopes(input),
7235
+ listStaleScopes: async (actor, filter) => {
7236
+ const rows = (await this.cp.listStaleScopes(filter)).map((r) => staleScope.parse(r));
7237
+ await this.recordAccess(actor, 'listStaleScopes', { tenantId: filter?.tenantId ?? null }, filter ?? null, rows.length);
7238
+ return rows;
7239
+ },
7240
+ listStaleScopeTakes: async (actor, filter) => {
7241
+ const rows = (await this.cp.listStaleScopeTakes(filter)).map((r) => staleScopeTake.parse(r));
7242
+ await this.recordAccess(actor, 'listStaleScopeTakes', { tenantId: null }, filter ?? null, rows.length);
7243
+ return rows;
7244
+ },
7186
7245
  recordModelUsage: async (input) => {
7187
7246
  const l = input.line;
7188
7247
  return this.cp.recordModelUsage({