@lunora/platform-node 1.0.0-alpha.227 → 1.0.0-alpha.229

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{NODE_CAPABILITIES as g}from"@lunora/platform";import{createNodeShardKvStore as D}from"../packem_shared/createNodeShardKvStore-Bh6oQZgs.mjs";import{createNodeSchedulerHost as k}from"../packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as T}from"../packem_shared/createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-DEn0kYmG.mjs";import{createNodeSocketHost as b}from"../packem_shared/createNodeSocketHost-BJf5HOHr.mjs";const P=()=>{const{database:o,dispose:m,host:p}=T(),h=D(o),i=H(),{directory:l}=i,{readFrames:w,restoreSocket:S,simulateRecycle:u,socket:f}=b(o),c=new Set,s=new Map,{dispose:y,scheduler:d,simulateDeadLetter:N}=k(o,{onDispatch:(e,a,t)=>{c.add(t.id),s.set(e,(s.get(e)??0)+1)}}),n=()=>{y(),m(),i.close()};return{capabilities:g,awaitAlarmFired:async e=>{await new Promise(a=>{setTimeout(a,Math.max(0,e-Date.now())+30)})},awaitJobDispatched:async e=>{const t=(await d.list?.())?.find(r=>r.id===e);return t!==void 0&&await new Promise(r=>{setTimeout(r,Math.max(0,t.scheduledFor-Date.now())+30)}),c.has(e)},cleanup:n,cronTicks:e=>s.get(e)??0,directory:l,disposeTerminally:n,kv:h,readFrames:w,restoreSocket:S,scheduler:d,shard:p,simulateDeadLetter:N,simulateRecycle:u,socket:f}};export{P as createNodeConformanceHost};
1
+ import{NODE_CAPABILITIES as g}from"@lunora/platform";import{createNodeShardKvStore as D}from"../packem_shared/createNodeShardKvStore-Bh6oQZgs.mjs";import{createNodeSchedulerHost as k}from"../packem_shared/createNodeSchedulerHost-B5KeCI9c.mjs";import{createNodeShardHost as T}from"../packem_shared/createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-DEn0kYmG.mjs";import{createNodeSocketHost as b}from"../packem_shared/createNodeSocketHost-BJf5HOHr.mjs";const P=()=>{const{database:o,dispose:m,host:p}=T(),h=D(o),i=H(),{directory:l}=i,{readFrames:w,restoreSocket:S,simulateRecycle:u,socket:f}=b(o),c=new Set,s=new Map,{dispose:y,scheduler:d,simulateDeadLetter:N}=k(o,{onDispatch:(e,a,t)=>{c.add(t.id),s.set(e,(s.get(e)??0)+1)}}),n=()=>{y(),m(),i.close()};return{capabilities:g,awaitAlarmFired:async e=>{await new Promise(a=>{setTimeout(a,Math.max(0,e-Date.now())+30)})},awaitJobDispatched:async e=>{const t=(await d.list?.())?.find(r=>r.id===e);return t!==void 0&&await new Promise(r=>{setTimeout(r,Math.max(0,t.scheduledFor-Date.now())+30)}),c.has(e)},cleanup:n,cronTicks:e=>s.get(e)??0,directory:l,disposeTerminally:n,kv:h,readFrames:w,restoreSocket:S,scheduler:d,shard:p,simulateDeadLetter:N,simulateRecycle:u,socket:f}};export{P as createNodeConformanceHost};
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{checkNodeAppHost as c,createNodeAppHost as d}from"./packem_shared/checkNodeAppHost-BW69Ja4_.mjs";import{N,c as f}from"./packem_shared/node-dispatch-route-DjQWVUkP.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-CKwkBmRI.mjs";import{createNodeHyperdrive as D}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as u}from"./packem_shared/createNodeShardKvStore-Bh6oQZgs.mjs";import{createNodeMailHost as E}from"./packem_shared/createNodeMailHost-AOATqXEM.mjs";import{createNodePlatform as _}from"./packem_shared/createNodePlatform-Dr9tUfyX.mjs";import{createNodeProfileHandler as R}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as P}from"./packem_shared/createNodeQueueHost--kuV6C8-.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-DEn0kYmG.mjs";import{bindShardSockets as j,createNodeShardState as q}from"./packem_shared/bindShardSockets-DjLmRlIA.mjs";import{createNodeSocketHost as K}from"./packem_shared/createNodeSocketHost-BJf5HOHr.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
+ 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-C79Egfug.mjs";import{N,c as f}from"./packem_shared/node-dispatch-route-DjQWVUkP.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-CKwkBmRI.mjs";import{createNodeHyperdrive as D}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as u}from"./packem_shared/createNodeShardKvStore-Bh6oQZgs.mjs";import{createNodeMailHost as E}from"./packem_shared/createNodeMailHost-AOATqXEM.mjs";import{createNodePlatform as _}from"./packem_shared/createNodePlatform-BmbU36lo.mjs";import{createNodeProfileHandler as R}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as P}from"./packem_shared/createNodeQueueHost--kuV6C8-.mjs";import{createNodeR2Bucket as v}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as I}from"./packem_shared/createNodeSchedulerHost-B5KeCI9c.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-DEn0kYmG.mjs";import{bindShardSockets as j,createNodeShardState as q}from"./packem_shared/bindShardSockets-DjLmRlIA.mjs";import{createNodeSocketHost as K}from"./packem_shared/createNodeSocketHost-BJf5HOHr.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{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-Dr9tUfyX.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};
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-BmbU36lo.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};
@@ -1 +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-DjQWVUkP.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-Bh6oQZgs.mjs";import{createNodeMailHost as de}from"./createNodeMailHost-AOATqXEM.mjs";import{createNodeQueueHost as le}from"./createNodeQueueHost--kuV6C8-.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-DEn0kYmG.mjs";import{createNodeSocketHost as me}from"./createNodeSocketHost-BJf5HOHr.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};
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-DjQWVUkP.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-Bh6oQZgs.mjs";import{createNodeMailHost as de}from"./createNodeMailHost-AOATqXEM.mjs";import{createNodeQueueHost as le}from"./createNodeQueueHost--kuV6C8-.mjs";import{createNodeR2Bucket as ce}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as he}from"./createNodeSchedulerHost-B5KeCI9c.mjs";import{createNodeShardHost as ue}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardRegistry as fe,SHARD_FILE_SUFFIX as k}from"./createNodeShardRegistry-DEn0kYmG.mjs";import{createNodeSocketHost as me}from"./createNodeSocketHost-BJf5HOHr.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,15 @@
1
+ import{randomUUID as ke}from"node:crypto";import{serialize as v,deserialize as K}from"node:v8";import{LunoraError as Q}from"@lunora/errors";import xe from"@lunora/scheduler/validate";import{parse as be}from"@visulima/cron-parser/cloudflare";const ve={seconds:"optional",tz:"UTC"},I={backoffMultiplier:2,initialDelayMs:1e3,maxAttempts:5,maxDelayMs:6e4},ce=2147483647,C=6e4,Ce=32,le=3e5,ie=1e3,D=6e4,de=D/3,Ue=1e3,je=5,$e=20,U=10,j=6048e5,ue=(s,_)=>{if(!xe(s))throw new Q("VALIDATION_ERROR",`@lunora/platform-node: ${_} has cron expression "${s}", which is invalid or never occurs`)},g="declared:",$=s=>s.key.startsWith(g)?`job "${s.key.slice(g.length)}" (${s.function_path})`:`"${s.expression}" (${s.function_path})`,Fe=(s,_)=>{const T=_?.initialDelayMs??I.initialDelayMs,w=_?.backoffMultiplier??I.backoffMultiplier,M=_?.maxDelayMs??I.maxDelayMs;return Math.min(M,T*w**Math.max(0,s-1))},Xe=(s,_={})=>{const T=new Map,w=(e,t)=>{const n=t.then(()=>{},()=>{});T.set(n,e),n.finally(()=>T.delete(n)).catch(()=>{})};s.exec(`CREATE TABLE IF NOT EXISTS _lunora_scheduler_jobs (
2
+ id TEXT PRIMARY KEY,
3
+ function_path TEXT NOT NULL,
4
+ args BLOB NOT NULL,
5
+ scheduled_for INTEGER NOT NULL,
6
+ attempts INTEGER NOT NULL DEFAULT 0,
7
+ retry BLOB,
8
+ state TEXT NOT NULL DEFAULT 'pending'
9
+ )`);const M=e=>s.prepare("PRAGMA table_info(_lunora_scheduler_jobs)").all().some(t=>t.name===e),fe=e=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},_e=e=>{for(let t=0;;t+=1)try{s.exec(`ALTER TABLE _lunora_scheduler_jobs ADD COLUMN ${e} INTEGER`);return}catch(n){if(M(e))return;if(!(n instanceof Error&&"code"in n&&n.code==="SQLITE_BUSY")||t>=je)throw n;fe($e*2**t)}};for(const e of["claimed_at","completed_at"])M(e)||_e(e);s.exec("CREATE INDEX IF NOT EXISTS _lunora_scheduler_jobs_state_completed ON _lunora_scheduler_jobs (state, completed_at)"),s.exec("CREATE INDEX IF NOT EXISTS _lunora_scheduler_jobs_state_scheduled ON _lunora_scheduler_jobs (state, scheduled_for)"),s.exec(`CREATE TABLE IF NOT EXISTS _lunora_scheduler_crons (
10
+ key TEXT PRIMARY KEY,
11
+ expression TEXT NOT NULL,
12
+ function_path TEXT NOT NULL,
13
+ args BLOB NOT NULL
14
+ )`);const me=s.prepare("INSERT INTO _lunora_scheduler_jobs (id, function_path, args, scheduled_for, retry) VALUES (?, ?, ?, ?, ?)"),F=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE id = ?"),Z=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE state = ? ORDER BY scheduled_for"),pe=s.prepare("SELECT id, scheduled_for, claimed_at FROM _lunora_scheduler_jobs WHERE state = 'pending' AND scheduled_for <= ? AND (claimed_at IS NULL OR claimed_at <= ?) ORDER BY scheduled_for LIMIT ?"),he=s.prepare("SELECT 1 AS found FROM _lunora_scheduler_jobs WHERE state = 'pending' LIMIT 1"),Ee=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'canceled', completed_at = ? WHERE id = ? AND state = 'pending'"),Te=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ?"),W=s.prepare("DELETE FROM _lunora_scheduler_jobs WHERE state IN ('succeeded', 'canceled') AND completed_at <= ?"),ye=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'succeeded', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ?"),Re=s.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND claimed_at = ? AND state = 'pending'"),Ae=s.prepare("UPDATE _lunora_scheduler_jobs SET attempts = ?, scheduled_for = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),Ne=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),De=s.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND state = 'pending' AND scheduled_for <= ? AND (claimed_at IS NULL OR claimed_at < ?) RETURNING *"),ge=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'pending', attempts = 0, completed_at = NULL, scheduled_for = ? WHERE id = ? AND state = 'dead'"),ee=s.prepare(`INSERT INTO _lunora_scheduler_crons (key, expression, function_path, args) VALUES (?, ?, ?, ?)
15
+ ON CONFLICT (key) DO UPDATE SET expression = excluded.expression, function_path = excluded.function_path, args = excluded.args`),te=s.prepare("SELECT * FROM _lunora_scheduler_crons"),ne=s.prepare("SELECT * FROM _lunora_scheduler_crons WHERE key = ?"),Se=s.prepare("DELETE FROM _lunora_scheduler_crons WHERE key = ?"),l=()=>s.open,y=()=>s.inTransaction,re=e=>e===null?void 0:K(e);let a=!1,R=!1;const P=async()=>{a||!l()||!y()||(await new Promise(e=>{setTimeout(e,U).unref()}),await P())},m=new Map,f=new Map,B=new Set;let H=new Set;const J=e=>({attempts:e.attempts,functionPath:e.function_path,id:e.id,scheduledFor:e.scheduled_for}),p=new Set,O=new Set,k=new Set,A=new Map,S=new Set,X=e=>{p.delete(e),S.delete(e);const t=m.get(e);t!==void 0&&(clearTimeout(t),m.delete(e))},h=(e,t)=>{if(X(e),R)return;const n=Math.max(0,t-Date.now());if(n>C)return;const o=setTimeout(()=>{m.delete(e),S.delete(e),p.add(e),z()},n);m.set(e,o)},Le=e=>{const t=F.get(e);!a&&t?.state==="pending"&&h(e,t.claimed_at===null?t.scheduled_for:t.claimed_at+D)};let u,L;const N=()=>{if(a||R||!l()){u?.unref();return}try{he.get()===void 0?y()||u?.unref():u?.ref()}catch{}};let oe=!1,Y=!1;const x=()=>{if(a||R||!l())return;if(y()){u?.ref(),L??=setTimeout(()=>{L=void 0,x()},U),L.unref();return}const e=Date.now(),t=e+C;let n;try{n=pe.all(t,e+C/2-D,ie)}catch(o){u?.ref(),console.error("[@lunora/platform-node] scheduler window pass could not read pending jobs; the next pass tries again",o);return}oe=n.length===ie,Y=!0;try{for(const o of n){const r=o.claimed_at===null?o.scheduled_for:Math.max(o.scheduled_for,o.claimed_at+D);r<=t&&!m.has(o.id)&&!p.has(o.id)&&!O.has(o.id)&&h(o.id,r),m.has(o.id)&&S.add(o.id)}}finally{Y=!1}N()},G=()=>{!Y&&oe&&p.size===0&&S.size===0&&x()},Ie=(e,t)=>{if(y()){a||h(e,t+U);return}try{const n=De.get(t,e,t,t-D);return n===void 0&&Le(e),n}catch{!a&&l()&&h(e,Date.now()+Ue);return}},we=(e,t)=>{let n=t,o;const r=c=>{o=setTimeout(()=>{if(!l())return;if(y()){r(U);return}const i=Date.now();try{Re.run(i,e,n).changes===1&&(n=i)}catch{}r(de)},c),o.unref()};return r(de),{release:()=>{clearTimeout(o)},stamp:()=>n}},Me=async(e,t)=>{if(!l())return;const n=Date.now(),o=Ie(e,n);if(o===void 0)return;t?.(`scheduled job ${o.function_path} (${e})`);const r=o.attempts+1,c=re(o.retry),i=we(e,n);try{if(await _.onDispatch?.(o.function_path,K(o.args),{attempts:r,id:e,scheduledFor:o.scheduled_for}),await P(),l()&&!y()){const d=Date.now();ye.run(r,d,e,i.stamp()),W.run(d-j)}}catch(d){if(await P(),console.error("[@lunora/platform-node] scheduled job %s (%s) failed on attempt %d",o.function_path,e,r,d),a||!l())return;const q=c?.maxAttempts??I.maxAttempts;if(r>=q){Ne.run(r,Date.now(),e,i.stamp());return}const ae=Date.now()+Fe(r,c);Ae.run(r,ae,e,i.stamp()).changes===1&&h(e,ae)}finally{i.release()}},z=()=>{if(a||R){p.clear();return}for(const e of p){if(k.size>=Ce)return;if(p.delete(e),O.has(e))continue;O.add(e),k.add(e);const t={label:`scheduled job ${e}`},n=setTimeout(()=>{A.delete(e),k.delete(e),console.warn(`[@lunora/platform-node] ${t.label} has run for ${String(le)} ms; it keeps running and its claim, but no longer holds a delivery slot`),z()},le);n.unref(),A.set(e,n),w(t,Me(e,o=>{t.label=o}).catch(()=>{}).finally(()=>{clearTimeout(A.get(e)),A.delete(e),k.delete(e),O.delete(e),N(),z(),G()}))}};let V,b;const E=e=>{if(B.has(e.key))return;const t=f.get(e.key);if(t!==void 0&&(clearTimeout(t),f.delete(e.key)),R)return;let n;try{n=be(e.expression,ve).next().getTime()}catch{return}const o=Math.max(0,n-Date.now());if(o>ce)return f.set(e.key,setTimeout(()=>{E(e)},ce)),n;const r=setTimeout(()=>{if(f.delete(e.key),a||!l())return;let c;try{c=ne.get(e.key)}catch(d){b(e,`could not read its row before the tick due ${new Date(n).toISOString()}, so that tick was skipped`,d);return}if(c===void 0){V(e,n,void 0);return}if(c.expression!==e.expression){E(c);return}const i=c;B.add(e.key),w({label:`cron ${$(i)}`},(async()=>{let d;try{await _.onDispatch?.(i.function_path,K(i.args),{attempts:0,id:`${e.key}:${String(n)}`,scheduledFor:n})}catch(q){d={error:q}}finally{B.delete(e.key)}V(i,n,d)})().catch(d=>{b(i,"failed to settle its tick",d)}))},o);return f.set(e.key,r),n};b=(e,t,n)=>{const o=a||!l()?void 0:E(e),r=o===void 0?"none scheduled, the scheduler is closed":new Date(o).toISOString();return console.error(`[@lunora/platform-node] cron ${$(e)} ${t}; re-armed from its last known definition, next run: ${r}`,n),o},V=(e,t,n)=>{let o;if(!a&&l()){let r,c=!1;try{r=ne.get(e.key)}catch(i){c=!0,o=b(e,"could not read its row after its tick",i)}r!==void 0?o=E(r):!c&&H.has(e.key)&&(H.delete(e.key),console.warn(`[@lunora/platform-node] declared cron ${$(e)} was removed from the database by another process passing \`crons\`; it stops firing here`))}if(n!==void 0){const r=o===void 0?"none scheduled":new Date(o).toISOString();console.error(`[@lunora/platform-node] cron ${$(e)} tick due ${new Date(t).toISOString()} failed; next run: ${r}`,n.error)}};const Oe={cancel:async e=>{if(a)return!1;X(e);const t=Date.now(),n=Ee.run(t,e).changes>0;return G(),W.run(t-j),N(),n},cron:async(e,t,n)=>{if(a)throw new Error("platform closed: cannot register a cron");ue(e,`cron for ${t}`);const o={args:v(n??{}),expression:e,function_path:t,key:`${e} ${t}`};ee.run(o.key,o.expression,o.function_path,o.args),E(o)},deadLetter:{list:async()=>a||!l()?[]:Z.all("dead").map(e=>J(e)),requeue:async e=>{if(a||!l())return!1;const t=Date.now();return ge.run(t,e).changes===0?!1:(h(e,t),N(),!0)}},get:async e=>{const t=a||!l()?void 0:F.get(e);if(t===void 0||t.completed_at!==null&&t.state!=="dead"&&t.completed_at<=Date.now()-j)return null;const n={canceled:"canceled",dead:"failed",pending:"pending",succeeded:"succeeded"},o=t.state==="pending"&&t.claimed_at!==null&&t.claimed_at>=Date.now()-D,r={...J(t),state:o?"running":n[t.state]};return t.completed_at!==null&&(r.completedAt=t.completed_at),r},list:async()=>a||!l()?[]:Z.all("pending").map(e=>J(e)),schedule:async(e,t,n)=>{if(a)throw new Error("platform closed: cannot schedule a job");if(n?.retry?.forever===!0)throw new Q("INVALID_INPUT","retry.forever is not supported by the Node scheduler host; set a finite retry.maxAttempts");const o=`node-job-${ke()}`;let r;return n?.at===void 0?r=Date.now()+(n?.delayMs??0):r=typeof n.at=="number"?n.at:n.at.getTime(),me.run(o,e,v(t),r,n?.retry===void 0?null:v(n.retry)),h(o,r),N(),{id:o,scheduledFor:r}}};W.run(Date.now()-j),u=setInterval(x,C/2),u.unref(),x();for(const e of te.all())e.key.startsWith(g)||E(e);const se=()=>{for(const e of m.values())clearTimeout(e);for(const e of f.values())clearTimeout(e);for(const e of A.values())clearTimeout(e);m.clear(),f.clear(),p.clear(),S.clear(),A.clear(),u?.unref(),clearInterval(u),u=void 0,clearTimeout(L),L=void 0};return{pendingDispatches:()=>({labels:[...T.values()].map(e=>e.label),waits:[...T.keys()]}),declareCrons:e=>{if(a)throw new Error("platform closed: cannot declare crons");const t=new Set;for(const r of e){if(t.has(r.name))throw new Q("VALIDATION_ERROR",`@lunora/platform-node: two declared cron jobs are named "${r.name}"; cron job names must be unique`);t.add(r.name),ue(r.expression,`cron job "${r.name}"`)}const n=e.map(r=>({args:v(r.args),expression:r.expression,function_path:r.functionPath,key:`${g}${r.name}`})),o=new Set(n.map(r=>r.key));s.transaction(()=>{for(const r of te.all())r.key.startsWith(g)&&!o.has(r.key)&&Se.run(r.key);for(const r of n)ee.run(r.key,r.expression,r.function_path,r.args)}).immediate();for(const[r,c]of f)r.startsWith(g)&&!o.has(r)&&(clearTimeout(c),f.delete(r));H=o;for(const r of n)E(r)},dispose:()=>{se(),a=!0},scheduler:Oe,simulateDeadLetter:async e=>{const t=F.get(e);if(t?.state!=="pending")return!1;X(e);const n=re(t.retry);return Te.run((n?.maxAttempts??I.maxAttempts)+1,Date.now(),e),G(),N(),!0},suspend:()=>{R=!0,se()}}};export{Xe as createNodeSchedulerHost};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/platform-node",
3
- "version": "1.0.0-alpha.227",
3
+ "version": "1.0.0-alpha.229",
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",
@@ -1,15 +0,0 @@
1
- import{randomUUID as me}from"node:crypto";import{serialize as D,deserialize as F}from"node:v8";import{LunoraError as W}from"@lunora/errors";import _e from"@lunora/scheduler/validate";import{parse as fe}from"@visulima/cron-parser/cloudflare";const Ee={seconds:"optional",tz:"UTC"},T={backoffMultiplier:2,initialDelayMs:1e3,maxAttempts:5,maxDelayMs:6e4},L=2147483647,I=6e4,V=I/3,he=1e3,Te=5,ye=20,P=10,g=6048e5,q=(s,p)=>{if(!_e(s))throw new W("VALIDATION_ERROR",`@lunora/platform-node: ${p} has cron expression "${s}", which is invalid or never occurs`)},h="declared:",S=s=>s.key.startsWith(h)?`job "${s.key.slice(h.length)}" (${s.function_path})`:`"${s.expression}" (${s.function_path})`,Ae=(s,p)=>{const E=p?.initialDelayMs??T.initialDelayMs,y=p?.backoffMultiplier??T.backoffMultiplier,A=p?.maxDelayMs??T.maxDelayMs;return Math.min(A,E*y**Math.max(0,s-1))},Se=(s,p={})=>{const E=new Map,y=(e,t)=>{const r=t.then(()=>{},()=>{});E.set(r,e),r.finally(()=>E.delete(r)).catch(()=>{})};s.exec(`CREATE TABLE IF NOT EXISTS _lunora_scheduler_jobs (
2
- id TEXT PRIMARY KEY,
3
- function_path TEXT NOT NULL,
4
- args BLOB NOT NULL,
5
- scheduled_for INTEGER NOT NULL,
6
- attempts INTEGER NOT NULL DEFAULT 0,
7
- retry BLOB,
8
- state TEXT NOT NULL DEFAULT 'pending'
9
- )`);const A=e=>s.prepare("PRAGMA table_info(_lunora_scheduler_jobs)").all().some(t=>t.name===e),z=e=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},K=e=>{for(let t=0;;t+=1)try{s.exec(`ALTER TABLE _lunora_scheduler_jobs ADD COLUMN ${e} INTEGER`);return}catch(r){if(A(e))return;if(!(r instanceof Error&&"code"in r&&r.code==="SQLITE_BUSY")||t>=Te)throw r;z(ye*2**t)}};for(const e of["claimed_at","completed_at"])A(e)||K(e);s.exec("CREATE INDEX IF NOT EXISTS _lunora_scheduler_jobs_state_completed ON _lunora_scheduler_jobs (state, completed_at)"),s.exec(`CREATE TABLE IF NOT EXISTS _lunora_scheduler_crons (
10
- key TEXT PRIMARY KEY,
11
- expression TEXT NOT NULL,
12
- function_path TEXT NOT NULL,
13
- args BLOB NOT NULL
14
- )`);const Q=s.prepare("INSERT INTO _lunora_scheduler_jobs (id, function_path, args, scheduled_for, retry) VALUES (?, ?, ?, ?, ?)"),k=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE id = ?"),w=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE state = ? ORDER BY scheduled_for"),Z=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'canceled', completed_at = ? WHERE id = ? AND state = 'pending'"),ee=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ?"),x=s.prepare("DELETE FROM _lunora_scheduler_jobs WHERE state IN ('succeeded', 'canceled') AND completed_at <= ?"),te=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'succeeded', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ?"),ne=s.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND claimed_at = ? AND state = 'pending'"),re=s.prepare("UPDATE _lunora_scheduler_jobs SET attempts = ?, scheduled_for = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),oe=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),se=s.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND state = 'pending' AND scheduled_for <= ? AND (claimed_at IS NULL OR claimed_at < ?) RETURNING *"),ae=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'pending', attempts = 0, completed_at = NULL, scheduled_for = ? WHERE id = ? AND state = 'dead'"),B=s.prepare(`INSERT INTO _lunora_scheduler_crons (key, expression, function_path, args) VALUES (?, ?, ?, ?)
15
- ON CONFLICT (key) DO UPDATE SET expression = excluded.expression, function_path = excluded.function_path, args = excluded.args`),H=s.prepare("SELECT * FROM _lunora_scheduler_crons"),J=s.prepare("SELECT * FROM _lunora_scheduler_crons WHERE key = ?"),ce=s.prepare("DELETE FROM _lunora_scheduler_crons WHERE key = ?"),i=()=>s.open,N=()=>s.inTransaction,X=e=>e===null?void 0:F(e);let c=!1,M=!1;const O=async()=>{c||!i()||!N()||(await new Promise(e=>{setTimeout(e,P).unref()}),await O())},_=new Map,u=new Map,b=new Set;let U=new Set;const C=e=>({attempts:e.attempts,functionPath:e.function_path,id:e.id,scheduledFor:e.scheduled_for}),v=e=>{const t=_.get(e);t!==void 0&&(clearTimeout(t),_.delete(e))},m=(e,t)=>{if(v(e),M)return;const r=Math.max(0,t-Date.now());if(r>L){const n=setTimeout(()=>{m(e,t)},L);_.set(e,n);return}const o=setTimeout(()=>{const n={label:`scheduled job ${e}`};y(n,ue(e,a=>{n.label=a}).catch(()=>{}))},r);_.set(e,o)},le=e=>{const t=k.get(e);!c&&t?.state==="pending"&&m(e,t.claimed_at===null?t.scheduled_for:t.claimed_at+I)},ie=(e,t)=>{if(N()){c||m(e,t+P);return}try{const r=se.get(t,e,t,t-I);return r===void 0&&le(e),r}catch{!c&&i()&&m(e,Date.now()+he);return}},de=(e,t)=>{let r=t,o;const n=a=>{o=setTimeout(()=>{if(!i())return;if(N()){n(P);return}const l=Date.now();try{ne.run(l,e,r).changes===1&&(r=l)}catch{}n(V)},a),o.unref()};return n(V),{release:()=>{clearTimeout(o)},stamp:()=>r}},ue=async(e,t)=>{if(_.delete(e),!i())return;const r=Date.now(),o=ie(e,r);if(o===void 0)return;t?.(`scheduled job ${o.function_path} (${e})`);const n=o.attempts+1,a=X(o.retry),l=de(e,r);try{if(await p.onDispatch?.(o.function_path,F(o.args),{attempts:n,id:e,scheduledFor:o.scheduled_for}),await O(),i()&&!N()){const d=Date.now();te.run(n,d,e,l.stamp()),x.run(d-g)}}catch(d){if(await O(),console.error("[@lunora/platform-node] scheduled job %s (%s) failed on attempt %d",o.function_path,e,n,d),c||!i())return;const $=a?.maxAttempts??T.maxAttempts;if(n>=$){oe.run(n,Date.now(),e,l.stamp());return}const G=Date.now()+Ae(n,a);re.run(n,G,e,l.stamp()).changes===1&&m(e,G)}finally{l.release()}};let j,R;const f=e=>{if(b.has(e.key))return;const t=u.get(e.key);if(t!==void 0&&(clearTimeout(t),u.delete(e.key)),M)return;let r;try{r=fe(e.expression,Ee).next().getTime()}catch{return}const o=Math.max(0,r-Date.now());if(o>L)return u.set(e.key,setTimeout(()=>{f(e)},L)),r;const n=setTimeout(()=>{if(u.delete(e.key),c||!i())return;let a;try{a=J.get(e.key)}catch(d){R(e,`could not read its row before the tick due ${new Date(r).toISOString()}, so that tick was skipped`,d);return}if(a===void 0){j(e,r,void 0);return}if(a.expression!==e.expression){f(a);return}const l=a;b.add(e.key),y({label:`cron ${S(l)}`},(async()=>{let d;try{await p.onDispatch?.(l.function_path,F(l.args),{attempts:0,id:`${e.key}:${String(r)}`,scheduledFor:r})}catch($){d={error:$}}finally{b.delete(e.key)}j(l,r,d)})().catch(d=>{R(l,"failed to settle its tick",d)}))},o);return u.set(e.key,n),r};R=(e,t,r)=>{const o=c||!i()?void 0:f(e),n=o===void 0?"none scheduled, the scheduler is closed":new Date(o).toISOString();return console.error(`[@lunora/platform-node] cron ${S(e)} ${t}; re-armed from its last known definition, next run: ${n}`,r),o},j=(e,t,r)=>{let o;if(!c&&i()){let n,a=!1;try{n=J.get(e.key)}catch(l){a=!0,o=R(e,"could not read its row after its tick",l)}n!==void 0?o=f(n):!a&&U.has(e.key)&&(U.delete(e.key),console.warn(`[@lunora/platform-node] declared cron ${S(e)} was removed from the database by another process passing \`crons\`; it stops firing here`))}if(r!==void 0){const n=o===void 0?"none scheduled":new Date(o).toISOString();console.error(`[@lunora/platform-node] cron ${S(e)} tick due ${new Date(t).toISOString()} failed; next run: ${n}`,r.error)}};const pe={cancel:async e=>{if(c)return!1;v(e);const t=Date.now(),r=Z.run(t,e).changes>0;return x.run(t-g),r},cron:async(e,t,r)=>{if(c)throw new Error("platform closed: cannot register a cron");q(e,`cron for ${t}`);const o={args:D(r??{}),expression:e,function_path:t,key:`${e} ${t}`};B.run(o.key,o.expression,o.function_path,o.args),f(o)},deadLetter:{list:async()=>c||!i()?[]:w.all("dead").map(e=>C(e)),requeue:async e=>{if(c||!i())return!1;const t=Date.now();return ae.run(t,e).changes===0?!1:(m(e,t),!0)}},get:async e=>{const t=c||!i()?void 0:k.get(e);if(t===void 0||t.completed_at!==null&&t.state!=="dead"&&t.completed_at<=Date.now()-g)return null;const r={canceled:"canceled",dead:"failed",pending:"pending",succeeded:"succeeded"},o=t.state==="pending"&&t.claimed_at!==null&&t.claimed_at>=Date.now()-I,n={...C(t),state:o?"running":r[t.state]};return t.completed_at!==null&&(n.completedAt=t.completed_at),n},list:async()=>c||!i()?[]:w.all("pending").map(e=>C(e)),schedule:async(e,t,r)=>{if(c)throw new Error("platform closed: cannot schedule a job");if(r?.retry?.forever===!0)throw new W("INVALID_INPUT","retry.forever is not supported by the Node scheduler host; set a finite retry.maxAttempts");const o=`node-job-${me()}`;let n;return r?.at===void 0?n=Date.now()+(r?.delayMs??0):n=typeof r.at=="number"?r.at:r.at.getTime(),Q.run(o,e,D(t),n,r?.retry===void 0?null:D(r.retry)),m(o,n),{id:o,scheduledFor:n}}};x.run(Date.now()-g);for(const e of w.all("pending"))m(e.id,e.scheduled_for);for(const e of H.all())e.key.startsWith(h)||f(e);const Y=()=>{for(const e of _.values())clearTimeout(e);for(const e of u.values())clearTimeout(e);_.clear(),u.clear()};return{pendingDispatches:()=>({labels:[...E.values()].map(e=>e.label),waits:[...E.keys()]}),declareCrons:e=>{if(c)throw new Error("platform closed: cannot declare crons");const t=new Set;for(const n of e){if(t.has(n.name))throw new W("VALIDATION_ERROR",`@lunora/platform-node: two declared cron jobs are named "${n.name}"; cron job names must be unique`);t.add(n.name),q(n.expression,`cron job "${n.name}"`)}const r=e.map(n=>({args:D(n.args),expression:n.expression,function_path:n.functionPath,key:`${h}${n.name}`})),o=new Set(r.map(n=>n.key));s.transaction(()=>{for(const n of H.all())n.key.startsWith(h)&&!o.has(n.key)&&ce.run(n.key);for(const n of r)B.run(n.key,n.expression,n.function_path,n.args)}).immediate();for(const[n,a]of u)n.startsWith(h)&&!o.has(n)&&(clearTimeout(a),u.delete(n));U=o;for(const n of r)f(n)},dispose:()=>{Y(),c=!0},scheduler:pe,simulateDeadLetter:async e=>{const t=k.get(e);if(t?.state!=="pending")return!1;v(e);const r=X(t.retry);return ee.run((r?.maxAttempts??T.maxAttempts)+1,Date.now(),e),!0},suspend:()=>{M=!0,Y()}}};export{Se as createNodeSchedulerHost};