@substrat-run/adapter-cloudflare 0.205.0 → 0.207.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.
@@ -0,0 +1,220 @@
1
+ import { ASYNC_LOCAL_STORAGE_GLOBAL } from './async-local-storage-global.js';
2
+ import type { AnalyticsEngineDatasetLike } from './connector-calls.js';
3
+ /**
4
+ * The scope DO's RPC entries, by the origin they are counted under. The scope DO wraps each name
5
+ * listed here when its class is defined, and a name it has no method for refuses the definition,
6
+ * so a renamed entry cannot quietly fall to `unattributed`.
7
+ *
8
+ * `operation` is the vertical's own work as a person or a connection calls it; `schedule` and
9
+ * `purge` are the vertical's declared schedules, which the platform's sweeper runs (`invoke` is
10
+ * split between the three by its arguments, in the scope DO). `load` is any dump loaded INTO this
11
+ * object — a preview fork's copy when the script is a preview, a restore or a carry when it is
12
+ * live — and `export` is a dump read OFF it, the source side of a fork or a backup.
13
+ */
14
+ export declare const SCOPE_WORK_ORIGINS: {
15
+ readonly operation: readonly ["invoke"];
16
+ readonly request: readonly ["admission", "claimWireNonce", "resolveProjectedIdentity", "freshnessProbe", "servesTenant", "seatsTenant"];
17
+ readonly purge: readonly ["runPurgeSweep"];
18
+ readonly live: readonly ["fetch", "alarm", "webSocketMessage", "webSocketClose", "webSocketError"];
19
+ readonly migration: readonly ["migrate", "retryMigrations", "migrationAttemptsOnInstance", "migrationFailure", "appliedMigrations", "appliedMigrationsIfHeld"];
20
+ readonly rewind: readonly ["rewindToBookmark", "rewindProbe"];
21
+ readonly drain: readonly ["undrainedEvents", "undrainedEventsRead", "undrainedEventsReadIfHeld", "markEventsDrained", "pruneDrainedEvents", "redrainEvents", "redrainCount", "redrainCountIfHeld", "exportedEventsRead"];
22
+ readonly executor: readonly ["pendingExecutorDeliveries", "pendingExecutorEvents", "recordExecutorAttempt", "executorAttempts", "executorDeadLetters", "pendingPlatformRequests", "platformRequestHistory", "settlePlatformRequest", "settlePlatformRequestWithEvent", "routeExecutorEventToPlatform"];
23
+ readonly 'event-import': readonly ["importApply", "importCursorMove", "importStateRead"];
24
+ readonly export: readonly ["exportDump", "exportDumpPage", "exportDumpChanges", "exportDumpStamped", "endDumpCapture", "estimateDump"];
25
+ readonly load: readonly ["importDump", "importDumpChecked", "importDumpJudged", "importDumpProjected", "stageDumpPage", "stageDumpChanges", "commitStagedDumpChecked", "commitStagedDumpJudged", "discardStagedDump", "keptCopy", "releaseKeptCopy", "discardKeptCopy", "wipeCarried", "loadMarker", "markCopy", "clearCopyMark", "isCopy", "isCleanRoomCopy"];
26
+ readonly lifecycle: readonly ["lifecycle", "setLifecycle"];
27
+ readonly sweep: readonly ["enqueueSweepRuns", "sweepFenceFacts", "orphanAttachmentsReply", "orphanSweepLicenceReply", "jobRunStartOrJoin", "jobRunById", "jobRunInsert", "jobRunsDue", "jobRunsDueKeys", "jobRunList", "jobRunPatch", "jobRunClaim", "jobRunMiss", "jobRunBegin", "jobStepBegin", "jobStepRow", "jobStepRecord", "jobCommitPass", "scheduleLastRun", "recordScheduleRun", "systemScheduleState", "switchSystemSchedules", "switchHoldToken", "switchHoldOn", "switchHoldClaim", "switchHoldJoin", "switchHoldYoungestMs", "switchHoldArm", "switchHoldDrop", "switchHoldsAll", "switchHoldClaims", "switchHoldRelease"];
28
+ readonly permissions: readonly ["writeTuple", "writeTupleAndAuditIntent", "seatTuple", "seatTuples", "seatTuplesFor", "grantEntityShape", "grantEntityShapeAndAuditIntent", "grantEntityShapeOnce", "topUpEntityGrantShapes", "hasEffectiveRoleGrantFor", "revokeTuple", "revokeTupleAndAuditIntent", "setPermissionSource", "applyProjection", "applyProjectionReply", "applyJudgedProjectionReply", "canAssignFor", "assignScopeRoleBoundedFor", "scopeRoleHoldersFor", "changeScopeRoleBoundedFor", "revokeScopeRolesBoundedFor", "reservedRoleRefusalFor", "reservedRoleRefusalHere", "reservedGrantRefusalFor", "reservedShapeRefusalFor", "roleStateHere", "reservationHere", "reservedAmong", "hasSystemGrant", "writeSystemGrant", "writeSystemGrantAndAuditIntent", "systemGrantsStatus", "systemDoorState", "switchPeer", "peerDoorState", "peerCovers", "peerGrantsStatus", "listConnectionGrants", "exchangeCapability", "exchangeBecomeLinkById", "mintBecomeCapabilityBoundedFor", "mintBindLinkBoundedFor", "unbindEntityHolderBoundedFor", "becomeLinkStatesFor", "revokeBecomeCapabilityFor", "mintBecomeCapability", "mintBecomeCapabilityAndAuditIntent", "revokeCapabilityAsPlatform", "listCapabilities"];
29
+ readonly attachment: readonly ["attachmentAdd", "attachmentAddReply", "attachmentList", "attachmentListReply", "attachmentRedeemUploadLinkReply", "uploadLinkInspectReply", "downloadLinkResolveReply", "attachmentAuthorize", "attachmentAuthorizeReply", "systemAttachmentAuthorize", "systemAttachmentAuthorizeReply", "attachmentRemove", "attachmentRemoveReply", "attachmentCheckWriteReply", "attachmentSearch", "attachmentTextSource", "attachmentTextRecord", "attachmentTextBackfillStart", "attachmentTextBackfillBatch", "capabilityAttachmentList", "capabilityAttachmentOpen", "capabilityAttachmentSearch", "capabilityAttachmentRefuseWrite"];
30
+ readonly erasure: readonly ["redactSubject", "readSubject"];
31
+ readonly observe: readonly ["databaseSize", "databaseSizeIfHeld", "attachmentBytes", "attachmentBytesIfHeld", "facetEvents", "facetEventsIfHeld", "eventCause", "eventCauseIfHeld", "eventEffects", "eventEffectsIfHeld", "invocationEvents", "invocationEventsIfHeld", "deadLetters", "deadLettersIfHeld", "lifecycleFlow", "lifecycleFlowIfHeld", "operationSeries", "operationSeriesIfHeld", "entityHistory", "entityHistoryIfHeld", "migrationBookmarks", "migrationBookmarksIfHeld", "introspectTables", "introspectTablesIfHeld", "introspectTable", "introspectTableIfHeld", "introspectTableReply", "introspectQuery", "introspectQueryIfHeld", "introspectQueryReply", "listDenials", "listRefusals", "summarizeDenials"];
32
+ readonly reap: readonly ["destroyStorage"];
33
+ };
34
+ /**
35
+ * An origin a scope object's rows are counted under: the table's, plus `schedule` (an `invoke` the
36
+ * sweeper makes), `wake` (the constructor) and `unattributed` (what no entry ran).
37
+ */
38
+ export type ScopeWorkOrigin = keyof typeof SCOPE_WORK_ORIGINS | 'schedule' | 'wake' | 'unattributed';
39
+ /**
40
+ * Where each field lands in an Analytics Engine data point. **A published shape** — a reader
41
+ * indexes into it by ordinal, as it does the router's and the connector calls' — so it only ever
42
+ * GROWS: a new field takes the next ordinal, and no position is reordered, renamed or reused.
43
+ * `absent` is what the position holds when the field is unknown.
44
+ *
45
+ * Its own dataset, never the router's or the connector calls': a point of this shape written
46
+ * there would be counted as requests or calls by every read of them.
47
+ *
48
+ * `durable_object.id` is the object's id, the key Cloudflare's `durableObjectsPeriodicGroups`
49
+ * reports `objectId` under, so these points join the billed per-object totals directly.
50
+ */
51
+ export declare const SCOPE_WORK_DATA_POINT_LAYOUT: {
52
+ readonly indexes: readonly [{
53
+ readonly ordinal: 'index1';
54
+ readonly name: 'substrat.tenant.id';
55
+ readonly unit: null;
56
+ readonly absent: '';
57
+ }];
58
+ readonly blobs: readonly [{
59
+ readonly ordinal: 'blob1';
60
+ readonly name: 'substrat.vertical';
61
+ readonly unit: null;
62
+ readonly absent: '';
63
+ }, {
64
+ readonly ordinal: 'blob2';
65
+ readonly name: 'substrat.scope.id';
66
+ readonly unit: null;
67
+ readonly absent: '';
68
+ }, {
69
+ readonly ordinal: 'blob3';
70
+ readonly name: 'durable_object.id';
71
+ readonly unit: null;
72
+ readonly absent: '';
73
+ }, {
74
+ readonly ordinal: 'blob4';
75
+ readonly name: 'substrat.version.id';
76
+ readonly unit: null;
77
+ readonly absent: '';
78
+ }, {
79
+ readonly ordinal: 'blob5';
80
+ readonly name: 'substrat.deployment.kind';
81
+ readonly unit: null;
82
+ readonly absent: '';
83
+ }, {
84
+ readonly ordinal: 'blob6';
85
+ readonly name: 'substrat.scope_work.origin';
86
+ readonly unit: null;
87
+ readonly absent: '';
88
+ }, {
89
+ readonly ordinal: 'blob7';
90
+ readonly name: 'substrat.scope_work.entry';
91
+ readonly unit: null;
92
+ readonly absent: '';
93
+ }];
94
+ readonly doubles: readonly [{
95
+ readonly ordinal: 'double1';
96
+ readonly name: 'db.rows_written';
97
+ readonly unit: '{row}';
98
+ readonly absent: 0;
99
+ }, {
100
+ readonly ordinal: 'double2';
101
+ readonly name: 'db.rows_read';
102
+ readonly unit: '{row}';
103
+ readonly absent: 0;
104
+ }, {
105
+ readonly ordinal: 'double3';
106
+ readonly name: 'db.statements';
107
+ readonly unit: '{statement}';
108
+ readonly absent: 0;
109
+ }];
110
+ };
111
+ /** One invocation's count, as it leaves. */
112
+ export interface ScopeWorkRecord {
113
+ readonly 'substrat.tenant.id': string | null;
114
+ readonly 'substrat.vertical': string | null;
115
+ readonly 'substrat.scope.id': string | null;
116
+ readonly 'durable_object.id': string | null;
117
+ readonly 'substrat.version.id': string | null;
118
+ /** `live` (the serving script) or `preview` (a version's own script), as the upload said. */
119
+ readonly 'substrat.deployment.kind': string | null;
120
+ readonly 'substrat.scope_work.origin': ScopeWorkOrigin;
121
+ /** The RPC entry, or `wake` / `ambient` for what no entry ran. */
122
+ readonly 'substrat.scope_work.entry': string;
123
+ readonly 'db.rows_written': number;
124
+ readonly 'db.rows_read': number;
125
+ readonly 'db.statements': number;
126
+ }
127
+ /** The data point a record becomes — built from {@link SCOPE_WORK_DATA_POINT_LAYOUT}. */
128
+ export declare function scopeWorkDataPoint(record: ScopeWorkRecord): {
129
+ indexes: string[];
130
+ blobs: string[];
131
+ doubles: number[];
132
+ };
133
+ /** `AsyncLocalStorage`, typed structurally so this module imports no `node:*`. */
134
+ interface AsyncLocalStorageLike<T> {
135
+ run<R>(store: T, fn: () => R): R;
136
+ getStore(): T | undefined;
137
+ }
138
+ type AsyncLocalStorageClass = new <T>() => AsyncLocalStorageLike<T>;
139
+ export { ASYNC_LOCAL_STORAGE_GLOBAL };
140
+ /** The platform entry's class, else node's (`nodejs_compat`, the workerd test pool), else none. */
141
+ export declare function asyncLocalStorageClass(): AsyncLocalStorageClass | undefined;
142
+ /** Who this object is, as each point stamps it. Read when a point is written, never per statement. */
143
+ export interface ScopeWorkIdentity {
144
+ /** The tenant the scope was provisioned for, or null while it is not. */
145
+ tenant(): string | null;
146
+ readonly vertical: string | null;
147
+ readonly scopeId: string | null;
148
+ readonly objectId: string | null;
149
+ readonly versionId: string | null;
150
+ readonly kind: string | null;
151
+ }
152
+ /**
153
+ * The per-object meter. Hand {@link counting} the raw `SqlStorage` under every other wrapper, and run
154
+ * each RPC entry through {@link run}. Every statement's cursor is kept on the tally of the entry whose
155
+ * async context ran it, and summed when that entry ends — so the hot path is one context read and one
156
+ * array push per statement.
157
+ */
158
+ export declare class ScopeWorkMeter {
159
+ private readonly dataset;
160
+ private readonly identity;
161
+ private readonly context;
162
+ /** What no entry ran: the constructor's work first (`wake`), then anything unattributed. */
163
+ private ambient;
164
+ private dropped;
165
+ /** Inside {@link uncounted}. */
166
+ private paused;
167
+ constructor(dataset: AnalyticsEngineDatasetLike, identity: ScopeWorkIdentity, Als?: AsyncLocalStorageClass | undefined);
168
+ /** Points a dataset refused, since the object woke. A refused write never fails the work. */
169
+ get droppedPoints(): number;
170
+ /**
171
+ * `raw` with every `exec` counted. Everything else on it passes straight through.
172
+ *
173
+ * A call holding several statements is counted per statement: the runtime's cursor for such a
174
+ * call reports the LAST statement's rows only, so the batch is run as the kernel's splitter cuts
175
+ * it (`executableSqlStatements`, the boundaries `guardSpine` runs a schema change at), and only
176
+ * when the pieces are the whole call (`piecesReproduce`). That is the batch's own behaviour: the
177
+ * runtime runs a batch's statements in order, each to completion, keeping earlier writes when a
178
+ * later statement fails, and binds parameters to the last statement only — so the earlier pieces
179
+ * run unbound and are read to the end, and the last gets the caller's bindings and returns its
180
+ * cursor. A batch that misplaced a parameter is still refused, in the runtime's per-statement
181
+ * words. A call that does not split cleanly runs whole, as before, and counts its last statement.
182
+ */
183
+ counting(raw: SqlStorage): SqlStorage;
184
+ /** The batches this object has run, split once: a statement's text is almost always a constant. */
185
+ private readonly batches;
186
+ /** `query`'s statements when it holds more than one and they are the whole of it, else null. */
187
+ private batchOf;
188
+ /**
189
+ * Run one RPC entry under its own count. A call made while another entry's context is current is
190
+ * part of that entry (a nested call), and runs uncounted here.
191
+ */
192
+ run<R>(entry: string, origin: ScopeWorkOrigin, fn: () => R): R;
193
+ /**
194
+ * Run platform work under its own count even when an entry's context is current: work an entry
195
+ * TRIGGERS but that is not the entry's own — the migration pass the first invocation after a
196
+ * promote runs, the copy bookkeeping before a write — so it is never billed as that entry.
197
+ */
198
+ apart<R>(entry: string, origin: ScopeWorkOrigin, fn: () => R): R;
199
+ private counted;
200
+ /**
201
+ * Run `fn` with nothing counted: the meter's own read of who the object is. Without this the
202
+ * read would land on a tally, and a point written for an unprovisioned scope would queue the
203
+ * next read, forever.
204
+ */
205
+ uncounted<T>(fn: () => T): T;
206
+ private note;
207
+ private end;
208
+ /** Sum the tally's cursors into one point, and start it again empty. A point of no rows is not written. */
209
+ private flush;
210
+ }
211
+ /** How an entry's origin is decided: fixed, or from the call (`invoke`'s arguments). */
212
+ export type ScopeWorkClassifier = ScopeWorkOrigin | ((self: unknown, args: readonly unknown[]) => ScopeWorkOrigin);
213
+ /**
214
+ * Wrap each entry `SCOPE_WORK_ORIGINS` names on `proto`, so a call runs through the instance's meter
215
+ * — or straight through when the instance has none (no dataset bound). `classify` overrides an
216
+ * entry's fixed origin. Refuses an entry `proto` has no method for: the table and the class are
217
+ * held together at definition, where a rename is caught by the first test that defines the class.
218
+ */
219
+ export declare function meterScopeWorkEntries(proto: object, meterOf: (self: unknown) => ScopeWorkMeter | undefined, classify?: Readonly<Record<string, ScopeWorkClassifier>>): void;
220
+ //# sourceMappingURL=scope-work.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scope-work.d.ts","sourceRoot":"","sources":["../src/scope-work.ts"],"names":[],"mappings":"AAwCA,OAAO,EAAE,0BAA0B,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;A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,CAAC,CAG7D;IAED;;;;OAIG;IACH,KAAK,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAG/D;IAED,OAAO,CAAC,OAAO;IA2Bf;;;;OAIG;IACH,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAQ3B;IAED,OAAO,CAAC,IAAI;IAgBZ,OAAO,CAAC,GAAG;IAKX,2GAA2G;IAC3G,OAAO,CAAC,KAAK;CAiCd;AAUD,wFAAwF;AACxF,MAAM,MAAM,mBAAmB,GAAG,eAAe,GAAG,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,OAAO,EAAE,KAAK,eAAe,CAAC,CAAC;AAEnH;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,cAAc,GAAG,SAAS,EACtD,QAAQ,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAM,GAC3D,IAAI,CAkBN"}
@@ -0,0 +1,395 @@
1
+ /**
2
+ * Platform work inside a tenant's scope (#3316): the rows a scope object writes and reads, per
3
+ * invocation, by ORIGIN — the vertical's own operation, or one of the platform's verbs (a preview
4
+ * fork's load, a migration, a drain, a purge, a sweep…) running in the same object.
5
+ *
6
+ * Cloudflare bills SQLite rows per Durable Object object (`durableObjectsPeriodicGroups`), and an
7
+ * object is a scope, so its analytics cannot tell a vertical's operation from the platform's work
8
+ * in the same object. This counts what the object itself executed, from the runtime's own numbers:
9
+ * each statement's cursor `rowsWritten`/`rowsRead`, read when the invocation ends, which are the
10
+ * values Cloudflare bills (`SqlStorageCursor`: "the final value is used for SQL billing"). Nothing
11
+ * is estimated, and nothing is written to SQL: the count leaves as one Analytics Engine point per
12
+ * invocation, so measuring writes no rows.
13
+ *
14
+ * **Attribution.** Each RPC entry the scope DO declares in its origin table runs inside an
15
+ * `AsyncLocalStorage` context of its own, so a statement belongs to the entry whose async context
16
+ * ran it: a nested call (`importDumpChecked` → `importDump`), the serial queue (it chains on the
17
+ * enqueuer's context) and work an entry left running after it returned all count to that entry,
18
+ * and two RPCs interleaved across an await stay apart. Platform work an entry only TRIGGERS is
19
+ * counted {@link ScopeWorkMeter.apart | apart} from it: the migration pass the first call after a
20
+ * promote runs (`migration`), and a copy's capture ending before a write (`export`). The object's
21
+ * constructor (the kernel DDL and migration bookkeeping every wake re-runs) is `wake`. A statement no
22
+ * entry ran — a method the table does not name, or a runtime with no `AsyncLocalStorage` — is
23
+ * `unattributed`, so the object's total is always whole and what this could not place is visible
24
+ * rather than guessed.
25
+ *
26
+ * **What it does not see.** The KV API (`ctx.storage.get/put/delete/list`) and `setAlarm` are billed
27
+ * as rows too but return no cursor; the scope DO uses them only for continuation positions, the
28
+ * live-expiry alarm and the reap marker. Nor does it count its own read of the tenant a point names
29
+ * (`uncounted`, until the scope is provisioned). The difference between Cloudflare's per-object
30
+ * total and the sum of these points is those, plus whatever ran before this code was deployed.
31
+ *
32
+ * **Inside an operation**, rows the platform's machinery writes on the operation's behalf stay with
33
+ * the operation, because they are in the operation's own statements: the write revision's bump, the
34
+ * outbox event, and — while a preview is being forked off this object — the capture's trigger rows,
35
+ * which SQLite counts in the cursor of the write that fired them.
36
+ *
37
+ * Whose each origin is — the tenant's usage or the platform's — is an owner decision (#3316); this
38
+ * only names them.
39
+ */
40
+ import { blankSqlComments, executableSqlStatements, piecesReproduce } from '@substrat-run/kernel';
41
+ import { ASYNC_LOCAL_STORAGE_GLOBAL } from './async-local-storage-global.js';
42
+ /**
43
+ * The scope DO's RPC entries, by the origin they are counted under. The scope DO wraps each name
44
+ * listed here when its class is defined, and a name it has no method for refuses the definition,
45
+ * so a renamed entry cannot quietly fall to `unattributed`.
46
+ *
47
+ * `operation` is the vertical's own work as a person or a connection calls it; `schedule` and
48
+ * `purge` are the vertical's declared schedules, which the platform's sweeper runs (`invoke` is
49
+ * split between the three by its arguments, in the scope DO). `load` is any dump loaded INTO this
50
+ * object — a preview fork's copy when the script is a preview, a restore or a carry when it is
51
+ * live — and `export` is a dump read OFF it, the source side of a fork or a backup.
52
+ */
53
+ export const SCOPE_WORK_ORIGINS = {
54
+ operation: ['invoke'],
55
+ request: ['admission', 'claimWireNonce', 'resolveProjectedIdentity', 'freshnessProbe', 'servesTenant', 'seatsTenant'],
56
+ purge: ['runPurgeSweep'],
57
+ live: ['fetch', 'alarm', 'webSocketMessage', 'webSocketClose', 'webSocketError'],
58
+ migration: ['migrate', 'retryMigrations', 'migrationAttemptsOnInstance', 'migrationFailure', 'appliedMigrations', 'appliedMigrationsIfHeld'],
59
+ rewind: ['rewindToBookmark', 'rewindProbe'],
60
+ drain: [
61
+ 'undrainedEvents', 'undrainedEventsRead', 'undrainedEventsReadIfHeld', 'markEventsDrained', 'pruneDrainedEvents',
62
+ 'redrainEvents', 'redrainCount', 'redrainCountIfHeld', 'exportedEventsRead',
63
+ ],
64
+ executor: [
65
+ 'pendingExecutorDeliveries', 'pendingExecutorEvents', 'recordExecutorAttempt', 'executorAttempts', 'executorDeadLetters',
66
+ 'pendingPlatformRequests', 'platformRequestHistory', 'settlePlatformRequest', 'settlePlatformRequestWithEvent',
67
+ 'routeExecutorEventToPlatform',
68
+ ],
69
+ 'event-import': ['importApply', 'importCursorMove', 'importStateRead'],
70
+ export: ['exportDump', 'exportDumpPage', 'exportDumpChanges', 'exportDumpStamped', 'endDumpCapture', 'estimateDump'],
71
+ load: [
72
+ 'importDump', 'importDumpChecked', 'importDumpJudged', 'importDumpProjected', 'stageDumpPage', 'stageDumpChanges',
73
+ 'commitStagedDumpChecked', 'commitStagedDumpJudged', 'discardStagedDump', 'keptCopy', 'releaseKeptCopy',
74
+ 'discardKeptCopy', 'wipeCarried', 'loadMarker', 'markCopy', 'clearCopyMark', 'isCopy', 'isCleanRoomCopy',
75
+ ],
76
+ lifecycle: ['lifecycle', 'setLifecycle'],
77
+ sweep: [
78
+ 'enqueueSweepRuns', 'sweepFenceFacts', 'orphanAttachmentsReply', 'orphanSweepLicenceReply', 'jobRunStartOrJoin',
79
+ 'jobRunById', 'jobRunInsert', 'jobRunsDue', 'jobRunsDueKeys', 'jobRunList', 'jobRunPatch', 'jobRunClaim', 'jobRunMiss',
80
+ 'jobRunBegin', 'jobStepBegin', 'jobStepRow', 'jobStepRecord', 'jobCommitPass', 'scheduleLastRun', 'recordScheduleRun',
81
+ 'systemScheduleState', 'switchSystemSchedules', 'switchHoldToken', 'switchHoldOn', 'switchHoldClaim', 'switchHoldJoin',
82
+ 'switchHoldYoungestMs', 'switchHoldArm', 'switchHoldDrop', 'switchHoldsAll', 'switchHoldClaims', 'switchHoldRelease',
83
+ ],
84
+ permissions: [
85
+ 'writeTuple', 'writeTupleAndAuditIntent', 'seatTuple', 'seatTuples', 'seatTuplesFor', 'grantEntityShape',
86
+ 'grantEntityShapeAndAuditIntent', 'grantEntityShapeOnce', 'topUpEntityGrantShapes', 'hasEffectiveRoleGrantFor',
87
+ 'revokeTuple', 'revokeTupleAndAuditIntent', 'setPermissionSource', 'applyProjection', 'applyProjectionReply',
88
+ 'applyJudgedProjectionReply', 'canAssignFor', 'assignScopeRoleBoundedFor', 'scopeRoleHoldersFor',
89
+ 'changeScopeRoleBoundedFor', 'revokeScopeRolesBoundedFor', 'reservedRoleRefusalFor', 'reservedRoleRefusalHere',
90
+ 'reservedGrantRefusalFor', 'reservedShapeRefusalFor', 'roleStateHere', 'reservationHere', 'reservedAmong',
91
+ 'hasSystemGrant', 'writeSystemGrant', 'writeSystemGrantAndAuditIntent', 'systemGrantsStatus', 'systemDoorState',
92
+ 'switchPeer', 'peerDoorState', 'peerCovers', 'peerGrantsStatus', 'listConnectionGrants', 'exchangeCapability',
93
+ 'exchangeBecomeLinkById', 'mintBecomeCapabilityBoundedFor', 'mintBindLinkBoundedFor', 'unbindEntityHolderBoundedFor',
94
+ 'becomeLinkStatesFor', 'revokeBecomeCapabilityFor', 'mintBecomeCapability', 'mintBecomeCapabilityAndAuditIntent',
95
+ 'revokeCapabilityAsPlatform', 'listCapabilities',
96
+ ],
97
+ attachment: [
98
+ 'attachmentAdd', 'attachmentAddReply', 'attachmentList', 'attachmentListReply', 'attachmentRedeemUploadLinkReply',
99
+ 'uploadLinkInspectReply', 'downloadLinkResolveReply', 'attachmentAuthorize', 'attachmentAuthorizeReply',
100
+ 'systemAttachmentAuthorize', 'systemAttachmentAuthorizeReply', 'attachmentRemove', 'attachmentRemoveReply',
101
+ 'attachmentCheckWriteReply', 'attachmentSearch', 'attachmentTextSource', 'attachmentTextRecord',
102
+ 'attachmentTextBackfillStart', 'attachmentTextBackfillBatch', 'capabilityAttachmentList', 'capabilityAttachmentOpen',
103
+ 'capabilityAttachmentSearch', 'capabilityAttachmentRefuseWrite',
104
+ ],
105
+ erasure: ['redactSubject', 'readSubject'],
106
+ observe: [
107
+ 'databaseSize', 'databaseSizeIfHeld', 'attachmentBytes', 'attachmentBytesIfHeld', 'facetEvents', 'facetEventsIfHeld',
108
+ 'eventCause', 'eventCauseIfHeld', 'eventEffects', 'eventEffectsIfHeld', 'invocationEvents', 'invocationEventsIfHeld',
109
+ 'deadLetters', 'deadLettersIfHeld', 'lifecycleFlow', 'lifecycleFlowIfHeld', 'operationSeries', 'operationSeriesIfHeld',
110
+ 'entityHistory', 'entityHistoryIfHeld', 'migrationBookmarks', 'migrationBookmarksIfHeld', 'introspectTables',
111
+ 'introspectTablesIfHeld', 'introspectTable', 'introspectTableIfHeld', 'introspectTableReply', 'introspectQuery',
112
+ 'introspectQueryIfHeld', 'introspectQueryReply', 'listDenials', 'listRefusals', 'summarizeDenials',
113
+ ],
114
+ reap: ['destroyStorage'],
115
+ };
116
+ /**
117
+ * Where each field lands in an Analytics Engine data point. **A published shape** — a reader
118
+ * indexes into it by ordinal, as it does the router's and the connector calls' — so it only ever
119
+ * GROWS: a new field takes the next ordinal, and no position is reordered, renamed or reused.
120
+ * `absent` is what the position holds when the field is unknown.
121
+ *
122
+ * Its own dataset, never the router's or the connector calls': a point of this shape written
123
+ * there would be counted as requests or calls by every read of them.
124
+ *
125
+ * `durable_object.id` is the object's id, the key Cloudflare's `durableObjectsPeriodicGroups`
126
+ * reports `objectId` under, so these points join the billed per-object totals directly.
127
+ */
128
+ export const SCOPE_WORK_DATA_POINT_LAYOUT = {
129
+ indexes: [{ ordinal: 'index1', name: 'substrat.tenant.id', unit: null, absent: '' }],
130
+ blobs: [
131
+ { ordinal: 'blob1', name: 'substrat.vertical', unit: null, absent: '' },
132
+ { ordinal: 'blob2', name: 'substrat.scope.id', unit: null, absent: '' },
133
+ { ordinal: 'blob3', name: 'durable_object.id', unit: null, absent: '' },
134
+ { ordinal: 'blob4', name: 'substrat.version.id', unit: null, absent: '' },
135
+ { ordinal: 'blob5', name: 'substrat.deployment.kind', unit: null, absent: '' },
136
+ { ordinal: 'blob6', name: 'substrat.scope_work.origin', unit: null, absent: '' },
137
+ { ordinal: 'blob7', name: 'substrat.scope_work.entry', unit: null, absent: '' },
138
+ ],
139
+ doubles: [
140
+ { ordinal: 'double1', name: 'db.rows_written', unit: '{row}', absent: 0 },
141
+ { ordinal: 'double2', name: 'db.rows_read', unit: '{row}', absent: 0 },
142
+ { ordinal: 'double3', name: 'db.statements', unit: '{statement}', absent: 0 },
143
+ ],
144
+ };
145
+ /** The data point a record becomes — built from {@link SCOPE_WORK_DATA_POINT_LAYOUT}. */
146
+ export function scopeWorkDataPoint(record) {
147
+ const L = SCOPE_WORK_DATA_POINT_LAYOUT;
148
+ return {
149
+ indexes: L.indexes.map((f) => record[f.name] ?? f.absent),
150
+ blobs: L.blobs.map((f) => record[f.name] ?? f.absent),
151
+ doubles: L.doubles.map((f) => record[f.name] ?? f.absent),
152
+ };
153
+ }
154
+ export { ASYNC_LOCAL_STORAGE_GLOBAL };
155
+ /** The platform entry's class, else node's (`nodejs_compat`, the workerd test pool), else none. */
156
+ export function asyncLocalStorageClass() {
157
+ try {
158
+ const published = globalThis[Symbol.for(ASYNC_LOCAL_STORAGE_GLOBAL)];
159
+ if (typeof published === 'function')
160
+ return published;
161
+ const proc = globalThis.process;
162
+ const mod = proc?.getBuiltinModule?.('node:async_hooks');
163
+ return typeof mod?.AsyncLocalStorage === 'function' ? mod.AsyncLocalStorage : undefined;
164
+ }
165
+ catch {
166
+ return undefined;
167
+ }
168
+ }
169
+ /**
170
+ * The per-object meter. Hand {@link counting} the raw `SqlStorage` under every other wrapper, and run
171
+ * each RPC entry through {@link run}. Every statement's cursor is kept on the tally of the entry whose
172
+ * async context ran it, and summed when that entry ends — so the hot path is one context read and one
173
+ * array push per statement.
174
+ */
175
+ export class ScopeWorkMeter {
176
+ dataset;
177
+ identity;
178
+ context;
179
+ /** What no entry ran: the constructor's work first (`wake`), then anything unattributed. */
180
+ ambient;
181
+ dropped = 0;
182
+ /** Inside {@link uncounted}. */
183
+ paused = false;
184
+ constructor(dataset, identity, Als = asyncLocalStorageClass()) {
185
+ this.dataset = dataset;
186
+ this.identity = identity;
187
+ // One storage per object, never shared: an RPC from one scope object to another in the same
188
+ // isolate must not find the caller's tally.
189
+ this.context = Als ? new Als() : undefined;
190
+ this.ambient = { entry: 'wake', origin: 'wake', cursors: [], closed: true, flushQueued: false };
191
+ }
192
+ /** Points a dataset refused, since the object woke. A refused write never fails the work. */
193
+ get droppedPoints() {
194
+ return this.dropped;
195
+ }
196
+ /**
197
+ * `raw` with every `exec` counted. Everything else on it passes straight through.
198
+ *
199
+ * A call holding several statements is counted per statement: the runtime's cursor for such a
200
+ * call reports the LAST statement's rows only, so the batch is run as the kernel's splitter cuts
201
+ * it (`executableSqlStatements`, the boundaries `guardSpine` runs a schema change at), and only
202
+ * when the pieces are the whole call (`piecesReproduce`). That is the batch's own behaviour: the
203
+ * runtime runs a batch's statements in order, each to completion, keeping earlier writes when a
204
+ * later statement fails, and binds parameters to the last statement only — so the earlier pieces
205
+ * run unbound and are read to the end, and the last gets the caller's bindings and returns its
206
+ * cursor. A batch that misplaced a parameter is still refused, in the runtime's per-statement
207
+ * words. A call that does not split cleanly runs whole, as before, and counts its last statement.
208
+ */
209
+ counting(raw) {
210
+ const exec = (query, ...bindings) => {
211
+ const pieces = this.paused ? null : this.batchOf(query);
212
+ if (pieces) {
213
+ for (let i = 0; i < pieces.length - 1; i++) {
214
+ const earlier = raw.exec(pieces[i]);
215
+ for (const rows = earlier.raw(); !rows.next().done;)
216
+ ;
217
+ this.note(earlier);
218
+ }
219
+ query = pieces[pieces.length - 1];
220
+ }
221
+ const cursor = raw.exec(query, ...bindings);
222
+ this.note(cursor);
223
+ return cursor;
224
+ };
225
+ return new Proxy(raw, {
226
+ get(target, prop) {
227
+ if (prop === 'exec')
228
+ return exec;
229
+ const value = Reflect.get(target, prop, target);
230
+ return typeof value === 'function' ? value.bind(target) : value;
231
+ },
232
+ });
233
+ }
234
+ /** The batches this object has run, split once: a statement's text is almost always a constant. */
235
+ batches = new Map();
236
+ /** `query`'s statements when it holds more than one and they are the whole of it, else null. */
237
+ batchOf(query) {
238
+ if (!query.includes(';'))
239
+ return null;
240
+ let pieces = this.batches.get(query);
241
+ if (pieces === undefined) {
242
+ const split = executableSqlStatements(query);
243
+ pieces = split.length > 1 && piecesReproduce(blankSqlComments(query), split) ? split : null;
244
+ if (this.batches.size >= 256)
245
+ this.batches.clear();
246
+ this.batches.set(query, pieces);
247
+ }
248
+ return pieces;
249
+ }
250
+ /**
251
+ * Run one RPC entry under its own count. A call made while another entry's context is current is
252
+ * part of that entry (a nested call), and runs uncounted here.
253
+ */
254
+ run(entry, origin, fn) {
255
+ if (!this.context || this.context.getStore())
256
+ return fn();
257
+ return this.counted(this.context, entry, origin, fn);
258
+ }
259
+ /**
260
+ * Run platform work under its own count even when an entry's context is current: work an entry
261
+ * TRIGGERS but that is not the entry's own — the migration pass the first invocation after a
262
+ * promote runs, the copy bookkeeping before a write — so it is never billed as that entry.
263
+ */
264
+ apart(entry, origin, fn) {
265
+ if (!this.context)
266
+ return fn();
267
+ return this.counted(this.context, entry, origin, fn);
268
+ }
269
+ counted(context, entry, origin, fn) {
270
+ const tally = { entry, origin, cursors: [], closed: false, flushQueued: false };
271
+ return context.run(tally, () => {
272
+ let result;
273
+ try {
274
+ result = fn();
275
+ }
276
+ catch (e) {
277
+ this.end(tally);
278
+ throw e;
279
+ }
280
+ if (isThenable(result)) {
281
+ return result.then((value) => {
282
+ this.end(tally);
283
+ return value;
284
+ }, (e) => {
285
+ this.end(tally);
286
+ throw e;
287
+ });
288
+ }
289
+ this.end(tally);
290
+ return result;
291
+ });
292
+ }
293
+ /**
294
+ * Run `fn` with nothing counted: the meter's own read of who the object is. Without this the
295
+ * read would land on a tally, and a point written for an unprovisioned scope would queue the
296
+ * next read, forever.
297
+ */
298
+ uncounted(fn) {
299
+ const was = this.paused;
300
+ this.paused = true;
301
+ try {
302
+ return fn();
303
+ }
304
+ finally {
305
+ this.paused = was;
306
+ }
307
+ }
308
+ note(cursor) {
309
+ if (this.paused)
310
+ return;
311
+ const tally = this.context?.getStore() ?? this.ambient;
312
+ tally.cursors.push(cursor);
313
+ if (tally.closed && !tally.flushQueued) {
314
+ tally.flushQueued = true;
315
+ queueMicrotask(() => {
316
+ tally.flushQueued = false;
317
+ this.flush(tally);
318
+ if (tally === this.ambient && tally.origin === 'wake') {
319
+ this.ambient = { entry: 'ambient', origin: 'unattributed', cursors: [], closed: true, flushQueued: false };
320
+ }
321
+ });
322
+ }
323
+ }
324
+ end(tally) {
325
+ tally.closed = true;
326
+ this.flush(tally);
327
+ }
328
+ /** Sum the tally's cursors into one point, and start it again empty. A point of no rows is not written. */
329
+ flush(tally) {
330
+ const cursors = tally.cursors;
331
+ if (cursors.length === 0)
332
+ return;
333
+ tally.cursors = [];
334
+ let written = 0;
335
+ let read = 0;
336
+ for (const c of cursors) {
337
+ written += c.rowsWritten;
338
+ read += c.rowsRead;
339
+ }
340
+ if (written === 0 && read === 0)
341
+ return;
342
+ try {
343
+ const id = this.identity;
344
+ this.dataset.writeDataPoint(scopeWorkDataPoint({
345
+ 'substrat.tenant.id': id.tenant(),
346
+ 'substrat.vertical': id.vertical,
347
+ 'substrat.scope.id': id.scopeId,
348
+ 'durable_object.id': id.objectId,
349
+ 'substrat.version.id': id.versionId,
350
+ 'substrat.deployment.kind': id.kind,
351
+ 'substrat.scope_work.origin': tally.origin,
352
+ 'substrat.scope_work.entry': tally.entry,
353
+ 'db.rows_written': written,
354
+ 'db.rows_read': read,
355
+ 'db.statements': cursors.length,
356
+ }));
357
+ }
358
+ catch {
359
+ // Analytics Engine being unavailable is not a reason for the scope's work to fail.
360
+ this.dropped += 1;
361
+ }
362
+ }
363
+ }
364
+ function isThenable(value) {
365
+ return (value !== null &&
366
+ (typeof value === 'object' || typeof value === 'function') &&
367
+ typeof value.then === 'function');
368
+ }
369
+ /**
370
+ * Wrap each entry `SCOPE_WORK_ORIGINS` names on `proto`, so a call runs through the instance's meter
371
+ * — or straight through when the instance has none (no dataset bound). `classify` overrides an
372
+ * entry's fixed origin. Refuses an entry `proto` has no method for: the table and the class are
373
+ * held together at definition, where a rename is caught by the first test that defines the class.
374
+ */
375
+ export function meterScopeWorkEntries(proto, meterOf, classify = {}) {
376
+ const target = proto;
377
+ for (const [origin, entries] of Object.entries(SCOPE_WORK_ORIGINS)) {
378
+ for (const entry of entries) {
379
+ const method = target[entry];
380
+ if (typeof method !== 'function') {
381
+ throw new Error(`scope-work: SCOPE_WORK_ORIGINS names '${entry}', which the scope DO does not define`);
382
+ }
383
+ const decide = classify[entry] ?? origin;
384
+ const original = method;
385
+ target[entry] = function meteredEntry(...args) {
386
+ const meter = meterOf(this);
387
+ if (!meter)
388
+ return original.apply(this, args);
389
+ const o = typeof decide === 'function' ? decide(this, args) : decide;
390
+ return meter.run(entry, o, () => original.apply(this, args));
391
+ };
392
+ }
393
+ }
394
+ }
395
+ //# sourceMappingURL=scope-work.js.map