@lunora/platform-node 1.0.0-alpha.220 → 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 +318 -136
- package/dist/index.d.ts +318 -136
- 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/createNodeMailHost-DrUo8de-.mjs +8 -0
- package/dist/packem_shared/createNodePlatform-De8dIBya.mjs +1 -0
- package/dist/packem_shared/createNodeQueueHost-glQ8GNCA.mjs +17 -0
- 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 -2
- package/dist/packem_shared/bindShardSockets-9GvSocBW.mjs +0 -1
- package/dist/packem_shared/createNodePlatform-C5LvauTf.mjs +0 -1
- package/dist/packem_shared/createNodeQueueHost-szMV0PBN.mjs +0 -17
- package/dist/packem_shared/createNodeShardHost-VU8MPeba.mjs +0 -1
- package/dist/packem_shared/createNodeShardRegistry-BHzxHBx1.mjs +0 -1
- package/dist/packem_shared/node-dispatch-route-ByuCR26s.mjs +0 -2
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DEFAULT_DRAIN_TIMEOUT_MS as o,drainTogether as t}from"./packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{
|
|
1
|
+
import{DEFAULT_DRAIN_TIMEOUT_MS as o,drainTogether as t}from"./packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{checkNodeAppHost as c,createNodeAppHost as d}from"./packem_shared/checkNodeAppHost-Cv5p7igg.mjs";import{N,c as f}from"./packem_shared/node-dispatch-route-B3GAZkHT.mjs";import{createNodeDurableObjectFactory as x}from"./packem_shared/createNodeDurableObjectFactory-hAwJt_pN.mjs";import{createNodeGlobalStore as s,createNodeSqlExec as H}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeHttpServer as h}from"./packem_shared/createNodeHttpServer-cUx4J9Z9.mjs";import{createNodeHyperdrive as D}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as u}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeMailHost as E}from"./packem_shared/createNodeMailHost-DrUo8de-.mjs";import{createNodePlatform as _}from"./packem_shared/createNodePlatform-De8dIBya.mjs";import{createNodeProfileHandler as R}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as P}from"./packem_shared/createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as v}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as I}from"./packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeSecretBindings as O}from"./packem_shared/createNodeSecretBindings-C7wh0fOm.mjs";import{createNodeShardHost as w}from"./packem_shared/createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardNamespace as C}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as L}from"./packem_shared/createNodeShardRegistry-D1r6M8Rg.mjs";import{bindShardSockets as j,createNodeShardState as q}from"./packem_shared/bindShardSockets-DjLmRlIA.mjs";import{createNodeSocketHost as K}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as z}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as V}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{o as DEFAULT_DRAIN_TIMEOUT_MS,N as NODE_SCHEDULER_DISPATCH_PATH,j as bindShardSockets,c as checkNodeAppHost,d as createNodeAppHost,f as createNodeDispatchRoute,x as createNodeDurableObjectFactory,s as createNodeGlobalStore,h as createNodeHttpServer,D as createNodeHyperdrive,E as createNodeMailHost,_ as createNodePlatform,R as createNodeProfileHandler,P as createNodeQueueHost,v as createNodeR2Bucket,I as createNodeSchedulerHost,O as createNodeSecretBindings,w as createNodeShardHost,u as createNodeShardKvStore,C as createNodeShardNamespace,L as createNodeShardRegistry,q as createNodeShardState,K as createNodeSocketHost,H as createNodeSqlExec,z as createNodeWorkflowHost,V as createNodeWorkflowStore,t as drainTogether};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{N as o,c as r,a as t}from"./node-dispatch-route-
|
|
1
|
+
import{N as o,c as r,a as t}from"./node-dispatch-route-B3GAZkHT.mjs";export{o as NODE_SCHEDULER_DISPATCH_PATH,r as createNodeDispatchRoute,t as createShardInvoke};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const l=(t,o)=>({acceptWebSocket:(e,a)=>{t.sockets.accept(e,void 0,a)},blockConcurrencyWhile:e=>{const a=t.shard.runSerialized(e);return o?.(a),a},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,o)=>{const e=async(a,s)=>{await t.webSocketMessage(a,s)};o.onMessage((a,s)=>{e(a,s).catch(c=>{console.error("[lunora] webSocketMessage threw:",c)})}),o.onClose(async(a,s,c,r)=>{try{await t.webSocketClose(a,s,c,r)}catch(n){console.error("[lunora] webSocketClose threw:",n)}})};export{i as bindShardSockets,l as createNodeShardState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mkdirSync as p,existsSync as m,realpathSync as h,lstatSync as g}from"node:fs";import{join as f,relative as y,isAbsolute as O}from"node:path";import{LunoraError as i}from"@lunora/errors";import{drainTimeoutMs as k,drainTogether as A,startDrainDeadline as R,settlesBefore as D}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeDurableObjectFactory as $}from"./createNodeDurableObjectFactory-hAwJt_pN.mjs";import{walkDeclaredCrons as N,createNodePlatform as v}from"./createNodePlatform-De8dIBya.mjs";import{createNodeShardNamespace as I}from"./createNodeShardNamespace-BgQjDv7V.mjs";const w=e=>{const r=new Set;let a=0;const t=()=>{const n=a===0?[]:[`${String(a)} ${e.label} failed`];return a=0,n},o=()=>r.size===0?[]:[`${String(r.size)} ${e.label}`];return{drain:async n=>{const c=R(n);try{for(;r.size>0;)if(!await D(Promise.all(r),c))return{failed:t(),pending:o(),timedOut:!0};return{failed:t(),pending:[],timedOut:!1}}finally{c.cancel()}},idle:()=>r.size===0,pending:o,track:n=>{const c=Promise.resolve(n).then(()=>{},d=>{e.reportFailures&&(a+=1,console.error("[@lunora/platform-node] work handed to waitUntil failed:",d))}).finally(()=>r.delete(c));r.add(c)}}},b=e=>{const r=[];for(const a of e)try{a.close({force:!0})}catch(t){r.push(t)}if(r.length>0)throw new AggregateError(r,`@lunora/platform-node: ${String(r.length)} platform(s) failed to close`)},S=e=>typeof e=="object"&&e!==null&&typeof e.fetch=="function",j=(e,r,a,t)=>{const o=$(r.worker[e.className],a);return v({crons:e.name===t?r.crons??{}:void 0,directory:r.dataDirectory===void 0?void 0:f(r.dataDirectory,e.name),onAlarm:async n=>{n!==void 0&&await(await o(n)).alarm?.()},onFetch:async(n,c)=>(await o(c)).fetch(n),path:r.dataDirectory===void 0?void 0:f(r.dataDirectory,`${e.name}.platform.sqlite3`)})},E=/^[A-Za-z_$][\w$]*$/u,L=(e,r)=>{const a=y(e,r);return a!==""&&!a.startsWith("..")&&!O(a)},T=(e,r)=>{if(!E.test(e))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${JSON.stringify(e)} is not a valid binding name (a JavaScript identifier such as SHARD), and its name becomes a directory under the data directory`);if(r===void 0||!m(r))return;const a=h(r);for(const t of[f(r,e),f(r,`${e}.platform.sqlite3`)]){let o;try{o=g(t)}catch{continue}if(o.isSymbolicLink()&&!m(t))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${e} would store data outside ${r}: ${t} is a link to nothing, which SQLite would follow`);if(!L(a,h(t)))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${e} would store data outside ${r}: ${t} links out of it`)}},_=e=>{const r=new Map;for(const{name:a}of e){const t=r.get(a.toLowerCase());if(t!==void 0)throw new i("VALIDATION_ERROR",t===a?`@lunora/platform-node: Durable Object binding ${a} is declared twice, and both would share one shard directory and platform database`:`@lunora/platform-node: Durable Object bindings ${t} and ${a} differ only in case, so on a case-insensitive volume they would share one shard directory and platform database — rename one`);r.set(a.toLowerCase(),a)}},P=e=>{if(typeof e!="function")return!1;try{return Reflect.construct(String,[],e),!0}catch{return!1}},x=e=>{if(!S(e.worker.default))throw new i("VALIDATION_ERROR","@lunora/platform-node: the worker module has no default export with a `fetch` handler");_(e.durableObjects);for(const t of e.durableObjects){T(t.name,e.dataDirectory);const o=Object.hasOwn(e.worker,t.className)?e.worker[t.className]:void 0;if(o===void 0)throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${t.name} names class ${t.className}, which the worker module does not export`);if(!P(o))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${t.name} names ${t.className}, which the worker module exports as something \`new\` cannot construct`)}const r=e.shardBinding??"SHARD";if(N(e.crons??{}).length>0&&!e.durableObjects.some(t=>t.name===r))throw new i("VALIDATION_ERROR",`@lunora/platform-node: the app declares crons, but no Durable Object binding is named ${r} to run them on`)},M=e=>{x(e);const r=e.worker.default,a={...e.env},t=[],o=w({label:"worker waitUntil task(s)",reportFailures:!0}),n=w({label:"worker request(s)",reportFailures:!1}),c=e.shardBinding??"SHARD";e.dataDirectory!==void 0&&p(e.dataDirectory,{recursive:!0});try{for(const s of e.durableObjects){const l=j(s,e,a,c);t.push(l),Object.defineProperty(a,s.name,{configurable:!0,enumerable:!0,value:I(l.directory),writable:!0})}}catch(s){try{b(t.splice(0))}catch(l){console.error("[@lunora/platform-node] closing the platforms of a host that failed to compose failed:",l)}throw s}const d={passThroughOnException:()=>{},waitUntil:o.track};let u;return{close:async s=>(k(s),u??=(async()=>{try{return await A([n,o,...t],s)}finally{b(t.splice(0))}})(),u),fetch:async s=>{const l=Promise.resolve(r.fetch(s,a,d));return n.track(l),l},rearmPersistedAlarms:()=>t.flatMap(s=>s.rearmPersistedAlarms())}};export{x as checkNodeAppHost,M as createNodeAppHost};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{bindShardSockets as k,createNodeShardState as l}from"./bindShardSockets-DjLmRlIA.mjs";const y=(w,S)=>{const o=new WeakMap,i=new WeakSet,b=e=>{const t=[];let c=!0;const n=l(e,u=>{c&&t.push(u)}),s=new w(n,S);c=!1;const a=Promise.all(t).then(()=>{});return a.catch(()=>{}),{instance:s,ready:a}},r=async e=>{let t=o.get(e);t===void 0&&(t=b(e),o.set(e,t),!i.has(e)&&(t.instance.webSocketClose!==void 0||t.instance.webSocketMessage!==void 0)&&(i.add(e),k({webSocketClose:async(c,n,s,a)=>{await(await r(e)).webSocketClose?.(c,n,s,a)},webSocketMessage:async(c,n)=>{await(await r(e)).webSocketMessage?.(c,n)}},e.inbound)));try{await t.ready}catch(c){throw o.get(e)===t&&o.delete(e),c}return t.instance};return r};export{y as createNodeDurableObjectFactory};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{AsyncLocalStorage as te}from"node:async_hooks";import{createHash as re}from"node:crypto";import{LunoraError as O}from"@lunora/errors";import{shouldCaptureMail as ne,createMailerFromEnv as ie,createMailer as V,assertValidIdempotencyKey as oe,consumeQueuedSend as ae,MailSendError as se,isRetryableMailError as le,isOutcomeUnknownMailError as Y}from"@lunora/mail";import{defineQueue as _e}from"@lunora/queue";import{createNodeQueueHost as ce,allowReservedQueueName as ue,RESERVED_MAIL_QUEUE_NAME as Ee,preparedSendOf as de}from"./createNodeQueueHost-glQ8GNCA.mjs";const A=Ee,G=10,M=3,pe=30,k=6e4,U=G*(k+4*1e4)+6e4,Q=180,h=15*864e5,H="CASE WHEN content_type = 'json' AND json_valid(CAST(body AS TEXT)) THEN json_extract(CAST(body AS TEXT), '$.idempotencyKey') END",C=h,me=3,J=(e,t=0)=>e instanceof Error?{message:e.message,name:e.name,stack:e.stack,...e.cause!==void 0&&t<me&&{cause:J(e.cause,t+1)}}:{message:String(e)},T=(e,t,r,i)=>{const _=JSON.stringify({attempts:r,error:J(i),event:t,queue:A});console[e](`[@lunora/platform-node] ${_}`)},Te="sending ",j="failed ",b=6e4,Ne=(e,t,r)=>{e.exec("CREATE TABLE IF NOT EXISTS _lunora_mail_sent (key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER NOT NULL)"),e.exec("CREATE INDEX IF NOT EXISTS _lunora_mail_sent_expires ON _lunora_mail_sent (expires_at)");const i=e.prepare("SELECT value FROM _lunora_mail_sent WHERE key = ? AND expires_at > ?"),_=e.prepare("INSERT INTO _lunora_mail_sent (key, value, expires_at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at"),y=e.prepare("DELETE FROM _lunora_mail_sent WHERE expires_at <= ?"),N=e.prepare("DELETE FROM _lunora_mail_sent WHERE key = ?"),S=e.transaction((l,E,m)=>{_.run(l,E,m),r(l)}),L=e.transaction((l,E,m)=>{_.run(l,"failed",m),N.run(E)});let p=Number.NEGATIVE_INFINITY;return{get:async l=>i.get(l,t())?.value,put:async(l,E,{expirationTtl:m})=>{const f=t();if(E==="failed"&&l.startsWith(j)){const D=l.slice(j.length),x=`${Te}${D}`,R=Number.parseInt(D,10);try{L(l,x,f+m*1e3)}catch(v){T("warn","lunora.mail.attempt_mark_failed",R,v);try{N.run(x)}catch(g){T("error","lunora.mail.attempt_mark_orphaned",R,g)}}return}f-p>=b&&(y.run(f),p=f),l.includes(" ")?_.run(l,E,f+m*1e3):S.immediate(l,E,f+m*1e3)}}},$=e=>Array.isArray(e)?`[${e.map(t=>$(t)).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,r])=>r!==void 0).toSorted(([r],[i])=>r<i?-1:1).map(([r,i])=>`${JSON.stringify(r)}:${$(i)}`).join(",")}}`:JSON.stringify(e),F=e=>{const t=typeof e=="string"?[e]:e;return Array.isArray(t)&&t.length===0?void 0:t},fe=(e,t)=>{const r=e!==null&&typeof e=="object"?e:{};return re("sha256").update($({bcc:F(r.bcc),cc:F(r.cc),from:r.from??t,headers:r.headers,html:r.html,replyTo:r.replyTo,subject:r.subject,text:r.text,to:F(r.to)})).digest("hex")},Ae=(e,t,r)=>{e.exec("CREATE TABLE IF NOT EXISTS _lunora_mail_claims (key TEXT PRIMARY KEY, message_id TEXT NOT NULL, expires_at INTEGER NOT NULL)"),e.exec("CREATE INDEX IF NOT EXISTS _lunora_mail_claims_expires ON _lunora_mail_claims (expires_at)"),e.exec("CREATE TABLE IF NOT EXISTS _lunora_mail_keys (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, expires_at INTEGER NOT NULL)"),e.exec("CREATE INDEX IF NOT EXISTS _lunora_mail_keys_expires ON _lunora_mail_keys (expires_at)"),e.exec("CREATE TABLE IF NOT EXISTS _lunora_mail_deliveries (key TEXT PRIMARY KEY, delivery INTEGER NOT NULL, first_at INTEGER NOT NULL, expires_at INTEGER NOT NULL)"),e.exec("CREATE INDEX IF NOT EXISTS _lunora_mail_deliveries_expires ON _lunora_mail_deliveries (expires_at)");const i=e.prepare(`INSERT INTO _lunora_mail_claims (key, message_id, expires_at) VALUES (?, ?, ?)
|
|
2
|
+
ON CONFLICT (key) DO UPDATE SET message_id = excluded.message_id, expires_at = excluded.expires_at
|
|
3
|
+
WHERE _lunora_mail_claims.expires_at <= ? OR _lunora_mail_claims.message_id = excluded.message_id`),_=e.prepare("DELETE FROM _lunora_mail_claims WHERE key = ? AND message_id = ?"),y=e.prepare("SELECT fingerprint FROM _lunora_mail_keys WHERE key = ? AND expires_at > ?"),N=e.prepare("INSERT INTO _lunora_mail_keys (key, fingerprint, expires_at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET fingerprint = excluded.fingerprint, expires_at = excluded.expires_at"),S=e.prepare("DELETE FROM _lunora_mail_claims WHERE expires_at <= ?"),L=e.prepare("DELETE FROM _lunora_mail_keys WHERE expires_at <= ?"),p=`EXISTS (SELECT 1 FROM _lunora_queue_messages WHERE queue = '${A}' AND state IN ('pending', 'dead') AND ${H} = _lunora_mail_deliveries.key AND id <> @excluded AND enqueued_at < _lunora_mail_deliveries.expires_at)`;let l,E;const m=n=>{l??=e.prepare(`DELETE FROM _lunora_mail_deliveries WHERE NOT ${p} AND expires_at <= @now`),l.run({excluded:"",now:n})},f=(n,a,c,u)=>{const s=`_lunora_mail_deliveries.expires_at <= @now AND @enqueued >= _lunora_mail_deliveries.expires_at AND NOT ${p}`;return E??=e.prepare(`INSERT INTO _lunora_mail_deliveries (key, delivery, first_at, expires_at) VALUES (@key, 1, @now, @expires)
|
|
4
|
+
ON CONFLICT (key) DO UPDATE SET
|
|
5
|
+
delivery = CASE WHEN ${s} THEN 1 ELSE _lunora_mail_deliveries.delivery + 1 END,
|
|
6
|
+
first_at = CASE WHEN ${s} THEN excluded.first_at ELSE _lunora_mail_deliveries.first_at END,
|
|
7
|
+
expires_at = excluded.expires_at
|
|
8
|
+
RETURNING delivery, first_at`),E.get({enqueued:u,excluded:c,expires:a+h,key:n,now:a})},D=e.prepare("SELECT first_at FROM _lunora_mail_deliveries WHERE key = ?"),x=e.prepare("UPDATE _lunora_mail_keys SET expires_at = max(expires_at, ?) WHERE key = ?");let R=Number.NEGATIVE_INFINITY,v;const g=n=>(v??=e.prepare(`SELECT body FROM _lunora_queue_messages WHERE queue = '${A}' AND state IN ('pending', 'dead') AND ${H} = ? ORDER BY enqueued_at LIMIT 1`),v.get(n)),I=(n,a)=>{const c=y.get(n,a)?.fingerprint;if(c!==void 0)return{fingerprint:c,recorded:!0};const u=g(n);return u===void 0?void 0:{fingerprint:r(JSON.parse(u.body.toString("utf8"))),recorded:!1}},w=n=>{n-R>=b&&(S.run(n),L.run(n),m(n),R=n)},o=e.transaction((n,a,c)=>{const u=t();w(u);const s=I(n,u);return s!==void 0&&s.fingerprint!==a?"conflict":(s?.recorded!==!0&&N.run(n,a,u+C),c(),"queued")}),d=e.transaction((n,a,c,u)=>{const s=t();w(s);const P=I(n,s);if(P!==void 0&&P.fingerprint!==a)return{outcome:"conflict"};if(i.run(n,c,s+U,s).changes===0)return{outcome:"busy"};N.run(n,a,Math.max(s+C,s+U));const K=f(n,s,c,u);return{delivery:K?.delivery??1,firstDeliveredAt:K?.first_at??s,outcome:"taken"}});return{firstDeliveredAt:n=>D.get(n)?.first_at,keepContent:n=>{x.run(t()+C,n)},release:(n,a)=>{_.run(n,a)},reserve:(n,a,c)=>o.immediate(n,a,c),take:(n,a,c,u)=>d.immediate(n,a,c,u)}},X=e=>{const t=e!==null&&typeof e=="object"?e.idempotencyKey:void 0;return typeof t=="string"&&t!==""?t:void 0},q=86400,ye=e=>{if(e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0||e>q))throw new O("VALIDATION_ERROR",`@lunora/platform-node: \`delaySeconds\` must be a whole number of seconds from 0 to ${String(q)} (24 hours), as on Cloudflare Queues, got ${typeof e=="number"?String(e):JSON.stringify(e)}`)},z=new Set(["0","1","false","true"]),Re=e=>{const t=e.LUNORA_MAIL_CAPTURE;return typeof t=="string"&&z.has(t.toLowerCase())?`LUNORA_MAIL_CAPTURE=${t}`:["CF_ENV","ENVIRONMENT","NODE_ENV","WORKER_ENV"].flatMap(r=>typeof e[r]=="string"&&e[r]!==""?[`${r}=${e[r]}`]:[]).join(", ")},Ie=e=>{const t=e.LUNORA_MAIL_CAPTURE;return typeof t=="string"&&t!==""&&!z.has(t.toLowerCase())?`; LUNORA_MAIL_CAPTURE=${t} was ignored, as only 1, true, 0 or false are read`:""},Oe=e=>{const r=e.SHARD!==void 0&&typeof e.LUNORA_ADMIN_TOKEN=="string"?"recorded in the studio's Mail inbox":"DISCARDED, because there is no SHARD namespace and LUNORA_ADMIN_TOKEN on env to record it with";console.warn(`[@lunora/platform-node] mail is captured, not sent (${Re(e)} selects dev capture${Ie(e)}): every send is ${r}. Set LUNORA_MAIL_CAPTURE=0 to deliver.`)},Se=(e,t,r)=>{const i=e.MAIL_FROM;if(typeof i!="string"||i==="")throw new O("VALIDATION_ERROR","@lunora/platform-node: mail needs MAIL_FROM, the default sender");if(ne(e))return Oe(e),ie(e,{queue:t,sendTimeoutMs:k});if(r!==void 0)return V({from:i,queue:t,sendTimeoutMs:k,transport:r});const _=e.RESEND_API_KEY;if(typeof _!="string"||_==="")throw new O("VALIDATION_ERROR","@lunora/platform-node: mail has nothing to deliver through — set RESEND_API_KEY or pass `transport` (Cloudflare Email Workers' send_email binding does not exist on Node)");return V({apiKey:_,from:i,queue:t,sendTimeoutMs:k})},W=(e,t,r)=>{e.parking.getStore()?.set(t.id,{attempts:t.attempts,reason:r}),t.retry({delaySeconds:q})},Z=(e,t,r)=>{t.attempts>M&&e.parking.getStore()?.set(t.id,{attempts:t.attempts,reason:"retries_exhausted"}),t.retry({delaySeconds:r})},ee=(e,t,r)=>{if(!le(r)){if(Y(r)){T("error","lunora.mail.send_outcome_unknown",t.attempts,r),W(e,t,"outcome_unknown");return}T("error","lunora.mail.send_refused",t.attempts,r),t.ack();return}t.attempts>M?T("error","lunora.mail.send_dead_lettered",t.attempts,r):T("warn","lunora.mail.send_retry",t.attempts,r),Z(e,t,Y(r)?Q:pe*2**(t.attempts-1))},Le=(e,t,r)=>{const i=new Error(`another delivery of idempotency key "${r}" is in flight`);T(t.attempts>M?"error":"warn",t.attempts>M?"lunora.mail.send_dead_lettered":"lunora.mail.send_key_busy",t.attempts,i),Z(e,t,Q)},De=(e,t,r)=>{if(r===void 0)return{delivery:t.attempts,firstDeliveredAt:t.timestamp.getTime(),outcome:"taken"};try{return e.claims.take(r,e.fingerprint(t.body),t.id,t.timestamp.getTime())}catch(i){ee(e,t,new se({cause:i,message:`@lunora/mail: could not claim idempotency key "${r}"`,retryable:!0}));return}},B=(e,t,r)=>{try{r()}catch(i){T("error",t,e.attempts,i)}},xe=async(e,t)=>{const r=X(t.body),i=De(e,t,r);if(i===void 0)return;if(i.outcome==="conflict"){T("error","lunora.mail.idempotency_key_conflict",t.attempts,new Error(`idempotency key "${String(r)}" belongs to different content; this send is parked in deadLetters, not sent`)),W(e,t,"idempotency_key_conflict");return}if(i.outcome==="busy"){Le(e,t,String(r));return}const _=i.firstDeliveredAt;if(i.delivery>1&&e.clock()-_>=h){r!==void 0&&B(t,"lunora.mail.claim_release_failed",()=>{e.claims.release(r,t.id)}),T("error","lunora.mail.send_evidence_expired",t.attempts,new Error("an earlier delivery of this key may have been sent, and its record in the sent ledger has expired")),W(e,t,"evidence_expired");return}const y=new Date(Date.now()-(e.clock()-_));try{try{await ae(e.mailer,t.body,{attempts:i.delivery,enqueuedAt:y,sent:e.sent,sentTtlSeconds:h/1e3})}catch(N){ee(e,t,N);return}t.ack()}finally{r!==void 0&&B(t,"lunora.mail.claim_release_failed",()=>{e.claims.release(r,t.id)})}},ve=(e,t)=>({...e,retry:r=>{e.retry({delaySeconds:(r?.delaySeconds??0)+t()})}}),Me=async(e,t)=>{const r=e.clock(),i=()=>Math.ceil(Math.max(0,e.clock()-r)/1e3);for(const _ of t.messages)await xe(e,ve(_,i))},Ue=(e,t={})=>{const r=t.env??{...process.env},i=t.now??Date.now,_={send:async(o,d)=>{const{delaySeconds:n,...a}=d??{};if(Object.keys(a).length>0)throw new O("VALIDATION_ERROR",`@lunora/platform-node: the mail queue takes only a \`delaySeconds\` option, got ${Object.keys(a).join(", ")}`);ye(n);const{insert:c,stored:u}=de(l,"mail")(o,n===void 0?void 0:{delaySeconds:n});oe(u?.idempotencyKey);const s=X(u);if(s===void 0)throw new O("VALIDATION_ERROR","@lunora/platform-node: a queued mail body needs an `idempotencyKey` (a non-empty string) — queue through `mailer.queue()`, which mints one");if(p.claims.reserve(s,p.fingerprint(u),c)==="conflict")throw new O("VALIDATION_ERROR",`@lunora/platform-node: idempotency key "${s}" was already queued with different content — a key names one message, so use a new key for new content`)}},y=Se(r,_,t.transport),N=r.MAIL_FROM,S=o=>fe(o,typeof N=="string"?N:void 0),L=Ae(e,i,S),p={claims:L,clock:i,fingerprint:S,mailer:y,sent:Ne(e,i,o=>{L.keepContent(o)}),parking:new te},l=ce(e,ue({now:i,onBatch:async o=>{await Me(p,o)},queues:{mail:_e({handler:()=>{},maxBatchSize:G,maxBatchTimeout:0,maxRetries:M,name:A})},visibilityTimeoutMs:U}));e.exec(`CREATE INDEX IF NOT EXISTS _lunora_mail_row_keys ON _lunora_queue_messages ((${H}), enqueued_at) WHERE queue = '${A}'`);const E=e.prepare(`UPDATE _lunora_queue_messages SET state = 'dead' WHERE id = ? AND queue = '${A}' AND state = 'pending' AND attempts = ?`);e.exec("CREATE TABLE IF NOT EXISTS _lunora_mail_parked (id TEXT PRIMARY KEY, reason TEXT NOT NULL)");const m=e.prepare("INSERT OR REPLACE INTO _lunora_mail_parked (id, reason) SELECT ?, ? WHERE EXISTS (SELECT 1 FROM _lunora_queue_messages WHERE id = ? AND queue = ? AND state = 'dead' AND attempts = ?)"),f=e.prepare("SELECT reason FROM _lunora_mail_parked WHERE id = ?"),D=e.prepare("DELETE FROM _lunora_mail_parked WHERE id = ?"),x=e.transaction((o,d,n)=>{n<=M&&E.run(o,n),m.run(o,d,o,A,n)}),R=e.prepare("UPDATE _lunora_queue_messages SET state = 'pending', visible_at = ? WHERE id = ? AND queue = ? AND state = 'dead'"),v=e.prepare("SELECT body, enqueued_at FROM _lunora_queue_messages WHERE id = ? AND queue = ? AND state = 'dead'"),g=e.transaction(o=>R.run(i(),o,A).changes===0?!1:(D.run(o),!0)),I=new Set;return{deadLetters:{list:()=>l.deadLetters.list(A).map(o=>({...o,reason:f.get(o.id)?.reason??"unknown"})),requeue:o=>{const d=v.get(o,A);if(d===void 0)return!1;const n=X(JSON.parse(d.body.toString("utf8"))),a=(n===void 0?void 0:p.claims.firstDeliveredAt(n))??d.enqueued_at;if(i()-a>=h)throw new O("VALIDATION_ERROR",`@lunora/platform-node: parked mail ${o} was first attempted 15 or more days ago, so the record of whether an earlier attempt was sent has expired — check the provider's logs and queue it again if it never arrived`);return g.immediate(o)}},drain:async()=>{await Promise.allSettled(I)},idle:()=>I.size===0,mailer:y,poll:async o=>{const d=new Map,n=p.parking.run(d,async()=>await l.poll(o)).finally(()=>{for(const[a,{attempts:c,reason:u}]of d)try{x.immediate(a,u,c)}catch(s){T("error","lunora.mail.park_failed",c,s)}});I.add(n);try{return await n}finally{I.delete(n)}},queue:_}};export{Ue as createNodeMailHost};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readdirSync as j,lstatSync as X,readlinkSync as Y,statSync as $,realpathSync as F}from"node:fs";import{join as m,dirname as p,basename as M,resolve as N}from"node:path";import{LunoraError as d}from"@lunora/errors";import{NODE_CAPABILITIES as z}from"@lunora/platform";import Z from"better-sqlite3";import{a as ee,c as te,i as re,A as oe}from"./node-dispatch-route-B3GAZkHT.mjs";import{startDrainDeadline as P,settlesBefore as D,drainTimeoutMs as ae,drainTogether as se}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeGlobalStore as ne}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as ie}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeMailHost as de}from"./createNodeMailHost-DrUo8de-.mjs";import{createNodeQueueHost as le}from"./createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as ce}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as he}from"./createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as ue}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardRegistry as fe,SHARD_FILE_SUFFIX as k}from"./createNodeShardRegistry-D1r6M8Rg.mjs";import{createNodeSocketHost as me}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as pe}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as we}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const ge="__root__",ye=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>{if(o.functionPath===void 0)throw new d("VALIDATION_ERROR",o.workflow===void 0?`@lunora/platform-node: cron job "${o.name}" has neither a function target nor a workflow target`:`@lunora/platform-node: cron job "${o.name}" starts workflow "${o.workflow}", which this host cannot do from a cron tick — schedule a function that calls ctx.workflows.get(name).create() instead`);return{args:o.args??{},expression:t,functionPath:o.functionPath,name:o.name}})),ve=(e,t)=>{const r=ye(e);if(r.length>0&&!t)throw new d("VALIDATION_ERROR","@lunora/platform-node: `crons` declares jobs but nothing can deliver them — pass `onFetch` (to run them on the shard) or `onDispatch`");return r},w=(e,{databaseFile:t})=>{const r=N(t?e.trim():e);try{return F(r)}catch{try{return m(F(p(r)),M(r))}catch{return r}}},V=40,Re=e=>{let t=N(e.trim());const r=[t];for(let o=0;o<=V;o+=1){let i;try{i=X(t).isSymbolicLink()}catch(a){if(a.code==="ENOENT")return r;throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" could not be resolved — pass a path it can check`,{cause:a})}if(!i)return r;try{t=N(p(t),Y(t)),r.push(t)}catch(a){throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a symlink whose target could not be read`,{cause:a})}}throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a chain of more than ${String(V)} symlinks (a loop?) — pass the file itself`)},H=(e,t)=>{try{const r=$(e.trim(),{bigint:!0}),o=$(t.trim(),{bigint:!0});return r.dev===o.dev&&r.ino===o.ino}catch{return w(e,{databaseFile:!0}).toLowerCase()===w(t,{databaseFile:!0}).toLowerCase()}},Se=e=>{const t=e.trim();if(t===""||t===":memory:")throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is not durable — the mail queue and its sent ledger must survive a restart, so give mail a database file`);if(t.toLowerCase().startsWith("file:"))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is a file: URI — pass a plain filesystem path instead (better-sqlite3 does not read URIs, and would open a file by that literal name)`)},Ae=e=>({drain:async t=>{const r=P(t);try{return await D(e.drain(),r)?{failed:[],pending:[],timedOut:!1}:(console.error("[@lunora/platform-node] platform drain deadline passed with a mail poll still running"),{failed:[],pending:["a mail poll"],timedOut:!0})}finally{r.cancel()}},idle:()=>e.idle(),pending:()=>e.idle()?[]:["a mail poll"]}),be=(e,t)=>{const r=Re(e),o=r.at(-1)??e,i=[["the shard database (`path`)",t.path],["the .global() store (`globalTablesPath`)",t.globalTablesPath]];for(const[l,s]of i)if(s!==void 0&&s!==":memory:"&&s!==""&&H(s,o))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is ${l} "${s}" — give mail a database file of its own`);const{directory:a}=t;if(a===void 0)return;const u=w(a,{databaseFile:!1});if(r.some(l=>{const s=m(w(p(l),{databaseFile:!1}),M(l));return s.endsWith(k)&&p(s)===u}))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a ${k} file inside the shard registry's directory "${a}", which would open it as a shard — move it out of that directory`);let f;try{f=j(a).filter(l=>l.endsWith(k))}catch{return}const h=f.find(l=>H(m(a,l),o));if(h!==void 0)throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is the same file as the shard registry's shard "${m(a,h)}" — give mail a database file of its own`)},_e=(e,t)=>{if(e===void 0)return;const{path:r,...o}=e;Se(r),be(r,t);const i=new Z(r);try{return{close:()=>{i.close()},mail:de(i,o)}}catch(a){throw i.close(),a}},ke=(e,t)=>async(r,o,i)=>{if(re(r,t,ge))throw new d("BAD_REQUEST",oe);const a=await e({args:o,functionPath:r,id:i.id,identity:void 0,scheduledFor:i.scheduledFor,shardKey:t,traceparent:void 0});if(!a.ok)throw new d("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(a.status)}`)},Ke=(e={})=>{const t=[],{database:r,dispose:o,drain:i,host:a,pendingAlarms:u,pendingBackground:g,suspendAlarms:f,takeFailures:h}=ue(e);t.push(o);try{const l=ie(r),s=fe(e);t.push(n=>{s.close(n)});const{directory:O}=s,I=ee(O,e.onFetch!==void 0),B=te({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:I,schedulerSecret:e.dispatch?.schedulerSecret}),C=e.onFetch===void 0?void 0:ke(I,e.shardKey??"__root__"),{declareCrons:U,dispose:q,pendingDispatches:y,scheduler:W,suspend:J}=he(r,{...e,onDispatch:e.onDispatch??C}),{socket:K}=me(r);t.push(q),e.crons!==void 0&&U(ve(e.crons,e.onDispatch!==void 0||e.onFetch!==void 0));const Q=e.queues===void 0?void 0:le(r,{onBatch:e.onQueueBatch??(()=>{throw new d("VALIDATION_ERROR","@lunora/platform-node: createNodePlatform was given `queues` without `onQueueBatch`, so a delivered batch has nowhere to go — pass the worker's queue export from createWorker")}),queues:e.queues}),v=_e(e.mail,e);v!==void 0&&t.push(v.close);const R=v?.mail,x=e.objectStorageDirectory===void 0?void 0:ce({directory:e.objectStorageDirectory}),S=e.globalTablesPath===void 0?void 0:ne({path:e.globalTablesPath});S!==void 0&&t.push(()=>{S.dispose()});const G=e.workflows===void 0?void 0:pe({store:we(r),workflows:e.workflows}),E=n=>{const c=[];for(const b of t.toReversed())try{b(n)}catch(_){c.push(_)}if(c.length>0)throw new AggregateError(c,`@lunora/platform-node: ${String(c.length)} resource(s) failed to close`)},T=()=>[...g()>0||u()>0?["waitUntil work on the platform host"]:[],...y().labels],A=[{drain:async n=>{const c=P(n);try{const[b,_]=await Promise.all([D(i(),c),D(Promise.allSettled(y().waits),c)]);if(b&&_)return{failed:h(),pending:[],timedOut:!1};const L=T();return console.error("[@lunora/platform-node] platform drain deadline passed with work still running: %s",L.join(", ")),{failed:h(),pending:L,timedOut:!0}}finally{c.cancel()}},idle:()=>g()===0&&u()===0&&y().waits.length===0,pending:T},s,...R===void 0?[]:[Ae(R)]];return{capabilities:z,close:E,directory:O,dispatch:n=>B(n),idle:()=>A.every(n=>n.idle()),pending:()=>A.flatMap(n=>n.pending()),drain:async n=>(ae(n),J(),f(),s.suspendAlarms(),se(A,n)),globalTables:S,kv:l,mail:R,objectStorage:x,rearmPersistedAlarms:()=>s.rearmPersistedAlarms(),queues:Q,scheduler:W,shard:a,sockets:K,workflows:G,[Symbol.dispose]:()=>{E()}}}catch(l){for(const s of t.toReversed())try{s()}catch{}throw l}};export{ke as createJobDelivery,Ke as createNodePlatform,ye as walkDeclaredCrons};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{randomUUID as P}from"node:crypto";import{deserialize as z,serialize as j}from"node:v8";import{LunoraError as d}from"@lunora/errors";import{isQueueDefinition as G,queueDefaultName as J,queueBindingName as K}from"@lunora/queue";const h={maxBatchSize:10,maxBatchTimeoutSeconds:5,maxRetries:3,retryDelaySeconds:0,visibilityTimeoutMs:3e4},Z=86400,I=131072,B=262144,ee=(e,s)=>{switch(s){case"bytes":{if(e instanceof ArrayBuffer)return Buffer.from(e);if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);throw new d("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "bytes" needs an ArrayBuffer or a typed array')}case"text":{if(typeof e!="string")throw new d("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "text" needs a string');return Buffer.from(e,"utf8")}case"v8":return j(e);default:return Buffer.from(JSON.stringify(e??null),"utf8")}},M=(e,s,E)=>{const p=ee(e,s);if(p.byteLength>I)throw new d("VALIDATION_ERROR",`@lunora/platform-node: a message for queue "${E}" encodes to ${String(p.byteLength)} bytes, over the Cloudflare Queues ceiling of ${String(I)} (128 KiB) per message — store the payload and enqueue a reference to it`);return p},A=(e,s)=>{switch(s){case"bytes":return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);case"text":return e.toString("utf8");case"v8":return z(e);default:return JSON.parse(e.toString("utf8"))}},te=e=>{try{return A(e.body,e.content_type)}catch{return}},R=e=>e===void 0||!Number.isFinite(e)?0:Math.min(Math.max(0,Math.ceil(e)),Z)*1e3,U=new WeakMap,ae=(e,s)=>{const E=U.get(e)?.get(s);if(E===void 0)throw new d("INTERNAL",`@lunora/platform-node: no queue "${s}" on this host`);return E},w="lunora-mail",x=new WeakSet,ie=e=>(x.add(e),e),b=new WeakMap,ue=(e,s)=>{e.pragma("journal_mode = WAL"),e.exec(`CREATE TABLE IF NOT EXISTS _lunora_queue_messages (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
queue TEXT NOT NULL,
|
|
4
|
+
body BLOB NOT NULL,
|
|
5
|
+
content_type TEXT NOT NULL,
|
|
6
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
visible_at INTEGER NOT NULL,
|
|
8
|
+
enqueued_at INTEGER NOT NULL,
|
|
9
|
+
state TEXT NOT NULL DEFAULT 'pending'
|
|
10
|
+
)`),e.exec("CREATE INDEX IF NOT EXISTS _lunora_queue_messages_due ON _lunora_queue_messages (queue, state, visible_at)");const E=e.prepare("INSERT INTO _lunora_queue_messages (id, queue, body, content_type, visible_at, enqueued_at) VALUES (?, ?, ?, ?, ?, ?)"),p=e.prepare(`UPDATE _lunora_queue_messages
|
|
11
|
+
SET attempts = attempts + 1, visible_at = ?
|
|
12
|
+
WHERE id IN (
|
|
13
|
+
SELECT id FROM _lunora_queue_messages
|
|
14
|
+
WHERE queue = ? AND state = 'pending' AND visible_at <= ?
|
|
15
|
+
ORDER BY visible_at, enqueued_at LIMIT ?
|
|
16
|
+
)
|
|
17
|
+
RETURNING *`),C=e.prepare("UPDATE _lunora_queue_messages SET visible_at = ? WHERE id = ?"),S=e.prepare("DELETE FROM _lunora_queue_messages WHERE id = ?"),W=e.prepare("UPDATE _lunora_queue_messages SET state = 'dead' WHERE id = ?"),$=e.prepare("SELECT enqueued_at FROM _lunora_queue_messages WHERE queue = ? AND state = 'pending' AND visible_at <= ? ORDER BY enqueued_at LIMIT 1"),k=e.prepare("SELECT COUNT(*) AS n FROM _lunora_queue_messages WHERE queue = ? AND state = 'pending' AND visible_at <= ?"),F=e.prepare("SELECT * FROM _lunora_queue_messages WHERE queue = ? AND state = 'dead' ORDER BY enqueued_at"),H=e.prepare("UPDATE _lunora_queue_messages SET state = 'pending', attempts = 0, visible_at = ? WHERE id = ? AND state = 'dead' AND queue IN (SELECT value FROM json_each(?))"),T=Object.entries(s.queues).map(([t,n])=>{if(!G(n))throw new d("VALIDATION_ERROR",`@lunora/platform-node: "${t}" is not a defineQueue result`);return{definition:n,exportName:t,name:n.name??J(t)}}),_=new Set(T.map(t=>t.name));if(_.has(w)&&!x.has(s))throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue name "${w}" is reserved for the mail host, which would otherwise share its rows with this queue — give the queue another name`);const N=b.get(e)??new Set,L=[..._].find(t=>N.has(t));if(L!==void 0)throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue "${L}" is already declared by another host on this database connection, and both would claim its rows — give it another name, or a connection of its own`);const Q=JSON.stringify([..._]);for(const t of T){const n=t.definition.deadLetterQueue;if(n!==void 0){if(n===t.name)throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue "${t.name}" names itself as its own deadLetterQueue, which would redeliver forever`);if(!_.has(n))throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue "${t.name}" names deadLetterQueue "${n}", which no declared queue provides — its dead letters would be unreachable`)}}const V=s.visibilityTimeoutMs??h.visibilityTimeoutMs,y=s.now??Date.now,g=(t,n,u,c,r)=>{E.run(P(),t,n,u,r+c,r)},X=(t,n,u,c,r)=>{if(u==="ack"){S.run(t.id);return}const a=n.definition.maxRetries??h.maxRetries;if(t.attempts>a){const l=n.definition.deadLetterQueue;l===void 0?W.run(t.id):(g(l,t.body,t.content_type,0,r),S.run(t.id));return}const m=R(c??n.definition.retryDelay??h.retryDelaySeconds);C.run(r+m,t.id)},O={},v={...s.env},D=new Map;for(const t of T){const n=(c,r)=>{const a=r?.contentType??"json",m=M(c,a,t.name),l=R(r?.delaySeconds);let f;return{insert:()=>{g(t.name,m,a,l,y())},get stored(){return f??={value:A(m,a)},f.value}}};D.set(t.exportName,n);const u={send:async(c,r)=>{n(c,r).insert()},sendBatch:async(c,r)=>{const a=y(),m=R(r?.delaySeconds),l=[...c].map(o=>{const i=o.contentType??"json";return{contentType:i,delay:o.delaySeconds===void 0?m:R(o.delaySeconds),encoded:M(o.body,i,t.name)}}),f=l.reduce((o,i)=>o+i.encoded.byteLength,0);if(f>B)throw new d("VALIDATION_ERROR",`@lunora/platform-node: a sendBatch for queue "${t.name}" encodes to ${String(f)} bytes, over the Cloudflare Queues ceiling of ${String(B)} (256 KiB) per batch — split it across more calls`);e.transaction(()=>{for(const o of l)g(t.name,o.encoded,o.contentType,o.delay,a)})()}};O[t.exportName]=u,v[K(t.exportName)]=u}const Y=async(t,n)=>{const u=Math.min(Math.max(1,t.definition.maxBatchSize??h.maxBatchSize),100),c=k.get(t.name,n)?.n??0;if(c===0)return!1;if(c<u){const o=$.get(t.name,n)?.enqueued_at,i=Math.min(Math.max(0,t.definition.maxBatchTimeout??h.maxBatchTimeoutSeconds),60)*1e3;if(o!==void 0&&n-o<i)return!1}const r=e.transaction(()=>p.all(n+V,t.name,n,u)).immediate();if(r.length===0)return!1;const a=new Map,m=r.map(o=>({ack:()=>{a.set(o.id,{outcome:"ack"})},attempts:o.attempts,body:A(o.body,o.content_type),id:o.id,retry:i=>{a.set(o.id,{delaySeconds:i?.delaySeconds,outcome:"retry"})},timestamp:new Date(o.enqueued_at)})),l={ackAll:()=>{for(const o of r)a.set(o.id,{outcome:"ack"})},messages:m,queue:t.name,retryAll:o=>{for(const i of r)a.set(i.id,{delaySeconds:o?.delaySeconds,outcome:"retry"})}};let f="ack";try{await s.onBatch(l)}catch{f="retry"}return e.transaction(()=>{for(const o of r){const i=a.get(o.id);X(o,t,i?.outcome??f,i?.delaySeconds,n)}})(),!0},q={bindings:O,deadLetters:{list:t=>F.all(t).map(n=>({attempts:n.attempts,body:te(n),id:n.id})),requeue:t=>H.run(y(),t,Q).changes>0},env:v,poll:async(t=y())=>{let n=0;for(const u of T)u.definition.mode!=="pull"&&await Y(u,t)&&(n+=1);return n}};U.set(q,D);for(const t of _)N.add(t);return b.set(e,N),q};export{w as RESERVED_MAIL_QUEUE_NAME,ie as allowReservedQueueName,ue as createNodeQueueHost,ae as preparedSendOf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AsyncLocalStorage as U}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,L=10,b=r=>r===void 0?null:r,ee=(r,a)=>({get databaseSize(){const f=r.pragma("page_count",{simple:!0}),u=r.pragma("page_size",{simple:!0});return f*u},exec:(f,...u)=>{a("run SQL");const c=J(r,f),y=u.map(i=>b(i)),o=c.reader&&c.readonly;let n;const h=()=>(n===void 0&&(a("run SQL"),c.reader?n=c.all(...y):(c.run(...y),n=[])),n);o||h();const d=function*(){a("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]:()=>h()[Symbol.iterator](),one:()=>{const i=h();if(i.length!==1)throw new Error(`expected exactly one row, got ${String(i.length)}`);return i[0]},...o?{raw:d}:{},toArray:()=>[...h()]}}}),re=(r,a,f,u,c=()=>{},y=()=>{})=>{let o,n,h=!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"),N=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=>N.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()},L),g=!0},I=()=>{const e=R.get();e!==void 0&&(o=e.scheduled_for,A(e.scheduled_for))},W=(e,s,_=t)=>{if(!r.open||o!==void 0||_!==t){e();return}if(r.inTransaction){E.add({retry:()=>{D(e,s,_)},settle:e}),T??=setTimeout(k,L);return}if(d+=1,d>K){d=0,e();return}const p=Date.now()+F*2**(d-1);if(z(p)){o=p,A(p),e();return}d=0,I(),e()},D=(e,s,_=t,p=0)=>{const B=d;try{W(e,s,_)}catch(q){if(d=B,r.open&&p+1<Z){E.add({retry:()=>{D(e,s,_,p+1)},settle:e}),T??=setTimeout(k,F*2**p);return}const P=new Date(s).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",P,u??"(unnamed)",p+1,q),y(`shard ${u??"(unnamed)"}: the retry of the alarm due ${P} could not be written`),e()}},k=()=>{if(T=void 0,r.open&&r.inTransaction){T=setTimeout(k,L);return}const e=[...E];E.clear();for(const s of e)s.retry()},x=(e,s=0)=>{if(h)return;const _=t;if(r.open&&r.inTransaction){v(()=>{x(e,s)});return}if(o=void 0,!!r.open){try{if(!C(e)){I();return}}catch{o=e,s<K&&(n=setTimeout(()=>{n=void 0,x(e,s+1)},F*2**s));return}c((async()=>{await f?.(),d=0})().catch(async p=>{console.error("[@lunora/platform-node] alarm handler on shard %s threw; retrying with backoff",u??"(unnamed)",p),await new Promise(B=>{D(B,e,_)})}))}},A=e=>{if(l(),h)return;const s=Math.max(0,e-Date.now());if(s>G){n=setTimeout(()=>{A(e)},G);return}n=setTimeout(()=>{n=void 0,x(e)},s)},Y={delete:()=>{if(!r.open)throw new Error("platform closed: cannot delete an alarm");if(a.assertOwnTurn("delete an alarm"),d=0,S(void 0),a.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");a.assertOwnTurn("set an alarm");const s=typeof e=="number"?e:e.getTime();if(d=0,S(s),a.inside()){i={at:s};return}t+=1,o=s,A(s)}},$=()=>{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)},H=()=>{if(m=void 0,!r.open)return;if(r.inTransaction){m=setTimeout(H,L);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),H()},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:()=>{h=!0,l(),m!==void 0&&(clearTimeout(m),m=void 0)}}},te=(r,a)=>{r.pragma("journal_mode = WAL");const f=new U;let u=!1;const c=t=>{if(u&&f.getStore()!==!0)throw new X("SHARD_UNAVAILABLE",`shard busy: cannot ${t} while another task holds this shard's transaction`)},y=ee(r,c),o=new Set,n=[],{alarms:h,commit:d,dispose:i,suspend:O,rollback:M}=re(r,{assertOwnTurn:c,inside:()=>f.getStore()===!0},a.onAlarm,a.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",a.shardKey??"(unnamed)",l),n.push(`shard ${a.shardKey??"(unnamed)"}: an alarm delivery failed outside its retry handling`)})},t=>{n.push(t)}),w=new Set,R=new U;let N=Promise.resolve();const S=async t=>{if(R.getStore()===!0)return await t();const l=N;let v=()=>{};N=new Promise(I=>{v=I}),await l;try{return await R.run(!0,t)}finally{v()}},z=t=>S(t),C=async t=>{r.exec("BEGIN"),u=!0;try{const l=await f.run(!0,t);return r.exec("COMMIT"),u=!1,d(),l}catch(l){u=!1;try{r.exec("ROLLBACK")}catch{}throw M(),l}},g=t=>S(async()=>C(t)),m={alarms:h,runSerialized:z,shardKey:a.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",a.shardKey??"(unnamed)",v)}).finally(()=>{w.delete(l)});w.add(l)}};return{alarmsSettled:()=>o.size===0?void 0:Promise.allSettled(o),database:r,dispose:()=>{i(),r.open&&r.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)}},le=(r={})=>{const a=new j(r.path??":memory:");try{return te(a,r)}catch(f){throw a.close(),f}};export{le as createNodeShardHost};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mkdirSync as P,readdirSync as W}from"node:fs";import{join as b}from"node:path";import{LunoraError as U}from"@lunora/errors";import x from"better-sqlite3";import{startDrainDeadline as z,settlesBefore as K}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeShardKvStore as T}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeShardHost as V}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeSocketHost as X}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("")),G=n=>decodeURIComponent(n),J=(n,s)=>{const d=s.slice(0,-v.length),l=b(n,s);let u;try{u=G(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(u)}${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 "${u}", 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}" "${b(n,f)}"`);return u},Q=(n,s)=>{let d;try{return d=new x(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()}},k=(n,s,d)=>n===0?"":`${String(n)} ${n===1?s:d}`,Y=(n,s)=>{const d=[k(s.requests,"request in flight","requests in flight"),k(s.alarms,"alarm running","alarms running"),k(s.background,"waitUntil task","waitUntil tasks"),s.closing?"a socket close handler running":""].filter(l=>l!=="");return`shard ${n}: ${d.join(", ")}`},ie=(n={})=>{const s=new Map;let d="open",l=!1;const u=()=>{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,h=new Set,E=[];if(n.directory!==void 0){P(n.directory,{recursive:!0});for(const e of W(n.directory))e.endsWith(v)&&S.add(J(n.directory,e))}const $=e=>{f();const t=s.get(e);if(t!==void 0)return t.shard;const r=n.directory===void 0?void 0:b(n.directory,`${F(e)}${v}`);let o;const{alarmsSettled:a,database:i,dispose:c,drain:g,host:w,pendingAlarms:_,pendingBackground:j,suspendAlarms:L,takeFailures:C}=V({onAlarm:()=>n.onAlarm?.(o),path:r,shardKey:e});let A;try{A=X(i),o={inbound:A,kv:T(i),shard:w,shardKey:e,sockets:A.socket}}catch(O){throw c(),O}return s.set(e,{alarmsSettled:a,dispose:c,drain:A.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=$(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 c=i.drain(),g=i.pendingBackground(),w=i.pendingAlarms();c!==void 0&&(t(a).closing=!0,r.push(c)),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])=>Y(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)},y=(e,t)=>{const r=N(e,t);if(r.length>0){Promise.allSettled(r).then(()=>{h.has(e)&&s.get(e)===t&&y(e,t)}).catch(()=>{});return}h.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?h.delete(e):r&&!h.has(e)&&(h.add(e),y(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=[];u();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 c=D(o,a,i.length>0);c!==void 0&&r.push({error:c,key:o})}else h.has(o)||(h.add(o),y(o,a))}R(),M(t,r)},drain:async e=>{const t=z(e);try{for(let r=p();r.waits.length>0;r=p())if(!await K(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)&&Q(b(e,`${F(r)}${v}`),r))try{$(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:$,suspendAlarms:u}};export{v as SHARD_FILE_SUFFIX,ie as createNodeShardRegistry};
|
|
@@ -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,7 +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/
|
|
51
|
+
"@lunora/mail": "^1.0.0-alpha.140",
|
|
52
|
+
"@lunora/platform": "^1.0.0-alpha.82",
|
|
52
53
|
"@lunora/queue": "^1.0.0-alpha.144",
|
|
53
54
|
"@lunora/runtime": "^1.0.0-alpha.292",
|
|
54
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{LunoraError as d}from"@lunora/errors";import{NODE_CAPABILITIES as H}from"@lunora/platform";import{a as q,c as U,i as $,A as C}from"./node-dispatch-route-ByuCR26s.mjs";import{startDrainDeadline as V,settlesBefore as N,drainTimeoutMs as Q,drainTogether as x}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeGlobalStore as G}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as K}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeQueueHost as M}from"./createNodeQueueHost-szMV0PBN.mjs";import{createNodeR2Bucket as W}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as J}from"./createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as j}from"./createNodeShardHost-VU8MPeba.mjs";import{createNodeShardRegistry as Y}from"./createNodeShardRegistry-BHzxHBx1.mjs";import{createNodeSocketHost as z}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as X}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as Z}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const ee="__root__",re=e=>Object.entries(e).flatMap(([o,r])=>r.map(t=>{if(t.functionPath===void 0)throw new d("VALIDATION_ERROR",t.workflow===void 0?`@lunora/platform-node: cron job "${t.name}" has neither a function target nor a workflow target`:`@lunora/platform-node: cron job "${t.name}" starts workflow "${t.workflow}", which this host cannot do from a cron tick — schedule a function that calls ctx.workflows.get(name).create() instead`);return{args:t.args??{},expression:o,functionPath:t.functionPath,name:t.name}})),oe=(e,o)=>{const r=re(e);if(r.length>0&&!o)throw new d("VALIDATION_ERROR","@lunora/platform-node: `crons` declares jobs but nothing can deliver them — pass `onFetch` (to run them on the shard) or `onDispatch`");return r},te=(e,o)=>async(r,t,c)=>{if($(r,o,ee))throw new d("BAD_REQUEST",C);const i=await e({args:t,functionPath:r,id:c.id,identity:void 0,scheduledFor:c.scheduledFor,shardKey:o,traceparent:void 0});if(!i.ok)throw new d("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(i.status)}`)},Se=(e={})=>{const o=[],{database:r,dispose:t,drain:c,host:i,pendingAlarms:p,pendingBackground:g,suspendAlarms:R,takeFailures:S}=j(e);o.push(t);try{const l=K(r),s=Y(e);o.push(a=>{s.close(a)});const{directory:v}=s,k=q(v,e.onFetch!==void 0),y=U({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:k,schedulerSecret:e.dispatch?.schedulerSecret}),E=e.onFetch===void 0?void 0:te(k,e.shardKey??"__root__"),{declareCrons:b,dispose:T,pendingDispatches:h,scheduler:I,suspend:F}=J(r,{...e,onDispatch:e.onDispatch??E}),{socket:O}=z(r);o.push(T),e.crons!==void 0&&b(oe(e.crons,e.onDispatch!==void 0||e.onFetch!==void 0));const P=e.queues===void 0?void 0:M(r,{onBatch:e.onQueueBatch??(()=>{throw new d("VALIDATION_ERROR","@lunora/platform-node: createNodePlatform was given `queues` without `onQueueBatch`, so a delivered batch has nowhere to go — pass the worker's queue export from createWorker")}),queues:e.queues}),B=e.objectStorageDirectory===void 0?void 0:W({directory:e.objectStorageDirectory}),u=e.globalTablesPath===void 0?void 0:G({path:e.globalTablesPath});u!==void 0&&o.push(()=>{u.dispose()});const L=e.workflows===void 0?void 0:X({store:Z(r),workflows:e.workflows}),A=a=>{const n=[];for(const m of o.toReversed())try{m(a)}catch(w){n.push(w)}if(n.length>0)throw new AggregateError(n,`@lunora/platform-node: ${String(n.length)} resource(s) failed to close`)},_=()=>[...g()>0||p()>0?["waitUntil work on the platform host"]:[],...h().labels],f={drain:async a=>{const n=V(a);try{const[m,w]=await Promise.all([N(c(),n),N(Promise.allSettled(h().waits),n)]);if(m&&w)return{failed:S(),pending:[],timedOut:!1};const D=_();return console.error("[@lunora/platform-node] platform drain deadline passed with work still running: %s",D.join(", ")),{failed:S(),pending:D,timedOut:!0}}finally{n.cancel()}},idle:()=>g()===0&&p()===0&&h().waits.length===0,pending:_};return{capabilities:H,close:A,directory:v,dispatch:a=>y(a),idle:()=>f.idle()&&s.idle(),pending:()=>[...f.pending(),...s.pending()],drain:async a=>(Q(a),F(),R(),s.suspendAlarms(),x([f,s],a)),globalTables:u,kv:l,objectStorage:B,rearmPersistedAlarms:()=>s.rearmPersistedAlarms(),queues:P,scheduler:I,shard:i,sockets:O,workflows:L,[Symbol.dispose]:()=>{A()}}}catch(l){for(const s of o.toReversed())try{s()}catch{}throw l}};export{te as createJobDelivery,Se as createNodePlatform};
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{randomUUID as F}from"node:crypto";import{deserialize as H,serialize as W}from"node:v8";import{LunoraError as m}from"@lunora/errors";import{isQueueDefinition as X,queueDefaultName as $,queueBindingName as Q}from"@lunora/queue";const _={maxBatchSize:10,maxBatchTimeoutSeconds:5,maxRetries:3,retryDelaySeconds:0,visibilityTimeoutMs:3e4},V=86400,A=131072,S=262144,k=(e,i)=>{switch(i){case"bytes":{if(e instanceof ArrayBuffer)return Buffer.from(e);if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);throw new m("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "bytes" needs an ArrayBuffer or a typed array')}case"text":{if(typeof e!="string")throw new m("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "text" needs a string');return Buffer.from(e,"utf8")}case"v8":return W(e);default:return Buffer.from(JSON.stringify(e??null),"utf8")}},O=(e,i,R)=>{const E=k(e,i);if(E.byteLength>A)throw new m("VALIDATION_ERROR",`@lunora/platform-node: a message for queue "${R}" encodes to ${String(E.byteLength)} bytes, over the Cloudflare Queues ceiling of ${String(A)} (128 KiB) per message — store the payload and enqueue a reference to it`);return E},D=(e,i)=>{switch(i){case"bytes":return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);case"text":return e.toString("utf8");case"v8":return H(e);default:return JSON.parse(e.toString("utf8"))}},Y=e=>{try{return D(e.body,e.content_type)}catch{return}},y=e=>e===void 0||!Number.isFinite(e)?0:Math.min(Math.max(0,Math.ceil(e)),V)*1e3,K=(e,i)=>{e.pragma("journal_mode = WAL"),e.exec(`CREATE TABLE IF NOT EXISTS _lunora_queue_messages (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
queue TEXT NOT NULL,
|
|
4
|
-
body BLOB NOT NULL,
|
|
5
|
-
content_type TEXT NOT NULL,
|
|
6
|
-
attempts INTEGER NOT NULL DEFAULT 0,
|
|
7
|
-
visible_at INTEGER NOT NULL,
|
|
8
|
-
enqueued_at INTEGER NOT NULL,
|
|
9
|
-
state TEXT NOT NULL DEFAULT 'pending'
|
|
10
|
-
)`),e.exec("CREATE INDEX IF NOT EXISTS _lunora_queue_messages_due ON _lunora_queue_messages (queue, state, visible_at)");const R=e.prepare("INSERT INTO _lunora_queue_messages (id, queue, body, content_type, visible_at, enqueued_at) VALUES (?, ?, ?, ?, ?, ?)"),E=e.prepare(`UPDATE _lunora_queue_messages
|
|
11
|
-
SET attempts = attempts + 1, visible_at = ?
|
|
12
|
-
WHERE id IN (
|
|
13
|
-
SELECT id FROM _lunora_queue_messages
|
|
14
|
-
WHERE queue = ? AND state = 'pending' AND visible_at <= ?
|
|
15
|
-
ORDER BY visible_at, enqueued_at LIMIT ?
|
|
16
|
-
)
|
|
17
|
-
RETURNING *`),q=e.prepare("UPDATE _lunora_queue_messages SET visible_at = ? WHERE id = ?"),h=e.prepare("DELETE FROM _lunora_queue_messages WHERE id = ?"),v=e.prepare("UPDATE _lunora_queue_messages SET state = 'dead' WHERE id = ?"),B=e.prepare("SELECT enqueued_at FROM _lunora_queue_messages WHERE queue = ? AND state = 'pending' AND visible_at <= ? ORDER BY enqueued_at LIMIT 1"),I=e.prepare("SELECT COUNT(*) AS n FROM _lunora_queue_messages WHERE queue = ? AND state = 'pending' AND visible_at <= ?"),M=e.prepare("SELECT * FROM _lunora_queue_messages WHERE queue = ? AND state = 'dead' ORDER BY enqueued_at"),b=e.prepare("UPDATE _lunora_queue_messages SET state = 'pending', attempts = 0, visible_at = ? WHERE id = ? AND state = 'dead'"),p=Object.entries(i.queues).map(([t,n])=>{if(!X(n))throw new m("VALIDATION_ERROR",`@lunora/platform-node: "${t}" is not a defineQueue result`);return{definition:n,exportName:t,name:n.name??$(t)}}),x=new Set(p.map(t=>t.name));for(const t of p){const n=t.definition.deadLetterQueue;if(n!==void 0){if(n===t.name)throw new m("VALIDATION_ERROR",`@lunora/platform-node: queue "${t.name}" names itself as its own deadLetterQueue, which would redeliver forever`);if(!x.has(n))throw new m("VALIDATION_ERROR",`@lunora/platform-node: queue "${t.name}" names deadLetterQueue "${n}", which no declared queue provides — its dead letters would be unreachable`)}}const U=i.visibilityTimeoutMs??_.visibilityTimeoutMs,T=i.now??Date.now,g=(t,n,s,u,o)=>{R.run(F(),t,n,s,o+u,o)},w=(t,n,s,u,o)=>{if(s==="ack"){h.run(t.id);return}const c=n.definition.maxRetries??_.maxRetries;if(t.attempts>c){const l=n.definition.deadLetterQueue;l===void 0?v.run(t.id):(g(l,t.body,t.content_type,0,o),h.run(t.id));return}const f=y(u??n.definition.retryDelay??_.retryDelaySeconds);q.run(o+f,t.id)},N={},L={...i.env};for(const t of p){const n={send:async(s,u)=>{const o=u?.contentType??"json";g(t.name,O(s,o,t.name),o,y(u?.delaySeconds),T())},sendBatch:async(s,u)=>{const o=T(),c=y(u?.delaySeconds),f=[...s].map(a=>{const r=a.contentType??"json";return{contentType:r,delay:a.delaySeconds===void 0?c:y(a.delaySeconds),encoded:O(a.body,r,t.name)}}),l=f.reduce((a,r)=>a+r.encoded.byteLength,0);if(l>S)throw new m("VALIDATION_ERROR",`@lunora/platform-node: a sendBatch for queue "${t.name}" encodes to ${String(l)} bytes, over the Cloudflare Queues ceiling of ${String(S)} (256 KiB) per batch — split it across more calls`);e.transaction(()=>{for(const a of f)g(t.name,a.encoded,a.contentType,a.delay,o)})()}};N[t.exportName]=n,L[Q(t.exportName)]=n}const C=async(t,n)=>{const s=Math.min(Math.max(1,t.definition.maxBatchSize??_.maxBatchSize),100),u=I.get(t.name,n)?.n??0;if(u===0)return!1;if(u<s){const r=B.get(t.name,n)?.enqueued_at,d=Math.min(Math.max(0,t.definition.maxBatchTimeout??_.maxBatchTimeoutSeconds),60)*1e3;if(r!==void 0&&n-r<d)return!1}const o=e.transaction(()=>E.all(n+U,t.name,n,s)).immediate();if(o.length===0)return!1;const c=new Map,f=o.map(r=>({ack:()=>{c.set(r.id,{outcome:"ack"})},attempts:r.attempts,body:D(r.body,r.content_type),id:r.id,retry:d=>{c.set(r.id,{delaySeconds:d?.delaySeconds,outcome:"retry"})},timestamp:new Date(r.enqueued_at)})),l={ackAll:()=>{for(const r of o)c.set(r.id,{outcome:"ack"})},messages:f,queue:t.name,retryAll:r=>{for(const d of o)c.set(d.id,{delaySeconds:r?.delaySeconds,outcome:"retry"})}};let a="ack";try{await i.onBatch(l)}catch{a="retry"}return e.transaction(()=>{for(const r of o){const d=c.get(r.id);w(r,t,d?.outcome??a,d?.delaySeconds,n)}})(),!0};return{bindings:N,deadLetters:{list:t=>M.all(t).map(n=>({attempts:n.attempts,body:Y(n),id:n.id})),requeue:t=>b.run(T(),t).changes>0},env:L,poll:async(t=T())=>{let n=0;for(const s of p)s.definition.mode!=="pull"&&await C(s,t)&&(n+=1);return n}}};export{K as createNodeQueueHost};
|
|
@@ -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{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};
|