@lunora/shard-engine 1.0.0-alpha.93 → 1.0.0-alpha.95
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 +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-DE3r3jrY.mjs → ADMIN_FUNCTIONS-D5mzmLFo.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-DaRHrce8.mjs → AGG_COUNT-DNnEXtyM.mjs} +1 -1
- package/dist/packem_shared/{AUDIT_LOG_TABLE-CMhmmmgR.mjs → AUDIT_LOG_TABLE-CZNxCRLv.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-Bkv7JskR.mjs → CDC_LOG_TABLE-QaBxSIZM.mjs} +1 -1
- package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-DPY-NtOH.mjs → CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs} +1 -1
- package/dist/packem_shared/{COMMIT_SEQ_FIELD-6lGDFLgk.mjs → COMMIT_SEQ_FIELD-BY_vc9bw.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-mUH4b2lA.mjs → DATA_MIGRATION_STATE_TABLE-BS6X-_Uu.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-B1zeutIo.mjs → DEFAULT_MAX_RELATION_KEYS-D_Urjl_L.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-CSb6oGUZ.mjs → DEFAULT_MAX_RELAYS-DnAAv8zm.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-k4x__lMt.mjs → DurableStreamRunner-C4SbxTDz.mjs} +1 -1
- package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-BpFE-qYL.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs} +1 -1
- package/dist/packem_shared/{IDEMPOTENCY_TABLE-CUc9L-o_.mjs → IDEMPOTENCY_TABLE-AOJCuq5U.mjs} +1 -1
- package/dist/packem_shared/{MAIL_RETENTION-kYNWpCbY.mjs → MAIL_RETENTION-BxAGL3hK.mjs} +1 -1
- package/dist/packem_shared/{NotUniqueError-Cnw4ctAu.mjs → NotUniqueError-CYBVrJib.mjs} +1 -1
- package/dist/packem_shared/{QUEUE_TABLE-D-5_s2hl.mjs → QUEUE_TABLE-DKANxmEZ.mjs} +1 -1
- package/dist/packem_shared/{REACTOR_STATE_TABLE-XAIYdVL0.mjs → REACTOR_STATE_TABLE-B8IehLv8.mjs} +1 -1
- package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-wAAIitt2.mjs → SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-CYVBglZe.mjs → SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs} +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-BlVsBsix.mjs → SEARCH_STATE_TABLE-wgl-SePe.mjs} +1 -1
- package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-BVskv7ei.mjs → SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs} +1 -1
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-TviV2Xnr.mjs → VECTOR_BACKFILL_MAX_PAGES-jQVe2NO6.mjs} +1 -1
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs +1 -0
- package/dist/packem_shared/appendStreamChunk-y5mkpRdi.mjs +17 -0
- package/dist/packem_shared/{archiveCdcSegment-CMAVUCck.mjs → archiveCdcSegment-BON69Nug.mjs} +1 -1
- package/dist/packem_shared/{backfillAggregateIndexes-DBY2H269.mjs → backfillAggregateIndexes-D5q_pbdY.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-Do3UTuDO.mjs → buildReprojectionMigration-IMrfRdvU.mjs} +1 -1
- package/dist/packem_shared/{buildShapeDiff-B5YzZbjX.mjs → buildShapeDiff-D-J_GmC1.mjs} +1 -1
- package/dist/packem_shared/{clearMemoryTables-BCDG0X9P.mjs → clearMemoryTables-CogAvVHR.mjs} +1 -1
- package/dist/packem_shared/compileWhereSql-DLfUbHc-.mjs +1 -0
- package/dist/packem_shared/{computeRankPage-BEyDlhws.mjs → computeRankPage-BosAhREj.mjs} +1 -1
- package/dist/packem_shared/{createCompanionSync-uTsHTJWE.mjs → createCompanionSync-BpE0xoMp.mjs} +1 -1
- package/dist/packem_shared/createReplicaLink-Z82FMxvY.mjs +7 -0
- package/dist/packem_shared/{ctx-db-relay-shapes-DBRHlvNu.mjs → ctx-db-relay-shapes-CClD3ldv.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-search-state-z0OqNIGe.mjs → ctx-db-search-state-DVCp4JQf.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-Dsx4iWIy.mjs → defineEngineContractSuite-6k3JzatE.mjs} +1 -1
- package/dist/packem_shared/{do-sql-DpyjVz_6.mjs → do-sql-BEFrJUds.mjs} +1 -1
- package/dist/packem_shared/{exportShardRows-BFpaZI99.mjs → exportShardRows-CTDgQEF8.mjs} +1 -1
- package/dist/packem_shared/{fts-companion-DcGBHZiM.mjs → fts-companion-pUdD6kF-.mjs} +1 -1
- package/dist/packem_shared/{ftsCompanionDdl-BaLv81YG.mjs → ftsCompanionDdl-Co6WSyCB.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-LAXWNkhC.mjs → isSoftDeleted-sGRSPPQq.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-CTCrmga8.mjs → materializeExternalRows-DhINQHwd.mjs} +1 -1
- package/dist/packem_shared/{runDrizzle-BlpM0R9P.mjs → runDrizzle-Du5HLitO.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-BtAyuuJb.mjs → runShardMigrations-DvjE3byP.mjs} +1 -1
- package/dist/packem_shared/{selectExpiredIds-BVZtw3Wb.mjs → selectExpiredIds-DQg6v5Uf.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-DTA3YUf4.mjs → selectShapeMembers-BXhvEt4X.mjs} +1 -1
- package/dist/packem_shared/where-sql-DFs8Zw7-.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/WORKERD_SQLITE_LIMITS-DlozcSQu.mjs +0 -1
- package/dist/packem_shared/appendStreamChunk-BRwBOTEN.mjs +0 -19
- package/dist/packem_shared/compileWhereSql-Bi04r4ut.mjs +0 -1
- package/dist/packem_shared/createReplicaLink-D_kkf5IG.mjs +0 -7
- package/dist/packem_shared/where-sql-BV8Kg4_B.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-
|
|
1
|
+
import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";const f=200,u=(o,n)=>{const i=r=>{const e=o.tables[r];return e!==void 0&&e.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(o.tables)).filter(r=>i(r))},p=async function*(o,n,i=f){let r=null,e=!1;for(;!e;){const t=await o.findMany(n,{cursor:r,includeDeleted:!0,limit:i});for(const s of t.page)yield{doc:s,table:n};r=t.continueCursor,e=t.isDone||r===null}},O=async function*(o,n,i){const r=u(n,i.tables),e=i.batchSize??f;for(const t of r)yield*p(o,t,e)},y=new Set(["_creationTime","_id"]),h=(o,n)=>{for(const[i,r]of Object.entries(o.shape)){const e=n[i];if(e===void 0&&r.kind==="optional")continue;const t=r.parse;if(typeof t=="function")try{t(e)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},m=(o,n,i)=>{const r=o.tables[n];if(!r)return`unknown table: ${n}`;if(r.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const e=Object.fromEntries(Object.entries(i).filter(([t])=>!y.has(t)));for(const t of Object.keys(e))if(!Object.hasOwn(r.shape,t))return`unexpected field "${t}": not declared in table "${n}"`;return h(r,e)},g=async(o,n,i)=>{try{if(o.lookupById){const r=await o.lookupById(i);return r===null?void 0:r.tableName}return await o.get(i,n)===null?void 0:n}catch{return}},w=o=>l in o?Object.fromEntries(Object.entries(o).filter(([n])=>n!==l)):o,S=async(o,n,i,r)=>{const{table:e}=i;let{doc:t}=i;if(typeof e!="string"||e.length===0)return{error:{code:"BAD_ROW",line:r,message:"row is missing `table`",table:e},kind:"error"};if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:r,message:"row is missing or malformed `doc`",table:e},kind:"error"};t=w(t);const s=m(n,e,t);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:r,message:s,table:e},kind:"error"};const c=typeof t._id=="string"?t._id:void 0;if(c!==void 0){const a=await g(o,e,c);if(a===e)return{kind:"conflict"};if(a!==void 0)return{error:{code:"ID_COLLISION",line:r,message:`_id "${c}" already belongs to table "${a}"`,table:e},kind:"error"}}try{return await o.insert(e,t,{allowExplicitId:!0}),{kind:"inserted",table:e}}catch(a){const{body:d}=b(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:r,message:d.message,table:e},kind:"error"}}},v=async(o,n,i)=>{const r=[],e={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await S(o,n,c,s);a.kind==="error"?r.push(a.error):a.kind==="conflict"?t+=1:e[a.table]=(e[a.table]??0)+1}return{conflicts:t,errors:r,inserted:e}},E=o=>{const n=Array.isArray(o.tables)?o.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof o.batchSize=="number"?o.batchSize:void 0,tables:n}},I=o=>{const n=Array.isArray(o.rows)?o.rows:[],i=[];for(const e of n){if(!e||typeof e!="object")continue;const t=e;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const r=typeof o.startLine=="number"?o.startLine:void 0;return{rows:i,startLine:r}};export{O as exportShardRows,v as importShardRows,E as parseExportShardArgs,I as parseImportShardArgs,u as selectExportTables,m as validateImportRow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{D as I}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import{D as I}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";const u=(i,t)=>{if(!t.includes("."))return i[t];let r=i;for(const $ of t.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[$]}return r},D=(i,t)=>`${i}__fts_${t}`,o="__text__",s="__id__",A=1e3,O=(i,t)=>t.document(i),N=(i,t)=>u(i,t),_=i=>typeof i=="string"?i:i==null?"":typeof i=="number"||typeof i=="bigint"||typeof i=="boolean"?String(i):JSON.stringify(i)??"",w=(i,t,r)=>i!==void 0&&t!==void 0&&N(i,r.field)===N(t,r.field),c=(i,t)=>O(_(N(i,t.field)),I(t.language)).slice(0,A),M=(i,t)=>c(i,t).join(" "),a=50,n="__rowid__",T=i=>`${i}__ids`,E=(i,t)=>e`${e.identifier(i)}.${e.identifier(t)}`,S=(i,t,{guard:r,unmappedRowids:$})=>{const d=T(i),f=r===void 0?e``:e` AND ${r}`,R=$===void 0?e`${E(i,"rowid")} > 0`:L(E(i,"rowid"),$,!1,a);return[e`DELETE FROM ${e.identifier(i)} WHERE ${R} AND CAST(${E(i,s)} AS TEXT) = ${t}${f}`,e`DELETE FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = (SELECT ${E(d,n)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}) AND ${E(i,s)} = ${t}${f}`]},U=i=>[e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(i)} USING fts5(${e.identifier(o)}, ${e.identifier(s)} UNINDEXED)`,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${i}__vocab`)} USING fts5vocab(${e.identifier(i)}, ${e.raw("instance")})`,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T(i))} (${e.identifier(n)} INTEGER PRIMARY KEY, ${e.identifier(s)} TEXT NOT NULL UNIQUE)`,e`INSERT INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT 0, '', '' WHERE NOT EXISTS (SELECT 1 FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = 0)`],F=(i,t,r,$={})=>{const d=T(i),f=$.guard===void 0?e``:e` AND ${$.guard}`,R=e`MIN(COALESCE((SELECT MIN(${E(d,n)}) FROM ${e.identifier(d)}), 0), 0) - 1`;return[...S(i,t,$),e`INSERT OR REPLACE INTO ${e.identifier(d)} (${e.identifier(n)}, ${e.identifier(s)}) SELECT ${R}, ${t} WHERE 1 = 1${f}`,e`INSERT OR REPLACE INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT ${E(d,n)}, ${r}, ${E(d,s)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}${f}`]},y=(i,t,r={})=>{const $=T(i),d=r.guard===void 0?e``:e` AND ${r.guard}`;return[...S(i,t,r),e`DELETE FROM ${e.identifier($)} WHERE ${E($,s)} = ${t}${d}`]},W=(i,t,r=0)=>e`SELECT ${E(i,"rowid")} AS ${e.identifier("rowid")}, ${E(i,s)} AS ${e.identifier("id")} FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} > ${e.param(Math.max(0,r))} AND ${E(i,s)} IS NOT NULL ORDER BY ${E(i,"rowid")} ASC LIMIT ${e.raw(String(t))}`,b=i=>{const t=new Map;for(const r of i){const $=String(r.id);t.set($,[...t.get($)??[],Number(r.rowid)])}return t};export{w as N,D as S,y as a,T as b,W as c,F as d,M as e,U as f,b as g,c as h,s as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-
|
|
1
|
+
import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-pUdD6kF-.mjs";import"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";export{t as ftsCompanionDdl,e as ftsPurgeDocument,p as ftsRowidMapName,m as ftsUnmappedPage,f as ftsWriteDocument,n as groupUnmappedRows};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-Du5HLitO.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-DhINQHwd.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BXhvEt4X.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as e}from"./WORKERD_SQLITE_LIMITS-
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{renderSql as l,WORKERD_SQLITE_LIMITS as e}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";const c=(t,n,...r)=>{if(n.length*3>e.sqlTextLength){const s=new TextEncoder().encode(n).length;if(s>e.sqlTextLength)throw new i("INTERNAL",`SQL statement is ${String(s)} bytes, over this runtime's ${String(e.sqlTextLength)}-byte limit`)}if(r.length>e.boundParams)throw new i("INTERNAL",`SQL statement binds ${String(r.length)} parameters, over this runtime's limit of ${String(e.boundParams)}`);return t.exec.call(t,n,...r)},u=(t,n)=>{const{params:r,sql:o}=l("sqlite",n);return c(t,o,...r)},d=(t,n)=>{for(const r of n)u(t,r)},g=t=>t??null,S=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{S as decodeJsonColumn,g as orNull,d as runAll,u as runDrizzle,c as runSql};
|
package/dist/packem_shared/{runShardMigrations-BtAyuuJb.mjs → runShardMigrations-DvjE3byP.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-pUdD6kF-.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-D5q_pbdY.mjs";import{migrateCdcLog as x,migrateCdcMeta as N}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{migrateGlobalShapeSnapshot as b}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{migrateIdempotency as D}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{m as U}from"./ctx-db-relay-shapes-CClD3ldv.mjs";import{migrateScheduleOutbox as M}from"./SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{m as G}from"./ctx-db-search-state-DVCp4JQf.mjs";import{migrateShapePokeCursor as X}from"./SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{runDrizzle as s,runAll as y}from"./runDrizzle-Du5HLitO.mjs";import{D as F,d as E,e as g,t as P,i as Y,g as k,a as B,b as j,A as p}from"./do-sql-BEFrJUds.mjs";import{renderSql as v}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{migrateDurableStreams as w}from"./appendStreamChunk-y5mkpRdi.mjs";import{rankTableName as H,sortColumnName as K}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{migrateReactorState as W}from"./REACTOR_STATE_TABLE-B8IehLv8.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";const A=r`_creationTime, id`,S=(e,i,o,t,n,a)=>{const c=r.join(n.map(d=>r`${d} IS NOT NULL`),r` AND `);if(s(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new l("INTERNAL",`unique index "${i}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(e,i,o,t,n,a)=>{const m=s(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const u=_.indexOf("(");return u===-1?void 0:_.slice(u,_.lastIndexOf(")")+1)},T=d(v("sqlite",E(i,o,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&S(e,i,o,t,a,"cannot be re-created with its new column list"),s(e,r`DROP INDEX IF EXISTS ${r.identifier(i)}`))},J=(e,i,o)=>s(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,i,o,t,n,a)=>{n&&!J(e,i,o)&&S(e,i,o,t,a,"cannot be created"),s(e,E(i,o,t,n))},Q=(e,i,o)=>{for(const t of o.indexes){const n=`${i}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=r.join(c,r`, `),d=a?m:r`${m}, ${A}`;z(e,n,i,d,a,c),I(e,n,i,d,a,c)}for(const[t,n]of P(o)){if(!n.unique)continue;const a=g(t);I(e,`${i}_unique_${t}`,i,a,!0,[a])}},Z=(e,i,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!Y(e))){for(const t of o.searchIndexes)y(e,L(h(i,t.name)));R(e,i,o)}},q=(e,i,o)=>{if(o.geoIndexes)for(const t of o.geoIndexes){const n=k(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${i}__geo_${t.name}__btree`;s(e,E(a,n,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},ee=(e,i,o)=>{if(o.aggregateIndexes)for(const t of o.aggregateIndexes){const n=O(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${B} TEXT PRIMARY KEY, ${j} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),s(e,r`PRAGMA table_info(${r.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(e,r`ALTER TABLE ${r.identifier(n)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},re=(e,i,o)=>{if(o.rankIndexes)for(const t of o.rankIndexes){const n=H(i,t.name),a=t.sortBy.map((f,_)=>K(_)),c=a.map(f=>r`${r.identifier(f)} BLOB`),m=c.length>0?r`, ${r.join(c,r`, `)}`:r``;s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const u=t.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(u==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${i}__rank_${t.name}__btree`;s(e,E(T,n,r.join(d,r`, `),!1))}},he=(e,i,o={})=>{o.schemaSnapshot!==void 0&&V(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),G(e);for(const[t,n]of Object.entries(i.tables))n.shardMode?.kind!=="global"&&(s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${r.identifier(F)} TEXT NOT NULL
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-Du5HLitO.mjs";import{e}from"./do-sql-BEFrJUds.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
|
package/dist/packem_shared/{selectShapeMembers-DTA3YUf4.mjs → selectShapeMembers-BXhvEt4X.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-Du5HLitO.mjs";import{D as p,r as d,e as h}from"./do-sql-BEFrJUds.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{c as S}from"./where-sql-DFs8Zw7-.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-BbZ5hKM7.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{sqliteInList as d,isJsonSafe as E,bytesAsHexJson as _,WORKERD_SQLITE_LIMITS as $}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{quoteIdentifier as x}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as L}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const y={binary:(t,n,s)=>e`${t} ${e.raw(n)} ${s}`,constant:t=>t?e`1 = 1`:e`0 = 1`,connect:(t,n,s)=>e`(${t}) ${e.raw(s)} (${n})`,contains:(t,n)=>e`instr(lower(${t}), lower(${n})) > 0`,inList:(t,n,s,o)=>d(t,n,s,o),negate:t=>e`NOT (${t})`,nullCheck:(t,n)=>n?e`${t} IS NOT NULL`:e`${t} IS NULL`,value:t=>e`${t}`},h=(...t)=>{let n="";const s=[];for(const o of t)typeof o=="string"?n+=o:(n+=o.text,s.push(...o.params));return{params:s,text:n}},f=t=>({params:[t],text:"?"}),b=t=>({params:[],text:t}),Y=t=>b(x(t)),H={binary:(t,n,s)=>h(t," ".concat(n," "),f(s)),constant:t=>b(t?"1 = 1":"0 = 1"),connect:(t,n,s)=>h("(",t,") ".concat(s," ("),n,")"),contains:(t,n)=>h("instr(lower(",t,"), lower(",n,")) > 0"),inList:(t,n,s,o)=>{const i=s?" NOT IN ":" IN ",r=n.every(l=>E(l)),c=n.length>o&&!r?_(n):void 0;if(c!==void 0)return h(t,i,'(SELECT unhex("value") FROM json_each(',f(c),"))");if(n.length>o&&!r)throw new T("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);if(n.length<=o){const l=[t,i,"("];for(const[a,u]of n.entries())a>0&&l.push(", "),l.push(f(u));return l.push(")"),h(...l)}return h(t,i,'(SELECT "value" FROM json_each(',f(JSON.stringify(n)),"))")},negate:t=>h("NOT (",t,")"),nullCheck:(t,n)=>h(t,n?" IS NOT NULL":" IS NULL"),value:f},C=$.boundParams/2,I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],w=new Set(I),j={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},A=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return!1;const n=Object.keys(t);return n.length>0&&n.every(s=>w.has(s))},U=(t,n,s,o,i)=>{const r=i.value(o.serialize(s,t));return o.containsExpr?o.containsExpr(n,r):i.contains(n,r)},v=(t,n,s,o,i,r,c)=>i===null?s==="eq"||s==="ne"?c.nullCheck(n,s==="ne"):c.constant(!1):c.binary(n,o,r.serialize(i,t)),M=(t,n,s,o,i,r)=>{if(!Array.isArray(o))throw new T("BAD_REQUEST",`\`${s==="IN"?"in":"notIn"}\` on "${t}" expects an array of values, received ${o===null?"null":typeof o}`);const c=o;if(c.length===0)return r.constant(s==="NOT IN");const l=c.map(u=>i.serialize(u,t)),a=s==="NOT IN";return i.inList?i.inList(n,l,a):r.inList(n,l,a,C)},O=$.boundParams/2,D=6e4,F=(t,n)=>{const s={bytes:[],hasNull:!1,numbers:[],strings:[]};for(const o of t)if(o===null)s.hasNull=!0;else if(o instanceof Uint8Array)s.bytes.push(Array.from(o,i=>i.toString(16).padStart(2,"0")).join(""));else if(typeof o=="number"&&E(o))s.numbers.push(o);else if(typeof o=="string"&&E(o))s.strings.push(o);else throw new T("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value that cannot be bound as one parameter (a non-finite number, or malformed text). Narrow the list to ${String(n)} values or fewer.`);return s},P=(t,n,s)=>{const o=[],i=e.identifier("v"),r=e.identifier("__in__"),c=a=>e`jsonb_array_elements_text(CAST(CAST(${JSON.stringify(a)} AS text) AS jsonb))`,l=(a,u)=>e`JSON_TABLE(${JSON.stringify(a)}, '$[*]' COLUMNS (${i} ${e.raw(u)} PATH '$')) ${r}`;return s.strings.length>0&&o.push(t==="postgres"?e`${n} IN (SELECT ${c(s.strings)})`:e`${n} IN (SELECT CONVERT(${i} USING utf8mb4) FROM ${l(s.strings,"LONGTEXT")})`),s.numbers.length>0&&o.push(t==="postgres"?e`${n} IN (SELECT CAST(${c(s.numbers)} AS double precision))`:e`${n} IN (SELECT ${i} FROM ${l(s.numbers,"DOUBLE")})`),s.bytes.length>0&&o.push(t==="postgres"?e`${n} IN (SELECT decode(${c(s.bytes)}, 'hex'))`:e`${n} IN (SELECT UNHEX(${i}) FROM ${l(s.bytes,"LONGTEXT")})`),o},W=t=>(n,s,o,i=O)=>{const r=Math.floor(D*i/O);if(s.length<=r){const u=e.join(s.map(p=>e`${p}`),e`, `);return o?e`${n} NOT IN (${u})`:e`${n} IN (${u})`}const c=F(s,r);if(o&&c.hasNull)return e`1 = 0`;const l=P(t,n,c);if(l.length===0)return e`1 = 0`;const a=l.length===1?l[0]:e`(${e.join(l,e` OR `)})`;return o?e`NOT (${a})`:a},k=(t,n,s,o,i)=>{const r=s,c=[];for(const l of I){if(!(l in r))continue;const a=r[l],u=j[l];u?c.push(v(t,n,l,u,a,o,i)):l==="isNull"?c.push(i.nullCheck(n,!a)):l==="contains"?c.push(U(t,n,a,o,i)):c.push(M(t,n,l==="in"?"IN":"NOT IN",a,o,i))}return c},B=(t,n,s,o)=>{const i=s.fieldRef(t);return A(n)?k(t,i,n,s,o):n===null?[o.nullCheck(i,!1)]:[o.binary(i,"=",s.serialize(n,t))]},N=(t,n,s)=>{if(t.length<=1)return t[0];const o=Math.floor(t.length/2);return s.connect(N(t.slice(0,o),n,s),N(t.slice(o),n,s),n)},g=(t,n,s,o)=>{const i=Array.isArray(t)?t:[],r=[];for(const c of i){const l=S(c??{},s,o);if(l!==void 0)r.push(l);else if(n==="OR")return}return r.length===0?n==="OR"?o.constant(!1):void 0:N(r,n,o)},q=new Set(["AND","NOT","OR",L]),z=(t,n,s,o)=>{if(t===L){if(!s.relationExists)throw new T("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return s.relationExists(n)}if(t==="NOT"){const i=S(n??{},s,o);return i===void 0?o.constant(!1):o.negate(i)}return g(n,t,s,o)},S=(t,n,s)=>{const o=[];for(const[i,r]of Object.entries(t))if(q.has(i)){const c=z(i,r,n,s);c!==void 0&&o.push(c)}else o.push(...B(i,r,n,s));return N(o,"AND",s)},m=t=>{let n=0,s=0;const o=i=>{const r=m(i);n+=r.lists,s+=r.scalars};if(Array.isArray(t)){for(const i of t)o(i);return{lists:n,scalars:s}}if(t===null||typeof t!="object")return{lists:n,scalars:s};for(const[i,r]of Object.entries(t))i==="in"||i==="notIn"?n+=1:i==="AND"||i==="NOT"||i==="OR"||A(r)?o(r):s+=1;return{lists:n,scalars:s}},V=(t,n,s=y,o=0)=>{if(!t||Object.keys(t).length===0)return;const{lists:i,scalars:r}=m(t);if(i===0)return S(t,n,s);const c=Math.max(1,Math.floor(Math.min(O,$.boundParams-r-o)/i)),l=n.inList??((a,u,p,R)=>s.inList(a,u,p,R??c));return S(t,{...n,inList:(a,u,p)=>l(a,u,p,c)},s)};export{V as c,Y as i,h as j,b as r,W as s,H as t};
|
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.95",
|
|
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",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.46",
|
|
52
52
|
"@lunora/platform": "1.0.0-alpha.41",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{MySqlDialect as S}from"drizzle-orm/mysql-core";import{PgDialect as p}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as u}from"drizzle-orm/sqlite-core";const f=new p,m=new S,L=new u,d={mysql:m,postgres:f,sqlite:L},l={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},h=l.boundParams/2,E=e=>e===null||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.isWellFormed(),D=(e,n)=>{const{params:r,sql:o}=d[e].sqlToQuery(n);return{params:r,sql:o}},I=e=>t`${e}`,N=e=>{if(e.length===0)throw new Error("unionAll: expected at least one branch");let n=[...e];for(;n.length>l.compoundSelect;){const r=[];for(let o=0;o<n.length;o+=l.compoundSelect){const s=t.join(n.slice(o,o+l.compoundSelect),t` UNION ALL `);r.push(t`SELECT * FROM (${s}) ${t.identifier("__u__")}`)}n=r}return t.join(n,t` UNION ALL `)},w=(e,n,r,o=h)=>{const s=r?t` NOT IN `:t` IN `,a=n.every(i=>E(i));if(n.length>o&&!a)throw new c("BAD_REQUEST",`an "in" list of ${String(n.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(n.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return n.length<=o?t`${e}${s}(${t.join(n.map(i=>I(i)),t`, `)})`:t`${e}${s}(SELECT ${t.identifier("value")} FROM json_each(${JSON.stringify(n)}))`};export{l as WORKERD_SQLITE_LIMITS,E as isJsonSafe,I as param,D as renderSql,w as sqliteInList,N as unionAll};
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-BlpM0R9P.mjs";const a="__stream_runs",o="__stream_chunks",N=r=>{E(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(a)} (
|
|
2
|
-
run_key TEXT PRIMARY KEY,
|
|
3
|
-
status TEXT NOT NULL,
|
|
4
|
-
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
5
|
-
error_code TEXT,
|
|
6
|
-
error TEXT,
|
|
7
|
-
started_at REAL NOT NULL,
|
|
8
|
-
ttl_ms REAL NOT NULL
|
|
9
|
-
)`),E(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (
|
|
10
|
-
run_key TEXT NOT NULL,
|
|
11
|
-
seq INTEGER NOT NULL,
|
|
12
|
-
data_json TEXT NOT NULL,
|
|
13
|
-
PRIMARY KEY (run_key, seq)
|
|
14
|
-
)`)},_=(r,t)=>{const s=E(r,e`SELECT status, last_seq, error_code, error, started_at FROM ${e.identifier(a)} WHERE run_key = ${t} LIMIT 1`).toArray()[0];if(s!==void 0)return{...s.error===null?{}:{error:s.error},...s.error_code===null?{}:{errorCode:s.error_code},lastSeq:s.last_seq,startedAt:s.started_at,status:s.status}},i=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(o)} WHERE run_key = ${t}`)},S=(r,t,n,s)=>_(r,t)!==void 0?!1:(i(r,t),E(r,e`INSERT INTO ${e.identifier(a)} (run_key, status, last_seq, started_at, ttl_ms)
|
|
15
|
-
VALUES (${t}, ${"running"}, 0, ${n}, ${s})`),!0),m=(r,t)=>{i(r,t),E(r,e`DELETE FROM ${e.identifier(a)} WHERE run_key = ${t}`)},$=(r,t,n,s)=>{E(r,e`INSERT OR IGNORE INTO ${e.identifier(o)} (run_key, seq, data_json) VALUES (${t}, ${n}, ${s})`)},c=(r,t,n)=>E(r,e`SELECT seq, data_json FROM ${e.identifier(o)} WHERE run_key = ${t} AND seq > ${n} ORDER BY seq ASC`).toArray().map(s=>({dataJson:s.data_json,seq:s.seq})),A=(r,t,n,s,T)=>{if(_(r,t)===void 0){i(r,t);return}const d=T?.code??null,R=T?.message??null;E(r,e`UPDATE ${e.identifier(a)}
|
|
16
|
-
SET status = ${n}, last_seq = ${s}, error_code = ${d}, error = ${R}
|
|
17
|
-
WHERE run_key = ${t}`)},O=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(o)} WHERE run_key IN (
|
|
18
|
-
SELECT run_key FROM ${e.identifier(a)} WHERE started_at + ttl_ms < ${t}
|
|
19
|
-
)`),E(r,e`DELETE FROM ${e.identifier(a)} WHERE started_at + ttl_ms < ${t}`)};export{o as STREAM_CHUNKS_TABLE,a as STREAM_RUNS_TABLE,$ as appendStreamChunk,S as claimStreamRun,m as deleteStreamRun,A as finishStreamRun,N as migrateDurableStreams,c as readStreamChunks,_ as readStreamRun,O as trimStreamRuns};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{c as o,l as t}from"./where-sql-BV8Kg4_B.mjs";import"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";export{o as compileWhereSql,t as literalInList};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-Bkv7JskR.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-BkL5cTCc.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
|
|
2
|
-
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
-
epoch TEXT NOT NULL,
|
|
4
|
-
applied_seq INTEGER NOT NULL,
|
|
5
|
-
synced_at REAL NOT NULL
|
|
6
|
-
)`),l.add(s))},c=s=>(_(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${d} WHERE id = 1`).toArray()[0]),f=(s,e)=>{_(s),s.exec(`INSERT INTO ${d} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
|
|
7
|
-
ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},q=s=>{const e=s.doName();if(e!==void 0&&R(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(s.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(E(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},a=s=>Response.json(S(s)),P=async(s,e)=>{if(s.rowCount()>F(s.env()))return a({cursor:0,epoch:e,rows:[],truncated:!0});const t=s.ownerCursor()??0,r=await s.exportRows();return a({cursor:t,epoch:e,rows:r})},x=(s,e,t)=>{const r=s.ownerFloor();if(y(r,t))return a({changes:[],cursor:s.ownerCursor()??t,epoch:e,floor:r});const o=s.ownerCursor()??0;if(t>o)return a({changes:[],cursor:o,epoch:e,...r===void 0?{}:{floor:r}});const{changes:n,cursor:i}=s.readChanges(t,w);return a({changes:n,cursor:i,epoch:e,...r===void 0?{}:{floor:r}})},K=async(s,e)=>{const t=q(s);if(t!==void 0)return t;const r=s.ownerEpoch();let o;try{o=await e.text()}catch{return new Response("bad request",{status:400})}if(!await A(s.env(),e.headers.get(g),o))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(o)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap")return P(s,r);if(n.type==="replica_pull"){const i=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0;return x(s,r,i)}return new Response("unknown replica frame",{status:400})};class M{constructor(e,t,r){this.host=e,this.ownerKey=t,this.region=r}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return c(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=c(this.host.sql());if(t===void 0){const r=await this.bootstrap();if(r===void 0)return"unavailable";t=r}return this.catchUp(t,e)}isCaughtUp(e){const t=c(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let r=e;for(let o=0;o<C;o+=1){const n=await this.pull(r.appliedSeq);if(n===void 0)return t===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,n))return"unavailable";const i=n.changes.length<w;if(r=await this.applyPage(n),i||this.isFreshEnough(r,t))return this.isFreshEnough(r,t)?"fresh":"stale"}return this.isFreshEnough(r,t)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const t={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),t),t}hasDiverged(e,t){const r=t.changes.length===0&&t.cursor>e.appliedSeq,o=t.floor??(r?t.cursor:0),n=o>0&&o>e.appliedSeq+1,i=t.cursor<e.appliedSeq;return t.epoch===e.epoch&&!n&&!i?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=p(await e.json());if(t.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(t.rows);if(r.length>0){this.divergent=!0;return}const o={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),o),o}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=v(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",m)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:p(await t.json())}async request(e){const t=this.host.shardBinding(),r=N(this.host.env(),t,this.ownerKey,this.host.shardJurisdiction());if(r===void 0)return;const o=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":t??""},i=E(this.host.env());i!==void 0&&(n[g]=await T(i,o));try{const u=await r.fetch("https://replica.internal/_lunora/replica",{body:o,headers:n,method:"POST"});return u.ok?u:void 0}catch{return}}}const j=s=>{const e=s.doName();if(e===void 0)return;const t=R(e);return t===void 0?void 0:new M(s,t.ownerKey,t.region)},G=async(s,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const r=await s.ensureFresh(I(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{j as createReplicaLink,G as gateReplicaDispatch,K as handleReplicaControl};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{sqliteInList as R,isJsonSafe as $,WORKERD_SQLITE_LIMITS as L}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as I}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const x={binary:(n,t,o)=>l`${n} ${l.raw(t)} ${o}`,constant:n=>n?l`1 = 1`:l`0 = 1`,connect:(n,t,o)=>l`(${n}) ${l.raw(o)} (${t})`,contains:(n,t)=>l`instr(lower(${n}), lower(${t})) > 0`,inList:(n,t,o,s)=>R(n,t,o,s),negate:n=>l`NOT (${n})`,nullCheck:(n,t)=>t?l`${n} IS NOT NULL`:l`${n} IS NULL`,value:n=>l`${n}`},p=(...n)=>{let t="";const o=[];for(const s of n)typeof s=="string"?t+=s:(t+=s.text,o.push(...s.params));return{params:o,text:t}},h=n=>({params:[n],text:"?"}),S=n=>({params:[],text:n}),Q=n=>S(m(n)),G={binary:(n,t,o)=>p(n," ".concat(t," "),h(o)),constant:n=>S(n?"1 = 1":"0 = 1"),connect:(n,t,o)=>p("(",n,") ".concat(o," ("),t,")"),contains:(n,t)=>p("instr(lower(",n,"), lower(",t,")) > 0"),inList:(n,t,o,s)=>{const i=o?" NOT IN ":" IN ";if(t.length>s&&!t.every(r=>$(r)))throw new T("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(s)} values or fewer.`);if(t.length<=s){const r=[n,i,"("];for(const[e,c]of t.entries())e>0&&r.push(", "),r.push(h(c));return r.push(")"),p(...r)}return p(n,i,'(SELECT "value" FROM json_each(',h(JSON.stringify(t)),"))")},negate:n=>p("NOT (",n,")"),nullCheck:(n,t)=>p(n,t?" IS NOT NULL":" IS NULL"),value:h},_=L.boundParams/2,E=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],j=new Set(E),w={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},b=n=>{if(n===null||typeof n!="object"||Array.isArray(n))return!1;const t=Object.keys(n);return t.length>0&&t.every(o=>j.has(o))},y=(n,t,o,s,i)=>{const r=i.value(s.serialize(o,n));return s.containsExpr?s.containsExpr(t,r):i.contains(t,r)},C=(n,t,o,s,i,r,e)=>i===null?o==="eq"||o==="ne"?e.nullCheck(t,o==="ne"):e.constant(!1):e.binary(t,s,r.serialize(i,n)),D=(n,t,o,s,i,r)=>{if(!Array.isArray(s))throw new T("BAD_REQUEST",`\`${o==="IN"?"in":"notIn"}\` on "${n}" expects an array of values, received ${s===null?"null":typeof s}`);const e=s;if(e.length===0)return r.constant(o==="NOT IN");const c=e.map(u=>i.serialize(u,n)),a=o==="NOT IN";return i.inList?i.inList(t,c,a):r.inList(t,c,a,_)},J=(n,t,o)=>{const s=l.join(t.map(i=>l`${i}`),l`, `);return o?l`${n} NOT IN (${s})`:l`${n} IN (${s})`},U=(n,t,o,s,i)=>{const r=o,e=[];for(const c of E){if(!(c in r))continue;const a=r[c],u=w[c];u?e.push(C(n,t,c,u,a,s,i)):c==="isNull"?e.push(i.nullCheck(t,!a)):c==="contains"?e.push(y(n,t,a,s,i)):e.push(D(n,t,c==="in"?"IN":"NOT IN",a,s,i))}return e},k=(n,t,o,s)=>{const i=o.fieldRef(n);return b(t)?U(n,i,t,o,s):t===null?[s.nullCheck(i,!1)]:[s.binary(i,"=",o.serialize(t,n))]},f=(n,t,o)=>{if(n.length<=1)return n[0];const s=Math.floor(n.length/2);return o.connect(f(n.slice(0,s),t,o),f(n.slice(s),t,o),t)},M=(n,t,o,s)=>{const i=Array.isArray(n)?n:[],r=[];for(const e of i){const c=N(e??{},o,s);if(c!==void 0)r.push(c);else if(t==="OR")return}return r.length===0?t==="OR"?s.constant(!1):void 0:f(r,t,s)},P=new Set(["AND","NOT","OR",I]),q=(n,t,o,s)=>{if(n===I){if(!o.relationExists)throw new T("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return o.relationExists(t)}if(n==="NOT"){const i=N(t??{},o,s);return i===void 0?s.constant(!1):s.negate(i)}return M(t,n,o,s)},N=(n,t,o)=>{const s=[];for(const[i,r]of Object.entries(n))if(P.has(i)){const e=q(i,r,t,o);e!==void 0&&s.push(e)}else s.push(...k(i,r,t,o));return f(s,"AND",o)},v=L.boundParams/2,A=n=>{let t=0,o=0;const s=i=>{const r=A(i);t+=r.lists,o+=r.scalars};if(Array.isArray(n)){for(const i of n)s(i);return{lists:t,scalars:o}}if(n===null||typeof n!="object")return{lists:t,scalars:o};for(const[i,r]of Object.entries(n))i==="in"||i==="notIn"?t+=1:i==="AND"||i==="NOT"||i==="OR"||b(r)?s(r):o+=1;return{lists:t,scalars:o}},W=(n,t,o=x,s=0)=>{if(!n||Object.keys(n).length===0)return;const{lists:i,scalars:r}=A(n);if(i===0)return N(n,t,o);const e=Math.max(1,Math.floor(Math.min(v,L.boundParams-r-s)/i)),c=t.inList??((a,u,O,d)=>o.inList(a,u,O,d??e));return N(n,{...t,inList:(a,u,O)=>c(a,u,O,e)},o)};export{W as c,Q as i,p as j,J as l,S as r,G as t};
|