@lunora/do 1.0.0-alpha.220 → 1.0.0-alpha.222

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/index.d.mts CHANGED
@@ -1,8 +1,40 @@
1
- import { SchemaLike, DatabaseWriterLike, CrossShardReadArgs, CdcChange, FilterClause, ExportRow, MigrationDirection, ReadFootprint, DependencyTracker, ReactiveCache, ShapeProbeCounters, GlobalPollCounters, ReactiveCacheOptions, TransactionHeadroomTracker, LifecycleDispatchInfo, MigrationRunResult, SearchBackfillProgress, VectorBackfillProgress, TableIndexInfo, ColumnMeta, AdvisoryFinding, AdvisorProcedure, RlsPoliciesResult, MaskPoliciesResult, StorageRulesResult, StudioFeaturesResult, FlagsResult, SubscriptionIdentity, QueuesResult, WorkflowsResult, ImportShardResult, RelatedPage, ShardRankPageResult, ShardSocketLike, SubscriptionQuery, ShapeSubscriptionQuery, MutationDelta, KeyRange, ResolvedShape, ShapeRow, TtlSweepSpec, ScheduleOutbox, SchedulerLike, TransactionLimits, IndexKeyEntry, SqlExec, CdcChangeKey } from '@lunora/shard-engine';
1
+ import { SubscriptionIdentity, SchemaLike, DatabaseWriterLike, CrossShardReadArgs, CdcChange, FilterClause, ExportRow, MigrationDirection, ReadFootprint, DependencyTracker, ReactiveCache, ShapeProbeCounters, GlobalPollCounters, ReactiveCacheOptions, TransactionHeadroomTracker, LifecycleDispatchInfo, MigrationRunResult, SearchBackfillProgress, VectorBackfillProgress, TableIndexInfo, ColumnMeta, AdvisoryFinding, AdvisorProcedure, RlsPoliciesResult, MaskPoliciesResult, StorageRulesResult, StudioFeaturesResult, FlagsResult, QueuesResult, WorkflowsResult, ImportShardResult, RelatedPage, ShardRankPageResult, ShardSocketLike, SubscriptionQuery, ShapeSubscriptionQuery, MutationDelta, KeyRange, ResolvedShape, ShapeRow, TtlSweepSpec, ScheduleOutbox, SchedulerLike, TransactionLimits, IndexKeyEntry, SqlExec, CdcChangeKey } from '@lunora/shard-engine';
2
2
  export { type AdvisorProcedure, type AdvisoryFinding, type AggregateIndexDefinitionLike, type DataMigrationLike, type DatabaseWriterLike, type ExportRow, type ExternalSourceLike, type FlagsResult, type ImportShardResult, type KeyRange, type MaskPoliciesResult, type MigrationRunResult, type MutationDelta, type QueuesResult, REPROJECTION_MIGRATION_PREFIX, type RankIndexDefinitionLike, type RelatedPage, type RlsPoliciesResult, type SchedulerLike, type SchemaLike, type SearchBackfillProgress, type ShardRankPageResult, type SourceClientLike, type SqlExec, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionIdentity, type SystemReaderStorageLike, type TransactionHeadroomTracker, UNVOUCHABLE_DEP, type ValidatorLike, type VectorBackfillProgress, type WhereInput, type WorkflowsResult, type WriteHook, applyCdcChanges, assertShapeShardable, backfillSearchIndexes, backfillVectorIndexes, buildReprojectionMigration, clearMemoryTables, countLegacyRows, createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, isSourceDue, markUnvouchableReads, pullExternalSourceIncrementalTick, pullExternalSourceTick, reprojectionMigrationId, reprojectionTables, runDataMigration, runShardMigrations, subscriptionListDeltas } from '@lunora/shard-engine';
3
3
  import { DatabaseInstrumentation, MetricHistoryOptions, LogEventInput, TraceAnchor, ContextLogLevel, ContextTracer, SqlClientLike, ContextFetch, ContextMetrics } from '@lunora/observability';
4
4
  import { DrizzleSqliteDODatabase } from 'drizzle-orm/durable-sqlite';
5
5
  export { type ShardPlatform, type WorkerPlatform, type WorkerPlatformOptions, createShardAlarms, createShardDirectory, createShardHost, createShardKvStore, createShardPlatform, createSocketHost, createWorkerPlatform } from '@lunora/platform-cloudflare';
6
+ /** Opaque authority scope and its monotonic revision. No access policy is stored on the shard. */
7
+ interface DeliveryPermit {
8
+ readonly epoch: number;
9
+ /** Opaque authority key, at most 256 UTF-8 bytes to bound persisted socket metadata. */
10
+ readonly scope: string;
11
+ }
12
+ interface DeliveryAuthorizationRequest {
13
+ /** True only for a reserved admin RPC with a validated bearer. */
14
+ readonly admin: boolean;
15
+ readonly args: Record<string, unknown>;
16
+ readonly functionPath: string;
17
+ readonly identity: SubscriptionIdentity;
18
+ readonly shardKey: string | undefined;
19
+ /** Trusted server dispatch at the native binding; always false for subscriptions. */
20
+ readonly system: boolean;
21
+ readonly transport: "subscription" | "rpc";
22
+ }
23
+ /**
24
+ * Resolve against current authority, including before receipt/cache replay.
25
+ * The application commits policy and pending invalidation together, denies new
26
+ * permits immediately, and retries installDeliveryFence before acknowledging
27
+ * revocation. It owns affected scopes; the shard stores no grant or topology copy.
28
+ */
29
+ type DeliveryAuthorization = (request: DeliveryAuthorizationRequest) => Promise<DeliveryPermit | undefined>;
30
+ /** Install through a private namespace binding. Acknowledgement covers this shard's durable local fence. */
31
+ declare const installDeliveryFence: (target: {
32
+ fetch: (url: string, init?: RequestInit) => Promise<Response>;
33
+ }, options: {
34
+ env: unknown;
35
+ fence: DeliveryPermit;
36
+ shardKey: string | undefined;
37
+ }) => Promise<void>;
6
38
  /** The framework roles that can share the shard class, named after their generated `_generated/` modules. */
7
39
  declare const MERGED_ROLES: readonly ["scheduler", "shardRegistry"];
8
40
  /** One of {@link MERGED_ROLES}. */
@@ -917,6 +949,86 @@ type ClientMutationClass = {
917
949
  expected: number;
918
950
  kind: "already" | "gap" | "next";
919
951
  };
952
+ /**
953
+ * The per-request identity/replay fields a dispatch must run under. Captured
954
+ * before the mutation-replay gate and re-pinned inside it, because the gate only
955
+ * delays ENTRY: a sibling `fetch()`'s prologue can overwrite the shared
956
+ * `currentRequest*` fields while this dispatch waits its turn. Kept as one named
957
+ * shape so the capture list lives in exactly one place instead of being an
958
+ * unenforced "remember to add the next field here too" invariant.
959
+ *
960
+ * It stays a hand-written LIST rather than "snapshot every `currentRequest*`
961
+ * field", because membership is a judgement, not a category: `currentRequestTrace`
962
+ * is ALSO threaded by value as `dispatchTrace` (it is here too only because the
963
+ * outbound-container traceparent reads the shared field),
964
+ * `currentResponseBookmark` is PRODUCED by the dispatch (the restore
965
+ * clears it on purpose), and `mutationBookkeeping` is written DURING the handler
966
+ * — re-pinning the captured `undefined` at the tail would wipe the handshake the
967
+ * post-dispatch bookkeeping reads next. A mechanism that cannot forget a field
968
+ * would still have to be told which of those three answers each new field wants,
969
+ * so it would relocate the judgement rather than remove it. What the shape does
970
+ * buy is that adding a field here is a compile error in
971
+ * {@link ShardDO.captureRequestScope}'s object literal until it is captured —
972
+ * the answer stays a judgement, but a half-made one cannot compile.
973
+ */
974
+ interface RequestScope {
975
+ /**
976
+ * The inbound `x-d1-bookmark`. In the scope for the same reason `userId` is:
977
+ * a queued mutation admitted after a sibling's prologue would otherwise have
978
+ * `getInboundBookmark()` hand its `.global()` reads ANOTHER request's D1
979
+ * session pin, which is read-your-writes reading someone else's.
980
+ */
981
+ /** The caller's CDC baseline (`x-lunora-base-seq`); see {@link ShardDO.currentRequestBaselineSeq}. */
982
+ baselineSeq: number | undefined;
983
+ bookmark: string | undefined;
984
+ clientId: string | undefined;
985
+ clientSeq: number | undefined;
986
+ deliveryPermit: DeliveryPermit | undefined;
987
+ /**
988
+ * The caller's CLAIMS — active org, role, tenant. Distinct from `userId` and
989
+ * far more load-bearing than the pairing suggests: RLS grants roles from this
990
+ * object (`readIdentityRoles`), and it is what `ctx.auth.getIdentity()`
991
+ * returns. Left out of the scope, a mutation admitted at the gate ran under
992
+ * its own `userId` and the SIBLING's role and tenant — an admin sibling
993
+ * handed it admin RLS; a finished one handed it no claims at all.
994
+ */
995
+ identity: Record<string, unknown> | undefined;
996
+ /**
997
+ * The caller's IP. In the scope for the same reason `userId` is: a nested
998
+ * call that re-pins the identity fields but not this one leaves `ctx.ip`
999
+ * reading whatever the guest left behind.
1000
+ */
1001
+ ip: string | undefined;
1002
+ mutationId: string | undefined;
1003
+ mutatorClass: ClientMutationClass | undefined;
1004
+ /** The request's origin; in the scope for the same reason `ip` is. */
1005
+ origin: string | undefined;
1006
+ /**
1007
+ * The propagated tail-bias toggle, travelling with `traceparent` below for
1008
+ * the same reason and with the same hazard: `buildCtx` hands both to
1009
+ * `createContainerContext`, so a guest dispatch that re-pinned one but not
1010
+ * the other would send a parked request's verdict to the container.
1011
+ */
1012
+ sampleErrors: boolean | undefined;
1013
+ system: boolean;
1014
+ /**
1015
+ * The dispatch's own trace anchor, minted when the request carried no
1016
+ * `traceparent`. `getCurrentTraceparent` falls back to it for outbound
1017
+ * container calls, so it travels with `traceparent` for the same reason:
1018
+ * a queued mutation admitted after a sibling's prologue would otherwise
1019
+ * forward the sibling's trace.
1020
+ */
1021
+ trace: TraceAnchor | undefined;
1022
+ /**
1023
+ * The inbound W3C `traceparent`, which `buildCtx` hands to
1024
+ * `createContainerContext` so an outbound container fetch joins the caller's
1025
+ * trace. Telemetry rather than authorization, but the same shared field with
1026
+ * the same interleaving — a guest dispatch that did not re-pin it filed its
1027
+ * container spans under a parked request's trace.
1028
+ */
1029
+ traceparent: string | undefined;
1030
+ userId: string | undefined;
1031
+ }
920
1032
  /**
921
1033
  * The read-set / cache-hit attribution for ONE `/rpc` dispatch, filled in by
922
1034
  * {@link ShardDO.runCachedQuery} and read back by {@link ShardDO.recordRequestLog}.
@@ -1017,6 +1129,8 @@ interface ShardDOOptions {
1017
1129
  * from a call to the accessor.
1018
1130
  */
1019
1131
  ctxDbCacheWired?: boolean;
1132
+ /** Current authority for ordinary subscriptions and RPC responses. Other live delivery modes are refused. */
1133
+ deliveryAuthorization?: DeliveryAuthorization;
1020
1134
  /**
1021
1135
  * Ceiling on the join keys one relation-crossing `where` predicate may pull
1022
1136
  * back via semijoin pre-resolution before failing closed. Reaches
@@ -1308,6 +1422,13 @@ declare abstract class ShardDO {
1308
1422
  * changelog proved their table had not moved.
1309
1423
  */
1310
1424
  protected globalPoll: GlobalPollCounters;
1425
+ private readonly deliveryAuthorization;
1426
+ private readonly deliveryFence;
1427
+ private readonly deliveryResponsePermits;
1428
+ private readonly deliveryRequestPermits;
1429
+ private currentDeliveryPermit;
1430
+ private transactionRequestScope;
1431
+ private readonly deliveryRegistrations;
1311
1432
  /** ctx-db relation knobs from {@link ShardDOOptions}, handed on by {@link ShardDO.ctxDbTuning}. */
1312
1433
  private readonly ctxDbRelationOptions;
1313
1434
  /**
@@ -1760,6 +1881,7 @@ declare abstract class ShardDO {
1760
1881
  * them, so a socket never receives room traffic before its join committed.
1761
1882
  */
1762
1883
  private readonly pendingRoomJoins;
1884
+ private retainedRoomsNeedCleanup;
1763
1885
  /**
1764
1886
  * Topics whose join was refused. A leave queued behind a refused join pairs with no
1765
1887
  * committed join, so it must not run `onLeave`.
@@ -2049,10 +2171,6 @@ declare abstract class ShardDO {
2049
2171
  */
2050
2172
  private currentStmtSamplesTruncated;
2051
2173
  constructor(state: ShardDOState, env: unknown, options?: ShardDOOptions);
2052
- /**
2053
- * Worker-side fetch entry point. Delegates to the host-neutral
2054
- * {@link ShardRunner}, which forwards to the Cloudflare implementation below.
2055
- */
2056
2174
  fetch(request: Request): Promise<Response>;
2057
2175
  /**
2058
2176
  * Hibernation API: invoked by the runtime when a message arrives on a
@@ -2392,7 +2510,9 @@ declare abstract class ShardDO {
2392
2510
  * @param work the side effect to hold until the commit lands
2393
2511
  */
2394
2512
  protected deferAfterCommit(work: () => Promise<void> | void): Promise<void>;
2395
- protected runInTransaction<T>(handler: () => Promise<T> | T): Promise<T>;
2513
+ protected runInTransaction<T>(handler: () => Promise<T> | T, options?: {
2514
+ independent: true;
2515
+ }): Promise<T>;
2396
2516
  /**
2397
2517
  * Returns the D1 Sessions API bookmark forwarded by the client on this
2398
2518
  * request, or `undefined` when none was supplied. Handlers pass this
@@ -3031,6 +3151,8 @@ declare abstract class ShardDO {
3031
3151
  * dedup.
3032
3152
  */
3033
3153
  protected isCustomMutator(_functionPath: string): boolean;
3154
+ /** Prepare a codegen-lazy procedure only after the caller's purpose is known. */
3155
+ protected prepareFunction(_functionPath: string, _reason: "rpc" | "subscription" | "stream" | "reactor"): void | Promise<void>;
3034
3156
  /**
3035
3157
  * Whether `functionPath` names a registered `mutation` — the only function
3036
3158
  * kind whose dispatch may enter the single-writer gate.
@@ -3924,7 +4046,7 @@ declare abstract class ShardDO {
3924
4046
  * Paired with {@link ShardDO.restoreRequestScope}; see that type's docstring
3925
4047
  * for why the dispatch path needs it.
3926
4048
  */
3927
- private captureRequestScope;
4049
+ protected captureRequestScope(): RequestScope;
3928
4050
  /**
3929
4051
  * Re-pin a {@link RequestScope} captured by {@link ShardDO.captureRequestScope}.
3930
4052
  *
@@ -3933,7 +4055,15 @@ declare abstract class ShardDO {
3933
4055
  * during the wait, and echoing it would report a stranger's D1 write position
3934
4056
  * as this request's. The dispatch path re-pins its own afterwards.
3935
4057
  */
3936
- private restoreRequestScope;
4058
+ protected restoreRequestScope(scope: RequestScope): void;
4059
+ private deliveryRoleSupported;
4060
+ private revokeSubscription;
4061
+ private sendFrame;
4062
+ private authorizeSubscription;
4063
+ private endSubscriptionOnAuthorityFailure;
4064
+ private authorizeDelivery;
4065
+ private installDeliveryFence;
4066
+ private fetchAuthorizedRpc;
3937
4067
  /**
3938
4068
  * What `instrumentDb` / `instrumentSql` hand their instrumenter, or
3939
4069
  * `undefined` when nothing collects (no sink, or `instrumentDatabase: "off"`).
@@ -4965,6 +5095,11 @@ declare abstract class ShardDO {
4965
5095
  * `{type:"error"}`. Either way drop the controller.
4966
5096
  */
4967
5097
  private handleStream;
5098
+ private reserveStream;
5099
+ private startStream;
5100
+ private pumpStream;
5101
+ private isStreamStopped;
5102
+ private releaseStream;
4968
5103
  /**
4969
5104
  * Attach a socket to a **durable** stream run.
4970
5105
  *
@@ -5244,6 +5379,8 @@ declare abstract class ShardDO {
5244
5379
  * @returns the cursor/epoch, the resume base (`baseCheckpoint`), whether this is a full re-seed, and the membership patch
5245
5380
  */
5246
5381
  private computeOpLogShapeSeed;
5382
+ /** Attachments can retain unsupported subscriptions when a deployment enables delivery authorization. */
5383
+ private rejectRetainedShapesAndRooms;
5247
5384
  /**
5248
5385
  * Fan the membership diff of every shape affected by this flush to its
5249
5386
  * subscribers — the partial-replication parallel to
@@ -5787,8 +5924,8 @@ declare abstract class ShardDO {
5787
5924
  * #20), the push can go out as one `{type:"delta"}` frame per changed row
5788
5925
  * instead of a full `{type:"data"}` snapshot. Which of the two is sent is
5789
5926
  * `subscriptionFrames`' call, made by rendering both and measuring them —
5790
- * this method just sends what it is handed. The memo is always advanced to
5791
- * the new `lastJson`/`tables` regardless of path.
5927
+ * this method just sends what it is handed. A fenced delivery leaves the
5928
+ * previous memo and cursor intact.
5792
5929
  *
5793
5930
  * `cursor` (when supplied) is the `__cdc_log` high-watermark this frame
5794
5931
  * covers; it is appended to the emitted `data`/`delta` JSON so a client can
@@ -5805,6 +5942,8 @@ declare abstract class ShardDO {
5805
5942
  * `pageDeltas` a redundant attachment read.
5806
5943
  */
5807
5944
  private pushSubscriptionData;
5945
+ private sendSubscriptionSettlement;
5946
+ private allowsSubscriptionOutcome;
5808
5947
  /**
5809
5948
  * Gate the upgrade request against two complementary controls:
5810
5949
  *
@@ -5964,6 +6103,8 @@ declare abstract class ShardDO {
5964
6103
  * pair's reservation.
5965
6104
  */
5966
6105
  private runWhisperAuthorizers;
6106
+ /** Retiring an unsupported room must not invoke its application mutations or broadcasts. */
6107
+ private rejectRetainedRooms;
5967
6108
  /**
5968
6109
  * Join (`join = true`) or leave a whisper `topic` on this socket. Membership rides
5969
6110
  * the hibernation attachment, bounded by
@@ -6181,4 +6322,4 @@ declare class ShardRegistryDO {
6181
6322
  * never share an id sequence for the same key.
6182
6323
  */
6183
6324
  declare const createStableIdFactory: (mutationId: string | undefined, scope: string) => (() => string);
6184
- export { type DispatchBookmark, type DurableObjectHandlers, type HibernatableWebSocket, MERGED_ROLES, type MergedDurableObject, type MergedRole, type MergedRoles, type QueryReadScope, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RoleClass, type RoleNamespaceTarget, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkRowArgs, type RunShardBulkRowResult, type RunShardExportArgs, type RunShardFindRelatedArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, SessionDO, type SessionRecord, ShardDO, type ShardDOOptions, type ShardDOState, ShardRegistryDO, type SubscriptionOutcome, type TelemetrySink, type TraceRefLike, createStableIdFactory, mergeDurableObjects, roleNamespace, serveRelationFanout };
6325
+ export { type DeliveryAuthorization, type DeliveryAuthorizationRequest, type DeliveryPermit, type DispatchBookmark, type DurableObjectHandlers, type HibernatableWebSocket, MERGED_ROLES, type MergedDurableObject, type MergedRole, type MergedRoles, type QueryReadScope, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RoleClass, type RoleNamespaceTarget, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkRowArgs, type RunShardBulkRowResult, type RunShardExportArgs, type RunShardFindRelatedArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, SessionDO, type SessionRecord, ShardDO, type ShardDOOptions, type ShardDOState, ShardRegistryDO, type SubscriptionOutcome, type TelemetrySink, type TraceRefLike, createStableIdFactory, installDeliveryFence, mergeDurableObjects, roleNamespace, serveRelationFanout };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,40 @@
1
- import { SchemaLike, DatabaseWriterLike, CrossShardReadArgs, CdcChange, FilterClause, ExportRow, MigrationDirection, ReadFootprint, DependencyTracker, ReactiveCache, ShapeProbeCounters, GlobalPollCounters, ReactiveCacheOptions, TransactionHeadroomTracker, LifecycleDispatchInfo, MigrationRunResult, SearchBackfillProgress, VectorBackfillProgress, TableIndexInfo, ColumnMeta, AdvisoryFinding, AdvisorProcedure, RlsPoliciesResult, MaskPoliciesResult, StorageRulesResult, StudioFeaturesResult, FlagsResult, SubscriptionIdentity, QueuesResult, WorkflowsResult, ImportShardResult, RelatedPage, ShardRankPageResult, ShardSocketLike, SubscriptionQuery, ShapeSubscriptionQuery, MutationDelta, KeyRange, ResolvedShape, ShapeRow, TtlSweepSpec, ScheduleOutbox, SchedulerLike, TransactionLimits, IndexKeyEntry, SqlExec, CdcChangeKey } from '@lunora/shard-engine';
1
+ import { SubscriptionIdentity, SchemaLike, DatabaseWriterLike, CrossShardReadArgs, CdcChange, FilterClause, ExportRow, MigrationDirection, ReadFootprint, DependencyTracker, ReactiveCache, ShapeProbeCounters, GlobalPollCounters, ReactiveCacheOptions, TransactionHeadroomTracker, LifecycleDispatchInfo, MigrationRunResult, SearchBackfillProgress, VectorBackfillProgress, TableIndexInfo, ColumnMeta, AdvisoryFinding, AdvisorProcedure, RlsPoliciesResult, MaskPoliciesResult, StorageRulesResult, StudioFeaturesResult, FlagsResult, QueuesResult, WorkflowsResult, ImportShardResult, RelatedPage, ShardRankPageResult, ShardSocketLike, SubscriptionQuery, ShapeSubscriptionQuery, MutationDelta, KeyRange, ResolvedShape, ShapeRow, TtlSweepSpec, ScheduleOutbox, SchedulerLike, TransactionLimits, IndexKeyEntry, SqlExec, CdcChangeKey } from '@lunora/shard-engine';
2
2
  export { type AdvisorProcedure, type AdvisoryFinding, type AggregateIndexDefinitionLike, type DataMigrationLike, type DatabaseWriterLike, type ExportRow, type ExternalSourceLike, type FlagsResult, type ImportShardResult, type KeyRange, type MaskPoliciesResult, type MigrationRunResult, type MutationDelta, type QueuesResult, REPROJECTION_MIGRATION_PREFIX, type RankIndexDefinitionLike, type RelatedPage, type RlsPoliciesResult, type SchedulerLike, type SchemaLike, type SearchBackfillProgress, type ShardRankPageResult, type SourceClientLike, type SqlExec, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionIdentity, type SystemReaderStorageLike, type TransactionHeadroomTracker, UNVOUCHABLE_DEP, type ValidatorLike, type VectorBackfillProgress, type WhereInput, type WorkflowsResult, type WriteHook, applyCdcChanges, assertShapeShardable, backfillSearchIndexes, backfillVectorIndexes, buildReprojectionMigration, clearMemoryTables, countLegacyRows, createReadFootprint, createShardCtxDb, exportShardRows, importShardRows, isSourceDue, markUnvouchableReads, pullExternalSourceIncrementalTick, pullExternalSourceTick, reprojectionMigrationId, reprojectionTables, runDataMigration, runShardMigrations, subscriptionListDeltas } from '@lunora/shard-engine';
3
3
  import { DatabaseInstrumentation, MetricHistoryOptions, LogEventInput, TraceAnchor, ContextLogLevel, ContextTracer, SqlClientLike, ContextFetch, ContextMetrics } from '@lunora/observability';
4
4
  import { DrizzleSqliteDODatabase } from 'drizzle-orm/durable-sqlite';
5
5
  export { type ShardPlatform, type WorkerPlatform, type WorkerPlatformOptions, createShardAlarms, createShardDirectory, createShardHost, createShardKvStore, createShardPlatform, createSocketHost, createWorkerPlatform } from '@lunora/platform-cloudflare';
6
+ /** Opaque authority scope and its monotonic revision. No access policy is stored on the shard. */
7
+ interface DeliveryPermit {
8
+ readonly epoch: number;
9
+ /** Opaque authority key, at most 256 UTF-8 bytes to bound persisted socket metadata. */
10
+ readonly scope: string;
11
+ }
12
+ interface DeliveryAuthorizationRequest {
13
+ /** True only for a reserved admin RPC with a validated bearer. */
14
+ readonly admin: boolean;
15
+ readonly args: Record<string, unknown>;
16
+ readonly functionPath: string;
17
+ readonly identity: SubscriptionIdentity;
18
+ readonly shardKey: string | undefined;
19
+ /** Trusted server dispatch at the native binding; always false for subscriptions. */
20
+ readonly system: boolean;
21
+ readonly transport: "subscription" | "rpc";
22
+ }
23
+ /**
24
+ * Resolve against current authority, including before receipt/cache replay.
25
+ * The application commits policy and pending invalidation together, denies new
26
+ * permits immediately, and retries installDeliveryFence before acknowledging
27
+ * revocation. It owns affected scopes; the shard stores no grant or topology copy.
28
+ */
29
+ type DeliveryAuthorization = (request: DeliveryAuthorizationRequest) => Promise<DeliveryPermit | undefined>;
30
+ /** Install through a private namespace binding. Acknowledgement covers this shard's durable local fence. */
31
+ declare const installDeliveryFence: (target: {
32
+ fetch: (url: string, init?: RequestInit) => Promise<Response>;
33
+ }, options: {
34
+ env: unknown;
35
+ fence: DeliveryPermit;
36
+ shardKey: string | undefined;
37
+ }) => Promise<void>;
6
38
  /** The framework roles that can share the shard class, named after their generated `_generated/` modules. */
7
39
  declare const MERGED_ROLES: readonly ["scheduler", "shardRegistry"];
8
40
  /** One of {@link MERGED_ROLES}. */
@@ -917,6 +949,86 @@ type ClientMutationClass = {
917
949
  expected: number;
918
950
  kind: "already" | "gap" | "next";
919
951
  };
952
+ /**
953
+ * The per-request identity/replay fields a dispatch must run under. Captured
954
+ * before the mutation-replay gate and re-pinned inside it, because the gate only
955
+ * delays ENTRY: a sibling `fetch()`'s prologue can overwrite the shared
956
+ * `currentRequest*` fields while this dispatch waits its turn. Kept as one named
957
+ * shape so the capture list lives in exactly one place instead of being an
958
+ * unenforced "remember to add the next field here too" invariant.
959
+ *
960
+ * It stays a hand-written LIST rather than "snapshot every `currentRequest*`
961
+ * field", because membership is a judgement, not a category: `currentRequestTrace`
962
+ * is ALSO threaded by value as `dispatchTrace` (it is here too only because the
963
+ * outbound-container traceparent reads the shared field),
964
+ * `currentResponseBookmark` is PRODUCED by the dispatch (the restore
965
+ * clears it on purpose), and `mutationBookkeeping` is written DURING the handler
966
+ * — re-pinning the captured `undefined` at the tail would wipe the handshake the
967
+ * post-dispatch bookkeeping reads next. A mechanism that cannot forget a field
968
+ * would still have to be told which of those three answers each new field wants,
969
+ * so it would relocate the judgement rather than remove it. What the shape does
970
+ * buy is that adding a field here is a compile error in
971
+ * {@link ShardDO.captureRequestScope}'s object literal until it is captured —
972
+ * the answer stays a judgement, but a half-made one cannot compile.
973
+ */
974
+ interface RequestScope {
975
+ /**
976
+ * The inbound `x-d1-bookmark`. In the scope for the same reason `userId` is:
977
+ * a queued mutation admitted after a sibling's prologue would otherwise have
978
+ * `getInboundBookmark()` hand its `.global()` reads ANOTHER request's D1
979
+ * session pin, which is read-your-writes reading someone else's.
980
+ */
981
+ /** The caller's CDC baseline (`x-lunora-base-seq`); see {@link ShardDO.currentRequestBaselineSeq}. */
982
+ baselineSeq: number | undefined;
983
+ bookmark: string | undefined;
984
+ clientId: string | undefined;
985
+ clientSeq: number | undefined;
986
+ deliveryPermit: DeliveryPermit | undefined;
987
+ /**
988
+ * The caller's CLAIMS — active org, role, tenant. Distinct from `userId` and
989
+ * far more load-bearing than the pairing suggests: RLS grants roles from this
990
+ * object (`readIdentityRoles`), and it is what `ctx.auth.getIdentity()`
991
+ * returns. Left out of the scope, a mutation admitted at the gate ran under
992
+ * its own `userId` and the SIBLING's role and tenant — an admin sibling
993
+ * handed it admin RLS; a finished one handed it no claims at all.
994
+ */
995
+ identity: Record<string, unknown> | undefined;
996
+ /**
997
+ * The caller's IP. In the scope for the same reason `userId` is: a nested
998
+ * call that re-pins the identity fields but not this one leaves `ctx.ip`
999
+ * reading whatever the guest left behind.
1000
+ */
1001
+ ip: string | undefined;
1002
+ mutationId: string | undefined;
1003
+ mutatorClass: ClientMutationClass | undefined;
1004
+ /** The request's origin; in the scope for the same reason `ip` is. */
1005
+ origin: string | undefined;
1006
+ /**
1007
+ * The propagated tail-bias toggle, travelling with `traceparent` below for
1008
+ * the same reason and with the same hazard: `buildCtx` hands both to
1009
+ * `createContainerContext`, so a guest dispatch that re-pinned one but not
1010
+ * the other would send a parked request's verdict to the container.
1011
+ */
1012
+ sampleErrors: boolean | undefined;
1013
+ system: boolean;
1014
+ /**
1015
+ * The dispatch's own trace anchor, minted when the request carried no
1016
+ * `traceparent`. `getCurrentTraceparent` falls back to it for outbound
1017
+ * container calls, so it travels with `traceparent` for the same reason:
1018
+ * a queued mutation admitted after a sibling's prologue would otherwise
1019
+ * forward the sibling's trace.
1020
+ */
1021
+ trace: TraceAnchor | undefined;
1022
+ /**
1023
+ * The inbound W3C `traceparent`, which `buildCtx` hands to
1024
+ * `createContainerContext` so an outbound container fetch joins the caller's
1025
+ * trace. Telemetry rather than authorization, but the same shared field with
1026
+ * the same interleaving — a guest dispatch that did not re-pin it filed its
1027
+ * container spans under a parked request's trace.
1028
+ */
1029
+ traceparent: string | undefined;
1030
+ userId: string | undefined;
1031
+ }
920
1032
  /**
921
1033
  * The read-set / cache-hit attribution for ONE `/rpc` dispatch, filled in by
922
1034
  * {@link ShardDO.runCachedQuery} and read back by {@link ShardDO.recordRequestLog}.
@@ -1017,6 +1129,8 @@ interface ShardDOOptions {
1017
1129
  * from a call to the accessor.
1018
1130
  */
1019
1131
  ctxDbCacheWired?: boolean;
1132
+ /** Current authority for ordinary subscriptions and RPC responses. Other live delivery modes are refused. */
1133
+ deliveryAuthorization?: DeliveryAuthorization;
1020
1134
  /**
1021
1135
  * Ceiling on the join keys one relation-crossing `where` predicate may pull
1022
1136
  * back via semijoin pre-resolution before failing closed. Reaches
@@ -1308,6 +1422,13 @@ declare abstract class ShardDO {
1308
1422
  * changelog proved their table had not moved.
1309
1423
  */
1310
1424
  protected globalPoll: GlobalPollCounters;
1425
+ private readonly deliveryAuthorization;
1426
+ private readonly deliveryFence;
1427
+ private readonly deliveryResponsePermits;
1428
+ private readonly deliveryRequestPermits;
1429
+ private currentDeliveryPermit;
1430
+ private transactionRequestScope;
1431
+ private readonly deliveryRegistrations;
1311
1432
  /** ctx-db relation knobs from {@link ShardDOOptions}, handed on by {@link ShardDO.ctxDbTuning}. */
1312
1433
  private readonly ctxDbRelationOptions;
1313
1434
  /**
@@ -1760,6 +1881,7 @@ declare abstract class ShardDO {
1760
1881
  * them, so a socket never receives room traffic before its join committed.
1761
1882
  */
1762
1883
  private readonly pendingRoomJoins;
1884
+ private retainedRoomsNeedCleanup;
1763
1885
  /**
1764
1886
  * Topics whose join was refused. A leave queued behind a refused join pairs with no
1765
1887
  * committed join, so it must not run `onLeave`.
@@ -2049,10 +2171,6 @@ declare abstract class ShardDO {
2049
2171
  */
2050
2172
  private currentStmtSamplesTruncated;
2051
2173
  constructor(state: ShardDOState, env: unknown, options?: ShardDOOptions);
2052
- /**
2053
- * Worker-side fetch entry point. Delegates to the host-neutral
2054
- * {@link ShardRunner}, which forwards to the Cloudflare implementation below.
2055
- */
2056
2174
  fetch(request: Request): Promise<Response>;
2057
2175
  /**
2058
2176
  * Hibernation API: invoked by the runtime when a message arrives on a
@@ -2392,7 +2510,9 @@ declare abstract class ShardDO {
2392
2510
  * @param work the side effect to hold until the commit lands
2393
2511
  */
2394
2512
  protected deferAfterCommit(work: () => Promise<void> | void): Promise<void>;
2395
- protected runInTransaction<T>(handler: () => Promise<T> | T): Promise<T>;
2513
+ protected runInTransaction<T>(handler: () => Promise<T> | T, options?: {
2514
+ independent: true;
2515
+ }): Promise<T>;
2396
2516
  /**
2397
2517
  * Returns the D1 Sessions API bookmark forwarded by the client on this
2398
2518
  * request, or `undefined` when none was supplied. Handlers pass this
@@ -3031,6 +3151,8 @@ declare abstract class ShardDO {
3031
3151
  * dedup.
3032
3152
  */
3033
3153
  protected isCustomMutator(_functionPath: string): boolean;
3154
+ /** Prepare a codegen-lazy procedure only after the caller's purpose is known. */
3155
+ protected prepareFunction(_functionPath: string, _reason: "rpc" | "subscription" | "stream" | "reactor"): void | Promise<void>;
3034
3156
  /**
3035
3157
  * Whether `functionPath` names a registered `mutation` — the only function
3036
3158
  * kind whose dispatch may enter the single-writer gate.
@@ -3924,7 +4046,7 @@ declare abstract class ShardDO {
3924
4046
  * Paired with {@link ShardDO.restoreRequestScope}; see that type's docstring
3925
4047
  * for why the dispatch path needs it.
3926
4048
  */
3927
- private captureRequestScope;
4049
+ protected captureRequestScope(): RequestScope;
3928
4050
  /**
3929
4051
  * Re-pin a {@link RequestScope} captured by {@link ShardDO.captureRequestScope}.
3930
4052
  *
@@ -3933,7 +4055,15 @@ declare abstract class ShardDO {
3933
4055
  * during the wait, and echoing it would report a stranger's D1 write position
3934
4056
  * as this request's. The dispatch path re-pins its own afterwards.
3935
4057
  */
3936
- private restoreRequestScope;
4058
+ protected restoreRequestScope(scope: RequestScope): void;
4059
+ private deliveryRoleSupported;
4060
+ private revokeSubscription;
4061
+ private sendFrame;
4062
+ private authorizeSubscription;
4063
+ private endSubscriptionOnAuthorityFailure;
4064
+ private authorizeDelivery;
4065
+ private installDeliveryFence;
4066
+ private fetchAuthorizedRpc;
3937
4067
  /**
3938
4068
  * What `instrumentDb` / `instrumentSql` hand their instrumenter, or
3939
4069
  * `undefined` when nothing collects (no sink, or `instrumentDatabase: "off"`).
@@ -4965,6 +5095,11 @@ declare abstract class ShardDO {
4965
5095
  * `{type:"error"}`. Either way drop the controller.
4966
5096
  */
4967
5097
  private handleStream;
5098
+ private reserveStream;
5099
+ private startStream;
5100
+ private pumpStream;
5101
+ private isStreamStopped;
5102
+ private releaseStream;
4968
5103
  /**
4969
5104
  * Attach a socket to a **durable** stream run.
4970
5105
  *
@@ -5244,6 +5379,8 @@ declare abstract class ShardDO {
5244
5379
  * @returns the cursor/epoch, the resume base (`baseCheckpoint`), whether this is a full re-seed, and the membership patch
5245
5380
  */
5246
5381
  private computeOpLogShapeSeed;
5382
+ /** Attachments can retain unsupported subscriptions when a deployment enables delivery authorization. */
5383
+ private rejectRetainedShapesAndRooms;
5247
5384
  /**
5248
5385
  * Fan the membership diff of every shape affected by this flush to its
5249
5386
  * subscribers — the partial-replication parallel to
@@ -5787,8 +5924,8 @@ declare abstract class ShardDO {
5787
5924
  * #20), the push can go out as one `{type:"delta"}` frame per changed row
5788
5925
  * instead of a full `{type:"data"}` snapshot. Which of the two is sent is
5789
5926
  * `subscriptionFrames`' call, made by rendering both and measuring them —
5790
- * this method just sends what it is handed. The memo is always advanced to
5791
- * the new `lastJson`/`tables` regardless of path.
5927
+ * this method just sends what it is handed. A fenced delivery leaves the
5928
+ * previous memo and cursor intact.
5792
5929
  *
5793
5930
  * `cursor` (when supplied) is the `__cdc_log` high-watermark this frame
5794
5931
  * covers; it is appended to the emitted `data`/`delta` JSON so a client can
@@ -5805,6 +5942,8 @@ declare abstract class ShardDO {
5805
5942
  * `pageDeltas` a redundant attachment read.
5806
5943
  */
5807
5944
  private pushSubscriptionData;
5945
+ private sendSubscriptionSettlement;
5946
+ private allowsSubscriptionOutcome;
5808
5947
  /**
5809
5948
  * Gate the upgrade request against two complementary controls:
5810
5949
  *
@@ -5964,6 +6103,8 @@ declare abstract class ShardDO {
5964
6103
  * pair's reservation.
5965
6104
  */
5966
6105
  private runWhisperAuthorizers;
6106
+ /** Retiring an unsupported room must not invoke its application mutations or broadcasts. */
6107
+ private rejectRetainedRooms;
5967
6108
  /**
5968
6109
  * Join (`join = true`) or leave a whisper `topic` on this socket. Membership rides
5969
6110
  * the hibernation attachment, bounded by
@@ -6181,4 +6322,4 @@ declare class ShardRegistryDO {
6181
6322
  * never share an id sequence for the same key.
6182
6323
  */
6183
6324
  declare const createStableIdFactory: (mutationId: string | undefined, scope: string) => (() => string);
6184
- export { type DispatchBookmark, type DurableObjectHandlers, type HibernatableWebSocket, MERGED_ROLES, type MergedDurableObject, type MergedRole, type MergedRoles, type QueryReadScope, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RoleClass, type RoleNamespaceTarget, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkRowArgs, type RunShardBulkRowResult, type RunShardExportArgs, type RunShardFindRelatedArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, SessionDO, type SessionRecord, ShardDO, type ShardDOOptions, type ShardDOState, ShardRegistryDO, type SubscriptionOutcome, type TelemetrySink, type TraceRefLike, createStableIdFactory, mergeDurableObjects, roleNamespace, serveRelationFanout };
6325
+ export { type DeliveryAuthorization, type DeliveryAuthorizationRequest, type DeliveryPermit, type DispatchBookmark, type DurableObjectHandlers, type HibernatableWebSocket, MERGED_ROLES, type MergedDurableObject, type MergedRole, type MergedRoles, type QueryReadScope, ROOT_DO_SIZE_WARN_BYTES, ROOT_SHARD_NAME, type RoleClass, type RoleNamespaceTarget, type RunShardApplyCdcArgs, type RunShardApplyCdcResult, type RunShardBulkRowArgs, type RunShardBulkRowResult, type RunShardExportArgs, type RunShardFindRelatedArgs, type RunShardImportArgs, type RunShardMigrationArgs, type RunShardRankBeforeArgs, type RunShardRankPageArgs, type RunShardWriteArgs, type RunShardWriteResult, SESSION_DO_TTL_DEFAULT, SHARD_REGISTRY_DO_NAME, SessionDO, type SessionRecord, ShardDO, type ShardDOOptions, type ShardDOState, ShardRegistryDO, type SubscriptionOutcome, type TelemetrySink, type TraceRefLike, createStableIdFactory, installDeliveryFence, mergeDurableObjects, roleNamespace, serveRelationFanout };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{MERGED_ROLES as a,mergeDurableObjects as o,roleNamespace as t}from"./packem_shared/MERGED_ROLES-C4RToZ16.mjs";import{serveRelationFanout as S}from"./packem_shared/serveRelationFanout-DcSjzAZv.mjs";import{SESSION_DO_TTL_DEFAULT as l,SessionDO as s}from"./packem_shared/SESSION_DO_TTL_DEFAULT-DSvTwRjc.mjs";import{ROOT_DO_SIZE_WARN_BYTES as p,ROOT_SHARD_NAME as R,ShardDO as d}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-DNXnJPf9.mjs";import{SHARD_REGISTRY_DO_NAME as D,ShardRegistryDO as E}from"./packem_shared/SHARD_REGISTRY_DO_NAME-DRIFt2FK.mjs";import{createStableIdFactory as h}from"./packem_shared/createStableIdFactory-CAEDEee5.mjs";import{createShardAlarms as u,createShardDirectory as x,createShardHost as T,createShardKvStore as b,createShardPlatform as f,createSocketHost as I,createWorkerPlatform as A}from"@lunora/platform-cloudflare";import{REPROJECTION_MIGRATION_PREFIX as g,UNVOUCHABLE_DEP as N,applyCdcChanges as k,assertShapeShardable as y,backfillSearchIndexes as L,backfillVectorIndexes as C,buildReprojectionMigration as F,clearMemoryTables as H,countLegacyRows as P,createReadFootprint as j,createShardCtxDb as U,exportShardRows as v,importShardRows as w,isSourceDue as G,markUnvouchableReads as B,pullExternalSourceIncrementalTick as V,pullExternalSourceTick as W,reprojectionMigrationId as Y,reprojectionTables as J,runDataMigration as K,runShardMigrations as X,subscriptionListDeltas as Z}from"@lunora/shard-engine";export{a as MERGED_ROLES,g as REPROJECTION_MIGRATION_PREFIX,p as ROOT_DO_SIZE_WARN_BYTES,R as ROOT_SHARD_NAME,l as SESSION_DO_TTL_DEFAULT,D as SHARD_REGISTRY_DO_NAME,s as SessionDO,d as ShardDO,E as ShardRegistryDO,N as UNVOUCHABLE_DEP,k as applyCdcChanges,y as assertShapeShardable,L as backfillSearchIndexes,C as backfillVectorIndexes,F as buildReprojectionMigration,H as clearMemoryTables,P as countLegacyRows,j as createReadFootprint,u as createShardAlarms,U as createShardCtxDb,x as createShardDirectory,T as createShardHost,b as createShardKvStore,f as createShardPlatform,I as createSocketHost,h as createStableIdFactory,A as createWorkerPlatform,v as exportShardRows,w as importShardRows,G as isSourceDue,B as markUnvouchableReads,o as mergeDurableObjects,V as pullExternalSourceIncrementalTick,W as pullExternalSourceTick,Y as reprojectionMigrationId,J as reprojectionTables,t as roleNamespace,K as runDataMigration,X as runShardMigrations,S as serveRelationFanout,Z as subscriptionListDeltas};
1
+ import{installDeliveryFence as a}from"./packem_shared/installDeliveryFence-B6M9KOnb.mjs";import{MERGED_ROLES as t,mergeDurableObjects as c,roleNamespace as S}from"./packem_shared/MERGED_ROLES-C4RToZ16.mjs";import{serveRelationFanout as i}from"./packem_shared/serveRelationFanout-DcSjzAZv.mjs";import{SESSION_DO_TTL_DEFAULT as n,SessionDO as p}from"./packem_shared/SESSION_DO_TTL_DEFAULT-DSvTwRjc.mjs";import{ROOT_DO_SIZE_WARN_BYTES as d,ROOT_SHARD_NAME as m,ShardDO as D}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-B87aOe8B.mjs";import{SHARD_REGISTRY_DO_NAME as O,ShardRegistryDO as h}from"./packem_shared/SHARD_REGISTRY_DO_NAME-DRIFt2FK.mjs";import{createStableIdFactory as x}from"./packem_shared/createStableIdFactory-CAEDEee5.mjs";import{createShardAlarms as f,createShardDirectory as T,createShardHost as b,createShardKvStore as I,createShardPlatform as A,createSocketHost as M,createWorkerPlatform as g}from"@lunora/platform-cloudflare";import{REPROJECTION_MIGRATION_PREFIX as k,UNVOUCHABLE_DEP as y,applyCdcChanges as F,assertShapeShardable as L,backfillSearchIndexes as C,backfillVectorIndexes as H,buildReprojectionMigration as P,clearMemoryTables as j,countLegacyRows as v,createReadFootprint as U,createShardCtxDb as w,exportShardRows as G,importShardRows as B,isSourceDue as V,markUnvouchableReads as W,pullExternalSourceIncrementalTick as Y,pullExternalSourceTick as J,reprojectionMigrationId as K,reprojectionTables as X,runDataMigration as Z,runShardMigrations as q,subscriptionListDeltas as z}from"@lunora/shard-engine";export{t as MERGED_ROLES,k as REPROJECTION_MIGRATION_PREFIX,d as ROOT_DO_SIZE_WARN_BYTES,m as ROOT_SHARD_NAME,n as SESSION_DO_TTL_DEFAULT,O as SHARD_REGISTRY_DO_NAME,p as SessionDO,D as ShardDO,h as ShardRegistryDO,y as UNVOUCHABLE_DEP,F as applyCdcChanges,L as assertShapeShardable,C as backfillSearchIndexes,H as backfillVectorIndexes,P as buildReprojectionMigration,j as clearMemoryTables,v as countLegacyRows,U as createReadFootprint,f as createShardAlarms,w as createShardCtxDb,T as createShardDirectory,b as createShardHost,I as createShardKvStore,A as createShardPlatform,M as createSocketHost,x as createStableIdFactory,g as createWorkerPlatform,G as exportShardRows,B as importShardRows,a as installDeliveryFence,V as isSourceDue,W as markUnvouchableReads,c as mergeDurableObjects,Y as pullExternalSourceIncrementalTick,J as pullExternalSourceTick,K as reprojectionMigrationId,X as reprojectionTables,S as roleNamespace,Z as runDataMigration,q as runShardMigrations,i as serveRelationFanout,z as subscriptionListDeltas};