@lunora/platform-node 1.0.0-alpha.221 → 1.0.0-alpha.222
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +220 -150
- package/dist/index.d.ts +220 -150
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{NODE_SCHEDULER_DISPATCH_PATH-uDl0zU2t.mjs → NODE_SCHEDULER_DISPATCH_PATH-DmMrAPjT.mjs} +1 -1
- package/dist/packem_shared/bindShardSockets-DjLmRlIA.mjs +1 -0
- package/dist/packem_shared/checkNodeAppHost-Cv5p7igg.mjs +1 -0
- package/dist/packem_shared/createNodeDurableObjectFactory-hAwJt_pN.mjs +1 -0
- package/dist/packem_shared/{createNodePlatform-BqtVmQqS.mjs → createNodePlatform-De8dIBya.mjs} +1 -1
- package/dist/packem_shared/createNodeShardHost-DZ2cwIKF.mjs +1 -0
- package/dist/packem_shared/createNodeShardRegistry-D1r6M8Rg.mjs +1 -0
- package/dist/packem_shared/node-dispatch-route-B3GAZkHT.mjs +2 -0
- package/package.json +3 -3
- package/dist/packem_shared/bindShardSockets-9GvSocBW.mjs +0 -1
- package/dist/packem_shared/createNodeShardHost-VU8MPeba.mjs +0 -1
- package/dist/packem_shared/createNodeShardRegistry-C1SRJQhd.mjs +0 -1
- package/dist/packem_shared/node-dispatch-route-ByuCR26s.mjs +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{toErrorResponse as u,resolveShard as l}from"@lunora/runtime";import{s as f}from"./hmac-url-Bogwm7I6.mjs";const c=(t,e)=>{const n=Math.max(t.length,e.length);let o=t.length^e.length;for(let a=0;a<n;a+=1){const r=a<t.length?t.charCodeAt(a):0,s=a<e.length?e.charCodeAt(a):0;o|=r^s}return o===0},E="/_lunora/scheduler/dispatch",g="__lunora_relation__:",_=t=>t.startsWith(g),h="agents:agentRun",y=(t,e,n)=>t===h&&e!==n,S=`\`${h}\` runs on the default shard only, where agent threads live; to run an agent's tools on another shard, start it from a mutation on that shard with \`ctx.agents.<name>.run\``,A=(t,e)=>{if(!e||e.length===0)return!1;const n=t.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:c(e,a.join(" ").trim())},w="x-lunora-scheduler-signature",m="x-lunora-scheduler-timestamp",p=5*6e4,D=t=>["v1",String(t.timestamp),t.userId??"",t.identity??"",t.body].join(`
|
|
2
|
+
`),T=(t,e)=>f(t,D(e)),R=async(t,e,n)=>{const o=t.headers.get(w),{schedulerSecret:a}=n;if(o!==null&&o.length>0&&a!==void 0&&a.length>0){const r=t.headers.get(m);if(r===null||!/^\d+$/u.test(r))return!1;const s=Number(r);if(!Number.isSafeInteger(s)||Math.abs((n.now??Date.now)()-s)>p)return!1;const d=await T(a,{body:e,identity:t.headers.get("x-lunora-identity")??void 0,timestamp:s,userId:t.headers.get("x-lunora-userid")??void 0});return c(d,o)}return A(t,n.adminToken)},N=async(t,e)=>{if(!t.body)return"";const n=t.body.getReader(),o=new TextDecoder;let a=0,r="";for(;;){const{done:s,value:d}=await n.read();if(s)break;if(d){if(a+=d.byteLength,a>e)return await n.cancel().catch(()=>{}),null;r+=o.decode(d,{stream:!0})}}return r+=o.decode(),r},I="x-lunora-paywall",P="1",v="x-lunora-scheduled-for",L=({forwardedIdentity:t,mutationId:e,scheduledFor:n,traceparent:o})=>{const a={"content-type":"application/json",[I]:P,"x-lunora-system":"1"};return t?.userId!==void 0&&t.userId.length>0&&(a["x-lunora-userid"]=t.userId),t?.identity!==void 0&&t.identity.length>0&&(a["x-lunora-identity"]=t.identity),e!==void 0&&e.length>0&&(a["x-lunora-mutation-id"]=e),o!==void 0&&o.length>0&&(a.traceparent=o),n!==void 0&&Number.isFinite(n)&&(a[v]=String(Math.trunc(n))),a},O=t=>{const e=t.headers.get("x-lunora-userid"),n=t.headers.get("x-lunora-identity");if(!(e===null&&n===null))return{...n===null?{}:{identity:n},...e===null?{}:{userId:e}}},C=1048576,H=async t=>{const e=await N(t,C);if(e===null)throw new i("PAYLOAD_TOO_LARGE","Scheduler dispatch body is too large");return e},U=async(t,e)=>{if(t.method!=="POST")throw new i("METHOD_NOT_ALLOWED","Scheduler dispatch endpoint requires POST",{status:405});const n=await H(t);if(!await R(t,n,{adminToken:e.adminToken,now:e.now,schedulerSecret:e.schedulerSecret}))throw new i("DISPATCH_UNAUTHENTICATED","Scheduler dispatch requires a valid signature or admin bearer");let a;try{a=JSON.parse(n)}catch{throw new i("BAD_REQUEST","Scheduler dispatch body must be valid JSON")}const r=a??{};if(typeof r.workflow=="string"||r.pool!==void 0)throw new i("SERVICE_UNAVAILABLE","Scheduler dispatch for a workflow or pool target is not served by the Node dispatch route");if(typeof r.functionPath!="string"||r.functionPath.length===0)throw new i("BAD_REQUEST","Scheduler dispatch is missing `functionPath`");if(_(r.functionPath))throw new i("FORBIDDEN","`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard");const s=typeof r.shardKey=="string"&&r.shardKey.length>0?r.shardKey:e.defaultShardKey;if(y(r.functionPath,s,e.defaultShardKey))throw new i("BAD_REQUEST",S);return e.invoke({args:r.args??{},functionPath:r.functionPath,id:typeof r.id=="string"&&r.id.length>0?r.id:void 0,identity:O(t),scheduledFor:typeof r.scheduledFor=="number"?r.scheduledFor:void 0,shardKey:s,traceparent:t.headers.get("traceparent")??void 0})},B=(t,e)=>n=>{if(!e)throw new i("SERVICE_UNAVAILABLE","@lunora/platform-node: the dispatch route needs `onFetch` to run a function; without it a shard only echoes its key");const o=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n.args,functionPath:n.functionPath}),headers:L({forwardedIdentity:n.identity,mutationId:n.id,scheduledFor:n.scheduledFor,traceparent:n.traceparent}),method:"POST"});return l(t,n.shardKey).fetch(o)},k=t=>async e=>{try{return await U(e,t)}catch(n){return u(n)}},M=E;export{S as A,M as N,B as a,k as c,y as i};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/platform-node",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.222",
|
|
4
4
|
"description": "Node implementation of the Lunora platform contracts: ShardHost, SocketHost, ShardDirectory, ShardKvStore, SchedulerHost over better-sqlite3 and an in-process socket registry (dev/test target)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"better-sqlite3",
|
|
@@ -48,8 +48,8 @@
|
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"@lunora/d1": "^1.0.0-alpha.237",
|
|
50
50
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
51
|
-
"@lunora/mail": "^1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "^1.0.0-alpha.
|
|
51
|
+
"@lunora/mail": "^1.0.0-alpha.140",
|
|
52
|
+
"@lunora/platform": "^1.0.0-alpha.82",
|
|
53
53
|
"@lunora/queue": "^1.0.0-alpha.144",
|
|
54
54
|
"@lunora/runtime": "^1.0.0-alpha.292",
|
|
55
55
|
"@lunora/scheduler": "^1.0.0-alpha.171",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const l=t=>({acceptWebSocket:(e,a)=>{t.sockets.accept(e,void 0,a)},blockConcurrencyWhile:e=>t.shard.runSerialized(e),getWebSockets:e=>t.sockets.getSockets(e),id:{name:t.shardKey},storage:{delete:e=>t.kv.delete(e),deleteAlarm:async()=>{await t.shard.alarms.delete()},get:e=>t.kv.get(e),getAlarm:async()=>t.shard.alarms.get(),list:e=>t.kv.list(e),put:(e,a)=>t.kv.put(e,a),setAlarm:async e=>{await t.shard.alarms.set(e)},sql:{get databaseSize(){return t.shard.sql.databaseSize},exec:(e,...a)=>t.shard.sql.exec(e,...a)},transaction:e=>t.shard.transaction(e)},waitUntil:e=>{t.shard.waitUntil?.(e)},openSocketPair:()=>t.sockets.newPair(),upgradeResponse:e=>t.sockets.upgradeResponse(e)}),i=(t,e)=>{const a=async(s,o)=>{await t.webSocketMessage(s,o)};e.onMessage((s,o)=>{a(s,o).catch(c=>{console.error("[lunora] webSocketMessage threw:",c)})}),e.onClose(async(s,o,c,r)=>{try{await t.webSocketClose(s,o,c,r)}catch(n){console.error("[lunora] webSocketClose threw:",n)}})};export{i as bindShardSockets,l as createNodeShardState};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{AsyncLocalStorage as H}from"node:async_hooks";import{LunoraError as X}from"@lunora/errors";import j from"better-sqlite3";import{p as J}from"./prepared-statement-3XBQZXtC.mjs";const G=2147483647,K=6,F=100,Z=4,N=10,b=r=>r===void 0?null:r,ee=(r,s)=>({get databaseSize(){const p=r.pragma("page_count",{simple:!0}),u=r.pragma("page_size",{simple:!0});return p*u},exec:(p,...u)=>{s("run SQL");const c=J(r,p),y=u.map(i=>b(i)),o=c.reader&&c.readonly;let n;const f=()=>(n===void 0&&(s("run SQL"),c.reader?n=c.all(...y):(c.run(...y),n=[])),n);o||f();const d=function*(){s("run SQL"),c.raw(!0);try{yield*c.iterate(...y)}finally{c.raw(!1)}};return{get columnNames(){return c.reader?c.columns().map(i=>i.name):void 0},[Symbol.iterator]:()=>f()[Symbol.iterator](),one:()=>{const i=f();if(i.length!==1)throw new Error(`expected exactly one row, got ${String(i.length)}`);return i[0]},...o?{raw:d}:{},toArray:()=>[...f()]}}}),re=(r,s,p,u,c=()=>{},y=()=>{})=>{let o,n,f=!1,d=0,i;r.exec("CREATE TABLE IF NOT EXISTS _lunora_alarm (id INTEGER PRIMARY KEY CHECK (id = 0), scheduled_for INTEGER NOT NULL)");const O=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0"),M=r.prepare("INSERT INTO _lunora_alarm (id, scheduled_for) VALUES (0, ?) ON CONFLICT (id) DO UPDATE SET scheduled_for = excluded.scheduled_for"),w=r.prepare("INSERT INTO _lunora_alarm (id, scheduled_for) VALUES (0, ?) ON CONFLICT (id) DO NOTHING"),R=r.prepare("SELECT scheduled_for FROM _lunora_alarm WHERE id = 0"),L=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0 AND scheduled_for = ?"),S=e=>{e===void 0?O.run():M.run(e)},z=e=>w.run(e).changes>0,C=e=>L.run(e).changes>0;let g=!1,m;const E=new Set;let T,t=0;const l=()=>{n!==void 0&&(clearTimeout(n),n=void 0),g=!1},v=e=>{n=setTimeout(()=>{n=void 0,g=!1,e()},N),g=!0},I=()=>{const e=R.get();e!==void 0&&(o=e.scheduled_for,A(e.scheduled_for))},W=(e,a,_=t)=>{if(!r.open||o!==void 0||_!==t){e();return}if(r.inTransaction){E.add({retry:()=>{D(e,a,_)},settle:e}),T??=setTimeout(k,N);return}if(d+=1,d>K){d=0,e();return}const h=Date.now()+F*2**(d-1);if(z(h)){o=h,A(h),e();return}d=0,I(),e()},D=(e,a,_=t,h=0)=>{const B=d;try{W(e,a,_)}catch(q){if(d=B,r.open&&h+1<Z){E.add({retry:()=>{D(e,a,_,h+1)},settle:e}),T??=setTimeout(k,F*2**h);return}const U=new Date(a).toISOString();console.error("[@lunora/platform-node] the retry of the alarm due %s on shard %s could not be written after %d attempts, so that alarm is lost",U,u??"(unnamed)",h+1,q),y(`shard ${u??"(unnamed)"}: the retry of the alarm due ${U} could not be written`),e()}},k=()=>{if(T=void 0,r.open&&r.inTransaction){T=setTimeout(k,N);return}const e=[...E];E.clear();for(const a of e)a.retry()},x=(e,a=0)=>{if(f)return;const _=t;if(r.open&&r.inTransaction){v(()=>{x(e,a)});return}if(o=void 0,!!r.open){try{if(!C(e)){I();return}}catch{o=e,a<K&&(n=setTimeout(()=>{n=void 0,x(e,a+1)},F*2**a));return}c((async()=>{await p?.(),d=0})().catch(async h=>{console.error("[@lunora/platform-node] alarm handler on shard %s threw; retrying with backoff",u??"(unnamed)",h),await new Promise(B=>{D(B,e,_)})}))}},A=e=>{if(l(),f)return;const a=Math.max(0,e-Date.now());if(a>G){n=setTimeout(()=>{A(e)},G);return}n=setTimeout(()=>{n=void 0,x(e)},a)},Y={delete:()=>{if(!r.open)throw new Error("platform closed: cannot delete an alarm");if(s.assertOwnTurn("delete an alarm"),d=0,S(void 0),s.inside()){i={at:void 0};return}t+=1,o=void 0,l()},get:()=>(i===void 0?o:i.at)??null,set:e=>{if(!r.open)throw new Error("platform closed: cannot set an alarm");s.assertOwnTurn("set an alarm");const a=typeof e=="number"?e:e.getTime();if(d=0,S(a),s.inside()){i={at:a};return}t+=1,o=a,A(a)}},$=()=>{if(i===void 0)return;const{at:e}=i;if(i=void 0,t+=1,e===void 0){o=void 0,l();return}o=e,A(e)},P=()=>{if(m=void 0,!r.open)return;if(r.inTransaction){m=setTimeout(P,N);return}const e=R.get();e!==void 0&&(n===void 0||g||o!==e.scheduled_for)&&(o=e.scheduled_for,A(e.scheduled_for))},Q=()=>{i=void 0,m!==void 0&&clearTimeout(m),P()},V=()=>{l(),m!==void 0&&(clearTimeout(m),m=void 0),T!==void 0&&(clearTimeout(T),T=void 0);for(const e of E)console.error("[@lunora/platform-node] alarm retry on shard %s given up: the database closed while it waited for another transaction to end",u??"(unnamed)"),e.settle();E.clear()};return I(),{alarms:Y,commit:$,dispose:V,rollback:Q,suspend:()=>{f=!0,l(),m!==void 0&&(clearTimeout(m),m=void 0)}}},ie=(r={})=>{const s=new j(r.path??":memory:");s.pragma("journal_mode = WAL");const p=new H;let u=!1;const c=t=>{if(u&&p.getStore()!==!0)throw new X("SHARD_UNAVAILABLE",`shard busy: cannot ${t} while another task holds this shard's transaction`)},y=ee(s,c),o=new Set,n=[],{alarms:f,commit:d,dispose:i,suspend:O,rollback:M}=re(s,{assertOwnTurn:c,inside:()=>p.getStore()===!0},r.onAlarm,r.shardKey,t=>{o.add(t),t.then(()=>o.delete(t)).catch(l=>{o.delete(t),console.error("[@lunora/platform-node] an alarm delivery on shard %s failed outside its retry handling",r.shardKey??"(unnamed)",l),n.push(`shard ${r.shardKey??"(unnamed)"}: an alarm delivery failed outside its retry handling`)})},t=>{n.push(t)}),w=new Set,R=new H;let L=Promise.resolve();const S=async t=>{if(R.getStore()===!0)return await t();const l=L;let v=()=>{};L=new Promise(I=>{v=I}),await l;try{return await R.run(!0,t)}finally{v()}},z=t=>S(t),C=async t=>{s.exec("BEGIN"),u=!0;try{const l=await p.run(!0,t);return s.exec("COMMIT"),u=!1,d(),l}catch(l){u=!1;try{s.exec("ROLLBACK")}catch{}throw M(),l}},g=t=>S(async()=>C(t)),m={alarms:f,runSerialized:z,shardKey:r.shardKey,sql:y,transaction:g,waitUntil:t=>{const l=t.catch(v=>{console.error("[@lunora/platform-node] work handed to waitUntil on shard %s failed",r.shardKey??"(unnamed)",v)}).finally(()=>{w.delete(l)});w.add(l)}};return{alarmsSettled:()=>o.size===0?void 0:Promise.allSettled(o),database:s,dispose:()=>{i(),s.open&&s.close()},drain:async()=>{for(;w.size>0||o.size>0;)await Promise.allSettled([...w,...o])},host:m,pendingAlarms:()=>o.size,pendingBackground:()=>w.size,suspendAlarms:O,takeFailures:()=>n.splice(0)}};export{ie as createNodeShardHost};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{mkdirSync as O,readdirSync as P}from"node:fs";import{join as A}from"node:path";import{LunoraError as U}from"@lunora/errors";import W from"better-sqlite3";import{startDrainDeadline as x,settlesBefore as z}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeShardKvStore as K}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeShardHost as T}from"./createNodeShardHost-VU8MPeba.mjs";import{createNodeSocketHost as V}from"./createNodeSocketHost-ByOmEGFe.mjs";const v=".sqlite3",F=n=>n.replaceAll(/[^\da-z._-]/gu,s=>[...Buffer.from(s,"utf8")].map(d=>`%${d.toString(16).padStart(2,"0").toUpperCase()}`).join("")),X=n=>decodeURIComponent(n),G=(n,s)=>{const d=s.slice(0,-v.length),l=A(n,s);let c;try{c=X(d)}catch{throw new U("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${l}" has a basename that is not valid percent-encoding, so the shard key it holds cannot be recovered. Rename or remove the file.`)}const f=`${F(c)}${v}`;if(f!==s)throw new U("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${l}" was written under an older shard-key encoding. It decodes to shard key "${c}", which this build stores as "${f}" — so the key would be listed for fan-out while every read opened a new, empty database. Rename it: mv "${l}" "${A(n,f)}"`);return c},J=(n,s)=>{let d;try{return d=new W(n,{fileMustExist:!0,readonly:!0}),d.prepare("SELECT 1 FROM _lunora_alarm LIMIT 1").get()!==void 0}catch(l){return console.error("[@lunora/platform-node] could not check shard %s for a persisted alarm, so it is opened to re-arm any",s,l),!0}finally{d?.close()}},y=(n,s,d)=>n===0?"":`${String(n)} ${n===1?s:d}`,Q=(n,s)=>{const d=[y(s.requests,"request in flight","requests in flight"),y(s.alarms,"alarm running","alarms running"),y(s.background,"waitUntil task","waitUntil tasks"),s.closing?"a socket close handler running":""].filter(l=>l!=="");return`shard ${n}: ${d.join(", ")}`},ae=(n={})=>{const s=new Map;let d="open",l=!1;const c=()=>{l=!0;for(const e of s.values())e.suspendAlarms()},f=()=>{if(d!=="open")throw new Error(`@lunora/platform-node: the shard registry is ${d}, so it opens no shard and takes no request`)},m=new Map,B=async(e,t)=>{const r=Promise.resolve().then(t),o=r.then(()=>{},()=>{});let a=m.get(e);return a===void 0&&(a=new Set,m.set(e,a)),a.add(o),o.finally(()=>{a.delete(o),a.size===0&&m.get(e)===a&&m.delete(e)}).catch(()=>{}),r},S=new Set,u=new Set,E=[];if(n.directory!==void 0){O(n.directory,{recursive:!0});for(const e of P(n.directory))e.endsWith(v)&&S.add(G(n.directory,e))}const b=e=>{f();const t=s.get(e);if(t!==void 0)return t.shard;const r=n.directory===void 0?void 0:A(n.directory,`${F(e)}${v}`);let o;const{alarmsSettled:a,database:i,dispose:h,drain:g,host:w,pendingAlarms:_,pendingBackground:j,suspendAlarms:L,takeFailures:C}=T({onAlarm:()=>n.onAlarm?.(o),path:r,shardKey:e}),k=V(i);return o={inbound:k,kv:K(i),shard:w,shardKey:e,sockets:k.socket},s.set(e,{alarmsSettled:a,dispose:h,drain:k.drain,drainHost:g,pendingAlarms:_,pendingBackground:j,shard:o,suspendAlarms:L,takeFailures:C}),S.add(e),l&&L(),o},H=e=>({fetch:async t=>{const r=b(e),{onFetch:o}=n;return o===void 0?new Response(e):B(e,()=>o(t,r))}}),I=()=>[...E.splice(0),...[...s.values()].flatMap(e=>e.takeFailures())],p=()=>{const e=new Map,t=a=>{let i=e.get(a);return i===void 0&&(i={alarms:0,background:0,closing:!1,requests:0},e.set(a,i)),i},r=[];for(const[a,i]of m)r.push(...i),t(a).requests+=i.size;for(const[a,i]of s){const h=i.drain(),g=i.pendingBackground(),w=i.pendingAlarms();h!==void 0&&(t(a).closing=!0,r.push(h)),g>0&&(t(a).background=g),w>0&&(t(a).alarms=w),(g>0||w>0)&&r.push(i.drainHost())}return{labels:[...e].map(([a,i])=>Q(a,i)),waits:r}},N=(e,t)=>{const r=t.drain(),o=t.alarmsSettled();return[...m.get(e)??[],...o===void 0?[]:[o],...r===void 0?[]:[r]]},R=()=>{d!=="open"&&s.size===0&&(d="closed")},q=(e,t)=>{try{t.dispose()}catch(r){return r??new Error(`shard ${e} failed to close`)}s.delete(e)},$=(e,t)=>{const r=N(e,t);if(r.length>0){Promise.allSettled(r).then(()=>{u.has(e)&&s.get(e)===t&&$(e,t)}).catch(()=>{});return}u.delete(e);const o=q(e,t);o!==void 0&&(console.error("[@lunora/platform-node] shard %s failed to close after the work using it settled",e,o),E.push(`shard ${e} failed to close after the work using it settled`)),R()},D=(e,t,r)=>{const o=q(e,t);return o===void 0?u.delete(e):r&&!u.has(e)&&(u.add(e),$(e,t)),o},M=(e,t)=>{e.length>0&&console.error("[@lunora/platform-node] closed %d shard(s) with a request, alarm handler or socket close handler still running: %s",e.length,e.join(", "));for(const{error:r,key:o}of t)console.error("[@lunora/platform-node] shard %s failed to close",o,r);if(t.length>0)throw new AggregateError(t.map(({error:r})=>r),`@lunora/platform-node: ${String(t.length)} shard(s) failed to close: ${t.map(({key:r})=>r).join(", ")}`)};return{close:e=>{d==="open"&&(d="closing");const t=[],r=[];c();for(const[o,a]of s){const i=N(o,a);if(i.length===0||e?.force===!0){i.length>0&&t.push(o);const h=D(o,a,i.length>0);h!==void 0&&r.push({error:h,key:o})}else u.has(o)||(u.add(o),$(o,a))}R(),M(t,r)},drain:async e=>{const t=x(e);try{for(let r=p();r.waits.length>0;r=p())if(!await z(Promise.allSettled(r.waits),t)){const o=p().labels;return console.error("[@lunora/platform-node] shard drain deadline passed with work still running: %s",o.join(", ")),{failed:I(),pending:o,timedOut:!0}}return{failed:I(),pending:[],timedOut:!1}}finally{t.cancel()}},directory:{get:e=>H(String(e)),getByName:e=>H(e),idForName:e=>e},idle:()=>p().waits.length===0,pending:()=>p().labels,rearmPersistedAlarms:()=>{f();const{directory:e}=n;if(e===void 0)return[];const t=[];for(const r of S)if(!s.has(r)&&J(A(e,`${F(r)}${v}`),r))try{b(r),t.push(r)}catch(o){console.error("[@lunora/platform-node] could not open shard %s to re-arm its persisted alarm",r,o)}return t},listShardKeys:()=>[...S],shardFor:b,suspendAlarms:c}};export{v as SHARD_FILE_SUFFIX,ae as createNodeShardRegistry};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{toErrorResponse as u,resolveShard as l}from"@lunora/runtime";import{s as f}from"./hmac-url-Bogwm7I6.mjs";const E=async(t,e)=>{if(!t.body)return"";const n=t.body.getReader(),o=new TextDecoder;let a=0,r="";for(;;){const{done:s,value:d}=await n.read();if(s)break;if(d){if(a+=d.byteLength,a>e)return await n.cancel().catch(()=>{}),null;r+=o.decode(d,{stream:!0})}}return r+=o.decode(),r},c=(t,e)=>{const n=Math.max(t.length,e.length);let o=t.length^e.length;for(let a=0;a<n;a+=1){const r=a<t.length?t.charCodeAt(a):0,s=a<e.length?e.charCodeAt(a):0;o|=r^s}return o===0},g="/_lunora/scheduler/dispatch",_="__lunora_relation__:",y=t=>t.startsWith(_),h="agents:agentRun",S=(t,e,n)=>t===h&&e!==n,A=`\`${h}\` runs on the default shard only, where agent threads live; to run an agent's tools on another shard, start it from a mutation on that shard with \`ctx.agents.<name>.run\``,w=(t,e)=>{if(!e||e.length===0)return!1;const n=t.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:c(e,a.join(" ").trim())},m="x-lunora-scheduler-signature",p="x-lunora-scheduler-timestamp",D=5*6e4,T=t=>["v1",String(t.timestamp),t.userId??"",t.identity??"",t.body].join(`
|
|
2
|
-
`),R=(t,e)=>f(t,T(e)),N=async(t,e,n)=>{const o=t.headers.get(m),{schedulerSecret:a}=n;if(o!==null&&o.length>0&&a!==void 0&&a.length>0){const r=t.headers.get(p);if(r===null||!/^\d+$/u.test(r))return!1;const s=Number(r);if(!Number.isSafeInteger(s)||Math.abs((n.now??Date.now)()-s)>D)return!1;const d=await R(a,{body:e,identity:t.headers.get("x-lunora-identity")??void 0,timestamp:s,userId:t.headers.get("x-lunora-userid")??void 0});return c(d,o)}return w(t,n.adminToken)},I="x-lunora-paywall",P="1",v="x-lunora-scheduled-for",L=({forwardedIdentity:t,mutationId:e,scheduledFor:n,traceparent:o})=>{const a={"content-type":"application/json",[I]:P,"x-lunora-system":"1"};return t?.userId!==void 0&&t.userId.length>0&&(a["x-lunora-userid"]=t.userId),t?.identity!==void 0&&t.identity.length>0&&(a["x-lunora-identity"]=t.identity),e!==void 0&&e.length>0&&(a["x-lunora-mutation-id"]=e),o!==void 0&&o.length>0&&(a.traceparent=o),n!==void 0&&Number.isFinite(n)&&(a[v]=String(Math.trunc(n))),a},O=t=>{const e=t.headers.get("x-lunora-userid"),n=t.headers.get("x-lunora-identity");if(!(e===null&&n===null))return{...n===null?{}:{identity:n},...e===null?{}:{userId:e}}},C=1048576,H=async t=>{const e=await E(t,C);if(e===null)throw new i("PAYLOAD_TOO_LARGE","Scheduler dispatch body is too large");return e},U=async(t,e)=>{if(t.method!=="POST")throw new i("METHOD_NOT_ALLOWED","Scheduler dispatch endpoint requires POST",{status:405});const n=await H(t);if(!await N(t,n,{adminToken:e.adminToken,now:e.now,schedulerSecret:e.schedulerSecret}))throw new i("DISPATCH_UNAUTHENTICATED","Scheduler dispatch requires a valid signature or admin bearer");let a;try{a=JSON.parse(n)}catch{throw new i("BAD_REQUEST","Scheduler dispatch body must be valid JSON")}const r=a??{};if(typeof r.workflow=="string"||r.pool!==void 0)throw new i("SERVICE_UNAVAILABLE","Scheduler dispatch for a workflow or pool target is not served by the Node dispatch route");if(typeof r.functionPath!="string"||r.functionPath.length===0)throw new i("BAD_REQUEST","Scheduler dispatch is missing `functionPath`");if(y(r.functionPath))throw new i("FORBIDDEN","`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard");const s=typeof r.shardKey=="string"&&r.shardKey.length>0?r.shardKey:e.defaultShardKey;if(S(r.functionPath,s,e.defaultShardKey))throw new i("BAD_REQUEST",A);return e.invoke({args:r.args??{},functionPath:r.functionPath,id:typeof r.id=="string"&&r.id.length>0?r.id:void 0,identity:O(t),scheduledFor:typeof r.scheduledFor=="number"?r.scheduledFor:void 0,shardKey:s,traceparent:t.headers.get("traceparent")??void 0})},B=(t,e)=>n=>{if(!e)throw new i("SERVICE_UNAVAILABLE","@lunora/platform-node: the dispatch route needs `onFetch` to run a function; without it a shard only echoes its key");const o=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n.args,functionPath:n.functionPath}),headers:L({forwardedIdentity:n.identity,mutationId:n.id,scheduledFor:n.scheduledFor,traceparent:n.traceparent}),method:"POST"});return l(t,n.shardKey).fetch(o)},k=t=>async e=>{try{return await U(e,t)}catch(n){return u(n)}},M=g;export{A,M as N,B as a,k as c,S as i};
|