@lunora/shard-engine 1.0.0-alpha.131 → 1.0.0-alpha.133
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/conformance/index.mjs +1 -1
- package/dist/index.d.mts +19 -4
- package/dist/index.d.ts +19 -4
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-B05iDlGI.mjs +8 -0
- package/dist/packem_shared/{defineEngineContractSuite-DdD3QXbx.mjs → defineEngineContractSuite-5b2mSLLd.mjs} +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-ZRhh4qpX.mjs +0 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-5b2mSLLd.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -2198,6 +2198,7 @@ interface RelayDetach {
|
|
|
2198
2198
|
interface RelayFrame {
|
|
2199
2199
|
cursor?: number;
|
|
2200
2200
|
epoch?: string;
|
|
2201
|
+
exceptConnectionId?: string;
|
|
2201
2202
|
frame: string;
|
|
2202
2203
|
originRelay?: number;
|
|
2203
2204
|
topic: string;
|
|
@@ -2240,7 +2241,19 @@ interface RelayShapePoke {
|
|
|
2240
2241
|
targetConnectionId?: string;
|
|
2241
2242
|
type: "relay_shape_poke";
|
|
2242
2243
|
}
|
|
2243
|
-
|
|
2244
|
+
interface RelayRoomEvent {
|
|
2245
|
+
attachment: Pick<SocketAttachment, "connectionId" | "context" | "identity" | "ip" | "userId">;
|
|
2246
|
+
connectionId: string;
|
|
2247
|
+
data?: unknown;
|
|
2248
|
+
kind: "join" | "leave" | "message";
|
|
2249
|
+
relayIndex: number;
|
|
2250
|
+
topic: string;
|
|
2251
|
+
type: "relay_room_event";
|
|
2252
|
+
}
|
|
2253
|
+
interface RelayRoomVerdict {
|
|
2254
|
+
admitted: boolean;
|
|
2255
|
+
}
|
|
2256
|
+
type OwnerRelayFrame = RelayAttach | RelayDetach | RelayFrame | RelayRoomEvent | RelayShapePoke | RelayShapeSubscribe | RelayShapeUnsubscribe;
|
|
2244
2257
|
interface SiblingStub {
|
|
2245
2258
|
fetch: (url: string, init?: RequestInit) => Promise<Response>;
|
|
2246
2259
|
}
|
|
@@ -2264,6 +2277,7 @@ interface RelayHost {
|
|
|
2264
2277
|
nextPokeId: () => string;
|
|
2265
2278
|
readAttachment: (ws: ShardSocketLike) => SocketAttachment;
|
|
2266
2279
|
recordShapePokeFanout: (iterated: number, delivered: number, elapsedMs: number) => void;
|
|
2280
|
+
relayRoomEvent: (event: RelayRoomEvent) => Promise<RelayRoomVerdict>;
|
|
2267
2281
|
resolveShape: (name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity) => ResolvedShape | undefined;
|
|
2268
2282
|
rlsMetadata: () => RlsPoliciesResult;
|
|
2269
2283
|
shardBinding: () => string | undefined;
|
|
@@ -2291,7 +2305,7 @@ declare abstract class RelayLink {
|
|
|
2291
2305
|
protected bindingName(): string | undefined;
|
|
2292
2306
|
protected postRelayMessage(targetName: string, message: OwnerRelayFrame): Promise<void>;
|
|
2293
2307
|
protected requestRelayMessage(targetName: string, message: OwnerRelayFrame): Promise<Response | undefined>;
|
|
2294
|
-
abstract forwardWhisper(topic: string, frame: string): Promise<void>;
|
|
2308
|
+
abstract forwardWhisper(topic: string, frame: string, exceptConnectionId?: string): Promise<void>;
|
|
2295
2309
|
abstract onFlush(changed: Set<string>, frameCursor: number): Promise<void>;
|
|
2296
2310
|
abstract seedRelayShape(ws: ShardSocketLike, subId: string, shape: ShapeSubscriptionQuery, identity: SubscriptionIdentity): Promise<"ok" | undefined | {
|
|
2297
2311
|
code: string;
|
|
@@ -2317,7 +2331,7 @@ declare class OwnerRelay extends RelayLink {
|
|
|
2317
2331
|
private recordedBinding;
|
|
2318
2332
|
private promotionState;
|
|
2319
2333
|
constructor(host: RelayHost, ownerKey: string);
|
|
2320
|
-
forwardWhisper(topic: string, frame: string): Promise<void>;
|
|
2334
|
+
forwardWhisper(topic: string, frame: string, exceptConnectionId?: string): Promise<void>;
|
|
2321
2335
|
onFlush(changed: Set<string>, frameCursor: number): Promise<void>;
|
|
2322
2336
|
seedRelayShape(): Promise<"ok" | undefined | {
|
|
2323
2337
|
code: string;
|
|
@@ -2357,6 +2371,7 @@ declare class RelayMember extends RelayLink {
|
|
|
2357
2371
|
private readonly shapeControl;
|
|
2358
2372
|
constructor(host: RelayHost, ownerKey: string, relayIndex: number);
|
|
2359
2373
|
forwardWhisper(topic: string, frame: string): Promise<void>;
|
|
2374
|
+
forwardRoomEvent(event: Omit<RelayRoomEvent, "relayIndex" | "type">): Promise<boolean>;
|
|
2360
2375
|
onFlush(): Promise<void>;
|
|
2361
2376
|
seedRelayShape(ws: ShardSocketLike, subId: string, shape: ShapeSubscriptionQuery, identity: SubscriptionIdentity): Promise<"ok" | {
|
|
2362
2377
|
code: string;
|
|
@@ -2602,4 +2617,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2602
2617
|
ordered: OrderedAfterWrites;
|
|
2603
2618
|
restart?: boolean;
|
|
2604
2619
|
}) => Promise<VectorBackfillProgress>;
|
|
2605
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2620
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -2198,6 +2198,7 @@ interface RelayDetach {
|
|
|
2198
2198
|
interface RelayFrame {
|
|
2199
2199
|
cursor?: number;
|
|
2200
2200
|
epoch?: string;
|
|
2201
|
+
exceptConnectionId?: string;
|
|
2201
2202
|
frame: string;
|
|
2202
2203
|
originRelay?: number;
|
|
2203
2204
|
topic: string;
|
|
@@ -2240,7 +2241,19 @@ interface RelayShapePoke {
|
|
|
2240
2241
|
targetConnectionId?: string;
|
|
2241
2242
|
type: "relay_shape_poke";
|
|
2242
2243
|
}
|
|
2243
|
-
|
|
2244
|
+
interface RelayRoomEvent {
|
|
2245
|
+
attachment: Pick<SocketAttachment, "connectionId" | "context" | "identity" | "ip" | "userId">;
|
|
2246
|
+
connectionId: string;
|
|
2247
|
+
data?: unknown;
|
|
2248
|
+
kind: "join" | "leave" | "message";
|
|
2249
|
+
relayIndex: number;
|
|
2250
|
+
topic: string;
|
|
2251
|
+
type: "relay_room_event";
|
|
2252
|
+
}
|
|
2253
|
+
interface RelayRoomVerdict {
|
|
2254
|
+
admitted: boolean;
|
|
2255
|
+
}
|
|
2256
|
+
type OwnerRelayFrame = RelayAttach | RelayDetach | RelayFrame | RelayRoomEvent | RelayShapePoke | RelayShapeSubscribe | RelayShapeUnsubscribe;
|
|
2244
2257
|
interface SiblingStub {
|
|
2245
2258
|
fetch: (url: string, init?: RequestInit) => Promise<Response>;
|
|
2246
2259
|
}
|
|
@@ -2264,6 +2277,7 @@ interface RelayHost {
|
|
|
2264
2277
|
nextPokeId: () => string;
|
|
2265
2278
|
readAttachment: (ws: ShardSocketLike) => SocketAttachment;
|
|
2266
2279
|
recordShapePokeFanout: (iterated: number, delivered: number, elapsedMs: number) => void;
|
|
2280
|
+
relayRoomEvent: (event: RelayRoomEvent) => Promise<RelayRoomVerdict>;
|
|
2267
2281
|
resolveShape: (name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity) => ResolvedShape | undefined;
|
|
2268
2282
|
rlsMetadata: () => RlsPoliciesResult;
|
|
2269
2283
|
shardBinding: () => string | undefined;
|
|
@@ -2291,7 +2305,7 @@ declare abstract class RelayLink {
|
|
|
2291
2305
|
protected bindingName(): string | undefined;
|
|
2292
2306
|
protected postRelayMessage(targetName: string, message: OwnerRelayFrame): Promise<void>;
|
|
2293
2307
|
protected requestRelayMessage(targetName: string, message: OwnerRelayFrame): Promise<Response | undefined>;
|
|
2294
|
-
abstract forwardWhisper(topic: string, frame: string): Promise<void>;
|
|
2308
|
+
abstract forwardWhisper(topic: string, frame: string, exceptConnectionId?: string): Promise<void>;
|
|
2295
2309
|
abstract onFlush(changed: Set<string>, frameCursor: number): Promise<void>;
|
|
2296
2310
|
abstract seedRelayShape(ws: ShardSocketLike, subId: string, shape: ShapeSubscriptionQuery, identity: SubscriptionIdentity): Promise<"ok" | undefined | {
|
|
2297
2311
|
code: string;
|
|
@@ -2317,7 +2331,7 @@ declare class OwnerRelay extends RelayLink {
|
|
|
2317
2331
|
private recordedBinding;
|
|
2318
2332
|
private promotionState;
|
|
2319
2333
|
constructor(host: RelayHost, ownerKey: string);
|
|
2320
|
-
forwardWhisper(topic: string, frame: string): Promise<void>;
|
|
2334
|
+
forwardWhisper(topic: string, frame: string, exceptConnectionId?: string): Promise<void>;
|
|
2321
2335
|
onFlush(changed: Set<string>, frameCursor: number): Promise<void>;
|
|
2322
2336
|
seedRelayShape(): Promise<"ok" | undefined | {
|
|
2323
2337
|
code: string;
|
|
@@ -2357,6 +2371,7 @@ declare class RelayMember extends RelayLink {
|
|
|
2357
2371
|
private readonly shapeControl;
|
|
2358
2372
|
constructor(host: RelayHost, ownerKey: string, relayIndex: number);
|
|
2359
2373
|
forwardWhisper(topic: string, frame: string): Promise<void>;
|
|
2374
|
+
forwardRoomEvent(event: Omit<RelayRoomEvent, "relayIndex" | "type">): Promise<boolean>;
|
|
2360
2375
|
onFlush(): Promise<void>;
|
|
2361
2376
|
seedRelayShape(ws: ShardSocketLike, subId: string, shape: ShapeSubscriptionQuery, identity: SubscriptionIdentity): Promise<"ok" | {
|
|
2362
2377
|
code: string;
|
|
@@ -2602,4 +2617,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2602
2617
|
ordered: OrderedAfterWrites;
|
|
2603
2618
|
restart?: boolean;
|
|
2604
2619
|
}) => Promise<VectorBackfillProgress>;
|
|
2605
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2620
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-yxw7vFf9.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as C,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-CuIP7PJ0.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CNXsYOSU.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-Dw4Azd33.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as se,minCdcReplayableSeq as ie,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-DsCz-DAV.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as he,readCdcArchivedThrough as xe,writeCdcArchivedThrough as Ee}from"./packem_shared/archiveCdcSegment-CIiYU1FU.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-8uVX84aT.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-DhYLePyV.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as we,writeGlobalShapeSnapshot as qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-DLSi_oBt.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as sr,probeScheduleOutbox as ir,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-CrTLPmFN.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as xr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Cr,writeShapePokeCursor as Ar,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-B1MIaRkE.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CmsAKy5V.mjs";import{SCAN_DEP as Mr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-B2GG3IJa.mjs";import{A as qr,a as vr,b as Kr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-DqU-17Fs.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as so,unionAll as io}from"./packem_shared/WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{appendStreamChunk as no,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-DF_Jrgpy.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Co}from"./packem_shared/DurableStreamRunner-Dzge_ywD.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Mo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-D2zEvCAa.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-D5MeQSk0.mjs";import{f as Ko,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-DzfEHonU.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as sa,ADMIN_FUNCTION_PREFIX as ia,DEFAULT_FANOUT_TOPIC_LIMIT as la,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as ha,listTables as xa,readTablePage as Ea,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Ca,selectMatchingIds as Aa,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-B0QCN3HM.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-BP1GSXQ0.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as ka,operatorFields as Ba,patchDependsOnRow as Ua,readPatchField as Ga,resolvePatch as wa}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as va,readBookmark as Ka}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Xa,applySelect as Ha,buildSeekBeforeWhere as Va,buildSeekWhere as za,decodeCursor as Qa,encodeCursor as Ya,equalityPinnedFields as ja,normalizeOrderKeys as Ja,nullsFirstOf as Za,nullsOrderSuffix as $a,softDeleteScope as et,tiebreakDirectionFor as rt,uniqueIndexFields as ot}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as tt,clearQueueMessages as st,isLossyBody as it,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-jEc6-2wm.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as ht,resolveRankPartition as xt,sortColumnName as Et}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Rt,reactiveCacheKey as Ct}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as gt,listReactorStates as _t,migrateReactorState as It,reactorNeedsRun as bt,readReactorState as Lt,writeReactorState as Dt}from"./packem_shared/REACTOR_STATE_TABLE-DHaBP_vb.mjs";import{UNVOUCHABLE_DEP as Ot,createReadFootprint as Ft,markUnvouchableReads as Mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Nt,indexKeysForRow as kt,keysTouchRanges as Bt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as Gt,whereFilter as wt,whereOfFilter as qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Kt,RELATED_DEPTH_DECAY as Wt,RELATED_MAX_DEPTH as Xt,RELATED_MAX_LIMIT as Ht,deriveRelationEdges as Vt,findRelated as zt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Yt,assertFlatPredicate as jt,assertShapeShardable as Jt,composeReadPredicate as Zt,containsRelationPredicate as $t,isRelationPredicate as es,resolveRelationPredicates as rs}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs";import{describeRelationWrites as as}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyOnDelete as ss,distinctValues as is,fanOutScalarCounts as ls,relationHooks as ns,resolveWith as ds,runRowValidators as cs}from"./packem_shared/applyOnDelete-BwxDC4lU.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ps,clampPromotionThresholds as Ss,nextPromotionState as us,relayCountFor as fs,shapeRoutingKey as hs}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Es,OwnerRelay as Ts,RelayMember as Rs,createRelayLink as Cs}from"./packem_shared/DEFAULT_MAX_RELAYS-ZRhh4qpX.mjs";import{createReplicaLink as gs,gateReplicaDispatch as _s,handleReplicaControl as Is}from"./packem_shared/createReplicaLink-Bd7jCjDt.mjs";import{buildReprojectionMigration as Ls,countLegacyRows as Ds,reprojectableFields as Ps,reprojectionTables as Os}from"./packem_shared/buildReprojectionMigration-DQV0q3w9.mjs";import{RLS_UNWRAP_SYMBOL as Ms,RlsRequiredError as ys,guardWriter as Ns}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Bs,readSchemaHistory as Us,readSchemaVersion as Gs,recordSchemaVersion as ws}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";import{serializeSqlValue as vs}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Ws,isDevEnvironment as Xs,readDeployInfo as Hs}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as zs}from"./packem_shared/buildShapeDiff-BHr3i1m6.mjs";import{ShapeDiffCache as Ys,createShapeDiffCache as js,globalShapeReadKey as Js}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as $s,diffGlobalMembership as ei,encodeRowsPatch as ri,projectColumns as oi}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ti}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as ii}from"./packem_shared/stubByName-C_P73AOx.mjs";import{runSocketPool as ni}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as ci,assertReadonly as mi,lintReadonlySql as pi,runReadonlySql as Si}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as fi,bigintSqlKey as hi,decodeBigintSqlKey as xi,decodeFloat64SqlKey as Ei,float64SqlKey as Ti}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Ci,subscriptionFrames as Ai,subscriptionListDeltas as gi,trySendFrame as _i}from"./packem_shared/awaitWsDrain-N-oR29RI.mjs";import{mergeChangedKeys as bi,recordChangedKeys as Li,writeTouchesMemo as Di}from"./packem_shared/mergeChangedKeys-CF2mjYuy.mjs";import{createSystemReader as Oi}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Mi}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ni,TransactionHeadroomTracker as ki}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as Ui,runTriggers as Gi}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as qi}from"./packem_shared/selectExpiredIds-B8PxwbIr.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ki,backfillVectorIndexes as Wi}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs";import{c as Hi,s as Vi}from"./packem_shared/where-sql-DO1vOrhc.mjs";import{RELATION_EXISTS_KEY as Qi}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as ji,reprojectionMigrationId as Ji}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as $i}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as rl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as al}from"./packem_shared/runShardMigrations-BeqUbznb.mjs";import{stableStringify as sl,stableWireKey as il}from"@lunora/wire";export{sa as ADMIN_FUNCTIONS,ia as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,qr as AGG_COUNT,vr as AGG_KEY,Kr as AGG_VALUE,D as AUDIT_LOG_TABLE,fi as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Xa as CURSOR_PREFIX,Mi as ConflictError,C as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,Es as DEFAULT_MAX_RELAYS,ps as DEFAULT_PROMOTION_THRESHOLDS,Ni as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,Eo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,Ke as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Ro as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,ci as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,Ts as OwnerRelay,tt as QUEUE_TABLE,mt as RANK_TIEBREAK,gt as REACTOR_STATE_TABLE,Kt as RELATED_DEFAULT_LIMIT,Wt as RELATED_DEPTH_DECAY,Xt as RELATED_MAX_DEPTH,Ht as RELATED_MAX_LIMIT,Qi as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ji as REPROJECTION_MIGRATION_PREFIX,Ms as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Rs as RelayMember,ys as RlsRequiredError,Mr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Bs as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Ys as ShapeDiffCache,ti as ShardRunner,ki as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,Ki as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,ss as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,mi as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,Ci as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Wi as backfillVectorIndexes,hi as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,$s as buildPokeFrames,Ls as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Ws as buildSettings,zs as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,Ss as clampPromotionThresholds,Da as clearCapturedMail,Fe as clearCompanionSignatures,Qe as clearMemoryTables,st as clearQueueMessages,h as coerceAggregateNumber,oe as compactCdcDocs,Hi as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Ds as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,Ft as createReadFootprint,Cs as createRelayLink,gs as createReplicaLink,js as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,Oi as createSystemReader,ae as cursorBelowRetainedFloor,Co as decideDurableAttach,xi as decodeBigintSqlKey,Qa as decodeCursor,Ei as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,xr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,as as describeRelationWrites,bo as diffExternalSource,ei as diffGlobalMembership,is as distinctValues,x as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,ri as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,ls as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,Ti as float64SqlKey,E as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,_s as gateReplicaDispatch,Vr as geoTableName,Js as globalShapeReadKey,zo as groupUnmappedRows,Ns as guardWriter,Is as handleReplicaControl,Ui as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Xs as isDevEnvironment,zr as isFtsAvailable,$i as isInternalTableName,it as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,es as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,ha as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,pi as lintReadonlySql,_t as listReactorStates,xa as listTables,Mt as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,bi as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,se as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,It as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,ie as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,us as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ja as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,Za as nullsFirstOf,$a as nullsOrderSuffix,Ba as operatorFields,ao as param,sr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,ir as probeScheduleOutbox,oi as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,rl as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,ht as rankTableName,Ct as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,he as readArchivedCdcChanges,F as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,xe as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Hs as readDeployInfo,lr as readDueScheduleOutbox,No as readExternalSourceBaseline,we as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,Ga as readPatchField,lt as readQueueMessageById,nt as readQueueMessages,Lt as readReactorState,Us as readSchemaHistory,Gs as readSchemaVersion,Sr as readSearchBackfillState,Cr as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,Ea as readTablePage,Fa as recordCapturedMail,Li as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,ws as recordSchemaVersion,Ca as recordShapeProbePass,ns as relationHooks,fs as relayCountFor,to as renderSql,Ps as reprojectableFields,Ji as reprojectionMigrationId,Os as reprojectionTables,wa as resolvePatch,xt as resolveRankPartition,$e as resolveRankSeekTuple,rs as resolveRelationPredicates,ds as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,Si as runReadonlySql,cs as runRowValidators,al as runShardMigrations,ni as runSocketPool,Gr as runSql,Gi as runTriggers,qi as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Aa as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,vs as serializeSqlValue,Vi as serverInList,hs as shapeRoutingKey,et as softDeleteScope,Et as sortColumnName,so as sqliteInList,sl as stableStringify,il as stableWireKey,G as stripReservedPatchFields,ii as stubByName,Ai as subscriptionFrames,gi as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,rt as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,ho as trimStreamRuns,eo as tryRowToDocument,_i as trySendFrame,io as unionAll,ot as uniqueIndexFields,l as validateImportRow,wt as whereFilter,qt as whereOfFilter,Ee as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Ar as writeShapePokeCursor,gr as writeShapePokeCursors,Di as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-yxw7vFf9.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as C,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-CuIP7PJ0.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CNXsYOSU.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-Dw4Azd33.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as se,minCdcReplayableSeq as ie,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-DsCz-DAV.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as he,readCdcArchivedThrough as xe,writeCdcArchivedThrough as Ee}from"./packem_shared/archiveCdcSegment-CIiYU1FU.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-8uVX84aT.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-DhYLePyV.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as we,writeGlobalShapeSnapshot as qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-DLSi_oBt.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as sr,probeScheduleOutbox as ir,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-CrTLPmFN.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as xr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Cr,writeShapePokeCursor as Ar,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-B1MIaRkE.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CmsAKy5V.mjs";import{SCAN_DEP as Mr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-B2GG3IJa.mjs";import{A as qr,a as vr,b as Kr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-DqU-17Fs.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as so,unionAll as io}from"./packem_shared/WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{appendStreamChunk as no,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-DF_Jrgpy.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Co}from"./packem_shared/DurableStreamRunner-Dzge_ywD.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Mo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-D2zEvCAa.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-D5MeQSk0.mjs";import{f as Ko,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-DzfEHonU.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as sa,ADMIN_FUNCTION_PREFIX as ia,DEFAULT_FANOUT_TOPIC_LIMIT as la,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as ha,listTables as xa,readTablePage as Ea,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Ca,selectMatchingIds as Aa,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-B0QCN3HM.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-BP1GSXQ0.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as ka,operatorFields as Ba,patchDependsOnRow as Ua,readPatchField as Ga,resolvePatch as wa}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as va,readBookmark as Ka}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Xa,applySelect as Ha,buildSeekBeforeWhere as Va,buildSeekWhere as za,decodeCursor as Qa,encodeCursor as Ya,equalityPinnedFields as ja,normalizeOrderKeys as Ja,nullsFirstOf as Za,nullsOrderSuffix as $a,softDeleteScope as et,tiebreakDirectionFor as rt,uniqueIndexFields as ot}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as tt,clearQueueMessages as st,isLossyBody as it,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-jEc6-2wm.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as ht,resolveRankPartition as xt,sortColumnName as Et}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Rt,reactiveCacheKey as Ct}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as gt,listReactorStates as _t,migrateReactorState as It,reactorNeedsRun as bt,readReactorState as Lt,writeReactorState as Dt}from"./packem_shared/REACTOR_STATE_TABLE-DHaBP_vb.mjs";import{UNVOUCHABLE_DEP as Ot,createReadFootprint as Ft,markUnvouchableReads as Mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Nt,indexKeysForRow as kt,keysTouchRanges as Bt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as Gt,whereFilter as wt,whereOfFilter as qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Kt,RELATED_DEPTH_DECAY as Wt,RELATED_MAX_DEPTH as Xt,RELATED_MAX_LIMIT as Ht,deriveRelationEdges as Vt,findRelated as zt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Yt,assertFlatPredicate as jt,assertShapeShardable as Jt,composeReadPredicate as Zt,containsRelationPredicate as $t,isRelationPredicate as es,resolveRelationPredicates as rs}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs";import{describeRelationWrites as as}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyOnDelete as ss,distinctValues as is,fanOutScalarCounts as ls,relationHooks as ns,resolveWith as ds,runRowValidators as cs}from"./packem_shared/applyOnDelete-BwxDC4lU.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ps,clampPromotionThresholds as Ss,nextPromotionState as us,relayCountFor as fs,shapeRoutingKey as hs}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Es,OwnerRelay as Ts,RelayMember as Rs,createRelayLink as Cs}from"./packem_shared/DEFAULT_MAX_RELAYS-B05iDlGI.mjs";import{createReplicaLink as gs,gateReplicaDispatch as _s,handleReplicaControl as Is}from"./packem_shared/createReplicaLink-Bd7jCjDt.mjs";import{buildReprojectionMigration as Ls,countLegacyRows as Ds,reprojectableFields as Ps,reprojectionTables as Os}from"./packem_shared/buildReprojectionMigration-DQV0q3w9.mjs";import{RLS_UNWRAP_SYMBOL as Ms,RlsRequiredError as ys,guardWriter as Ns}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Bs,readSchemaHistory as Us,readSchemaVersion as Gs,recordSchemaVersion as ws}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";import{serializeSqlValue as vs}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Ws,isDevEnvironment as Xs,readDeployInfo as Hs}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as zs}from"./packem_shared/buildShapeDiff-BHr3i1m6.mjs";import{ShapeDiffCache as Ys,createShapeDiffCache as js,globalShapeReadKey as Js}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as $s,diffGlobalMembership as ei,encodeRowsPatch as ri,projectColumns as oi}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ti}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as ii}from"./packem_shared/stubByName-C_P73AOx.mjs";import{runSocketPool as ni}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as ci,assertReadonly as mi,lintReadonlySql as pi,runReadonlySql as Si}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as fi,bigintSqlKey as hi,decodeBigintSqlKey as xi,decodeFloat64SqlKey as Ei,float64SqlKey as Ti}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Ci,subscriptionFrames as Ai,subscriptionListDeltas as gi,trySendFrame as _i}from"./packem_shared/awaitWsDrain-N-oR29RI.mjs";import{mergeChangedKeys as bi,recordChangedKeys as Li,writeTouchesMemo as Di}from"./packem_shared/mergeChangedKeys-CF2mjYuy.mjs";import{createSystemReader as Oi}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Mi}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ni,TransactionHeadroomTracker as ki}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as Ui,runTriggers as Gi}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as qi}from"./packem_shared/selectExpiredIds-B8PxwbIr.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ki,backfillVectorIndexes as Wi}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs";import{c as Hi,s as Vi}from"./packem_shared/where-sql-DO1vOrhc.mjs";import{RELATION_EXISTS_KEY as Qi}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as ji,reprojectionMigrationId as Ji}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as $i}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as rl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as al}from"./packem_shared/runShardMigrations-BeqUbznb.mjs";import{stableStringify as sl,stableWireKey as il}from"@lunora/wire";export{sa as ADMIN_FUNCTIONS,ia as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,qr as AGG_COUNT,vr as AGG_KEY,Kr as AGG_VALUE,D as AUDIT_LOG_TABLE,fi as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Xa as CURSOR_PREFIX,Mi as ConflictError,C as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,Es as DEFAULT_MAX_RELAYS,ps as DEFAULT_PROMOTION_THRESHOLDS,Ni as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,Eo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,Ke as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Ro as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,ci as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,Ts as OwnerRelay,tt as QUEUE_TABLE,mt as RANK_TIEBREAK,gt as REACTOR_STATE_TABLE,Kt as RELATED_DEFAULT_LIMIT,Wt as RELATED_DEPTH_DECAY,Xt as RELATED_MAX_DEPTH,Ht as RELATED_MAX_LIMIT,Qi as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ji as REPROJECTION_MIGRATION_PREFIX,Ms as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Rs as RelayMember,ys as RlsRequiredError,Mr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Bs as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Ys as ShapeDiffCache,ti as ShardRunner,ki as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,Ki as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,ss as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,mi as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,Ci as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Wi as backfillVectorIndexes,hi as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,$s as buildPokeFrames,Ls as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Ws as buildSettings,zs as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,Ss as clampPromotionThresholds,Da as clearCapturedMail,Fe as clearCompanionSignatures,Qe as clearMemoryTables,st as clearQueueMessages,h as coerceAggregateNumber,oe as compactCdcDocs,Hi as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Ds as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,Ft as createReadFootprint,Cs as createRelayLink,gs as createReplicaLink,js as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,Oi as createSystemReader,ae as cursorBelowRetainedFloor,Co as decideDurableAttach,xi as decodeBigintSqlKey,Qa as decodeCursor,Ei as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,xr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,as as describeRelationWrites,bo as diffExternalSource,ei as diffGlobalMembership,is as distinctValues,x as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,ri as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,ls as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,Ti as float64SqlKey,E as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,_s as gateReplicaDispatch,Vr as geoTableName,Js as globalShapeReadKey,zo as groupUnmappedRows,Ns as guardWriter,Is as handleReplicaControl,Ui as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Xs as isDevEnvironment,zr as isFtsAvailable,$i as isInternalTableName,it as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,es as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,ha as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,pi as lintReadonlySql,_t as listReactorStates,xa as listTables,Mt as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,bi as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,se as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,It as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,ie as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,us as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ja as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,Za as nullsFirstOf,$a as nullsOrderSuffix,Ba as operatorFields,ao as param,sr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,ir as probeScheduleOutbox,oi as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,rl as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,ht as rankTableName,Ct as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,he as readArchivedCdcChanges,F as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,xe as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Hs as readDeployInfo,lr as readDueScheduleOutbox,No as readExternalSourceBaseline,we as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,Ga as readPatchField,lt as readQueueMessageById,nt as readQueueMessages,Lt as readReactorState,Us as readSchemaHistory,Gs as readSchemaVersion,Sr as readSearchBackfillState,Cr as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,Ea as readTablePage,Fa as recordCapturedMail,Li as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,ws as recordSchemaVersion,Ca as recordShapeProbePass,ns as relationHooks,fs as relayCountFor,to as renderSql,Ps as reprojectableFields,Ji as reprojectionMigrationId,Os as reprojectionTables,wa as resolvePatch,xt as resolveRankPartition,$e as resolveRankSeekTuple,rs as resolveRelationPredicates,ds as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,Si as runReadonlySql,cs as runRowValidators,al as runShardMigrations,ni as runSocketPool,Gr as runSql,Gi as runTriggers,qi as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Aa as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,vs as serializeSqlValue,Vi as serverInList,hs as shapeRoutingKey,et as softDeleteScope,Et as sortColumnName,so as sqliteInList,sl as stableStringify,il as stableWireKey,G as stripReservedPatchFields,ii as stubByName,Ai as subscriptionFrames,gi as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,rt as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,ho as trimStreamRuns,eo as tryRowToDocument,_i as trySendFrame,io as unionAll,ot as uniqueIndexFields,l as validateImportRow,wt as whereFilter,qt as whereOfFilter,Ee as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Ar as writeShapePokeCursor,gr as writeShapePokeCursors,Di as writeTouchesMemo};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{toErrorBody as D,LunoraError as F}from"@lunora/errors";import{encodeWire as O,stableWireKey as R,decodeWire as v}from"@lunora/wire";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-B2GG3IJa.mjs";import{WORKERD_SQLITE_LIMITS as U}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{d as K,w,a as A,m as $,r as W,b as Y,c as B}from"./ctx-db-relay-shapes-CPwELrMf.mjs";import{envPositiveInt as _}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as b,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as H,shapeRoutingKey as g,relayProxyKey as M,parseRelayName as q,clampPromotionThresholds as j}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{encodeRowsPatch as X,buildPokeFrames as P}from"./buildPokeFrames-WR-hp0mX.mjs";import{verifySiblingBody as z,RELAY_SIGNATURE_HEADER as x,siblingStub as G,siblingSecretOf as J,signSiblingBody as V}from"./stubByName-C_P73AOx.mjs";import{awaitWsDrain as Q,trySendFrame as L}from"./awaitWsDrain-N-oR29RI.mjs";const f="__lunora_relay_memos",Z=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
|
|
2
|
+
connection_id TEXT NOT NULL,
|
|
3
|
+
sub_id TEXT NOT NULL,
|
|
4
|
+
cursor INTEGER NOT NULL,
|
|
5
|
+
epoch TEXT,
|
|
6
|
+
PRIMARY KEY (connection_id, sub_id)
|
|
7
|
+
)`)},ee=i=>{const e=m(i,y`SELECT connection_id, sub_id, cursor, epoch FROM ${y.identifier(f)}`).toArray(),s=new Map;for(const t of e){let o=s.get(t.connection_id);o===void 0&&(o=new Map,s.set(t.connection_id,o)),o.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},te=4,C=(i,e)=>{const s=Math.floor(U.boundParams/te);for(let t=0;t<e.length;t+=s){const o=e.slice(t,t+s),r=y.join(o.map(n=>y`(${n.connectionId}, ${n.subId}, ${n.cursor}, ${n.epoch??null})`),y`, `);m(i,y`INSERT INTO ${y.identifier(f)} (connection_id, sub_id, cursor, epoch) VALUES ${r}
|
|
8
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},se=(i,e,s)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e} AND sub_id = ${s}`)},oe=(i,e)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e}`)},re=i=>{m(i,y`DELETE FROM ${y.identifier(f)}`)},ne=2,ae=8,I={},ie=i=>{throw new F("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},ce=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,N=i=>Response.json(i,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class k{constructor(e,s){this.host=e,this.roleId=s}host;roleId;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await z(this.host.env(),e.headers.get(x),s))return new Response("forbidden",{status:403});let t;try{t=JSON.parse(s)}catch{return new Response("bad request",{status:400})}switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex),S();case"relay_detach":return this.onDetach(t.relayIndex),S();case"relay_frame":{const{exceptConnectionId:o}=t,r=o===void 0?void 0:this.host.getWebSockets().find(n=>this.host.readAttachment(n).connectionId===o);return this.host.deliverWhisperLocal(t.topic,t.frame,r),await this.onWhisperFrame(t),S()}case"relay_room_event":return N(await this.host.relayRoomEvent(t));case"relay_shape_poke":{const o=this.host.getWebSockets().length,r=Date.now(),{delivered:n,matched:a}=this.onShapePoke({...t,args:v(t.args)});return this.host.recordShapePokeFanout(o,n,Date.now()-r),n<a?Response.json({delivered:n,matched:a},{status:503}):S()}case"relay_shape_subscribe":return N(this.onShapeSubscribe({...t,args:v(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),S();default:return ie(t)}}maxRelays(){return _(this.host.env(),"LUNORA_MAX_RELAYS",ae)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return G(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const o=JSON.stringify(s),r={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=J(this.host.env());n!==void 0&&(r[x]=await V(n,o));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:o,headers:r,method:"POST"})}catch{return}}}class he extends k{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s,t){if(!this.canAddressSiblings())return;const o=this.ownerRelaySet();o.size!==0&&await Promise.all([...o].map(r=>this.postRelayMessage(b(this.roleId.ownerKey,r),{exceptConnectionId:t,frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=_(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),t=_(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=H(this.promotionState,e,j(s,t)),this.promotionState==="owned")return 0;const o=_(this.host.env(),"LUNORA_RELAY_FAN",ne);return Math.min(this.maxRelays(),Math.max(1,o))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const o of[...e.values(),...s.values()])t=t===void 0?o.cursor:Math.min(t,o.cursor);return t}isShapeRelayUniform(e,s){const t=g(e,s),o=this.shapeUniformCache.get(t);if(o!==void 0)return o;const r=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,r),r}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:M(e.relayIndex,e.connectionId,e.subId);for(const[o,r]of s)r.relayIndex!==e.relayIndex||r.connectionId!==e.connectionId||(t===void 0||o===t)&&s.delete(o);K(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.postRelayMessage(b(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}buildShapePoke(e,s,t,o,r){let n;try{n=this.host.resolveShape(e.name,e.args,s)}catch{return}if(n===void 0||n.global===!0||!t.has(n.table))return;const a=e,h=a.cursor,c=this.host.buildShapeDiff(n,h,o);if(c.length!==0)return a.cursor=o,w(this.host.sql(),a.key,o),{args:O(e.args),checkpoint:o,epoch:r,fromCursor:h,name:e.name,rowsPatch:X(c),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:o}=this.relayShapes();if(o.size===0)return;const r=this.host.currentCdcEpoch(),n=[];for(const a of o.values()){const h=this.buildShapePoke(a,I,e,s,r);h&&n.push(this.multicastToRelays(t,h,a))}await Promise.all(n)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async r=>(await this.requestRelayMessage(b(this.roleId.ownerKey,r),s))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const o=this.host.currentCdcEpoch(),r=[];for(const n of t.values()){const a=this.buildShapePoke(n,n.identity,e,s,o);a&&r.push(this.proxyToRelay(a,n))}await Promise.all(r)}async proxyToRelay(e,s){(await this.requestRelayMessage(b(this.roleId.ownerKey,s.relayIndex),{...e,targetConnectionId:s.connectionId}))?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(l){const{body:p}=D(l,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:o,cursor:r,epoch:n,reset:a,rowsPatch:h}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let c=r;const{cohort:d,proxies:E}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const l=g(e.name,e.args);let p=d.get(l);p===void 0&&(p={args:e.args,cursor:r,key:l,name:e.name},d.set(l,p),A(this.host.sql(),p)),c=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const l=M(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:r,identity:s,key:l,name:e.name,relayIndex:e.relayIndex};E.set(l,p),A(this.host.sql(),p)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const u=P([{reset:a,rowsPatch:h,shapeId:e.subId}],{baseCheckpoint:o,checkpoint:c,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:c,epoch:n,frames:u}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),$(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const s=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=s[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of W(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,w(this.host.sql(),t.key,s))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e);const{cohort:t,proxies:o}=this.relayShapes();for(const[r,n]of o)n.relayIndex===e&&o.delete(r);Y(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),B(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,I)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(c=>c.on==="read"&&c.table===t.table)||this.tableHasAnyMask(t.table))return!1;const o=R(t.effectiveWhere),r=R(t.columns);let n=!1;const a=c=>{const d={groups:[`grp_${c}`],roles:[c],sub:`__lunora_probe_${c}__`};return{identity:new Proxy(d,{get:(u,l)=>typeof l=="symbol"||l in u?Reflect.get(u,l):`${c}:${l}`,getOwnPropertyDescriptor:(u,l)=>(n=!0,Reflect.getOwnPropertyDescriptor(u,l)),has:(u,l)=>typeof l=="symbol"?Reflect.has(u,l):!0,ownKeys:u=>(n=!0,Reflect.ownKeys(u))}),ip:`__lunora_probe_${c}__`,userId:`__lunora_probe_${c}__`}};return[I,a("a"),a("b")].every(c=>{let d;try{d=this.host.resolveShape(e,s,c)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&R(d.effectiveWhere)===o&&R(d.columns)===r})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class le extends k{relayAnnounced=!1;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}async forwardRoomEvent(e){const s=await this.requestRelayMessage(this.roleId.ownerKey,{...e,relayIndex:this.roleId.relayIndex,type:"relay_room_event"});if(!s?.ok)return!1;try{return(await s.json()).admitted}catch{return!1}}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,o){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:r}=this.host.readAttachment(e),n={args:O(t.args??{}),connectionId:r,identity:o.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:o.userId},a=await this.queueShapeControl(r,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,n)));if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let h;try{h=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(h.error!==void 0)return h.error;if(h.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await Q(e);for(const c of h.frames)L(e,c);return this.recordRelayShapeMemo(e,s,h.cursor??0,h.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.host.getWebSockets().some(s=>s!==e)||(this.relayMemos().clear(),re(this.host.sql()),this.canAddressSiblings()&&(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),o={},r=()=>{this.shapeControl.get(e)===o.chain&&this.shapeControl.delete(e)},n=t.then(r,r);return o.chain=n,this.shapeControl.set(e,n),t}relayMemos(){return this.relayMemoCache===void 0&&(Z(this.host.sql()),this.relayMemoCache=ee(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,o){const{connectionId:r}=this.host.readAttachment(e);r!==void 0&&(this.connectionMemos(r).set(s,{cursor:t,epoch:o}),C(this.host.sql(),[{connectionId:r,cursor:t,epoch:o,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),oe(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),se(this.host.sql(),e,s)}deliverShapePoke(e){const s=g(e.name,e.args),t=[];let o=0,r=0;for(const n of this.host.getWebSockets()){const{connectionId:a,shapes:h}=this.host.readAttachment(n);if(h===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const c=this.pokeSocketShapes(n,h,this.connectionMemos(a),e,s);r+=c.matched.length,o+=c.sent;for(const d of c.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return C(this.host.sql(),t),{delivered:o,matched:r}}pokeSocketShapes(e,s,t,o,r){const n=[];let a=0;for(const[h,c]of Object.entries(s)){const d=t.get(h);if(g(c.name,c.args)!==r||!ce(d,o))continue;const u=P([{baseCheckpoint:d?.cursor,rowsPatch:o.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:o.checkpoint,epoch:o.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(l=>L(e,l)).every(Boolean);t.set(h,{cursor:o.checkpoint,epoch:o.epoch}),n.push(h),u&&(a+=1)}return{matched:n,sent:a}}}const Ee=i=>{const e=i.doName();if(e===void 0)return;const s=q(e);return s===void 0?new he(i,e):new le(i,s.ownerKey,s.relayIndex)};export{ae as DEFAULT_MAX_RELAYS,he as OwnerRelay,le as RelayMember,Ee as createRelayLink};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as _}from"./NotUniqueError-CNXsYOSU.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-
|
|
1
|
+
import{createShardCtxDb as _}from"./NotUniqueError-CNXsYOSU.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-B05iDlGI.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-BeqUbznb.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.133",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.66",
|
|
53
53
|
"@lunora/wire": "1.0.0-alpha.1",
|
|
54
54
|
"drizzle-orm": "^0.45.3"
|
|
55
55
|
},
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{encodeWire as N,stableWireKey as R,decodeWire as v}from"@lunora/wire";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-B2GG3IJa.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{d as U,w,a as A,m as $,r as K,b as Y,c as W}from"./ctx-db-relay-shapes-CPwELrMf.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as b,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as _,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-WR-hp0mX.mjs";import{verifySiblingBody as j,RELAY_SIGNATURE_HEADER as L,siblingStub as z,siblingSecretOf as G,signSiblingBody as J}from"./stubByName-C_P73AOx.mjs";import{awaitWsDrain as V,trySendFrame as x}from"./awaitWsDrain-N-oR29RI.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
|
|
2
|
-
connection_id TEXT NOT NULL,
|
|
3
|
-
sub_id TEXT NOT NULL,
|
|
4
|
-
cursor INTEGER NOT NULL,
|
|
5
|
-
epoch TEXT,
|
|
6
|
-
PRIMARY KEY (connection_id, sub_id)
|
|
7
|
-
)`)},Z=i=>{const e=m(i,y`SELECT connection_id, sub_id, cursor, epoch FROM ${y.identifier(f)}`).toArray(),s=new Map;for(const t of e){let o=s.get(t.connection_id);o===void 0&&(o=new Map,s.set(t.connection_id,o)),o.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},ee=4,C=(i,e)=>{const s=Math.floor(F.boundParams/ee);for(let t=0;t<e.length;t+=s){const o=e.slice(t,t+s),n=y.join(o.map(r=>y`(${r.connectionId}, ${r.subId}, ${r.cursor}, ${r.epoch??null})`),y`, `);m(i,y`INSERT INTO ${y.identifier(f)} (connection_id, sub_id, cursor, epoch) VALUES ${n}
|
|
8
|
-
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},te=(i,e,s)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e} AND sub_id = ${s}`)},se=(i,e)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e}`)},oe=i=>{m(i,y`DELETE FROM ${y.identifier(f)}`)},re=2,ne=8,I={},ae=i=>{throw new D("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},ie=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,ce=i=>Response.json(i,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class P{constructor(e,s){this.host=e,this.roleId=s}host;roleId;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await j(this.host.env(),e.headers.get(L),s))return new Response("forbidden",{status:403});let t;try{t=JSON.parse(s)}catch{return new Response("bad request",{status:400})}switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex),S();case"relay_detach":return this.onDetach(t.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(t.topic,t.frame,void 0),await this.onWhisperFrame(t),S();case"relay_shape_poke":{const o=this.host.getWebSockets().length,n=Date.now(),{delivered:r,matched:a}=this.onShapePoke({...t,args:v(t.args)});return this.host.recordShapePokeFanout(o,r,Date.now()-n),r<a?Response.json({delivered:r,matched:a},{status:503}):S()}case"relay_shape_subscribe":return ce(this.onShapeSubscribe({...t,args:v(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),S();default:return ae(t)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",ne)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return z(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const o=JSON.stringify(s),n={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},r=G(this.host.env());r!==void 0&&(n[L]=await J(r,o));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:o,headers:n,method:"POST"})}catch{return}}}class he extends P{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s){if(!this.canAddressSiblings())return;const t=this.ownerRelaySet();t.size!==0&&await Promise.all([...t].map(o=>this.postRelayMessage(b(this.roleId.ownerKey,o),{frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),t=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=B(this.promotionState,e,q(s,t)),this.promotionState==="owned")return 0;const o=g(this.host.env(),"LUNORA_RELAY_FAN",re);return Math.min(this.maxRelays(),Math.max(1,o))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const o of[...e.values(),...s.values()])t=t===void 0?o.cursor:Math.min(t,o.cursor);return t}isShapeRelayUniform(e,s){const t=_(e,s),o=this.shapeUniformCache.get(t);if(o!==void 0)return o;const n=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,n),n}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:M(e.relayIndex,e.connectionId,e.subId);for(const[o,n]of s)n.relayIndex!==e.relayIndex||n.connectionId!==e.connectionId||(t===void 0||o===t)&&s.delete(o);U(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.postRelayMessage(b(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}buildShapePoke(e,s,t,o,n){let r;try{r=this.host.resolveShape(e.name,e.args,s)}catch{return}if(r===void 0||r.global===!0||!t.has(r.table))return;const a=e,h=a.cursor,c=this.host.buildShapeDiff(r,h,o);if(c.length!==0)return a.cursor=o,w(this.host.sql(),a.key,o),{args:N(e.args),checkpoint:o,epoch:n,fromCursor:h,name:e.name,rowsPatch:X(c),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:o}=this.relayShapes();if(o.size===0)return;const n=this.host.currentCdcEpoch(),r=[];for(const a of o.values()){const h=this.buildShapePoke(a,I,e,s,n);h&&r.push(this.multicastToRelays(t,h,a))}await Promise.all(r)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async n=>(await this.requestRelayMessage(b(this.roleId.ownerKey,n),s))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const r of t.values()){const a=this.buildShapePoke(r,r.identity,e,s,o);a&&n.push(this.proxyToRelay(a,r))}await Promise.all(n)}async proxyToRelay(e,s){(await this.requestRelayMessage(b(this.roleId.ownerKey,s.relayIndex),{...e,targetConnectionId:s.connectionId}))?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(l){const{body:p}=k(l,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:o,cursor:n,epoch:r,reset:a,rowsPatch:h}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let c=n;const{cohort:d,proxies:E}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const l=_(e.name,e.args);let p=d.get(l);p===void 0&&(p={args:e.args,cursor:n,key:l,name:e.name},d.set(l,p),A(this.host.sql(),p)),c=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const l=M(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:n,identity:s,key:l,name:e.name,relayIndex:e.relayIndex};E.set(l,p),A(this.host.sql(),p)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const u=O([{reset:a,rowsPatch:h,shapeId:e.subId}],{baseCheckpoint:o,checkpoint:c,epoch:r,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:c,epoch:r,frames:u}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),$(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const s=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=s[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of K(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,w(this.host.sql(),t.key,s))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e);const{cohort:t,proxies:o}=this.relayShapes();for(const[n,r]of o)r.relayIndex===e&&o.delete(n);Y(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),W(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,I)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(c=>c.on==="read"&&c.table===t.table)||this.tableHasAnyMask(t.table))return!1;const o=R(t.effectiveWhere),n=R(t.columns);let r=!1;const a=c=>{const d={groups:[`grp_${c}`],roles:[c],sub:`__lunora_probe_${c}__`};return{identity:new Proxy(d,{get:(u,l)=>typeof l=="symbol"||l in u?Reflect.get(u,l):`${c}:${l}`,getOwnPropertyDescriptor:(u,l)=>(r=!0,Reflect.getOwnPropertyDescriptor(u,l)),has:(u,l)=>typeof l=="symbol"?Reflect.has(u,l):!0,ownKeys:u=>(r=!0,Reflect.ownKeys(u))}),ip:`__lunora_probe_${c}__`,userId:`__lunora_probe_${c}__`}};return[I,a("a"),a("b")].every(c=>{let d;try{d=this.host.resolveShape(e,s,c)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&R(d.effectiveWhere)===o&&R(d.columns)===n})&&!r}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class le extends P{relayAnnounced=!1;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,o){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:n}=this.host.readAttachment(e),r={args:N(t.args??{}),connectionId:n,identity:o.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:o.userId},a=await this.queueShapeControl(n,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,r)));if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let h;try{h=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(h.error!==void 0)return h.error;if(h.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await V(e);for(const c of h.frames)x(e,c);return this.recordRelayShapeMemo(e,s,h.cursor??0,h.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.host.getWebSockets().some(s=>s!==e)||(this.relayMemos().clear(),oe(this.host.sql()),this.canAddressSiblings()&&(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),o={},n=()=>{this.shapeControl.get(e)===o.chain&&this.shapeControl.delete(e)},r=t.then(n,n);return o.chain=r,this.shapeControl.set(e,r),t}relayMemos(){return this.relayMemoCache===void 0&&(Q(this.host.sql()),this.relayMemoCache=Z(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,o){const{connectionId:n}=this.host.readAttachment(e);n!==void 0&&(this.connectionMemos(n).set(s,{cursor:t,epoch:o}),C(this.host.sql(),[{connectionId:n,cursor:t,epoch:o,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),se(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),te(this.host.sql(),e,s)}deliverShapePoke(e){const s=_(e.name,e.args),t=[];let o=0,n=0;for(const r of this.host.getWebSockets()){const{connectionId:a,shapes:h}=this.host.readAttachment(r);if(h===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const c=this.pokeSocketShapes(r,h,this.connectionMemos(a),e,s);n+=c.matched.length,o+=c.sent;for(const d of c.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return C(this.host.sql(),t),{delivered:o,matched:n}}pokeSocketShapes(e,s,t,o,n){const r=[];let a=0;for(const[h,c]of Object.entries(s)){const d=t.get(h);if(_(c.name,c.args)!==n||!ie(d,o))continue;const u=O([{baseCheckpoint:d?.cursor,rowsPatch:o.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:o.checkpoint,epoch:o.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(l=>x(e,l)).every(Boolean);t.set(h,{cursor:o.checkpoint,epoch:o.epoch}),r.push(h),u&&(a+=1)}return{matched:r,sent:a}}}const Ee=i=>{const e=i.doName();if(e===void 0)return;const s=H(e);return s===void 0?new he(i,e):new le(i,s.ownerKey,s.relayIndex)};export{ne as DEFAULT_MAX_RELAYS,he as OwnerRelay,le as RelayMember,Ee as createRelayLink};
|