@substrat-run/adapter-cloudflare 0.205.0 → 0.206.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.
@@ -2,6 +2,7 @@ import { DurableObject } from 'cloudflare:workers';
2
2
  import { type TenantId } from '@substrat-run/contracts';
3
3
  import { type DeclaredPermissions, type SwitchSql, type ModuleRegistration, type OperationHandler } from '@substrat-run/kernel';
4
4
  import { type DoReply } from './do-reply.js';
5
+ import type { AnalyticsEngineDatasetLike } from './connector-calls.js';
5
6
  import { splitSqlStatements } from '@substrat-run/kernel';
6
7
  /**
7
8
  * `defineScopeDO` — one Durable Object per scope, the CF analogue of a single
@@ -40,6 +41,16 @@ export interface ScopeDoEnv {
40
41
  * version, a script uploaded before the binding, or a test worker compares nothing.
41
42
  */
42
43
  SUBSTRAT_MIGRATIONS_DIGEST?: string;
44
+ /**
45
+ * #3316: the Analytics Engine dataset each invocation's rows are counted into, by origin
46
+ * (`scope-work.ts`). Injected at upload; without it nothing is counted and no entry is wrapped
47
+ * at run time beyond one property read.
48
+ */
49
+ SUBSTRAT_SCOPE_WORK?: AnalyticsEngineDatasetLike;
50
+ /** #3316: the vertical's slug, injected at upload beside the dataset, stamped on each point. */
51
+ SUBSTRAT_VERTICAL?: string;
52
+ /** #3316: `live` on the serving script, `preview` on a version's own script, as the upload says. */
53
+ SUBSTRAT_SCRIPT_KIND?: string;
43
54
  }
44
55
  /** #2016: how a tenant reads against a scope's record (`ScopeDO.tenantVerdict`). */
45
56
  export type TenantVerdict = 'recorded' | 'inferred' | 'foreign' | 'unknown';
@@ -1 +1 @@
1
- {"version":3,"file":"scope-do.d.ts","sourceRoot":"","sources":["../src/scope-do.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAwDL,KAAK,QAAQ,EAmBd,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAiEL,KAAK,mBAAmB,EASxB,KAAK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CAAE,CAAC;AAulBjG,kGAAkG;AAClG,wBAAgB,QAAQ,CAAC,GAAG,EAAE,SAAS,OAAO,EAAE,GAAG,MAAM,CAQxD;AAgQD;;;GAGG;AACH,MAAM,MAAM,yBAAyB,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC;AAmBtD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,UAAU,GAAG,SAAS,CAOxD;AAED,gHAAgH;AAChH,OAAO,EAAE,kBAAkB,EAAE,CAAC;AA2B9B,wBAAgB,aAAa,CAC3B,OAAO,EAAE,kBAAkB,EAAE,EAC7B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AACzD;;;;GAIG;AACH,OAAO,GAAE;IAAE,WAAW,CAAC,EAAE,mBAAmB,CAAA;CAAO,GAClD,KAAK,GAAG,EAAE,kBAAkB,EAAE,GAAG,EAAE,UAAU,KAAK,aAAa,CAAC,UAAU,CAAC,CA+1R7E"}
package/dist/scope-do.js CHANGED
@@ -6,6 +6,7 @@ import { ulid, DO_SQL_LIMITS, unknownRoleError, createUlid, assertAllowed, Conne
6
6
  import { isUpgradeRequest, readSubscription, LIVE_DECIDE_ATTEMPTS, LIVE_FANOUT_LIMIT, LIVE_PRINCIPAL_HEADER, LIVE_SCOPE_HEADER, LIVE_SUBSCRIBE_PATH, LIVE_TENANT_HEADER, LIVE_WITHIN_HEADER, LIVE_EXPIRES_HEADER, LIVE_CLOSE, LIVE_SOCKETS_PER_PRINCIPAL, decodeLiveWithin, liveInstant, liveRefusal, liveRefusalStatus, } from './live-reads.js';
7
7
  import { replyOf } from './do-reply.js';
8
8
  import { OperationQueue } from './serialization.js';
9
+ import { meterScopeWorkEntries, ScopeWorkMeter } from './scope-work.js';
9
10
  import { assertNoWorkerdStorage, doScopedSql, doBuiltColumnsOf, doRedactionSql, doSpineSql } from './sql.js';
10
11
  import { actorOf, admitPeer, boundToPeerDeclarations, collectPeers, switchPeer, peerSubjectRef, subjectGrantState, assertNoSecret, CAPABILITY_DDL, UPLOAD_LINK_DDL, DOWNLOAD_LINK_DDL, createAttachmentVerbs, inspectUploadLink, resolveDownloadLink, redeemUploadLinkInTransaction, COPY_ORIGIN_DDL, ENTITY_STATE_MOVES_DDL, SWITCH_FENCES_DDL, TABLE_OWNERS_DDL, assertMigrationLeavesLedgerAlone, recordOwnershipSteps, runMigrationStatements, splitSqlStatements, executableSqlStatements, blankSqlComments, CAPABILITY_EXCHANGE_OPERATION, CAPABILITY_BECOME_MINT_OPERATION, becomeMintCheck, mintBecomeCapabilityAsPrincipal, CAPABILITY_BIND_MINT_OPERATION, bindLinkMintCheck, mintBindLinkAsPrincipal, revokeBecomeCapabilityAsPrincipal, readBecomeLinkStates, ENTITY_UNBIND_OPERATION, allowedFor, unbindEntityHolderBounded, capabilityAttachmentWriteRefused, createCapabilityVerbs, createEntityEdgeVerbs, createEntityStateVerbs, createTrashedReads, CONTINUATION_POSITION_CAP, visibleContinuation, searchStateWhere, uncheckedView, addStatePlans, addUpdatedStampPlans, watchUpdatedStamps, assertNoCallerPurge, isUnreachableParent, PURGE_BATCH, heldPurgePass, lifecycleRefusal, purgeHeldBy, assertPlatformRequestRoom, purgeDueOf, purgeOnlyKeysOf, runPurgePass, refuseTrashedTarget, assertBoundOperations, checkHeldOperationsOf, countChecks, noteUncheckedCompletion, registerTrashTargets, withheldKeysFor, capCoverage, delegationCeilingOf, delegationStampOf, outsideCeiling, parseScopeDelegation, statefulTablesOf, afterMigration, afterRuntimeDdl, derivesAnything, repairDerivedObjects, StateColumnLost, exchangeCapability, exchangeBecomeLinkById, guardSecrets, mintBecomeCapability, redactSecrets, redactSecretText, moduleLog, asyncInvocationId, asyncLinePass, resolveCapabilitySession, revokeCapabilityAsPlatform, readCapabilityPage, domainEventOf, facetEvents, readDeadLetters, readLifecycleFlow, readOperationSeries, readHistory, readInvocation, readUndrainedOutbox, walkEventCause, walkEventEffects, } from '@substrat-run/kernel';
11
12
  import { COPY_RESTORE_FENCE_LAPSED, copyRestoreFenceLapsed, orphanSweepVersionRefusal } from '@substrat-run/kernel';
@@ -619,7 +620,6 @@ function decodeDumpCursor(cursor) {
619
620
  * and over-counting only refuses a restore that could have landed.
620
621
  */
621
622
  class WriteRevision {
622
- raw;
623
623
  storage;
624
624
  suspended;
625
625
  refusal;
@@ -644,16 +644,24 @@ class WriteRevision {
644
644
  /** Inside `untracked`: a capture's own bookkeeping, which nothing here counts. */
645
645
  bypass = false;
646
646
  sql;
647
- constructor(raw, storage, suspended,
647
+ /** The handle every statement runs on: the runtime's, under the scope-work meter when there is one (#3316). */
648
+ raw;
649
+ constructor(runtime, storage, suspended,
648
650
  /** Why this store takes no write at all right now, or null (a `carried_away` copy, #1722). */
649
651
  refusal,
650
652
  /** Run before every write statement (#2450: an idle capture's triggers go before the write). */
651
- beforeWrite = () => undefined) {
652
- this.raw = raw;
653
+ beforeWrite = () => undefined,
654
+ /**
655
+ * #3316: the scope-work meter's counting wrapper, put UNDER everything here, so the revision's
656
+ * own bump and the capture's bypass are counted with the statement that caused them.
657
+ */
658
+ counted) {
653
659
  this.storage = storage;
654
660
  this.suspended = suspended;
655
661
  this.refusal = refusal;
656
662
  this.beforeWrite = beforeWrite;
663
+ const raw = counted ? counted(runtime) : runtime;
664
+ this.raw = raw;
657
665
  const exec = (query, ...bindings) => {
658
666
  if (this.bypass) {
659
667
  // Enforced, not trusted, as `bookkeeping` is: a write here that is not the capture's own
@@ -911,7 +919,7 @@ options = {}) {
911
919
  noteReservedKeys(declaredReserved, m.manifest);
912
920
  noteDeclaredKeys(declaredListed, m.manifest);
913
921
  }
914
- return class ScopeDO extends DurableObject {
922
+ const ScopeDO = class ScopeDO extends DurableObject {
915
923
  /**
916
924
  * #2351: the migrations this class registers, read by the control plane, which evaluates the
917
925
  * bundle in an isolate with no bindings and calls this before it stores the version. The same
@@ -1066,6 +1074,26 @@ options = {}) {
1066
1074
  carriedAwayCopy = false;
1067
1075
  /** #1722: the write revision, and the one way this object opens a transaction. */
1068
1076
  revision;
1077
+ /** #3316: this object's rows by origin, or undefined when the upload bound no dataset. */
1078
+ scopeWork;
1079
+ /** #3316: the tenant each point names, once known. */
1080
+ scopeWorkTenantId = null;
1081
+ /**
1082
+ * #3316: the tenant this scope was provisioned for, for the scope-work points — read with the
1083
+ * meter paused, the one read it does not count: two indexed lookups per point until the scope is
1084
+ * provisioned, then none again in this wake.
1085
+ */
1086
+ scopeWorkTenant() {
1087
+ if (this.scopeWorkTenantId !== null || !this.scopeWork)
1088
+ return this.scopeWorkTenantId;
1089
+ try {
1090
+ this.scopeWorkTenantId = this.scopeWork.uncounted(() => this.provisionedFor());
1091
+ }
1092
+ catch {
1093
+ // A point with no tenant is still a count; the scope and object ids name it.
1094
+ }
1095
+ return this.scopeWorkTenantId;
1096
+ }
1069
1097
  constructor(ctx, env) {
1070
1098
  super(ctx, env);
1071
1099
  // #1860: the client's 45s keep-alive (demos/ticket0/app/src/feed.ts) answered at
@@ -1073,11 +1101,24 @@ options = {}) {
1073
1101
  // subscriber's ping still reaches `webSocketMessage` and pins the DO in memory —
1074
1102
  // exactly the hibernation cost `acceptWebSocket` (below) exists to avoid.
1075
1103
  ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair('ping', 'pong'));
1104
+ // #3316: the rows each invocation runs, by origin, into Analytics Engine — only when the
1105
+ // upload bound a dataset. Built first, so the wake's own statements below are counted (`wake`).
1106
+ const scopeWork = env.SUBSTRAT_SCOPE_WORK;
1107
+ this.scopeWork = scopeWork
1108
+ ? new ScopeWorkMeter(scopeWork, {
1109
+ tenant: () => this.scopeWorkTenant(),
1110
+ vertical: env.SUBSTRAT_VERTICAL ?? null,
1111
+ scopeId: ctx.id.name ?? null,
1112
+ objectId: ctx.id.toString(),
1113
+ versionId: env.SUBSTRAT_VERSION_ID ?? null,
1114
+ kind: env.SUBSTRAT_SCRIPT_KIND ?? null,
1115
+ })
1116
+ : undefined;
1076
1117
  // #1722: the ONE handle this object writes through and the one way it opens a transaction,
1077
1118
  // so every write advances the write revision a carry's restore is fenced on, inside the
1078
1119
  // transaction that commits it. Nothing else here may take the raw handle or open a
1079
1120
  // transaction on `ctx.storage` itself (`carried-copy.test.ts` in the kernel holds that).
1080
- this.revision = new WriteRevision(ctx.storage.sql, ctx.storage, () => this.revisionSuspended, () => (this.carriedAwayCopy ? CARRIED_AWAY_WRITE_REFUSAL : null), () => this.expireIdleCaptures());
1121
+ this.revision = new WriteRevision(ctx.storage.sql, ctx.storage, () => this.revisionSuspended, () => (this.carriedAwayCopy ? CARRIED_AWAY_WRITE_REFUSAL : null), () => this.expireIdleCaptures(), this.scopeWork ? (runtime) => this.scopeWork.counting(runtime) : undefined);
1081
1122
  this.sql = this.revision.sql;
1082
1123
  for (const stmt of executableSqlStatements(KERNEL_DDL)) {
1083
1124
  this.sql.exec(stmt);
@@ -5022,8 +5063,13 @@ options = {}) {
5022
5063
  }
5023
5064
  // -- migrations (port of applyPendingMigrations) --------------------------
5024
5065
  ensureMigrations() {
5025
- if (!this.migrationPromise)
5026
- this.migrationPromise = this.applyPendingMigrations();
5066
+ if (!this.migrationPromise) {
5067
+ // #3316: counted as the migration it is, not as whichever entry woke it — the first
5068
+ // operation after a promote runs the whole pass.
5069
+ this.migrationPromise = this.scopeWork
5070
+ ? this.scopeWork.apart('migration-pass', 'migration', () => this.applyPendingMigrations())
5071
+ : this.applyPendingMigrations();
5072
+ }
5027
5073
  return this.migrationPromise;
5028
5074
  }
5029
5075
  /** Every registered module's derivation plans — what `repairDerivedObjects` and its checks read. */
@@ -6050,7 +6096,9 @@ options = {}) {
6050
6096
  this.readCaptureClock();
6051
6097
  if (this.captureIdleAt === null || this.captureIdleAt === undefined || Date.now() < this.captureIdleAt)
6052
6098
  return;
6053
- this.revision.untracked(() => {
6099
+ // #3316: a copy's capture ending is the copy's work, not the write's that found it idle.
6100
+ const apart = (fn) => (this.scopeWork ? this.scopeWork.apart('capture-expiry', 'export', fn) : fn());
6101
+ apart(() => this.revision.untracked(() => {
6054
6102
  // A load took the capture's tables with it: there is nothing left to end.
6055
6103
  if (!this.hasTable('_substrat_capture'))
6056
6104
  return;
@@ -6059,7 +6107,7 @@ options = {}) {
6059
6107
  .toArray();
6060
6108
  for (const { copy_id } of idle)
6061
6109
  this.forgetCapture(copy_id);
6062
- });
6110
+ }));
6063
6111
  // Read again at the next write, not now: should the write's own transaction roll back, the
6064
6112
  // capture is back, and the next write ends it again.
6065
6113
  this.captureIdleAt = undefined;
@@ -6074,10 +6122,15 @@ options = {}) {
6074
6122
  dropIdleCaptureLater() {
6075
6123
  setTimeout(() => {
6076
6124
  try {
6077
- this.revision.untracked(() => {
6125
+ const drop = () => this.revision.untracked(() => {
6078
6126
  if (this.hasTable('_substrat_capture'))
6079
6127
  this.dropCaptureIfIdle();
6080
6128
  });
6129
+ // #3316: the copy's teardown, counted apart from the write whose turn scheduled it.
6130
+ if (this.scopeWork)
6131
+ this.scopeWork.apart('capture-drop', 'export', drop);
6132
+ else
6133
+ drop();
6081
6134
  }
6082
6135
  catch {
6083
6136
  // Left to the next capture call or wake, as above.
@@ -8216,5 +8269,18 @@ options = {}) {
8216
8269
  return row?.effective === 1;
8217
8270
  }
8218
8271
  };
8272
+ // #3316: each RPC entry counts the rows it runs under its origin (`scope-work.ts`). `invoke` is
8273
+ // the vertical's own operation when a person or a connection calls it, and one of its declared
8274
+ // schedules when the platform's sweeper does (`systemModuleId`, its eighth argument) — a purge
8275
+ // schedule apart, since a binned row's purge is the platform's retention, not the vertical's work.
8276
+ meterScopeWorkEntries(ScopeDO.prototype, (self) => self.scopeWork, {
8277
+ invoke: (self, args) => {
8278
+ if (typeof args[7] !== 'string')
8279
+ return 'operation';
8280
+ const purges = self.purgeSchedules;
8281
+ return purges?.has(String(args[0])) ? 'purge' : 'schedule';
8282
+ },
8283
+ });
8284
+ return ScopeDO;
8219
8285
  }
8220
8286
  //# sourceMappingURL=scope-do.js.map