@lunora/platform-node 1.0.0-alpha.229 → 1.0.0-alpha.230
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{checkNodeAppHost-C79Egfug.mjs → checkNodeAppHost-CZVkTaph.mjs} +1 -1
- package/dist/packem_shared/createNodeDurableObjectFactory-Br3hrJ4E.mjs +1 -0
- package/dist/packem_shared/{createNodePlatform-BmbU36lo.mjs → createNodePlatform-C2ZDvuyh.mjs} +1 -1
- package/dist/packem_shared/createNodeShardRegistry-CfXUcBxA.mjs +1 -0
- package/package.json +1 -1
- package/dist/packem_shared/createNodeDurableObjectFactory-hAwJt_pN.mjs +0 -1
- package/dist/packem_shared/createNodeShardRegistry-DEn0kYmG.mjs +0 -1
|
@@ -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-B5KeCI9c.mjs";import{createNodeShardHost as T}from"../packem_shared/createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-
|
|
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-CfXUcBxA.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.d.mts
CHANGED
|
@@ -580,6 +580,12 @@ interface NodeSocketHost {
|
|
|
580
580
|
declare const createNodeSocketHost: (database: Database.Database) => NodeSocketHost;
|
|
581
581
|
/** The contracts scoped to one shard key. */
|
|
582
582
|
interface NodeShard {
|
|
583
|
+
/**
|
|
584
|
+
* Register a synchronous callback run immediately before this shard's database is closed, on every close path, forced
|
|
585
|
+
* or not: the place for a Durable Object instance to write what it buffers in memory. A callback that throws is logged
|
|
586
|
+
* and the shard is still closed. If the close itself fails and the shard stays live, the callbacks run again on the retry.
|
|
587
|
+
*/
|
|
588
|
+
beforeClose: (flush: () => void) => void;
|
|
583
589
|
/**
|
|
584
590
|
* Inbound socket events for this shard's registry. Bind the shard that owns
|
|
585
591
|
* the sockets here, so a frame or close reaches its `webSocketMessage` and
|
|
@@ -1019,6 +1025,8 @@ declare const createNodeAppHost: (options: NodeAppHostOptions) => NodeAppHost;
|
|
|
1019
1025
|
interface NodeDurableObjectInstance {
|
|
1020
1026
|
alarm?: () => Promise<void> | void;
|
|
1021
1027
|
fetch: (request: Request) => Promise<Response> | Response;
|
|
1028
|
+
/** Write what the instance buffers in memory; the host calls it right before closing the shard's database. */
|
|
1029
|
+
flushBeforeClose?: () => void;
|
|
1022
1030
|
webSocketClose?: (socket: unknown, code: number, reason: string, wasClean: boolean) => Promise<void> | void;
|
|
1023
1031
|
webSocketMessage?: (socket: unknown, data: ArrayBuffer | string) => Promise<void> | void;
|
|
1024
1032
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -580,6 +580,12 @@ interface NodeSocketHost {
|
|
|
580
580
|
declare const createNodeSocketHost: (database: Database.Database) => NodeSocketHost;
|
|
581
581
|
/** The contracts scoped to one shard key. */
|
|
582
582
|
interface NodeShard {
|
|
583
|
+
/**
|
|
584
|
+
* Register a synchronous callback run immediately before this shard's database is closed, on every close path, forced
|
|
585
|
+
* or not: the place for a Durable Object instance to write what it buffers in memory. A callback that throws is logged
|
|
586
|
+
* and the shard is still closed. If the close itself fails and the shard stays live, the callbacks run again on the retry.
|
|
587
|
+
*/
|
|
588
|
+
beforeClose: (flush: () => void) => void;
|
|
583
589
|
/**
|
|
584
590
|
* Inbound socket events for this shard's registry. Bind the shard that owns
|
|
585
591
|
* the sockets here, so a frame or close reaches its `webSocketMessage` and
|
|
@@ -1019,6 +1025,8 @@ declare const createNodeAppHost: (options: NodeAppHostOptions) => NodeAppHost;
|
|
|
1019
1025
|
interface NodeDurableObjectInstance {
|
|
1020
1026
|
alarm?: () => Promise<void> | void;
|
|
1021
1027
|
fetch: (request: Request) => Promise<Response> | Response;
|
|
1028
|
+
/** Write what the instance buffers in memory; the host calls it right before closing the shard's database. */
|
|
1029
|
+
flushBeforeClose?: () => void;
|
|
1022
1030
|
webSocketClose?: (socket: unknown, code: number, reason: string, wasClean: boolean) => Promise<void> | void;
|
|
1023
1031
|
webSocketMessage?: (socket: unknown, data: ArrayBuffer | string) => Promise<void> | void;
|
|
1024
1032
|
}
|
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-
|
|
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-CZVkTaph.mjs";import{N,c as f}from"./packem_shared/node-dispatch-route-DjQWVUkP.mjs";import{createNodeDurableObjectFactory as x}from"./packem_shared/createNodeDurableObjectFactory-Br3hrJ4E.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-C2ZDvuyh.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-CfXUcBxA.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-
|
|
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-Br3hrJ4E.mjs";import{walkDeclaredCrons as N,createNodePlatform as v}from"./createNodePlatform-C2ZDvuyh.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 b,createNodeShardState as g}from"./bindShardSockets-DjLmRlIA.mjs";const v=(d,S)=>{const c=new WeakMap,u=new WeakSet,w=new WeakSet,l=new WeakSet,f=e=>{const n=[];let t=!0;const o=g(e,k=>{t&&n.push(k)}),s=new d(o,S);t=!1;const a=Promise.all(n).then(()=>{}),i={instance:s,ready:a};return a.then(()=>w.add(i)).catch(()=>{}),i},r=async e=>{let n=c.get(e);n===void 0&&(n=f(e),c.set(e,n),l.has(e)||(l.add(e),e.beforeClose(()=>{const t=c.get(e);t!==void 0&&w.has(t)&&t.instance.flushBeforeClose?.()})),!u.has(e)&&(n.instance.webSocketClose!==void 0||n.instance.webSocketMessage!==void 0)&&(u.add(e),b({webSocketClose:async(t,o,s,a)=>{await(await r(e)).webSocketClose?.(t,o,s,a)},webSocketMessage:async(t,o)=>{await(await r(e)).webSocketMessage?.(t,o)}},e.inbound)));try{await n.ready}catch(t){throw c.get(e)===n&&c.delete(e),t}return n.instance};return r};export{v as createNodeDurableObjectFactory};
|
package/dist/packem_shared/{createNodePlatform-BmbU36lo.mjs → createNodePlatform-C2ZDvuyh.mjs}
RENAMED
|
@@ -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-B5KeCI9c.mjs";import{createNodeShardHost as ue}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardRegistry as fe,SHARD_FILE_SUFFIX as k}from"./createNodeShardRegistry-
|
|
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-CfXUcBxA.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 @@
|
|
|
1
|
+
import{mkdirSync as W,readdirSync as x}from"node:fs";import{join as A}from"node:path";import{LunoraError as B}from"@lunora/errors";import z from"better-sqlite3";import{startDrainDeadline as K,settlesBefore as T}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeShardKvStore as V}from"./createNodeShardKvStore-Bh6oQZgs.mjs";import{createNodeShardHost as X}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeSocketHost as G}from"./createNodeSocketHost-BJf5HOHr.mjs";const v=".sqlite3",E=n=>n.replaceAll(/[^\da-z._-]/gu,s=>[...Buffer.from(s,"utf8")].map(i=>`%${i.toString(16).padStart(2,"0").toUpperCase()}`).join("")),J=n=>decodeURIComponent(n),Q=(n,s)=>{const i=s.slice(0,-v.length),d=A(n,s);let u;try{u=J(i)}catch{throw new B("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${d}" has a basename that is not valid percent-encoding, so the shard key it holds cannot be recovered. Rename or remove the file.`)}const h=`${E(u)}${v}`;if(h!==s)throw new B("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${d}" was written under an older shard-key encoding. It decodes to shard key "${u}", which this build stores as "${h}" — so the key would be listed for fan-out while every read opened a new, empty database. Rename it: mv "${d}" "${A(n,h)}"`);return u},Y=(n,s)=>{let i;try{return i=new z(n,{fileMustExist:!0,readonly:!0}),i.prepare("SELECT 1 FROM _lunora_alarm LIMIT 1").get()!==void 0}catch(d){return console.error("[@lunora/platform-node] could not check shard %s for a persisted alarm, so it is opened to re-arm any",s,d),!0}finally{i?.close()}},F=(n,s,i)=>n===0?"":`${String(n)} ${n===1?s:i}`,Z=(n,s)=>{const i=[F(s.requests,"request in flight","requests in flight"),F(s.alarms,"alarm running","alarms running"),F(s.background,"waitUntil task","waitUntil tasks"),s.closing?"a socket close handler running":""].filter(d=>d!=="");return`shard ${n}: ${i.join(", ")}`},ie=(n={})=>{const s=new Map;let i="open",d=!1;const u=()=>{d=!0;for(const e of s.values())e.suspendAlarms()},h=()=>{if(i!=="open")throw new Error(`@lunora/platform-node: the shard registry is ${i}, so it opens no shard and takes no request`)},m=new Map,D=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,f=new Set,C=[];if(n.directory!==void 0){W(n.directory,{recursive:!0});for(const e of x(n.directory))e.endsWith(v)&&S.add(Q(n.directory,e))}const $=e=>{h();const t=s.get(e);if(t!==void 0)return t.shard;const r=n.directory===void 0?void 0:A(n.directory,`${E(e)}${v}`);let o;const{alarmsSettled:a,database:l,dispose:c,drain:g,host:w,pendingAlarms:j,pendingBackground:O,suspendAlarms:L,takeFailures:P}=X({onAlarm:()=>n.onAlarm?.(o),path:r,shardKey:e});let b;const U=[];try{b=G(l),o={beforeClose:k=>{U.push(k)},inbound:b,kv:V(l),shard:w,shardKey:e,sockets:b.socket}}catch(k){throw c(),k}return s.set(e,{alarmsSettled:a,beforeClose:U,dispose:c,drain:b.drain,drainHost:g,pendingAlarms:j,pendingBackground:O,shard:o,suspendAlarms:L,takeFailures:P}),S.add(e),d&&L(),o},H=e=>({fetch:async t=>{const r=$(e),{onFetch:o}=n;return o===void 0?new Response(e):D(e,()=>o(t,r))}}),I=()=>[...C.splice(0),...[...s.values()].flatMap(e=>e.takeFailures())],p=()=>{const e=new Map,t=a=>{let l=e.get(a);return l===void 0&&(l={alarms:0,background:0,closing:!1,requests:0},e.set(a,l)),l},r=[];for(const[a,l]of m)r.push(...l),t(a).requests+=l.size;for(const[a,l]of s){const c=l.drain(),g=l.pendingBackground(),w=l.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(l.drainHost())}return{labels:[...e].map(([a,l])=>Z(a,l)),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=()=>{i!=="open"&&s.size===0&&(i="closed")},q=(e,t)=>{for(const r of t.beforeClose)try{r()}catch(o){console.error("[@lunora/platform-node] shard %s failed to flush before closing",e,o)}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(()=>{f.has(e)&&s.get(e)===t&&y(e,t)}).catch(()=>{});return}f.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),C.push(`shard ${e} failed to close after the work using it settled`)),R()},M=(e,t,r)=>{const o=q(e,t);return o===void 0?f.delete(e):r&&!f.has(e)&&(f.add(e),y(e,t)),o},_=(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=>{i==="open"&&(i="closing");const t=[],r=[];u();for(const[o,a]of s){const l=N(o,a);if(l.length===0||e?.force===!0){l.length>0&&t.push(o);const c=M(o,a,l.length>0);c!==void 0&&r.push({error:c,key:o})}else f.has(o)||(f.add(o),y(o,a))}R(),_(t,r)},drain:async e=>{const t=K(e);try{for(let r=p();r.waits.length>0;r=p())if(!await T(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:()=>{h();const{directory:e}=n;if(e===void 0)return[];const t=[];for(const r of S)if(!s.has(r)&&Y(A(e,`${E(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};
|
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.230",
|
|
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 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
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-Bh6oQZgs.mjs";import{createNodeShardHost as V}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeSocketHost as X}from"./createNodeSocketHost-BJf5HOHr.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};
|