@lunora/runtime 1.0.0-alpha.300 → 1.0.0-alpha.302

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.
@@ -1 +0,0 @@
1
- import{toErrorBody as B}from"@lunora/errors";import{a as F,b as L}from"./base64-DANXv-kI.mjs";import{LunoraError as C}from"./LunoraError-PkZWF-_g.mjs";import{resolveShard as V}from"./applyJurisdiction-DKQE8kOA.mjs";const Re=r=>({listShardKeys(e){return r[e]??[]}}),_e=(r,e)=>({listShardKeys(s){if(r===void 0)throw new C(`cannot discover the shards of "${s}": the worker has no \`resolveTableSharding\` to tell a sharded table from a root one, and no shard registry is configured`,{code:"BAD_REQUEST",status:400});const o=r(s)?.mode.kind;if(o==="shardBy")throw new C(`cannot discover the shards of "${s}": it is \`.shardBy()\` and the worker has no shard registry — declare \`.shardRegistry((env) => env.SHARD_REGISTRY)\` on the app builder and bind \`SHARD_REGISTRY\` to \`ShardRegistryDO\` (or pass \`queryCoordinator\` to \`createWorker\`)`,{code:"BAD_REQUEST",status:400});return o==="global"?[]:[e]}}),x=16,D=5e3,y=r=>r!==null&&typeof r=="object"&&"result"in r?r.result:r,$=r=>{const e=r??{};return{changed:typeof e.changed=="number"?e.changed:0,processed:typeof e.processed=="number"?e.processed:0,status:typeof e.status=="string"?e.status:void 0}},H=(r,e)=>r?"failed":e?"in_progress":"completed",j=r=>{const e=[];let s=0,o=0,t=0,a=0,n=!1,c=!1;for(const d of r){if(d.kind==="err"){o+=1,e.push({error:{message:d.message,timedOut:d.timedOut},shardKey:d.shardKey});continue}s+=1;const i=y(d.value),u=$(i);t+=u.changed,a+=u.processed,n||=u.status==="in_progress",c||=u.status==="failed",e.push({result:i,shardKey:d.shardKey})}return{changed:t,failed:o,ok:s,processed:a,shards:e,status:H(c,n||o>0)}},G=r=>{const e=r??{};return{before:typeof e.before=="number"&&Number.isFinite(e.before)?e.before:0,total:typeof e.total=="number"&&Number.isFinite(e.total)?e.total:0}},J=r=>{const e=[];let s=0,o=0,t=0,a=0;for(const n of r){if(n.kind==="err"){o+=1,e.push({error:{message:n.message,timedOut:n.timedOut},shardKey:n.shardKey});continue}s+=1;const c=G(y(n.value));t+=c.before,a+=c.total,e.push({result:c,shardKey:n.shardKey})}return{failed:o,ok:s,partial:o>0,position:t+1,shards:e,total:a}},U=0,I=1,Y=2,K=(r,e)=>r<e?-1:r>e?1:0,E=r=>r==null?U:typeof r=="number"?I:Y,v=(r,e)=>{const s=E(r),o=E(e);return s!==o?s<o?-1:1:s===U?0:s===I?K(r,e):K(String(r),String(e))},Q=(r,e,s)=>{const o=v(r.partitionKey,e.partitionKey);if(o!==0)return o;const t=Math.max(r.sortValues.length,e.sortValues.length);for(let a=0;a<t;a+=1){const n=v(r.sortValues[a],e.sortValues[a]);if(n!==0)return s[a]==="desc"?-n:n}return v(r.rowId,e.rowId)},W=r=>L(new TextEncoder().encode(JSON.stringify(r))),X=r=>{try{const e=JSON.parse(new TextDecoder().decode(F(r)));if(e!==null&&typeof e=="object"&&"perShard"in e){const{perShard:s}=e;if(s!==null&&typeof s=="object")return{perShard:s}}}catch{}return{perShard:{}}},z=r=>{const e=r??{},s=Array.isArray(e.rows)?e.rows:[];return{directions:Array.isArray(e.directions)?e.directions:[],hasMore:e.hasMore===!0,rows:s}},Z=(r,e)=>{let s;for(const o of r){const t=o.rows[o.head];t!==void 0&&(s===void 0||Q(t.key,s.row.key,e)<0)&&(s={row:t,slice:o})}return s},q=(r,e)=>{let s=!1;const o=new Set;for(const a of r)o.add(a.shardKey),(a.head<a.rows.length||a.hasMore)&&(s=!0);const t={...e};for(const a of Object.keys(e))o.has(a)||(s=!0);return s?W({perShard:t}):null},ee=(r,e,s,o)=>{const t=[],a={...o};for(;t.length<e;){const c=Z(r,s);if(c===void 0)break;t.push(c.row.doc),a[c.slice.shardKey]=c.row.key,c.slice.head+=1}const n=q(r,a);return{isDone:n===null,nextCursor:n,page:t}},re=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({error:{message:t.message,timedOut:t.timedOut},shardKey:t.shardKey});continue}s+=1;const a=y(t.value),n=Array.isArray(a?.rows)?a.rows:[];e.push({rows:n,shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},te=r=>{const e=[];let s=0,o=0;for(const{outcome:t,sinceEpoch:a,sinceSeq:n}of r){if(t.kind==="err"){o+=1,e.push({cursor:n,error:{code:t.code,message:t.message,timedOut:t.timedOut},shardKey:t.shardKey,...a===void 0?{}:{epoch:a}});continue}s+=1;const c=y(t.value),d=Array.isArray(c?.changes)?c.changes:[],i=typeof c?.cursor=="number"?c.cursor:n,u=typeof c?.epoch=="string"&&c.epoch.length>0?c.epoch:a;e.push({changes:d,cursor:i,shardKey:t.shardKey,...u===void 0?{}:{epoch:u}})}return{failed:o,ok:s,shards:e}},se=r=>{let e=0,s=0,o=0;for(const t of r){if(t.kind==="err"){s+=1;continue}e+=1;const a=y(t.value);o+=typeof a?.applied=="number"?a.applied:0}return{applied:o,failed:s,ok:e}},oe=r=>{const e=r??{};return typeof e.requests=="number"&&Number.isFinite(e.requests)&&e.requests>=0?e.requests:0},ne=r=>{const e=[];let s=0,o=0;for(const t of r){if(t.kind==="err"){o+=1,e.push({requests:0,shardKey:t.shardKey});continue}s+=1,e.push({requests:oe(y(t.value)),shardKey:t.shardKey})}return{failed:o,ok:s,shards:e}},ae=r=>{const e=[],s={},o=[];let t=0,a=0,n=0,c=0,d=0;for(const i of r){if(i.kind==="err"){d+=1,e.push({error:{message:i.message,timedOut:i.timedOut},shardKey:i.shardKey});continue}c+=1;const u=y(i.value),l=u?.inserted??{};for(const[m,S]of Object.entries(l))s[m]=(s[m]??0)+S;const h=u?.errors;Array.isArray(h)&&o.push(...h),t+=u?.conflicts??0,a+=u?.deleted??0,n+=u?.replaced??0,e.push({result:{conflicts:u?.conflicts??0,deleted:u?.deleted??0,errors:u?.errors??[],inserted:l,replaced:u?.replaced??0},shardKey:i.shardKey})}return{conflicts:t,deleted:a,errors:o,failed:d,inserted:s,ok:c,replaced:n,shards:e}},P=new WeakMap,Ae=(r,e)=>{P.set(r,e)},ve=async r=>{const e=P.get(r);return e===void 0?r:e(r)},p=r=>({body:JSON.stringify({args:r.args??{},functionPath:r.functionPath}),headers:{"content-type":"application/json",...r.headers},refresh:r.headers===void 0?void 0:P.get(r.headers)}),ce=async r=>{try{const s=(await r.json())?.error;return typeof s?.code!="string"||s.code.length===0?void 0:{code:s.code,message:typeof s.message=="string"?s.message:""}}catch{return}},g=async(r,e,s,o)=>{const t=V(r,e),a=new AbortController;let n;const c=new Promise(i=>{n=setTimeout(()=>{try{a.abort()}catch{}i({code:"SHARD_TIMEOUT",kind:"err",message:`shard "${e}" timed out after ${String(o)}ms`,shardKey:e,timedOut:!0})},o)}),d=(async()=>{try{const i=new Request("https://shard.internal/rpc",{body:s.body,headers:s.refresh===void 0?s.headers:await s.refresh(s.headers),method:"POST",signal:a.signal}),u=await t.fetch(i);if(!u.ok){const h=await ce(u),m=`shard "${e}" returned ${String(u.status)}`;return{code:h?.code??"SHARD_HTTP_ERROR",kind:"err",message:h===void 0||h.message.length===0?m:`${m}: ${h.message}`,shardKey:e,timedOut:!1}}const l=await u.json();return{kind:"ok",shardKey:e,value:l}}catch(i){const{body:u}=B(i,{fallbackCode:"INTERNAL",redactedMessage:"shard call failed"});return{code:u.code,kind:"err",message:`shard "${e}" failed: ${u.message}`,shardKey:e,timedOut:!1}}})();try{return await Promise.race([d,c])}finally{n!==void 0&&clearTimeout(n)}},w=async(r,e,s)=>{if(r.length===0)return[];const o=Array.from({length:r.length});let t=0;const a=async()=>{for(;;){const c=t;t+=1;const d=r[c];if(c>=r.length||d===void 0)return;o[c]=await s(d,c)}},n=Math.min(e,r.length);return await Promise.all(Array.from({length:n},()=>a())),o},b=(r,e)=>r.length>0||e===null?r:[e],O=async(r,e,s)=>{const o=await Promise.all(e.map(async t=>b(await r.listShardKeys(t),s)));return[...new Set(o.flat())]},k=async(r,e,s,o,t)=>{const a=p(s);return w(e,o,async n=>g(r,n,a,t))},ie=r=>{const e={};for(const s of Object.keys(r).toSorted(K))e[s]=r[s]??null;return JSON.stringify(e)},de=r=>r.flatMap(e=>Array.isArray(e)?e:[]),ue=(r,e,s)=>{switch(s){case"max":return Math.max(r,e);case"min":return Math.min(r,e);case"sum":return r+e;default:return r}},le=(r,e,s)=>{if(e===null||typeof e!="object")return;const o=e.key??{},t=e.value??null,a=ie(o),n=r.get(a);if(!n){r.set(a,{key:o,value:t});return}if(n.value===null){n.value=t;return}t!==null&&(n.value=ue(n.value,t,s))},he=(r,e)=>{const s=new Map;for(const o of r)if(Array.isArray(o))for(const t of o)le(s,t,e);return[...s.values()]},M=(r,e)=>{let s=null;for(const o of r)typeof o=="number"&&Number.isFinite(o)&&(s=s===null?o:e(s,o));return s},fe=r=>{let e=0;for(const s of r)typeof s=="number"&&Number.isFinite(s)&&(e+=s);return e},ye=r=>{let e=0,s=0;for(const o of r){if(o===null||typeof o!="object")continue;const t=o;typeof t.before=="number"&&Number.isFinite(t.before)&&(e+=t.before),typeof t.total=="number"&&Number.isFinite(t.total)&&(s+=t.total)}return{position:e+1,total:s}},me=(r,e,s)=>{let o=0,t=r.length;for(;o<t;){const a=Math.floor((o+t)/2),n=r[a];n!==void 0&&s(e,n)<0?t=a:o=a+1}return o},pe=(r,e,s)=>{const o=[];for(const t of r){const a=me(o,t,s);a<e&&(o.splice(a,0,t),o.length>e&&o.pop())}return o},ge=(r,e)=>{const s=[];for(const n of r)if(Array.isArray(n))for(const c of n){if(c===null||typeof c!="object")continue;const d=c[e.by],i=typeof d=="number"&&Number.isFinite(d)?d:Number.NEGATIVE_INFINITY;s.push({row:c,score:i})}const o=e.direction??"desc",t=(n,c)=>o==="asc"?K(n.score,c.score):K(c.score,n.score),{k:a}=e;return!Number.isInteger(a)||a<0||2*a>=s.length?(s.sort(t),s.slice(0,a).map(n=>n.row)):pe(s,a,t).map(n=>n.row)},we=(r,e)=>{switch(e.kind){case"concat":return de(r);case"first":return r[0];case"groupBy":return he(r,e.op??"sum");case"max":return M(r,Math.max);case"min":return M(r,Math.min);case"rank":return ye(r);case"sum":return fe(r);case"topK":return ge(r,e);default:return r}},N=(r,e)=>(Array.isArray(e)?e:[]).filter(s=>typeof s=="string").map(s=>({shardKey:r,table:s})),Oe=async(r,e,s)=>{const o=new Map,t=await Promise.all(s.tables.map(async i=>({keys:await r.listShardKeys(i),table:i})));for(const{keys:i,table:u}of t)for(const l of i)o.set(l,[...o.get(l)??[],u]);const a=await w([...o],x,async([i,u])=>({outcome:await g(e,i,p({args:{dryRun:s.dryRun===!0,tables:u},functionPath:"__lunora_admin__:releaseShardRegistration",headers:s.headers}),D),tables:u})),n=[],c=[],d=[];for(const{outcome:i,tables:u}of a){if(i.kind==="err"){n.push({message:i.message,shardKey:i.shardKey,tables:u});continue}const l=y(i.value)??{};c.push(...N(i.shardKey,l.kept)),d.push(...N(i.shardKey,l.released))}if(s.dryRun!==!0)for(const i of new Set(d.map(u=>u.table)))r.invalidate?.(i);return{failed:n,kept:c,released:d}},Ce=r=>{const e=r.maxConcurrency??x,s=r.perShardTimeoutMs??D;if(e<1)throw new C("maxConcurrency must be >= 1",{code:"BAD_REQUEST",status:400});return{async fanOut(o,t){const a=await r.registry.listShardKeys(t.fanOut.table),n=await k(o,a,t,e,s),c=[],d=[];for(const i of n)i.kind==="ok"?c.push(i.value):d.push({code:i.code,message:i.message,shardKey:i.shardKey,timedOut:i.timedOut});return{data:we(c,t.fanOut.merge),errors:d,failed:d.length,ok:c.length}},async orchestrateExport(o,t){const a=await O(r.registry,t.tables,t.defaultShardKey),n=b(a,t.defaultShardKey),c={args:{...t.args,tables:[...t.tables]},functionPath:"__lunora_admin__:exportShard",headers:t.headers},d=await k(o,n,c,e,s);return re(d)},async orchestrateCdcSync(o,t){const a=b(await O(r.registry,t.tables,t.defaultShardKey),t.defaultShardKey),n=t.cursors??{},c=t.epochs??{},d=await w(a,e,async i=>{const u=n[i]??0,l=c[i];return{outcome:await g(o,i,p({args:{limit:t.limit,sinceEpoch:l,sinceSeq:u},functionPath:"__lunora_admin__:cdcSync",headers:t.headers}),s),sinceEpoch:l,sinceSeq:u}});return te(d)},async orchestrateImport(o,t){const{batches:a}=t,n=async(d,i)=>g(o,d,p({args:i,functionPath:"__lunora_admin__:importShard",headers:t.headers}),s),c=await w(a,e,async d=>{if(t.dryRun===!0){const i=await n(d.shardKey,{dryRun:!0,rows:[],startLine:1});if(i.kind==="err")return i;if(y(i.value)?.dryRun!==!0)return{code:"SHARD_DRY_RUN_UNSUPPORTED",kind:"err",message:`shard "${d.shardKey}" cannot check rows without writing them`,shardKey:d.shardKey,timedOut:!1}}return n(d.shardKey,{deletes:t.deletes===!0,dryRun:t.dryRun===!0,onConflict:t.onConflict??"skip",rows:[...d.rows],startLine:d.startLine??1})});return ae(c)},async orchestrateImportSession(o,t){return(await w(t.calls,e,async n=>g(o,n.shardKey,p({args:n.args,functionPath:t.functionPath,headers:t.headers}),s))).map(n=>n.kind==="err"?{error:{code:n.code,message:n.message,timedOut:n.timedOut},shardKey:n.shardKey}:{shardKey:n.shardKey,value:y(n.value)})},async orchestrateApplyCdc(o,t){const{batches:a}=t,n=await w(a,e,async c=>g(o,c.shardKey,p({args:{changes:[...c.changes]},functionPath:"__lunora_admin__:applyCdc",headers:t.headers}),s));return se(n)},async orchestrateMigration(o,t){const a=b(await r.registry.listShardKeys(t.table),t.defaultShardKey),n=await k(o,a,t,e,s);return j(n)},async orchestrateRank(o,t){const a=await r.registry.listShardKeys(t.table),n={args:{index:t.index,partitionKey:t.partitionKey,rowId:t.rowId,sortValues:[...t.sortValues],table:t.table},functionPath:"__lunora_admin__:rankBefore",headers:t.headers},c=await k(o,a,n,e,s);return J(c)},async orchestrateRankPage(o,t){const a=await r.registry.listShardKeys(t.table),n=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),c=t.directions??[],d=t.cursor?X(t.cursor):{perShard:{}},i=await w(a,e,async f=>{const T=d.perShard[f],_={index:t.index,table:t.table,take:n};t.partitionKey!==void 0&&(_.partitionKey=t.partitionKey),T!==void 0&&(_.after=T);const R=await g(o,f,p({args:_,functionPath:"__lunora_admin__:rankPage",headers:t.headers}),s);if(R.kind==="err")return{error:{message:R.message,timedOut:R.timedOut},shardKey:f};const A=z(y(R.value));return{directions:A.directions,hasMore:A.hasMore,rows:A.rows,shardKey:f}}),u=[];let l=0,h=0,m;for(const f of i){if(f.error){h+=1;continue}l+=1,m===void 0&&f.directions&&f.directions.length>0&&(m=f.directions),u.push({hasMore:f.hasMore??!1,head:0,rows:f.rows??[],shardKey:f.shardKey})}const S=ee(u,n,m??c,d.perShard);return{continueCursor:S.nextCursor,failed:h,isDone:S.isDone,ok:l,page:S.page,partial:h>0,shards:i}},async orchestrateShardTraffic(o,t){const a=await r.registry.listShardKeys(t.table),n={functionPath:"__lunora_admin__:getMetrics",headers:t.headers},c=await k(o,a,n,e,s);return ne(c)},registry:r.registry,async shardKeysForTables(o,t){return b(await O(r.registry,o,t),t)}}};export{_e as createDefaultShardRegistry,Ce as createQueryCoordinator,Re as createStaticShardRegistry,Oe as pruneShardRegistry,Ae as refreshShardHeadersPerCall,ve as refreshedShardHeaders};