@lunora/shard-engine 1.0.0-alpha.151 → 1.0.0-alpha.153
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 +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-Cug8Z4jD.mjs → ADMIN_FUNCTIONS-CPXCHyOg.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-B5swBl_q.mjs +8 -0
- package/dist/packem_shared/{defineEngineContractSuite-BiXyk2gE.mjs → defineEngineContractSuite-BOxz-Izu.mjs} +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-CrsP5Ldh.mjs +0 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BOxz-Izu.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -143,6 +143,7 @@ interface SubscriptionEnvelope {
|
|
|
143
143
|
sinceCheckpoint?: number;
|
|
144
144
|
sinceChunk?: number;
|
|
145
145
|
sinceEpoch?: string;
|
|
146
|
+
token?: string;
|
|
146
147
|
topic?: string;
|
|
147
148
|
type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
|
|
148
149
|
}
|
|
@@ -153,6 +154,7 @@ interface RpcRequest {
|
|
|
153
154
|
interface SocketAttachment {
|
|
154
155
|
admin?: boolean;
|
|
155
156
|
adminBinding?: string;
|
|
157
|
+
authenticated?: boolean;
|
|
156
158
|
clientId?: string;
|
|
157
159
|
connected?: boolean;
|
|
158
160
|
connectionId?: string;
|
|
@@ -166,6 +168,7 @@ interface SocketAttachment {
|
|
|
166
168
|
ip?: string;
|
|
167
169
|
liveGrants?: Record<string, string>;
|
|
168
170
|
pageDeltas?: boolean;
|
|
171
|
+
pendingSince?: number;
|
|
169
172
|
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
170
173
|
socketFunction?: string;
|
|
171
174
|
socketPath?: string;
|
|
@@ -1845,6 +1848,7 @@ interface StorageReferenceResult {
|
|
|
1845
1848
|
declare const findStorageReferences: (sql: SqlExec, storageColumns: Record<string, string[]>, keys: string[]) => StorageReferenceResult;
|
|
1846
1849
|
interface SocketAttachmentLike {
|
|
1847
1850
|
admin?: boolean;
|
|
1851
|
+
authenticated?: boolean;
|
|
1848
1852
|
subs?: Record<string, SubscriptionInfo>;
|
|
1849
1853
|
}
|
|
1850
1854
|
declare const summarizeSubscriptions: (attachments: SocketAttachmentLike[]) => SubscriptionsResult;
|
|
@@ -1883,6 +1887,7 @@ interface FanoutMetricsResult {
|
|
|
1883
1887
|
whisper: FanoutPathCounters;
|
|
1884
1888
|
}
|
|
1885
1889
|
interface FanoutAttachmentLike {
|
|
1890
|
+
authenticated?: boolean;
|
|
1886
1891
|
shapes?: Record<string, {
|
|
1887
1892
|
name?: string;
|
|
1888
1893
|
}>;
|
|
@@ -2345,6 +2350,7 @@ declare abstract class RelayLink {
|
|
|
2345
2350
|
handleControl(request: Request): Promise<Response>;
|
|
2346
2351
|
maxRelays(): number;
|
|
2347
2352
|
protected canAddressSiblings(): boolean;
|
|
2353
|
+
protected isAdmitted(ws: ShardSocketLike): boolean;
|
|
2348
2354
|
protected siblingStub(targetName: string): SiblingStub | undefined;
|
|
2349
2355
|
protected bindingName(): string | undefined;
|
|
2350
2356
|
protected nextRelaySeq(): number;
|
package/dist/index.d.ts
CHANGED
|
@@ -143,6 +143,7 @@ interface SubscriptionEnvelope {
|
|
|
143
143
|
sinceCheckpoint?: number;
|
|
144
144
|
sinceChunk?: number;
|
|
145
145
|
sinceEpoch?: string;
|
|
146
|
+
token?: string;
|
|
146
147
|
topic?: string;
|
|
147
148
|
type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
|
|
148
149
|
}
|
|
@@ -153,6 +154,7 @@ interface RpcRequest {
|
|
|
153
154
|
interface SocketAttachment {
|
|
154
155
|
admin?: boolean;
|
|
155
156
|
adminBinding?: string;
|
|
157
|
+
authenticated?: boolean;
|
|
156
158
|
clientId?: string;
|
|
157
159
|
connected?: boolean;
|
|
158
160
|
connectionId?: string;
|
|
@@ -166,6 +168,7 @@ interface SocketAttachment {
|
|
|
166
168
|
ip?: string;
|
|
167
169
|
liveGrants?: Record<string, string>;
|
|
168
170
|
pageDeltas?: boolean;
|
|
171
|
+
pendingSince?: number;
|
|
169
172
|
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
170
173
|
socketFunction?: string;
|
|
171
174
|
socketPath?: string;
|
|
@@ -1845,6 +1848,7 @@ interface StorageReferenceResult {
|
|
|
1845
1848
|
declare const findStorageReferences: (sql: SqlExec, storageColumns: Record<string, string[]>, keys: string[]) => StorageReferenceResult;
|
|
1846
1849
|
interface SocketAttachmentLike {
|
|
1847
1850
|
admin?: boolean;
|
|
1851
|
+
authenticated?: boolean;
|
|
1848
1852
|
subs?: Record<string, SubscriptionInfo>;
|
|
1849
1853
|
}
|
|
1850
1854
|
declare const summarizeSubscriptions: (attachments: SocketAttachmentLike[]) => SubscriptionsResult;
|
|
@@ -1883,6 +1887,7 @@ interface FanoutMetricsResult {
|
|
|
1883
1887
|
whisper: FanoutPathCounters;
|
|
1884
1888
|
}
|
|
1885
1889
|
interface FanoutAttachmentLike {
|
|
1890
|
+
authenticated?: boolean;
|
|
1886
1891
|
shapes?: Record<string, {
|
|
1887
1892
|
name?: string;
|
|
1888
1893
|
}>;
|
|
@@ -2345,6 +2350,7 @@ declare abstract class RelayLink {
|
|
|
2345
2350
|
handleControl(request: Request): Promise<Response>;
|
|
2346
2351
|
maxRelays(): number;
|
|
2347
2352
|
protected canAddressSiblings(): boolean;
|
|
2353
|
+
protected isAdmitted(ws: ShardSocketLike): boolean;
|
|
2348
2354
|
protected siblingStub(targetName: string): SiblingStub | undefined;
|
|
2349
2355
|
protected bindingName(): string | undefined;
|
|
2350
2356
|
protected nextRelaySeq(): number;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-b0pfdTXz.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 E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,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-BFJ65SRS.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-BR7jasrr.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DSplGrR_.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 ie,minCdcReplayableSeq as se,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-C7o2xrt1.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ae,migrateClientWatermark as Ce,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.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-Da1DjGqo.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-3MlVqWZD.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-BMS8yYTx.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-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as ir,probeScheduleOutbox as sr,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-FjgzTFok.mjs";import{SHAPE_POKE_CURSOR_TABLE as Er,deleteShapePokeCursor as hr,deleteShapePokeCursorsForConnection as xr,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Ar,writeShapePokeCursor as Cr,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-D1FtktFp.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-RC09zZrh.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-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as io,unionAll as so}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.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 Eo}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as xo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Ao}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.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-rYWz87LR.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-DXANkomm.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-CA8mLJWq.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 ia,ADMIN_FUNCTION_PREFIX as sa,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 Ea,listTables as ha,readTablePage as xa,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Aa,selectMatchingIds as Ca,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-Cug8Z4jD.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-DMolrLYt.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 it,isLossyBody as st,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as Et,resolveRankPartition as ht,sortColumnName as xt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Rt,reactiveCacheKey as At}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-D2Mn204f.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 ei,resolveRelationPredicates as ri}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as ai}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as ii,applyOnDelete as si,distinctValues as li,fanOutScalarCounts as ni,relationHooks as di,resolveWith as ci,runRowValidators as mi}from"./packem_shared/applyInsertDefaults-vVfUyiJ2.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Si,clampPromotionThresholds as ui,nextPromotionState as fi,relayCountFor as Ei,shapeRoutingKey as hi}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ti,OwnerRelay as Ri,RelayMember as Ai,createRelayLink as Ci}from"./packem_shared/DEFAULT_MAX_RELAYS-CrsP5Ldh.mjs";import{createReplicaLink as _i,gateReplicaDispatch as Ii,handleReplicaControl as bi}from"./packem_shared/createReplicaLink-CSbJvezn.mjs";import{buildReprojectionMigration as Di,countLegacyRows as Pi,reprojectableFields as Oi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as yi,RlsRequiredError as Ni,guardWriter as ki}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ui,readSchemaHistory as Gi,readSchemaVersion as wi,recordSchemaVersion as qi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Ki}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Xi,isDevEnvironment as Hi,readDeployInfo as Vi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Qi}from"./packem_shared/buildShapeDiff-Dc9TOdHq.mjs";import{ShapeDiffCache as ji,createShapeDiffCache as Ji,globalShapeReadKey as Zi}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as es,diffGlobalMembership as rs,encodeRowsPatch as os,projectColumns as as}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as is}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{RELAY_SIGNATURE_HEADER as ls,siblingSecretOf as ns,signSiblingBody as ds,stubByName as cs,verifySiblingBody as ms}from"./packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{runSocketPool as Ss}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as fs,assertReadonly as Es,lintReadonlySql as hs,runReadonlySql as xs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as Rs,bigintSqlKey as As,decodeBigintSqlKey as Cs,decodeFloat64SqlKey as gs,float64SqlKey as _s}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as bs,subscriptionFrames as Ls,subscriptionListDeltas as Ds,trySendFrame as Ps}from"./packem_shared/awaitWsDrain-N-oR29RI.mjs";import{mergeChangedKeys as Fs,recordChangedKeys as Ms,writeTouchesMemo as ys}from"./packem_shared/mergeChangedKeys-CF2mjYuy.mjs";import{createSystemReader as ks}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Us}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as ws,TransactionHeadroomTracker as qs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as Ks,runTriggers as Ws}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Hs}from"./packem_shared/selectExpiredIds-DDQyqbLk.mjs";import{VECTOR_BACKFILL_MAX_PAGES as zs,backfillVectorIndexes as Qs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-zxItOlPE.mjs";import{c as js,s as Js}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as $s}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as rl,reprojectionMigrationId as ol}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as tl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as sl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as nl}from"./packem_shared/runShardMigrations-CEZTl9LV.mjs";import{stableStringify as cl,stableWireKey as ml}from"@lunora/wire";export{ia as ADMIN_FUNCTIONS,sa 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,Rs 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,Us as ConflictError,A as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,Ti as DEFAULT_MAX_RELAYS,Si as DEFAULT_PROMOTION_THRESHOLDS,ws as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,xo 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,fs as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,Ri 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,$s as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ls as RELAY_SIGNATURE_HEADER,rl as REPROJECTION_MIGRATION_PREFIX,yi as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Ai as RelayMember,Ni as RlsRequiredError,Mr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Ui as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,Er as SHAPE_POKE_CURSOR_TABLE,ji as ShapeDiffCache,is as ShardRunner,qs as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,zs as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ae 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,ii as applyInsertDefaults,si as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,Es as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,bs as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Qs as backfillVectorIndexes,As as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,es as buildPokeFrames,Di as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Xi as buildSettings,Qi 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,ui as clampPromotionThresholds,Da as clearCapturedMail,Fe as clearCompanionSignatures,Qe as clearMemoryTables,it as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,js as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Pi as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,Ft as createReadFootprint,Ci as createRelayLink,_i as createReplicaLink,Ji as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,ks as createSystemReader,ae as cursorBelowRetainedFloor,Ao as decideDurableAttach,Cs as decodeBigintSqlKey,Qa as decodeCursor,gs as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,hr as deleteShapePokeCursor,xr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,ai as describeRelationWrites,bo as diffExternalSource,rs as diffGlobalMembership,li as distinctValues,h as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,os as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,ni as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,_s as float64SqlKey,x as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,Ii as gateReplicaDispatch,Vr as geoTableName,Zi as globalShapeReadKey,zo as groupUnmappedRows,ki as guardWriter,bi as handleReplicaControl,Ks as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Hi as isDevEnvironment,zr as isFtsAvailable,tl as isInternalTableName,st as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,ei as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,Ea as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,hs as lintReadonlySql,_t as listReactorStates,ha as listTables,Mt as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,Fs as mergeChangedKeys,C as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ce 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,se as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,fi 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,ir as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,sr as probeScheduleOutbox,as as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,sl as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,Et as rankTableName,At as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,F as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,he as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Vi 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,Gi as readSchemaHistory,wi as readSchemaVersion,Sr as readSearchBackfillState,Ar as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,xa as readTablePage,Fa as recordCapturedMail,Ms as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,qi as recordSchemaVersion,Aa as recordShapeProbePass,di as relationHooks,Ei as relayCountFor,to as renderSql,Oi as reprojectableFields,ol as reprojectionMigrationId,Fi as reprojectionTables,wa as resolvePatch,ht as resolveRankPartition,$e as resolveRankSeekTuple,ri as resolveRelationPredicates,ci as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,xs as runReadonlySql,mi as runRowValidators,nl as runShardMigrations,Ss as runSocketPool,Gr as runSql,Ws as runTriggers,Hs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ca as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,Ki as serializeSqlValue,Js as serverInList,hi as shapeRoutingKey,ns as siblingSecretOf,ds as signSiblingBody,et as softDeleteScope,xt as sortColumnName,io as sqliteInList,cl as stableStringify,ml as stableWireKey,G as stripReservedPatchFields,cs as stubByName,Ls as subscriptionFrames,Ds 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,Eo as trimStreamRuns,eo as tryRowToDocument,Ps as trySendFrame,so as unionAll,ot as uniqueIndexFields,l as validateImportRow,ms as verifySiblingBody,wt as whereFilter,qt as whereOfFilter,xe as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Cr as writeShapePokeCursor,gr as writeShapePokeCursors,ys as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-b0pfdTXz.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 E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,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-BFJ65SRS.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-BR7jasrr.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DSplGrR_.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 ie,minCdcReplayableSeq as se,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-C7o2xrt1.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ae,migrateClientWatermark as Ce,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.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-Da1DjGqo.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-3MlVqWZD.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-BMS8yYTx.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-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as ir,probeScheduleOutbox as sr,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-FjgzTFok.mjs";import{SHAPE_POKE_CURSOR_TABLE as Er,deleteShapePokeCursor as hr,deleteShapePokeCursorsForConnection as xr,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Ar,writeShapePokeCursor as Cr,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-D1FtktFp.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-RC09zZrh.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-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as io,unionAll as so}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.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 Eo}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as xo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Ao}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.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-rYWz87LR.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-DXANkomm.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-CA8mLJWq.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 ia,ADMIN_FUNCTION_PREFIX as sa,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 Ea,listTables as ha,readTablePage as xa,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Aa,selectMatchingIds as Ca,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-CPXCHyOg.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-DMolrLYt.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 it,isLossyBody as st,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as Et,resolveRankPartition as ht,sortColumnName as xt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Rt,reactiveCacheKey as At}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-D2Mn204f.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 ei,resolveRelationPredicates as ri}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as ai}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as ii,applyOnDelete as si,distinctValues as li,fanOutScalarCounts as ni,relationHooks as di,resolveWith as ci,runRowValidators as mi}from"./packem_shared/applyInsertDefaults-vVfUyiJ2.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Si,clampPromotionThresholds as ui,nextPromotionState as fi,relayCountFor as Ei,shapeRoutingKey as hi}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ti,OwnerRelay as Ri,RelayMember as Ai,createRelayLink as Ci}from"./packem_shared/DEFAULT_MAX_RELAYS-B5swBl_q.mjs";import{createReplicaLink as _i,gateReplicaDispatch as Ii,handleReplicaControl as bi}from"./packem_shared/createReplicaLink-CSbJvezn.mjs";import{buildReprojectionMigration as Di,countLegacyRows as Pi,reprojectableFields as Oi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as yi,RlsRequiredError as Ni,guardWriter as ki}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ui,readSchemaHistory as Gi,readSchemaVersion as wi,recordSchemaVersion as qi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Ki}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Xi,isDevEnvironment as Hi,readDeployInfo as Vi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Qi}from"./packem_shared/buildShapeDiff-Dc9TOdHq.mjs";import{ShapeDiffCache as ji,createShapeDiffCache as Ji,globalShapeReadKey as Zi}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as es,diffGlobalMembership as rs,encodeRowsPatch as os,projectColumns as as}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as is}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{RELAY_SIGNATURE_HEADER as ls,siblingSecretOf as ns,signSiblingBody as ds,stubByName as cs,verifySiblingBody as ms}from"./packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{runSocketPool as Ss}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as fs,assertReadonly as Es,lintReadonlySql as hs,runReadonlySql as xs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as Rs,bigintSqlKey as As,decodeBigintSqlKey as Cs,decodeFloat64SqlKey as gs,float64SqlKey as _s}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as bs,subscriptionFrames as Ls,subscriptionListDeltas as Ds,trySendFrame as Ps}from"./packem_shared/awaitWsDrain-N-oR29RI.mjs";import{mergeChangedKeys as Fs,recordChangedKeys as Ms,writeTouchesMemo as ys}from"./packem_shared/mergeChangedKeys-CF2mjYuy.mjs";import{createSystemReader as ks}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Us}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as ws,TransactionHeadroomTracker as qs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as Ks,runTriggers as Ws}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Hs}from"./packem_shared/selectExpiredIds-DDQyqbLk.mjs";import{VECTOR_BACKFILL_MAX_PAGES as zs,backfillVectorIndexes as Qs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-zxItOlPE.mjs";import{c as js,s as Js}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as $s}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as rl,reprojectionMigrationId as ol}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as tl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as sl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as nl}from"./packem_shared/runShardMigrations-CEZTl9LV.mjs";import{stableStringify as cl,stableWireKey as ml}from"@lunora/wire";export{ia as ADMIN_FUNCTIONS,sa 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,Rs 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,Us as ConflictError,A as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,Ti as DEFAULT_MAX_RELAYS,Si as DEFAULT_PROMOTION_THRESHOLDS,ws as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,xo 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,fs as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,Ri 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,$s as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ls as RELAY_SIGNATURE_HEADER,rl as REPROJECTION_MIGRATION_PREFIX,yi as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Ai as RelayMember,Ni as RlsRequiredError,Mr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Ui as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,Er as SHAPE_POKE_CURSOR_TABLE,ji as ShapeDiffCache,is as ShardRunner,qs as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,zs as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ae 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,ii as applyInsertDefaults,si as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,Es as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,bs as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Qs as backfillVectorIndexes,As as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,es as buildPokeFrames,Di as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Xi as buildSettings,Qi 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,ui as clampPromotionThresholds,Da as clearCapturedMail,Fe as clearCompanionSignatures,Qe as clearMemoryTables,it as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,js as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Pi as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,Ft as createReadFootprint,Ci as createRelayLink,_i as createReplicaLink,Ji as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,ks as createSystemReader,ae as cursorBelowRetainedFloor,Ao as decideDurableAttach,Cs as decodeBigintSqlKey,Qa as decodeCursor,gs as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,hr as deleteShapePokeCursor,xr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,ai as describeRelationWrites,bo as diffExternalSource,rs as diffGlobalMembership,li as distinctValues,h as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,os as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,ni as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,_s as float64SqlKey,x as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,Ii as gateReplicaDispatch,Vr as geoTableName,Zi as globalShapeReadKey,zo as groupUnmappedRows,ki as guardWriter,bi as handleReplicaControl,Ks as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Hi as isDevEnvironment,zr as isFtsAvailable,tl as isInternalTableName,st as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,ei as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,Ea as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,hs as lintReadonlySql,_t as listReactorStates,ha as listTables,Mt as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,Fs as mergeChangedKeys,C as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ce 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,se as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,fi 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,ir as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,sr as probeScheduleOutbox,as as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,sl as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,Et as rankTableName,At as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,F as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,he as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Vi 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,Gi as readSchemaHistory,wi as readSchemaVersion,Sr as readSearchBackfillState,Ar as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,xa as readTablePage,Fa as recordCapturedMail,Ms as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,qi as recordSchemaVersion,Aa as recordShapeProbePass,di as relationHooks,Ei as relayCountFor,to as renderSql,Oi as reprojectableFields,ol as reprojectionMigrationId,Fi as reprojectionTables,wa as resolvePatch,ht as resolveRankPartition,$e as resolveRankSeekTuple,ri as resolveRelationPredicates,ci as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,xs as runReadonlySql,mi as runRowValidators,nl as runShardMigrations,Ss as runSocketPool,Gr as runSql,Ws as runTriggers,Hs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ca as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,Ki as serializeSqlValue,Js as serverInList,hi as shapeRoutingKey,ns as siblingSecretOf,ds as signSiblingBody,et as softDeleteScope,xt as sortColumnName,io as sqliteInList,cl as stableStringify,ml as stableWireKey,G as stripReservedPatchFields,cs as stubByName,Ls as subscriptionFrames,Ds 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,Eo as trimStreamRuns,eo as tryRowToDocument,Ps as trySendFrame,so as unionAll,ot as uniqueIndexFields,l as validateImportRow,ms as verifySiblingBody,wt as whereFilter,qt as whereOfFilter,xe as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Cr as writeShapePokeCursor,gr as writeShapePokeCursors,ys as writeTouchesMemo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{decodeWire as x}from"@lunora/wire";import{sql as j}from"drizzle-orm";import{isInternalTableName as M}from"./isInternalTableName-BoljO2tP.mjs";import{n as A,o as U}from"./do-sql-BWrJQAOh.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as q,sqliteInList as B}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{serializeSqlValue as k}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as Q}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const Te="__lunora_admin__:",Ae="__lunora_relation__:",Ie="__lunora_flags__:",Re={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},W=50,b=500,H=30,G=200,d="__doc__",$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},K=e=>{const{[A]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[A]:t,...n}:{...n,...x(t)}},X=(e,t)=>{if(!e.includes(d))return{columns:e,rows:t};const n=[];for(const o of t){const a=o[d],_=typeof a=="string"?$(a):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(o).filter(([l])=>l!==d));n.push({...c,...K(_)})}const r=e.filter(o=>o!==d),s=[],i=new Set(r);for(const o of n)for(const a of Object.keys(o))i.has(a)||(i.add(a),s.push(a));return{columns:[...r,...s],rows:n}},I=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),D=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},ve=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)M(r)||n.push({name:r,rowCount:D(e,u(r))});return n},F=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,w=(e,t)=>{if(M(t)||!F(e,t))throw new S("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},R=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),V={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",Y=new Set(["gt","gte","lt","lte"]),J=e=>e.operator==="contains"?L(e.value)==="":Y.has(e.operator)&&e.value==="",E=(e,t)=>{const n=t.includes(e),r=t.includes(d);if(!(!n&&!r))return n?{expression:u(e),params:[]}:{expression:`json_extract(${u(d)}, ?)`,params:[`$.${U(e)}`]}},z=/^-?\d+$/u,Z=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!z.test(r))throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(n)},ee=(e,t)=>t==="bigint"&&typeof e=="string"?Q(e)??e:e,te=(e,t,n)=>{const r=E(e.column,t);if(r===void 0||J(e))return;const{expression:s,params:i}=r,o=t.includes(e.column)?void 0:n?.[e.column];if(e.operator==="contains"){if(o==="bigint")throw new S("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);return{params:[...i,L(e.value)],sql:I(s)}}return e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:i,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...i,Z(e,o)],sql:`${s} ${V[e.operator]} ?`}},ne=new Set(["date","timestamp"]),re=[`$.${A}`,`$."${A}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),oe=e=>`(${I(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${I("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${re}))`,se=/["\\\u0000-\u001F]/u,ae=e=>se.test(e)?"":e,ie=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,_e=e=>{const t=ie.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),s=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||s!==void 0&&(s<1||s>31)||n<100)return;const i=Date.UTC(n,(r??1)-1,s??1);if(s!==void 0&&new Date(i).getUTCDate()!==s)return;let o;return s!==void 0?o=Date.UTC(n,(r??1)-1,s+1):r===void 0?o=Date.UTC(n+1,0,1):o=Date.UTC(n,r,1),{from:i,to:o}},y=(e,t,n,r)=>{const s=[],i=[];if(t!==""&&e.length>0){const o=e.map(_=>_===d?oe(u(_)):I(u(_)));i.push(...e.flatMap(_=>_===d?[ae(t),t]:[t]));const a=_e(t);if(a!==void 0){for(const c of e)o.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),i.push(a.from,a.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ne.has(r?.[c]??""));_.length>0&&e.includes(d)&&(o.push(`EXISTS (SELECT 1 FROM json_each(${u(d)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),i.push(JSON.stringify(_),a.from,a.to))}s.push(`(${o.join(" OR ")})`)}for(const o of n??[]){const a=te(o,e,r);a!==void 0&&(s.push(`(${a.sql})`),i.push(...a.params))}return s.length===0?void 0:{parameters:i,where:s.join(" AND ")}},ce=(e,t)=>{if(e===void 0)return;const n=E(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Me=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??W),1,b),s=Math.max(0,Math.trunc(t.offset??0)),i=u(n),o=R(e,i),a=t.search?.trim()??"",_=T=>{if(t.refs===void 0)return T;const v={};for(const N of T.columns){const O=t.refs[N];O!==void 0&&(v[N]=O)}return Object.keys(v).length>0?{...T,refs:v}:T},c=y(o,a,t.filters,t.columnKinds),l=ce(t.orderBy,o),f=c===void 0?"":` WHERE ${c.where}`,g=l===void 0?"":` ORDER BY ${l.sql}`,p=c?.parameters??[],h=l?.params??[];let m;t.skipCount||(m=c===void 0?D(e,i):Number(e.exec(`SELECT COUNT(*) AS c FROM ${i}${f}`,...p).one().c));const P=e.exec(`SELECT * FROM ${i}${f}${g} LIMIT ? OFFSET ?`,...p,...h,r,s).toArray();return _({...X(o,P),sqlColumns:o,total:m})},Ce=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??b),1,b),s=u(n),i=R(e,s),o=t.search?.trim()??"";for(const m of t.filters??[])if(E(m.column,i)===void 0)throw new S("BAD_REQUEST",`unknown column: ${m.column}`);const a=y(i,o,t.filters,t.columnKinds);if(a===void 0&&(t.filters?.length??0)>0)throw new S("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];a!==void 0&&(_.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const l=_.length===0?"":` WHERE ${_.join(" AND ")}`,f=t.after===void 0?"":" ORDER BY id",g=e.exec(`SELECT id FROM ${s}${l}${f} LIMIT ?`,...c,r+1).toArray(),p=g.length>r,h=g.slice(0,r).map(m=>m.id);return{hasMore:p,ids:h}},le=(e,t,n,r)=>{const s=new Set(n.filter(o=>o!==d));if(!n.includes(d))return s;for(const o of Object.keys(r??{}))s.add(o);const i=e.exec(`SELECT ${u(d)} AS doc FROM ${t} LIMIT ?`,b).toArray();for(const{doc:o}of i){const a=typeof o=="string"?$(o):void 0;if(a!==void 0)for(const _ of Object.keys(a))s.add(_)}return s},we=(e,t)=>{const{column:n,table:r}=t;w(e,r);const s=u(r),i=R(e,s);if(!le(e,s,i,t.columnKinds).has(n))throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const o=E(n,i);if(o===void 0)throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=C(Math.trunc(t.limit??H),1,G),_=t.search?.trim()??"",c=y(i,_,t.filters,t.columnKinds),l=c===void 0?"":` WHERE ${c.where}`,f=c?.parameters??[],g=e.exec(`SELECT ${o.expression} AS value, COUNT(*) AS count FROM ${s}${l} GROUP BY ${o.expression} ORDER BY count DESC LIMIT ?`,...o.params,...f,...o.params,a+1).toArray(),p=g.length>a,h=i.includes(n)?void 0:t.columnKinds?.[n];return{truncated:p,values:g.slice(0,a).map(m=>({count:Number(m.count),value:ee(m.value,h)}))}},ye=(e,t,n)=>{const r={},s=n.slice(0,b);for(const i of s)r[i]=[];if(s.length===0)return{references:r,storageColumns:t};for(const[i,o]of Object.entries(t)){if(M(i)||!F(e,i))continue;const a=u(i),_=R(e,a);for(const c of o){const l=E(c,_);if(l===void 0)continue;const f=q("sqlite",B(j.raw(l.expression),s,!1)),g=e.exec(`SELECT id, ${l.expression} AS ref FROM ${a} WHERE ${f.sql}`,...l.params,...l.params,...f.params).toArray();for(const p of g)r[p.ref]?.push({column:c,id:p.id,table:i})}}return{references:r,storageColumns:t}},Ne=e=>{const t=e.map((r,s)=>{const i=Object.values(r.subs??{}).map(o=>({args:o.args,functionPath:o.functionPath,table:o.table}));return{admin:r.admin===!0,id:s,subscriptions:i}}),n=t.reduce((r,s)=>r+s.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},ue=20,Oe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),ke=()=>({run:0,served:0}),$e=()=>({drains:0,pairsSkipped:0}),De=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Fe=(e,t,n)=>({run:e.run+t,served:e.served+n}),Le=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Pe=(e,t=ue)=>{const n=new Map,r=new Map;for(const o of e){for(const a of Object.values(o.shapes??{})){const _=a.name??"(unknown shape)";n.set(_,(n.get(_)??0)+1)}for(const a of o.whispers??[])r.set(a,(r.get(a)??0)+1)}const s=[...[...n].map(([o,a])=>({kind:"shape",subscribers:a,topic:o})),...[...r].map(([o,a])=>({kind:"whisper",subscribers:a,topic:o}))];return s.sort((o,a)=>a.subscribers-o.subscribers||o.topic.localeCompare(a.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:e.length}};export{Re as ADMIN_FUNCTIONS,Te as ADMIN_FUNCTION_PREFIX,ue as DEFAULT_FANOUT_TOPIC_LIMIT,Ie as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,Ae as RELATION_FUNCTION_PREFIX,Oe as createFanoutCounters,$e as createGlobalPollCounters,ke as createShapeProbeCounters,_e as datePrefixRange,we as facetColumn,ye as findStorageReferences,M as isInternalTableName,J as isVacuousFilterClause,ve as listTables,Me as readTablePage,Le as recordFanoutPass,De as recordGlobalPollPass,Fe as recordShapeProbePass,Ce as selectMatchingIds,Pe as summarizeFanoutTopics,Ne as summarizeSubscriptions};
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{decodeWire as x}from"@lunora/wire";import{sql as j}from"drizzle-orm";import{isInternalTableName as M}from"./isInternalTableName-BoljO2tP.mjs";import{n as A,o as U}from"./do-sql-BWrJQAOh.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as q,sqliteInList as B}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{serializeSqlValue as k}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as Q}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const Te="__lunora_admin__:",Ae="__lunora_relation__:",Ie="__lunora_flags__:",Re={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},W=50,b=500,H=30,G=200,d="__doc__",$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},K=e=>{const{[A]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[A]:t,...n}:{...n,...x(t)}},X=(e,t)=>{if(!e.includes(d))return{columns:e,rows:t};const n=[];for(const i of t){const o=i[d],_=typeof o=="string"?$(o):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(i).filter(([l])=>l!==d));n.push({...c,...K(_)})}const r=e.filter(i=>i!==d),s=[],a=new Set(r);for(const i of n)for(const o of Object.keys(i))a.has(o)||(a.add(o),s.push(o));return{columns:[...r,...s],rows:n}},I=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),D=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},ve=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)M(r)||n.push({name:r,rowCount:D(e,u(r))});return n},F=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,w=(e,t)=>{if(M(t)||!F(e,t))throw new S("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},R=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),V={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",Y=new Set(["gt","gte","lt","lte"]),J=e=>e.operator==="contains"?L(e.value)==="":Y.has(e.operator)&&e.value==="",E=(e,t)=>{const n=t.includes(e),r=t.includes(d);if(!(!n&&!r))return n?{expression:u(e),params:[]}:{expression:`json_extract(${u(d)}, ?)`,params:[`$.${U(e)}`]}},z=/^-?\d+$/u,Z=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!z.test(r))throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(n)},ee=(e,t)=>t==="bigint"&&typeof e=="string"?Q(e)??e:e,te=(e,t,n)=>{const r=E(e.column,t);if(r===void 0||J(e))return;const{expression:s,params:a}=r,i=t.includes(e.column)?void 0:n?.[e.column];if(e.operator==="contains"){if(i==="bigint")throw new S("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);return{params:[...a,L(e.value)],sql:I(s)}}return e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:a,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...a,Z(e,i)],sql:`${s} ${V[e.operator]} ?`}},ne=new Set(["date","timestamp"]),re=[`$.${A}`,`$."${A}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),oe=e=>`(${I(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${I("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${re}))`,se=/["\\\u0000-\u001F]/u,ae=e=>se.test(e)?"":e,ie=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,_e=e=>{const t=ie.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),s=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||s!==void 0&&(s<1||s>31)||n<100)return;const a=Date.UTC(n,(r??1)-1,s??1);if(s!==void 0&&new Date(a).getUTCDate()!==s)return;let i;return s!==void 0?i=Date.UTC(n,(r??1)-1,s+1):r===void 0?i=Date.UTC(n+1,0,1):i=Date.UTC(n,r,1),{from:a,to:i}},y=(e,t,n,r)=>{const s=[],a=[];if(t!==""&&e.length>0){const i=e.map(_=>_===d?oe(u(_)):I(u(_)));a.push(...e.flatMap(_=>_===d?[ae(t),t]:[t]));const o=_e(t);if(o!==void 0){for(const c of e)i.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),a.push(o.from,o.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ne.has(r?.[c]??""));_.length>0&&e.includes(d)&&(i.push(`EXISTS (SELECT 1 FROM json_each(${u(d)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),a.push(JSON.stringify(_),o.from,o.to))}s.push(`(${i.join(" OR ")})`)}for(const i of n??[]){const o=te(i,e,r);o!==void 0&&(s.push(`(${o.sql})`),a.push(...o.params))}return s.length===0?void 0:{parameters:a,where:s.join(" AND ")}},ce=(e,t)=>{if(e===void 0)return;const n=E(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Me=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??W),1,b),s=Math.max(0,Math.trunc(t.offset??0)),a=u(n),i=R(e,a),o=t.search?.trim()??"",_=T=>{if(t.refs===void 0)return T;const v={};for(const N of T.columns){const O=t.refs[N];O!==void 0&&(v[N]=O)}return Object.keys(v).length>0?{...T,refs:v}:T},c=y(i,o,t.filters,t.columnKinds),l=ce(t.orderBy,i),f=c===void 0?"":` WHERE ${c.where}`,g=l===void 0?"":` ORDER BY ${l.sql}`,p=c?.parameters??[],h=l?.params??[];let m;t.skipCount||(m=c===void 0?D(e,a):Number(e.exec(`SELECT COUNT(*) AS c FROM ${a}${f}`,...p).one().c));const P=e.exec(`SELECT * FROM ${a}${f}${g} LIMIT ? OFFSET ?`,...p,...h,r,s).toArray();return _({...X(i,P),sqlColumns:i,total:m})},Ce=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??b),1,b),s=u(n),a=R(e,s),i=t.search?.trim()??"";for(const m of t.filters??[])if(E(m.column,a)===void 0)throw new S("BAD_REQUEST",`unknown column: ${m.column}`);const o=y(a,i,t.filters,t.columnKinds);if(o===void 0&&(t.filters?.length??0)>0)throw new S("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];o!==void 0&&(_.push(o.where),c.push(...o.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const l=_.length===0?"":` WHERE ${_.join(" AND ")}`,f=t.after===void 0?"":" ORDER BY id",g=e.exec(`SELECT id FROM ${s}${l}${f} LIMIT ?`,...c,r+1).toArray(),p=g.length>r,h=g.slice(0,r).map(m=>m.id);return{hasMore:p,ids:h}},le=(e,t,n,r)=>{const s=new Set(n.filter(i=>i!==d));if(!n.includes(d))return s;for(const i of Object.keys(r??{}))s.add(i);const a=e.exec(`SELECT ${u(d)} AS doc FROM ${t} LIMIT ?`,b).toArray();for(const{doc:i}of a){const o=typeof i=="string"?$(i):void 0;if(o!==void 0)for(const _ of Object.keys(o))s.add(_)}return s},we=(e,t)=>{const{column:n,table:r}=t;w(e,r);const s=u(r),a=R(e,s);if(!le(e,s,a,t.columnKinds).has(n))throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const i=E(n,a);if(i===void 0)throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const o=C(Math.trunc(t.limit??H),1,G),_=t.search?.trim()??"",c=y(a,_,t.filters,t.columnKinds),l=c===void 0?"":` WHERE ${c.where}`,f=c?.parameters??[],g=e.exec(`SELECT ${i.expression} AS value, COUNT(*) AS count FROM ${s}${l} GROUP BY ${i.expression} ORDER BY count DESC LIMIT ?`,...i.params,...f,...i.params,o+1).toArray(),p=g.length>o,h=a.includes(n)?void 0:t.columnKinds?.[n];return{truncated:p,values:g.slice(0,o).map(m=>({count:Number(m.count),value:ee(m.value,h)}))}},ye=(e,t,n)=>{const r={},s=n.slice(0,b);for(const a of s)r[a]=[];if(s.length===0)return{references:r,storageColumns:t};for(const[a,i]of Object.entries(t)){if(M(a)||!F(e,a))continue;const o=u(a),_=R(e,o);for(const c of i){const l=E(c,_);if(l===void 0)continue;const f=q("sqlite",B(j.raw(l.expression),s,!1)),g=e.exec(`SELECT id, ${l.expression} AS ref FROM ${o} WHERE ${f.sql}`,...l.params,...l.params,...f.params).toArray();for(const p of g)r[p.ref]?.push({column:c,id:p.id,table:a})}}return{references:r,storageColumns:t}},Ne=e=>{const n=e.filter(s=>s.authenticated!==!1).map((s,a)=>{const i=Object.values(s.subs??{}).map(o=>({args:o.args,functionPath:o.functionPath,table:o.table}));return{admin:s.admin===!0,id:a,subscriptions:i}}),r=n.reduce((s,a)=>s+a.subscriptions.length,0);return{connections:n,totalConnections:n.length,totalSubscriptions:r}},ue=20,Oe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),ke=()=>({run:0,served:0}),$e=()=>({drains:0,pairsSkipped:0}),De=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Fe=(e,t,n)=>({run:e.run+t,served:e.served+n}),Le=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Pe=(e,t=ue)=>{const n=new Map,r=new Map,s=e.filter(o=>o.authenticated!==!1);for(const o of s){for(const _ of Object.values(o.shapes??{})){const c=_.name??"(unknown shape)";n.set(c,(n.get(c)??0)+1)}for(const _ of o.whispers??[])r.set(_,(r.get(_)??0)+1)}const a=[...[...n].map(([o,_])=>({kind:"shape",subscribers:_,topic:o})),...[...r].map(([o,_])=>({kind:"whisper",subscribers:_,topic:o}))];return a.sort((o,_)=>_.subscribers-o.subscribers||o.topic.localeCompare(_.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:s.length}};export{Re as ADMIN_FUNCTIONS,Te as ADMIN_FUNCTION_PREFIX,ue as DEFAULT_FANOUT_TOPIC_LIMIT,Ie as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,Ae as RELATION_FUNCTION_PREFIX,Oe as createFanoutCounters,$e as createGlobalPollCounters,ke as createShapeProbeCounters,_e as datePrefixRange,we as facetColumn,ye as findStorageReferences,M as isInternalTableName,J as isVacuousFilterClause,ve as listTables,Me as readTablePage,Le as recordFanoutPass,De as recordGlobalPollPass,Fe as recordShapeProbePass,Ce as selectMatchingIds,Pe as summarizeFanoutTopics,Ne as summarizeSubscriptions};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{toErrorBody as Y,LunoraError as G}from"@lunora/errors";import{encodeWire as q,stableWireKey as _,decodeWire as g}from"@lunora/wire";import{sql as u}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as W}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{d as $,w as I,a as A,m as B,r as K,b as H,c as j}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as X,shapeRoutingKey as E,relayProxyKey as w,relayName as M,parseRelayName as z,clampPromotionThresholds as V}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{encodeRowsPatch as J,buildPokeFrames as D}from"./buildPokeFrames-WR-hp0mX.mjs";import{verifySiblingBody as Q,RELAY_SIGNATURE_HEADER as L,siblingStub as Z,siblingSecretOf as ee,signSiblingBody as te}from"./RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{awaitWsDrain as se,trySendFrame as C}from"./awaitWsDrain-N-oR29RI.mjs";const S="__lunora_relay_memos",re=i=>{m(i,u`CREATE TABLE IF NOT EXISTS ${u.identifier(S)} (
|
|
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
|
+
)`)},oe=i=>{const e=m(i,u`SELECT connection_id, sub_id, cursor, epoch FROM ${u.identifier(S)}`).toArray(),s=new Map;for(const t of e){let r=s.get(t.connection_id);r===void 0&&(r=new Map,s.set(t.connection_id,r)),r.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},ne=4,N=(i,e)=>{const s=Math.floor(W.boundParams/ne);for(let t=0;t<e.length;t+=s){const r=e.slice(t,t+s),o=u.join(r.map(n=>u`(${n.connectionId}, ${n.subId}, ${n.cursor}, ${n.epoch??null})`),u`, `);m(i,u`INSERT INTO ${u.identifier(S)} (connection_id, sub_id, cursor, epoch) VALUES ${o}
|
|
8
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},ae=(i,e,s)=>{m(i,u`DELETE FROM ${u.identifier(S)} WHERE connection_id = ${e} AND sub_id = ${s}`)},ie=(i,e)=>{m(i,u`DELETE FROM ${u.identifier(S)} WHERE connection_id = ${e}`)},le=i=>{m(i,u`DELETE FROM ${u.identifier(S)}`)},ce=2,he=i=>{const e=i?.LUNORA_WS_BEARER;return typeof e=="string"&&e.length>0},de=8,ue=2e3,ye=2e3,O=async i=>{let e;const s=new Promise(t=>{e=setTimeout(()=>{t(void 0)},ye)});return Promise.race([i,s]).finally(()=>{clearTimeout(e)})},b={},pe=i=>{throw new G("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},fe=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,k=i=>Response.json(i,{headers:{"content-type":"application/json"}}),me=new Set(["relay_attach","relay_detach","relay_room_event","relay_shape_unsubscribe"]),Se=new Set(["relay_attach","relay_shape_subscribe"]),Re=(i,e)=>{let s;try{s=JSON.parse(i)}catch{return}if(typeof s!="object"||s===null)return;const t=s,{relayIndex:r}=t;if(r===void 0?!me.has(t.type):Number.isSafeInteger(r)&&r>=0&&(!Se.has(t.type)||r<e))return t},f=()=>new Response(null,{status:204}),x=(i,e)=>{i.then(async s=>s===e?void 0:s?.body?.cancel()).catch(()=>{})},_e=3e4,F=410,P=()=>new Response("stale relay frame",{status:409}),ve=i=>Math.max(Date.now()*1e3,i+1);class U{constructor(e,s){this.host=e,this.roleId=s}host;roleId;lastSequence=0;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await Q(this.host.env(),e.headers.get(L),s))return new Response("forbidden",{status:403});const t=Re(s,this.maxRelays());if(t===void 0)return new Response("bad request",{status:400});if((t.type==="relay_frame"||t.type==="relay_live_frame"||t.type==="relay_shape_poke")&&this.refusesAsIdle())return new Response(void 0,{status:F});switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex,t.seq)?f():P();case"relay_detach":return this.onDetach(t.relayIndex,t.seq)?f():P();case"relay_frame":{const{exceptConnectionId:r}=t,o=r===void 0?void 0:this.host.getWebSockets().find(n=>this.host.readAttachment(n).connectionId===r);return this.host.deliverWhisperLocal(t.topic,t.frame,o),await this.onWhisperFrame(t),f()}case"relay_live_control":return this.onLiveControl(t.control);case"relay_live_frame":return this.host.deliverLiveLocal(t.topic,t.key,t.frame),f();case"relay_room_event":return k(await this.host.relayRoomEvent(t));case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),{delivered:n,matched:a}=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,n,Date.now()-o),n<a?Response.json({delivered:n,matched:a},{status:503}):f()}case"relay_shape_subscribe":return k(this.onShapeSubscribe({...t,args:g(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),f();default:return pe(t)}}maxRelays(){return v(this.host.env(),"LUNORA_MAX_RELAYS",de)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}isAdmitted(e){return this.host.readAttachment(e).authenticated!==!1}siblingStub(e){return Z(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}nextRelaySeq(){return this.lastSequence=ve(this.lastSequence),this.lastSequence}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=ee(this.host.env());n!==void 0&&(o[L]=await te(n,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class Ee extends U{shapeUniformCache=new Map;relaySetCache;liveGrantRelayCache;relayTablesReady=!1;relaySeqMarks=new Map;pendingSubscribeRelays=new Map;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s,t){if(!this.canAddressSiblings())return;const r=this.ownerRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{exceptConnectionId:t,frame:s,topic:e,type:"relay_frame"})))}forwardLiveControl(e){if(!this.canAddressSiblings())return Promise.resolve(void 0);const s={...e,seq:this.nextRelaySeq()},t=s.action==="unsubscribe"?new Set([...this.liveGrantRelaySet(),...this.pendingSubscribeRelays.keys()]):this.ownerRelaySet();if(t.size===0)return Promise.resolve(void 0);const r=[...t].map(o=>this.liveControlAnswer(o,s));return Promise.any(r.map(async o=>{const n=await o;if(n===void 0||n.status===404)throw new Error("relay does not hold the socket");return n})).catch(()=>{}).then(o=>{for(const n of r)x(n,o);return o})}async forwardLiveFrame(e,s,t){if(!this.canAddressSiblings())return;const r=this.liveGrantRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{frame:t,key:s,topic:e,type:"relay_live_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(!0)}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets(),s=he(this.host.env())?e.filter(n=>this.isAdmitted(n)).length:e.length,t=v(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),r=v(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=X(this.promotionState,s,V(t,r)),this.promotionState==="owned")return 0;const o=v(this.host.env(),"LUNORA_RELAY_FAN",ce);return Math.min(this.maxRelays(),Math.max(1,o))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const r of[...e.values(),...s.values()])t=t===void 0?r.cursor:Math.min(t,r.cursor);return t}isShapeRelayUniform(e,s){const t=E(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,o),o}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:w(e.relayIndex,e.connectionId,e.subId);for(const[r,o]of s)o.relayIndex!==e.relayIndex||o.connectionId!==e.connectionId||(t===void 0||r===t)&&s.delete(r);$(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e,s){return this.recordRelaySeq(e,s),this.addRelayToSet(e),!0}onDetach(e,s){return this.acceptRelaySeq(e,s)?(this.removeRelayFromSet(e),!0):!1}refusesAsIdle(){return!1}onLiveControl(e){return this.host.liveControl(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.forwardToRelay(s,{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}relaySeqMark(e){if(this.relaySeqMarks.has(e))return this.relaySeqMarks.get(e);this.ensureRelayTables();const[s]=this.host.sql().exec("SELECT seq FROM __lunora_relay_seqs WHERE idx = ?",e).toArray(),t=s===void 0?void 0:Number(s.seq);return this.relaySeqMarks.set(e,t),t}recordRelaySeq(e,s){if(s===void 0)return;const t=this.relaySeqMark(e);(t===void 0||s>t)&&(this.host.sql().exec("INSERT OR REPLACE INTO __lunora_relay_seqs (idx, seq) VALUES (?, ?)",e,s),this.relaySeqMarks.set(e,s))}acceptRelaySeq(e,s){if(s===void 0)return!0;const t=this.relaySeqMark(e);return t!==void 0&&s<t?!1:(this.recordRelaySeq(e,s),!0)}buildShapePoke(e,s,t,r,o){if(e.table!==void 0&&!t.has(e.table))return;let n;try{n=this.host.resolveShape(e.name,e.args,s)}catch{return}if(n===void 0||n.global===!0)return;const a=e;if(a.table=n.table,!t.has(n.table))return;const c=a.cursor,l=this.host.buildShapeDiff(n,c,r);if(l.length!==0)return a.cursor=r,I(this.host.sql(),a.key,r),{args:q(e.args),checkpoint:r,epoch:o,fromCursor:c,name:e.name,rowsPatch:J(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const a of r.values()){const c=this.buildShapePoke(a,b,e,s,o);c&&n.push(this.multicastToRelays(t,c,a))}await Promise.all(n)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async o=>{const{dropped:n,response:a}=await this.requestDroppingIdle(o,s);return n||a?.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 r=this.host.currentCdcEpoch(),o=[];for(const n of t.values()){const a=this.buildShapePoke(n,n.identity,e,s,r);a&&o.push(this.proxyToRelay(a,n))}await Promise.all(o)}async proxyToRelay(e,s){const{dropped:t,response:r}=await this.requestDroppingIdle(s.relayIndex,{...e,targetConnectionId:s.connectionId});!t&&r?.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(h){const{body:p}=Y(h,{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:r,cursor:o,epoch:n,reset:a,rowsPatch:c}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let l=o;const{cohort:d,proxies:R}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=E(e.name,e.args);let p=d.get(h);p===void 0&&(p={args:e.args,cursor:o,key:h,name:e.name,table:t.table},d.set(h,p),A(this.host.sql(),p)),l=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=w(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:o,identity:s,key:h,name:e.name,relayIndex:e.relayIndex,table:t.table};R.set(h,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 y=D([{reset:a,rowsPatch:c,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:l,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:l,epoch:n,frames:y}}ensureRelayTables(){this.relayTablesReady||(this.relayTablesReady=!0,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_grants (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_seqs (idx INTEGER PRIMARY KEY, seq INTEGER NOT NULL)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),B(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,I(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}liveGrantRelaySet(){if(this.liveGrantRelayCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relay_grants").toArray();this.liveGrantRelayCache=new Set(e.map(s=>Number(s.idx)))}return this.liveGrantRelayCache}recordLiveGrantRelay(e){const s=this.liveGrantRelaySet();s.has(e)||(this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relay_grants (idx) VALUES (?)",e),s.add(e))}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}async forwardToRelay(e,s){await this.requestDroppingIdle(e,s)}async requestDroppingIdle(e,s){const t=this.relaySeqMark(e),r=await this.requestRelayMessage(M(this.roleId.ownerKey,e),s);return r?.status!==F||this.relaySeqMark(e)!==t?{dropped:!1,response:r}:(this.removeRelayFromSet(e),{dropped:!0,response:r})}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e),this.host.sql().exec("DELETE FROM __lunora_relay_grants WHERE idx = ?",e),this.liveGrantRelaySet().delete(e);const{cohort:t,proxies:r}=this.relayShapes();for(const[o,n]of r)n.relayIndex===e&&r.delete(o);H(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),j(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,b)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(l=>l.on==="read"&&l.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=_(t.effectiveWhere),o=_(t.columns);let n=!1;const a=l=>{const d={groups:[`grp_${l}`],roles:[l],sub:`__lunora_probe_${l}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${l}:${h}`,getOwnPropertyDescriptor:(y,h)=>(n=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(n=!0,Reflect.ownKeys(y))}),ip:`__lunora_probe_${l}__`,userId:`__lunora_probe_${l}__`}};return[b,a("a"),a("b")].every(l=>{let d;try{d=this.host.resolveShape(e,s,l)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&_(d.effectiveWhere)===r&&_(d.columns)===o})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}async liveControlAnswer(e,s){const t=s.action==="subscribe";t&&this.pendingSubscribeRelays.set(e,(this.pendingSubscribeRelays.get(e)??0)+1);const r=this.requestRelayMessage(M(this.roleId.ownerKey,e),{control:s,type:"relay_live_control"}).then(a=>(t&&a?.ok===!0&&this.recordLiveGrantRelay(e),a)).finally(()=>{if(!t)return;const a=(this.pendingSubscribeRelays.get(e)??1)-1;a===0?this.pendingSubscribeRelays.delete(e):this.pendingSubscribeRelays.set(e,a)});let o;const n=new Promise(a=>{o=setTimeout(()=>{a(void 0)},ue)});return Promise.race([r,n]).then(a=>(a===void 0&&x(r,void 0),a)).finally(()=>{clearTimeout(o)})}}class be extends U{relayAnnounced=!1;liveControlSeqs=new Map;pendingAnnounce;announceGeneration=0;pendingDetach;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,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:o}=this.host.readAttachment(e),n={args:q(t.args??{}),connectionId:o,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},a=await this.queueShapeControl(o,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 c;try{c=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(c.error!==void 0)return c.error;if(c.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await se(e);for(const l of c.frames)C(e,l);return this.recordRelayShapeMemo(e,s,c.cursor??0,c.epoch),"ok"}announce(){if(this.relayAnnounced||!this.canAddressSiblings())return Promise.resolve(!0);if(this.pendingAnnounce===void 0){const e=this.announceGeneration;this.pendingAnnounce=(this.pendingDetach??Promise.resolve()).then(async()=>O(this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_attach"}))).then(s=>{const t=s?.ok===!0;return e===this.announceGeneration&&(this.relayAnnounced=t),t}).finally(()=>{e===this.announceGeneration&&(this.pendingAnnounce=void 0)})}return this.pendingAnnounce}async announceDrain(e){if(this.host.getWebSockets().some(o=>o!==e&&this.isAdmitted(o))||(this.relayMemos().clear(),le(this.host.sql()),this.liveControlSeqs.clear(),!this.canAddressSiblings()))return;this.relayAnnounced=!1,this.announceGeneration+=1;const s=this.pendingAnnounce;this.pendingAnnounce=void 0;const t=this.pendingDetach,r=Promise.all([s?.catch(()=>!1),t]).then(async()=>O(this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_detach"}))).catch(()=>{}).finally(()=>{this.pendingDetach===r&&(this.pendingDetach=void 0)});this.pendingDetach=r,await r}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(){return!0}refusesAsIdle(){return this.host.getWebSockets().some(e=>this.isAdmitted(e))?!1:(this.relayAnnounced=!1,this.announceGeneration+=1,this.pendingAnnounce=void 0,!0)}onDetach(){return!0}async onLiveControl(e){const{connectionId:s,seq:t,subscriptionId:r}=e;if(t===void 0)return this.host.liveControl(e);const o=Date.now();for(const[d,R]of this.liveControlSeqs){if(o-R.appliedAt<=_e)break;this.liveControlSeqs.delete(d)}const n=`${s}\0${r}`,a=this.liveControlSeqs.get(n);if(a!==void 0&&t<a.seq)return Response.json({error:{code:"LIVE_CONTROL_SUPERSEDED",message:"a later live control call already applied"}},{status:409});const c={appliedAt:o,seq:t};this.liveControlSeqs.delete(n),this.liveControlSeqs.set(n,c);const l=await this.host.liveControl(e);return l.status===404&&this.liveControlSeqs.get(n)===c&&this.liveControlSeqs.delete(n),l}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),r={},o=()=>{this.shapeControl.get(e)===r.chain&&this.shapeControl.delete(e)},n=t.then(o,o);return r.chain=n,this.shapeControl.set(e,n),t}relayMemos(){return this.relayMemoCache===void 0&&(re(this.host.sql()),this.relayMemoCache=oe(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,r){const{connectionId:o}=this.host.readAttachment(e);o!==void 0&&(this.connectionMemos(o).set(s,{cursor:t,epoch:r}),N(this.host.sql(),[{connectionId:o,cursor:t,epoch:r,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),ie(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),ae(this.host.sql(),e,s)}deliverShapePoke(e){const s=E(e.name,e.args),t=[];let r=0,o=0;for(const n of this.host.getWebSockets()){const{connectionId:a,shapes:c}=this.host.readAttachment(n);if(c===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const l=this.pokeSocketShapes(n,c,this.connectionMemos(a),e,s);o+=l.matched.length,r+=l.sent;for(const d of l.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return N(this.host.sql(),t),{delivered:r,matched:o}}pokeSocketShapes(e,s,t,r,o){const n=[];let a=0;for(const[c,l]of Object.entries(s)){const d=t.get(c);if(E(l.name,l.args)!==o||!fe(d,r))continue;const y=D([{baseCheckpoint:d?.cursor,rowsPatch:r.rowsPatch,shapeId:c}],{baseCheckpoint:void 0,checkpoint:r.checkpoint,epoch:r.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(h=>C(e,h)).every(Boolean);t.set(c,{cursor:r.checkpoint,epoch:r.epoch}),n.push(c),y&&(a+=1)}return{matched:n,sent:a}}}const xe=i=>{const e=i.doName();if(e===void 0)return;const s=z(e);return s===void 0?new Ee(i,e):new be(i,s.ownerKey,s.relayIndex)};export{de as DEFAULT_MAX_RELAYS,Ee as OwnerRelay,be as RelayMember,xe as createRelayLink};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as _}from"./NotUniqueError-BR7jasrr.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-
|
|
1
|
+
import{createShardCtxDb as _}from"./NotUniqueError-BR7jasrr.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-B5swBl_q.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-CEZTl9LV.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.153",
|
|
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.74",
|
|
53
53
|
"@lunora/wire": "1.0.0-alpha.2",
|
|
54
54
|
"drizzle-orm": "1.0.0-rc.5"
|
|
55
55
|
},
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as Y,LunoraError as G}from"@lunora/errors";import{encodeWire as q,stableWireKey as _,decodeWire as g}from"@lunora/wire";import{sql as u}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as W}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{d as $,w as I,a as A,m as K,r as B,b as H,c as j}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as X,shapeRoutingKey as b,relayProxyKey as w,relayName as M,parseRelayName as z,clampPromotionThresholds as V}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{encodeRowsPatch as J,buildPokeFrames as D}from"./buildPokeFrames-WR-hp0mX.mjs";import{verifySiblingBody as Q,RELAY_SIGNATURE_HEADER as L,siblingStub as Z,siblingSecretOf as ee,signSiblingBody as te}from"./RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{awaitWsDrain as se,trySendFrame as C}from"./awaitWsDrain-N-oR29RI.mjs";const m="__lunora_relay_memos",re=i=>{S(i,u`CREATE TABLE IF NOT EXISTS ${u.identifier(m)} (
|
|
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
|
-
)`)},oe=i=>{const e=S(i,u`SELECT connection_id, sub_id, cursor, epoch FROM ${u.identifier(m)}`).toArray(),s=new Map;for(const t of e){let r=s.get(t.connection_id);r===void 0&&(r=new Map,s.set(t.connection_id,r)),r.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},ne=4,N=(i,e)=>{const s=Math.floor(W.boundParams/ne);for(let t=0;t<e.length;t+=s){const r=e.slice(t,t+s),o=u.join(r.map(n=>u`(${n.connectionId}, ${n.subId}, ${n.cursor}, ${n.epoch??null})`),u`, `);S(i,u`INSERT INTO ${u.identifier(m)} (connection_id, sub_id, cursor, epoch) VALUES ${o}
|
|
8
|
-
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},ae=(i,e,s)=>{S(i,u`DELETE FROM ${u.identifier(m)} WHERE connection_id = ${e} AND sub_id = ${s}`)},ie=(i,e)=>{S(i,u`DELETE FROM ${u.identifier(m)} WHERE connection_id = ${e}`)},le=i=>{S(i,u`DELETE FROM ${u.identifier(m)}`)},ce=2,he=8,de=2e3,ue=2e3,O=async i=>{let e;const s=new Promise(t=>{e=setTimeout(()=>{t(void 0)},ue)});return Promise.race([i,s]).finally(()=>{clearTimeout(e)})},E={},ye=i=>{throw new G("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},pe=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,x=i=>Response.json(i,{headers:{"content-type":"application/json"}}),fe=new Set(["relay_attach","relay_detach","relay_room_event","relay_shape_unsubscribe"]),Se=new Set(["relay_attach","relay_shape_subscribe"]),me=(i,e)=>{let s;try{s=JSON.parse(i)}catch{return}if(typeof s!="object"||s===null)return;const t=s,{relayIndex:r}=t;if(r===void 0?!fe.has(t.type):Number.isSafeInteger(r)&&r>=0&&(!Se.has(t.type)||r<e))return t},f=()=>new Response(null,{status:204}),k=(i,e)=>{i.then(async s=>s===e?void 0:s?.body?.cancel()).catch(()=>{})},Re=3e4,F=410,P=()=>new Response("stale relay frame",{status:409}),_e=i=>Math.max(Date.now()*1e3,i+1);class U{constructor(e,s){this.host=e,this.roleId=s}host;roleId;lastSequence=0;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await Q(this.host.env(),e.headers.get(L),s))return new Response("forbidden",{status:403});const t=me(s,this.maxRelays());if(t===void 0)return new Response("bad request",{status:400});if((t.type==="relay_frame"||t.type==="relay_live_frame"||t.type==="relay_shape_poke")&&this.refusesAsIdle())return new Response(void 0,{status:F});switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex,t.seq)?f():P();case"relay_detach":return this.onDetach(t.relayIndex,t.seq)?f():P();case"relay_frame":{const{exceptConnectionId:r}=t,o=r===void 0?void 0:this.host.getWebSockets().find(n=>this.host.readAttachment(n).connectionId===r);return this.host.deliverWhisperLocal(t.topic,t.frame,o),await this.onWhisperFrame(t),f()}case"relay_live_control":return this.onLiveControl(t.control);case"relay_live_frame":return this.host.deliverLiveLocal(t.topic,t.key,t.frame),f();case"relay_room_event":return x(await this.host.relayRoomEvent(t));case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),{delivered:n,matched:a}=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,n,Date.now()-o),n<a?Response.json({delivered:n,matched:a},{status:503}):f()}case"relay_shape_subscribe":return x(this.onShapeSubscribe({...t,args:g(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),f();default:return ye(t)}}maxRelays(){return v(this.host.env(),"LUNORA_MAX_RELAYS",he)}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()}nextRelaySeq(){return this.lastSequence=_e(this.lastSequence),this.lastSequence}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=ee(this.host.env());n!==void 0&&(o[L]=await te(n,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class ve extends U{shapeUniformCache=new Map;relaySetCache;liveGrantRelayCache;relayTablesReady=!1;relaySeqMarks=new Map;pendingSubscribeRelays=new Map;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s,t){if(!this.canAddressSiblings())return;const r=this.ownerRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{exceptConnectionId:t,frame:s,topic:e,type:"relay_frame"})))}forwardLiveControl(e){if(!this.canAddressSiblings())return Promise.resolve(void 0);const s={...e,seq:this.nextRelaySeq()},t=s.action==="unsubscribe"?new Set([...this.liveGrantRelaySet(),...this.pendingSubscribeRelays.keys()]):this.ownerRelaySet();if(t.size===0)return Promise.resolve(void 0);const r=[...t].map(o=>this.liveControlAnswer(o,s));return Promise.any(r.map(async o=>{const n=await o;if(n===void 0||n.status===404)throw new Error("relay does not hold the socket");return n})).catch(()=>{}).then(o=>{for(const n of r)k(n,o);return o})}async forwardLiveFrame(e,s,t){if(!this.canAddressSiblings())return;const r=this.liveGrantRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{frame:t,key:s,topic:e,type:"relay_live_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(!0)}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=v(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),t=v(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=X(this.promotionState,e,V(s,t)),this.promotionState==="owned")return 0;const r=v(this.host.env(),"LUNORA_RELAY_FAN",ce);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const r of[...e.values(),...s.values()])t=t===void 0?r.cursor:Math.min(t,r.cursor);return t}isShapeRelayUniform(e,s){const t=b(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,o),o}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:w(e.relayIndex,e.connectionId,e.subId);for(const[r,o]of s)o.relayIndex!==e.relayIndex||o.connectionId!==e.connectionId||(t===void 0||r===t)&&s.delete(r);$(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e,s){return this.recordRelaySeq(e,s),this.addRelayToSet(e),!0}onDetach(e,s){return this.acceptRelaySeq(e,s)?(this.removeRelayFromSet(e),!0):!1}refusesAsIdle(){return!1}onLiveControl(e){return this.host.liveControl(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.forwardToRelay(s,{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}relaySeqMark(e){if(this.relaySeqMarks.has(e))return this.relaySeqMarks.get(e);this.ensureRelayTables();const[s]=this.host.sql().exec("SELECT seq FROM __lunora_relay_seqs WHERE idx = ?",e).toArray(),t=s===void 0?void 0:Number(s.seq);return this.relaySeqMarks.set(e,t),t}recordRelaySeq(e,s){if(s===void 0)return;const t=this.relaySeqMark(e);(t===void 0||s>t)&&(this.host.sql().exec("INSERT OR REPLACE INTO __lunora_relay_seqs (idx, seq) VALUES (?, ?)",e,s),this.relaySeqMarks.set(e,s))}acceptRelaySeq(e,s){if(s===void 0)return!0;const t=this.relaySeqMark(e);return t!==void 0&&s<t?!1:(this.recordRelaySeq(e,s),!0)}buildShapePoke(e,s,t,r,o){if(e.table!==void 0&&!t.has(e.table))return;let n;try{n=this.host.resolveShape(e.name,e.args,s)}catch{return}if(n===void 0||n.global===!0)return;const a=e;if(a.table=n.table,!t.has(n.table))return;const c=a.cursor,l=this.host.buildShapeDiff(n,c,r);if(l.length!==0)return a.cursor=r,I(this.host.sql(),a.key,r),{args:q(e.args),checkpoint:r,epoch:o,fromCursor:c,name:e.name,rowsPatch:J(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const a of r.values()){const c=this.buildShapePoke(a,E,e,s,o);c&&n.push(this.multicastToRelays(t,c,a))}await Promise.all(n)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async o=>{const{dropped:n,response:a}=await this.requestDroppingIdle(o,s);return n||a?.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 r=this.host.currentCdcEpoch(),o=[];for(const n of t.values()){const a=this.buildShapePoke(n,n.identity,e,s,r);a&&o.push(this.proxyToRelay(a,n))}await Promise.all(o)}async proxyToRelay(e,s){const{dropped:t,response:r}=await this.requestDroppingIdle(s.relayIndex,{...e,targetConnectionId:s.connectionId});!t&&r?.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(h){const{body:p}=Y(h,{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:r,cursor:o,epoch:n,reset:a,rowsPatch:c}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let l=o;const{cohort:d,proxies:R}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=b(e.name,e.args);let p=d.get(h);p===void 0&&(p={args:e.args,cursor:o,key:h,name:e.name,table:t.table},d.set(h,p),A(this.host.sql(),p)),l=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=w(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:o,identity:s,key:h,name:e.name,relayIndex:e.relayIndex,table:t.table};R.set(h,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 y=D([{reset:a,rowsPatch:c,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:l,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:l,epoch:n,frames:y}}ensureRelayTables(){this.relayTablesReady||(this.relayTablesReady=!0,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_grants (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_seqs (idx INTEGER PRIMARY KEY, seq INTEGER NOT NULL)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),K(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 B(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,I(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}liveGrantRelaySet(){if(this.liveGrantRelayCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relay_grants").toArray();this.liveGrantRelayCache=new Set(e.map(s=>Number(s.idx)))}return this.liveGrantRelayCache}recordLiveGrantRelay(e){const s=this.liveGrantRelaySet();s.has(e)||(this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relay_grants (idx) VALUES (?)",e),s.add(e))}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}async forwardToRelay(e,s){await this.requestDroppingIdle(e,s)}async requestDroppingIdle(e,s){const t=this.relaySeqMark(e),r=await this.requestRelayMessage(M(this.roleId.ownerKey,e),s);return r?.status!==F||this.relaySeqMark(e)!==t?{dropped:!1,response:r}:(this.removeRelayFromSet(e),{dropped:!0,response:r})}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e),this.host.sql().exec("DELETE FROM __lunora_relay_grants WHERE idx = ?",e),this.liveGrantRelaySet().delete(e);const{cohort:t,proxies:r}=this.relayShapes();for(const[o,n]of r)n.relayIndex===e&&r.delete(o);H(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),j(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,E)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(l=>l.on==="read"&&l.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=_(t.effectiveWhere),o=_(t.columns);let n=!1;const a=l=>{const d={groups:[`grp_${l}`],roles:[l],sub:`__lunora_probe_${l}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${l}:${h}`,getOwnPropertyDescriptor:(y,h)=>(n=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(n=!0,Reflect.ownKeys(y))}),ip:`__lunora_probe_${l}__`,userId:`__lunora_probe_${l}__`}};return[E,a("a"),a("b")].every(l=>{let d;try{d=this.host.resolveShape(e,s,l)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&_(d.effectiveWhere)===r&&_(d.columns)===o})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}async liveControlAnswer(e,s){const t=s.action==="subscribe";t&&this.pendingSubscribeRelays.set(e,(this.pendingSubscribeRelays.get(e)??0)+1);const r=this.requestRelayMessage(M(this.roleId.ownerKey,e),{control:s,type:"relay_live_control"}).then(a=>(t&&a?.ok===!0&&this.recordLiveGrantRelay(e),a)).finally(()=>{if(!t)return;const a=(this.pendingSubscribeRelays.get(e)??1)-1;a===0?this.pendingSubscribeRelays.delete(e):this.pendingSubscribeRelays.set(e,a)});let o;const n=new Promise(a=>{o=setTimeout(()=>{a(void 0)},de)});return Promise.race([r,n]).then(a=>(a===void 0&&k(r,void 0),a)).finally(()=>{clearTimeout(o)})}}class be extends U{relayAnnounced=!1;liveControlSeqs=new Map;pendingAnnounce;announceGeneration=0;pendingDetach;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,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:o}=this.host.readAttachment(e),n={args:q(t.args??{}),connectionId:o,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},a=await this.queueShapeControl(o,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 c;try{c=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(c.error!==void 0)return c.error;if(c.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await se(e);for(const l of c.frames)C(e,l);return this.recordRelayShapeMemo(e,s,c.cursor??0,c.epoch),"ok"}announce(){if(this.relayAnnounced||!this.canAddressSiblings())return Promise.resolve(!0);if(this.pendingAnnounce===void 0){const e=this.announceGeneration;this.pendingAnnounce=(this.pendingDetach??Promise.resolve()).then(async()=>O(this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_attach"}))).then(s=>{const t=s?.ok===!0;return e===this.announceGeneration&&(this.relayAnnounced=t),t}).finally(()=>{e===this.announceGeneration&&(this.pendingAnnounce=void 0)})}return this.pendingAnnounce}async announceDrain(e){if(this.host.getWebSockets().some(o=>o!==e)||(this.relayMemos().clear(),le(this.host.sql()),this.liveControlSeqs.clear(),!this.canAddressSiblings()))return;this.relayAnnounced=!1,this.announceGeneration+=1;const s=this.pendingAnnounce;this.pendingAnnounce=void 0;const t=this.pendingDetach,r=Promise.all([s?.catch(()=>!1),t]).then(async()=>O(this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_detach"}))).catch(()=>{}).finally(()=>{this.pendingDetach===r&&(this.pendingDetach=void 0)});this.pendingDetach=r,await r}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(){return!0}refusesAsIdle(){return this.host.getWebSockets().length>0?!1:(this.relayAnnounced=!1,this.announceGeneration+=1,this.pendingAnnounce=void 0,!0)}onDetach(){return!0}async onLiveControl(e){const{connectionId:s,seq:t,subscriptionId:r}=e;if(t===void 0)return this.host.liveControl(e);const o=Date.now();for(const[d,R]of this.liveControlSeqs){if(o-R.appliedAt<=Re)break;this.liveControlSeqs.delete(d)}const n=`${s}\0${r}`,a=this.liveControlSeqs.get(n);if(a!==void 0&&t<a.seq)return Response.json({error:{code:"LIVE_CONTROL_SUPERSEDED",message:"a later live control call already applied"}},{status:409});const c={appliedAt:o,seq:t};this.liveControlSeqs.delete(n),this.liveControlSeqs.set(n,c);const l=await this.host.liveControl(e);return l.status===404&&this.liveControlSeqs.get(n)===c&&this.liveControlSeqs.delete(n),l}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),r={},o=()=>{this.shapeControl.get(e)===r.chain&&this.shapeControl.delete(e)},n=t.then(o,o);return r.chain=n,this.shapeControl.set(e,n),t}relayMemos(){return this.relayMemoCache===void 0&&(re(this.host.sql()),this.relayMemoCache=oe(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,r){const{connectionId:o}=this.host.readAttachment(e);o!==void 0&&(this.connectionMemos(o).set(s,{cursor:t,epoch:r}),N(this.host.sql(),[{connectionId:o,cursor:t,epoch:r,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),ie(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),ae(this.host.sql(),e,s)}deliverShapePoke(e){const s=b(e.name,e.args),t=[];let r=0,o=0;for(const n of this.host.getWebSockets()){const{connectionId:a,shapes:c}=this.host.readAttachment(n);if(c===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const l=this.pokeSocketShapes(n,c,this.connectionMemos(a),e,s);o+=l.matched.length,r+=l.sent;for(const d of l.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return N(this.host.sql(),t),{delivered:r,matched:o}}pokeSocketShapes(e,s,t,r,o){const n=[];let a=0;for(const[c,l]of Object.entries(s)){const d=t.get(c);if(b(l.name,l.args)!==o||!pe(d,r))continue;const y=D([{baseCheckpoint:d?.cursor,rowsPatch:r.rowsPatch,shapeId:c}],{baseCheckpoint:void 0,checkpoint:r.checkpoint,epoch:r.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(h=>C(e,h)).every(Boolean);t.set(c,{cursor:r.checkpoint,epoch:r.epoch}),n.push(c),y&&(a+=1)}return{matched:n,sent:a}}}const xe=i=>{const e=i.doName();if(e===void 0)return;const s=z(e);return s===void 0?new ve(i,e):new be(i,s.ownerKey,s.relayIndex)};export{he as DEFAULT_MAX_RELAYS,ve as OwnerRelay,be as RelayMember,xe as createRelayLink};
|