@lunora/platform-node 1.0.0-alpha.231 → 1.0.0-alpha.232
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 +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{bindShardSockets-DjLmRlIA.mjs → bindShardSockets-DQRQ5Twp.mjs} +1 -1
- package/dist/packem_shared/{checkNodeAppHost-CzH-jdhY.mjs → checkNodeAppHost-DcEvEPbz.mjs} +1 -1
- package/dist/packem_shared/{createNodeDurableObjectFactory-DhewI6JL.mjs → createNodeDurableObjectFactory-BSdfUE6p.mjs} +1 -1
- package/dist/packem_shared/{createNodePlatform-4XLWgRgP.mjs → createNodePlatform-DtC6ezAS.mjs} +1 -1
- package/dist/packem_shared/createNodeShardHost-Cvbm_FZm.mjs +1 -0
- package/dist/packem_shared/{createNodeShardRegistry-Dt2izX_5.mjs → createNodeShardRegistry-D1-T8Tyy.mjs} +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/createNodeShardHost-PBzbPuHa.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-
|
|
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-Cvbm_FZm.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-D1-T8Tyy.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
|
@@ -1196,6 +1196,11 @@ interface NodeShardState {
|
|
|
1196
1196
|
client: unknown;
|
|
1197
1197
|
server: unknown;
|
|
1198
1198
|
};
|
|
1199
|
+
/**
|
|
1200
|
+
* The shard host's read gate, which `@lunora/platform-cloudflare`'s `createShardHost` passes through as
|
|
1201
|
+
* `ShardHost.runShared`: one shared connection has no input gate, so a query has to wait for an open mutation here.
|
|
1202
|
+
*/
|
|
1203
|
+
runShared?: <T>(function_: () => Promise<T>) => Promise<T>;
|
|
1199
1204
|
storage: {
|
|
1200
1205
|
delete: (key: string) => Promise<boolean>;
|
|
1201
1206
|
deleteAlarm: () => Promise<void>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1196,6 +1196,11 @@ interface NodeShardState {
|
|
|
1196
1196
|
client: unknown;
|
|
1197
1197
|
server: unknown;
|
|
1198
1198
|
};
|
|
1199
|
+
/**
|
|
1200
|
+
* The shard host's read gate, which `@lunora/platform-cloudflare`'s `createShardHost` passes through as
|
|
1201
|
+
* `ShardHost.runShared`: one shared connection has no input gate, so a query has to wait for an open mutation here.
|
|
1202
|
+
*/
|
|
1203
|
+
runShared?: <T>(function_: () => Promise<T>) => Promise<T>;
|
|
1199
1204
|
storage: {
|
|
1200
1205
|
delete: (key: string) => Promise<boolean>;
|
|
1201
1206
|
deleteAlarm: () => Promise<void>;
|
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-DcEvEPbz.mjs";import{N,c as f}from"./packem_shared/node-dispatch-route-DjQWVUkP.mjs";import{createNodeDurableObjectFactory as x}from"./packem_shared/createNodeDurableObjectFactory-BSdfUE6p.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-DtC6ezAS.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-Cvbm_FZm.mjs";import{createNodeShardNamespace as C}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as L}from"./packem_shared/createNodeShardRegistry-D1-T8Tyy.mjs";import{bindShardSockets as j,createNodeShardState as q}from"./packem_shared/bindShardSockets-DQRQ5Twp.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
|
-
const l=(t,o)=>({acceptWebSocket:(e,a)=>{t.sockets.accept(e,void 0,a)},blockConcurrencyWhile:e=>{const a=t.shard.runSerialized(e);return o?.(a),a},getWebSockets:e=>t.sockets.getSockets(e),id:{name:t.shardKey},storage:{delete:e=>t.kv.delete(e),deleteAlarm:async()=>{await t.shard.alarms.delete()},get:e=>t.kv.get(e),getAlarm:async()=>t.shard.alarms.get(),list:e=>t.kv.list(e),put:(e,a)=>t.kv.put(e,a),setAlarm:async e=>{await t.shard.alarms.set(e)},sql:{get databaseSize(){return t.shard.sql.databaseSize},exec:(e,...a)=>t.shard.sql.exec(e,...a)},transaction:e=>t.shard.transaction(e)},waitUntil:e=>{t.shard.waitUntil?.(e)},openSocketPair:()=>t.sockets.newPair(),upgradeResponse:e=>t.sockets.upgradeResponse(e)}),i=(t,o)=>{const e=async(a,s)=>{await t.webSocketMessage(a,s)};o.onMessage((a,s)=>{e(a,s).catch(
|
|
1
|
+
const l=(t,o)=>({acceptWebSocket:(e,a)=>{t.sockets.accept(e,void 0,a)},blockConcurrencyWhile:e=>{const a=t.shard.runSerialized(e);return o?.(a),a},getWebSockets:e=>t.sockets.getSockets(e),id:{name:t.shardKey},storage:{delete:e=>t.kv.delete(e),deleteAlarm:async()=>{await t.shard.alarms.delete()},get:e=>t.kv.get(e),getAlarm:async()=>t.shard.alarms.get(),list:e=>t.kv.list(e),put:(e,a)=>t.kv.put(e,a),setAlarm:async e=>{await t.shard.alarms.set(e)},sql:{get databaseSize(){return t.shard.sql.databaseSize},exec:(e,...a)=>t.shard.sql.exec(e,...a)},transaction:e=>t.shard.transaction(e)},waitUntil:e=>{t.shard.waitUntil?.(e)},openSocketPair:()=>t.sockets.newPair(),...t.shard.runShared===void 0?{}:{runShared:t.shard.runShared},upgradeResponse:e=>t.sockets.upgradeResponse(e)}),i=(t,o)=>{const e=async(a,s)=>{await t.webSocketMessage(a,s)};o.onMessage((a,s)=>{e(a,s).catch(r=>{console.error("[lunora] webSocketMessage threw:",r)})}),o.onClose(async(a,s,r,c)=>{try{await t.webSocketClose(a,s,r,c)}catch(n){console.error("[lunora] webSocketClose threw:",n)}})};export{i as bindShardSockets,l as createNodeShardState};
|
|
@@ -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-BSdfUE6p.mjs";import{walkDeclaredCrons as N,createNodePlatform as v}from"./createNodePlatform-DtC6ezAS.mjs";import{createNodeShardNamespace as S}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`)},I=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),maxOpenShards:r.maxOpenShards,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`)}},x=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)}},_=e=>{if(typeof e!="function")return!1;try{return Reflect.construct(String,[],e),!0}catch{return!1}},P=e=>{if(!I(e.worker.default))throw new i("VALIDATION_ERROR","@lunora/platform-node: the worker module has no default export with a `fetch` handler");x(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(!_(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=>{P(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:S(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{P as checkNodeAppHost,M as createNodeAppHost};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{bindShardSockets as b,createNodeShardState as g}from"./bindShardSockets-
|
|
1
|
+
import{bindShardSockets as b,createNodeShardState as g}from"./bindShardSockets-DQRQ5Twp.mjs";const p=(k,l)=>{const c=new WeakMap,w=new WeakSet,r=new WeakSet,f=new WeakSet,d=e=>{const n=[];let t=!0;const o=g(e,S=>{t&&n.push(S)}),s=new k(o,l);t=!1;const a=Promise.all(n).then(()=>{}),u={instance:s,ready:a};return a.then(()=>r.add(u)).catch(()=>{}),u},i=async e=>{let n=c.get(e);n===void 0&&(n=d(e),c.set(e,n),f.has(e)||(f.add(e),e.beforeClose(()=>{const t=c.get(e);t!==void 0&&r.has(t)&&t.instance.flushBeforeClose?.()}),e.keepOpen(()=>{const t=c.get(e);return t===void 0?!1:r.has(t)?t.instance.hasUnfinishedWork?.()??!0:!0})),!w.has(e)&&(n.instance.webSocketClose!==void 0||n.instance.webSocketMessage!==void 0)&&(w.add(e),b({webSocketClose:async(t,o,s,a)=>{await(await i(e)).webSocketClose?.(t,o,s,a)},webSocketMessage:async(t,o)=>{await(await i(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 i};export{p as createNodeDurableObjectFactory};
|
package/dist/packem_shared/{createNodePlatform-4XLWgRgP.mjs → createNodePlatform-DtC6ezAS.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-
|
|
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-Cvbm_FZm.mjs";import{createNodeShardRegistry as fe,SHARD_FILE_SUFFIX as k}from"./createNodeShardRegistry-D1-T8Tyy.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{AsyncLocalStorage as G}from"node:async_hooks";import{LunoraError as V}from"@lunora/errors";import j from"better-sqlite3";import{p as J}from"./prepared-statement-3XBQZXtC.mjs";const q=2147483647,Q=6,K=100,Z=4,B=10,b=r=>r===void 0?null:r,ee=(r,s)=>({get databaseSize(){const h=r.pragma("page_count",{simple:!0}),m=r.pragma("page_size",{simple:!0});return h*m},exec:(h,...m)=>{s("run SQL");const c=J(r,h),v=m.map(l=>b(l)),n=c.reader&&c.readonly;let i;const T=()=>(i===void 0&&(s("run SQL"),c.reader?i=c.all(...v):(c.run(...v),i=[])),i);n||T();const d=function*(){s("run SQL"),c.raw(!0);try{yield*c.iterate(...v)}finally{c.raw(!1)}};return{get columnNames(){return c.reader?c.columns().map(l=>l.name):void 0},[Symbol.iterator]:()=>T()[Symbol.iterator](),one:()=>{const l=T();if(l.length!==1)throw new Error(`expected exactly one row, got ${String(l.length)}`);return l[0]},...n?{raw:d}:{},toArray:()=>[...T()]}}}),re=(r,s,h,m,c=()=>{},v=()=>{})=>{let n,i,T=!1,d=0,l;r.exec("CREATE TABLE IF NOT EXISTS _lunora_alarm (id INTEGER PRIMARY KEY CHECK (id = 0), scheduled_for INTEGER NOT NULL)");const U=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0"),H=r.prepare("INSERT INTO _lunora_alarm (id, scheduled_for) VALUES (0, ?) ON CONFLICT (id) DO UPDATE SET scheduled_for = excluded.scheduled_for"),S=r.prepare("INSERT INTO _lunora_alarm (id, scheduled_for) VALUES (0, ?) ON CONFLICT (id) DO NOTHING"),N=r.prepare("SELECT scheduled_for FROM _lunora_alarm WHERE id = 0"),O=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0 AND scheduled_for = ?"),y=e=>{e===void 0?U.run():H.run(e)},_=e=>S.run(e).changes>0,A=e=>O.run(e).changes>0;let u=!1,f;const p=new Set;let g,E=0;const R=()=>{i!==void 0&&(clearTimeout(i),i=void 0),u=!1},C=e=>{i=setTimeout(()=>{i=void 0,u=!1,e()},B),u=!0},M=()=>{const e=N.get();e!==void 0&&(n=e.scheduled_for,I(e.scheduled_for))},P=(e,a,L=E)=>{if(!r.open||n!==void 0||L!==E){e();return}if(r.inTransaction){p.add({retry:()=>{x(e,a,L)},settle:e}),g??=setTimeout(z,B);return}if(d+=1,d>Q){d=0,e();return}const w=Date.now()+K*2**(d-1);if(_(w)){n=w,I(w),e();return}d=0,M(),e()},x=(e,a,L=E,w=0)=>{const k=d;try{P(e,a,L)}catch(W){if(d=k,r.open&&w+1<Z){p.add({retry:()=>{x(e,a,L,w+1)},settle:e}),g??=setTimeout(z,K*2**w);return}const $=new Date(a).toISOString();console.error("[@lunora/platform-node] the retry of the alarm due %s on shard %s could not be written after %d attempts, so that alarm is lost",$,m??"(unnamed)",w+1,W),v(`shard ${m??"(unnamed)"}: the retry of the alarm due ${$} could not be written`),e()}},z=()=>{if(g=void 0,r.open&&r.inTransaction){g=setTimeout(z,B);return}const e=[...p];p.clear();for(const a of e)a.retry()},D=(e,a=0)=>{if(T)return;const L=E;if(r.open&&r.inTransaction){C(()=>{D(e,a)});return}if(n=void 0,!r.open)return;try{if(!A(e)){M();return}}catch{n=e,a<Q&&(i=setTimeout(()=>{i=void 0,D(e,a+1)},K*2**a));return}let w=()=>{};c(new Promise(k=>{w=k})),w((async()=>{await h?.(),d=0})().catch(async k=>{console.error("[@lunora/platform-node] alarm handler on shard %s threw; retrying with backoff",m??"(unnamed)",k),await new Promise(W=>{x(W,e,L)})}))},I=e=>{if(R(),T)return;const a=Math.max(0,e-Date.now());if(a>q){i=setTimeout(()=>{I(e)},q);return}i=setTimeout(()=>{i=void 0,D(e)},a)},Y={delete:()=>{if(!r.open)throw new Error("platform closed: cannot delete an alarm");if(s.assertOwnTurn("delete an alarm"),d=0,y(void 0),s.inside()){l={at:void 0};return}E+=1,n=void 0,R()},get:()=>(l===void 0?n:l.at)??null,set:e=>{if(!r.open)throw new Error("platform closed: cannot set an alarm");s.assertOwnTurn("set an alarm");const a=typeof e=="number"?e:e.getTime();if(d=0,y(a),s.inside()){l={at:a};return}E+=1,n=a,I(a)}},t=()=>{if(l===void 0)return;const{at:e}=l;if(l=void 0,E+=1,e===void 0){n=void 0,R();return}n=e,I(e)},o=()=>{if(f=void 0,!r.open)return;if(r.inTransaction){f=setTimeout(o,B);return}const e=N.get();e!==void 0&&(i===void 0||u||n!==e.scheduled_for)&&(n=e.scheduled_for,I(e.scheduled_for))},F=()=>{l=void 0,f!==void 0&&clearTimeout(f),o()},X=()=>{R(),f!==void 0&&(clearTimeout(f),f=void 0),g!==void 0&&(clearTimeout(g),g=void 0);for(const e of p)console.error("[@lunora/platform-node] alarm retry on shard %s given up: the database closed while it waited for another transaction to end",m??"(unnamed)"),e.settle();p.clear()};return M(),{alarms:Y,commit:t,dispose:X,rollback:F,suspend:()=>{T=!0,R(),f!==void 0&&(clearTimeout(f),f=void 0)}}},te=(r,s)=>{r.pragma("journal_mode = WAL");const h=new G;let m=!1;const c=t=>{if(m&&h.getStore()!==!0)throw new V("SHARD_UNAVAILABLE",`shard busy: cannot ${t} while another task holds this shard's transaction`)},v=ee(r,c),n=new Set,i=[],{alarms:T,commit:d,dispose:l,suspend:U,rollback:H}=re(r,{assertOwnTurn:c,inside:()=>h.getStore()===!0},s.onAlarm,s.shardKey,t=>{n.add(t),t.then(()=>n.delete(t)).catch(o=>{n.delete(t),console.error("[@lunora/platform-node] an alarm delivery on shard %s failed outside its retry handling",s.shardKey??"(unnamed)",o),i.push(`shard ${s.shardKey??"(unnamed)"}: an alarm delivery failed outside its retry handling`)})},t=>{i.push(t)}),S=new Set,N=new G,O=new G,y=[];let _=0,A=!1,u;const f=()=>{u?.holder.active===!1&&(y.unshift({admit:u.admit,exclusive:!0}),u=void 0)},p=()=>{if(f(),!A){if(u!==void 0){if(_===1){const{admit:t}=u;u=void 0,A=!0,t()}return}for(;y.length>0;){const t=y[0];if(t.exclusive){_===0&&(y.shift(),A=!0,t.admit());return}y.shift(),_+=1,t.admit()}}},g=t=>new Promise(o=>{y.push({admit:o,exclusive:t}),p()}),E=()=>{A=!1,p()},R=async t=>{if(f(),u!==void 0)throw new V("SHARD_UNAVAILABLE","shard busy: another read on this shard is already waiting to take its writer lock");await new Promise(o=>{u={admit:o,holder:t},p()})},C=async t=>{if(N.getStore()===!0)return await t();const o=O.getStore();await(o?.active===!0?R(o):g(!0));try{return await N.run(!0,t)}finally{E()}},M=async t=>{if(N.getStore()===!0||O.getStore()?.active===!0)return await t();A||u!==void 0||y.length>0?await g(!1):_+=1;const o={active:!0};try{return await O.run(o,t)}finally{o.active=!1,_-=1,p()}},P=t=>C(t),x=async t=>{r.exec("BEGIN"),m=!0;try{const o=await h.run(!0,t);return r.exec("COMMIT"),m=!1,d(),o}catch(o){m=!1;try{r.exec("ROLLBACK")}catch{}throw H(),o}},z=t=>C(async()=>x(t)),D={alarms:T,runSerialized:P,runShared:M,shardKey:s.shardKey,sql:v,transaction:z,waitUntil:t=>{const o=t.catch(F=>{console.error("[@lunora/platform-node] work handed to waitUntil on shard %s failed",s.shardKey??"(unnamed)",F)}).finally(()=>{S.delete(o)});S.add(o)}};return{alarmsSettled:()=>n.size===0?void 0:Promise.allSettled(n),database:r,dispose:()=>{l(),r.open&&r.close()},drain:async()=>{for(;S.size>0||n.size>0;)await Promise.allSettled([...S,...n])},host:D,pendingAlarms:()=>n.size,pendingBackground:()=>S.size,suspendAlarms:U,takeFailures:()=>i.splice(0)}},le=(r={})=>{const s=new j(r.path??":memory:");try{return te(s,r)}catch(h){throw s.close(),h}};export{le as createNodeShardHost};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as oe,readdirSync as se}from"node:fs";import{join as F}from"node:path";import{LunoraError as G}from"@lunora/errors";import ne from"better-sqlite3";import{startDrainDeadline as ae,settlesBefore as ie}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeShardKvStore as le}from"./createNodeShardKvStore-Bh6oQZgs.mjs";import{createNodeShardHost as de}from"./createNodeShardHost-
|
|
1
|
+
import{mkdirSync as oe,readdirSync as se}from"node:fs";import{join as F}from"node:path";import{LunoraError as G}from"@lunora/errors";import ne from"better-sqlite3";import{startDrainDeadline as ae,settlesBefore as ie}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeShardKvStore as le}from"./createNodeShardKvStore-Bh6oQZgs.mjs";import{createNodeShardHost as de}from"./createNodeShardHost-Cvbm_FZm.mjs";import{createNodeSocketHost as ce}from"./createNodeSocketHost-BJf5HOHr.mjs";const A=".sqlite3",C=a=>a.replaceAll(/[^\da-z._-]/gu,i=>[...Buffer.from(i,"utf8")].map(s=>`%${s.toString(16).padStart(2,"0").toUpperCase()}`).join("")),fe=a=>decodeURIComponent(a),ue=(a,i)=>{const s=i.slice(0,-A.length),d=F(a,i);let u;try{u=fe(s)}catch{throw new G("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 p=`${C(u)}${A}`;if(p!==i)throw new G("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 "${p}" — so the key would be listed for fan-out while every read opened a new, empty database. Rename it: mv "${d}" "${F(a,p)}"`);return u},he=(a,i)=>{let s;try{return s=new ne(a,{fileMustExist:!0,readonly:!0}),s.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",i,d),!0}finally{s?.close()}},L=(a,i,s)=>a===0?"":`${String(a)} ${a===1?i:s}`,pe=(a,i)=>{const s=[L(i.requests,"request in flight","requests in flight"),L(i.alarms,"alarm running","alarms running"),L(i.background,"waitUntil task","waitUntil tasks"),i.closing?"a socket close handler running":""].filter(d=>d!=="");return`shard ${a}: ${s.join(", ")}`},me=256,ge=32,we=5e3,Ie=(a={})=>{const{maxOpenShards:i=me}=a;if(!Number.isSafeInteger(i)||i<1)throw new Error(`@lunora/platform-node: maxOpenShards must be a positive whole number, and it is ${String(i)}`);const s=new Map;let d="open",u=!1;const p=()=>{u=!0;for(const e of s.values())e.suspendAlarms()},N=()=>{if(d!=="open")throw new Error(`@lunora/platform-node: the shard registry is ${d}, so it opens no shard and takes no request`)},g=e=>{const r=s.get(e);r!==void 0&&(s.delete(e),s.set(e,r))},h=new Map,k=new Set,c=new Set,D=[];if(a.directory!==void 0){oe(a.directory,{recursive:!0});for(const e of se(a.directory))e.endsWith(A)&&k.add(ue(a.directory,e))}const H=(e,r)=>{for(const t of r.beforeClose)try{t()}catch(o){console.error("[@lunora/platform-node] shard %s failed to flush before closing",e,o)}},M=(e,r)=>{try{r.dispose()}catch(t){return t??new Error(`shard ${e} failed to close`)}s.delete(e)},R=(e,r)=>(H(e,r),M(e,r)),B=new WeakSet,J=(e,r)=>r.keepOpen.some(t=>{try{return t()}catch(o){return B.has(r)||(B.add(r),console.error("[@lunora/platform-node] a keepOpen check for shard %s threw, so the shard is kept open",e,o)),!0}}),U=(e,r)=>!h.has(e)&&!c.has(e)&&r.pendingAlarms()===0&&r.pendingBackground()===0&&r.drain()===void 0&&r.shard.sockets.getSockets().length===0&&r.shard.shard.alarms.get()===null&&!J(e,r),q=()=>a.directory!==void 0&&d==="open"&&s.size>i,z=e=>{if(!q())return;const r=[];for(const t of s){if(r.length>=ge)break;t[0]!==e&&r.push(t)}for(const[t,o]of r){if(s.size<=i)return;if(!U(t,o)){g(t);continue}if(H(t,o),!U(t,o)){g(t);continue}const n=M(t,o);n!==void 0&&(console.error("[@lunora/platform-node] idle shard %s failed to close",t,n),g(t))}};let m;const P=()=>{m!==void 0&&(clearInterval(m),m=void 0)};let I=!1,$=!1;const O=e=>{if(I){$=!0;return}I=!0;try{z(e),$&&($=!1,z(e))}finally{I=!1,$=!1}if(!q()){P();return}m===void 0&&(m=setInterval(()=>{O()},we),m.unref())},Q=async(e,r)=>{const t=Promise.resolve().then(r),o=t.then(()=>{},()=>{});let n=h.get(e);return n===void 0&&(n=new Set,h.set(e,n)),n.add(o),o.finally(()=>{n.delete(o),n.size===0&&h.get(e)===n&&h.delete(e),g(e),s.size>i&&O()}).catch(()=>{}),t},_=e=>{N();const r=s.get(e);if(r!==void 0)return g(e),r.shard;const t=a.directory===void 0?void 0:F(a.directory,`${C(e)}${A}`);let o;const{alarmsSettled:n,database:l,dispose:f,drain:v,host:S,pendingAlarms:ee,pendingBackground:re,suspendAlarms:K,takeFailures:te}=de({onAlarm:()=>a.onAlarm?.(o),path:t,shardKey:e});let E;const V=[],X=[];try{E=ce(l),o={beforeClose:b=>{V.push(b)},inbound:E,keepOpen:b=>{X.push(b)},kv:le(l),shard:S,shardKey:e,sockets:E.socket}}catch(b){throw f(),b}return s.set(e,{alarmsSettled:n,beforeClose:V,dispose:f,drain:E.drain,drainHost:v,keepOpen:X,pendingAlarms:ee,pendingBackground:re,shard:o,suspendAlarms:K,takeFailures:te}),k.add(e),u&&K(),O(e),o},W=e=>({fetch:async r=>{const t=_(e),{onFetch:o}=a;return o===void 0?new Response(e):Q(e,()=>o(r,t))}}),j=()=>[...D.splice(0),...[...s.values()].flatMap(e=>e.takeFailures())],w=()=>{const e=new Map,r=n=>{let l=e.get(n);return l===void 0&&(l={alarms:0,background:0,closing:!1,requests:0},e.set(n,l)),l},t=[];for(const[n,l]of h)t.push(...l),r(n).requests+=l.size;for(const[n,l]of s){const f=l.drain(),v=l.pendingBackground(),S=l.pendingAlarms();f!==void 0&&(r(n).closing=!0,t.push(f)),v>0&&(r(n).background=v),S>0&&(r(n).alarms=S),(v>0||S>0)&&t.push(l.drainHost())}return{labels:[...e].map(([n,l])=>pe(n,l)),waits:t}},x=(e,r)=>{const t=r.drain(),o=r.alarmsSettled();return[...h.get(e)??[],...o===void 0?[]:[o],...t===void 0?[]:[t]]},T=()=>{d!=="open"&&s.size===0&&(d="closed")},y=(e,r)=>{const t=x(e,r);if(t.length>0){Promise.allSettled(t).then(()=>{c.has(e)&&s.get(e)===r&&y(e,r)}).catch(()=>{});return}c.delete(e);const o=R(e,r);o!==void 0&&(console.error("[@lunora/platform-node] shard %s failed to close after the work using it settled",e,o),D.push(`shard ${e} failed to close after the work using it settled`)),T()},Y=(e,r,t)=>{const o=R(e,r);return o===void 0?c.delete(e):t&&!c.has(e)&&(c.add(e),y(e,r)),o},Z=(e,r)=>{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:t,key:o}of r)console.error("[@lunora/platform-node] shard %s failed to close",o,t);if(r.length>0)throw new AggregateError(r.map(({error:t})=>t),`@lunora/platform-node: ${String(r.length)} shard(s) failed to close: ${r.map(({key:t})=>t).join(", ")}`)};return{close:e=>{d==="open"&&(d="closing"),P();const r=[],t=[];p();for(const[o,n]of s){const l=x(o,n);if(l.length===0||e?.force===!0){l.length>0&&r.push(o);const f=Y(o,n,l.length>0);f!==void 0&&t.push({error:f,key:o})}else c.has(o)||(c.add(o),y(o,n))}T(),Z(r,t)},drain:async e=>{const r=ae(e);try{for(let t=w();t.waits.length>0;t=w())if(!await ie(Promise.allSettled(t.waits),r)){const o=w().labels;return console.error("[@lunora/platform-node] shard drain deadline passed with work still running: %s",o.join(", ")),{failed:j(),pending:o,timedOut:!0}}return{failed:j(),pending:[],timedOut:!1}}finally{r.cancel()}},directory:{get:e=>W(String(e)),getByName:e=>W(e),idForName:e=>e},idle:()=>w().waits.length===0,pending:()=>w().labels,rearmPersistedAlarms:()=>{N();const{directory:e}=a;if(e===void 0)return[];const r=[];for(const t of k)if(!s.has(t)&&he(F(e,`${C(t)}${A}`),t))try{_(t),r.push(t)}catch(o){console.error("[@lunora/platform-node] could not open shard %s to re-arm its persisted alarm",t,o)}return r},listShardKeys:()=>[...k],shardFor:_,suspendAlarms:p}};export{A 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.232",
|
|
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",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"@lunora/d1": "^1.0.0-alpha.238",
|
|
50
50
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
51
51
|
"@lunora/mail": "^1.0.0-alpha.140",
|
|
52
|
-
"@lunora/platform": "^1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "^1.0.0-alpha.85",
|
|
53
53
|
"@lunora/queue": "^1.0.0-alpha.146",
|
|
54
54
|
"@lunora/runtime": "^1.0.0-alpha.305",
|
|
55
55
|
"@lunora/scheduler": "^1.0.0-alpha.175",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{AsyncLocalStorage as G}from"node:async_hooks";import{LunoraError as X}from"@lunora/errors";import j from"better-sqlite3";import{p as J}from"./prepared-statement-3XBQZXtC.mjs";const K=2147483647,W=6,F=100,Z=4,O=10,b=r=>r===void 0?null:r,ee=(r,a)=>({get databaseSize(){const f=r.pragma("page_count",{simple:!0}),u=r.pragma("page_size",{simple:!0});return f*u},exec:(f,...u)=>{a("run SQL");const c=J(r,f),w=u.map(i=>b(i)),o=c.reader&&c.readonly;let n;const p=()=>(n===void 0&&(a("run SQL"),c.reader?n=c.all(...w):(c.run(...w),n=[])),n);o||p();const d=function*(){a("run SQL"),c.raw(!0);try{yield*c.iterate(...w)}finally{c.raw(!1)}};return{get columnNames(){return c.reader?c.columns().map(i=>i.name):void 0},[Symbol.iterator]:()=>p()[Symbol.iterator](),one:()=>{const i=p();if(i.length!==1)throw new Error(`expected exactly one row, got ${String(i.length)}`);return i[0]},...o?{raw:d}:{},toArray:()=>[...p()]}}}),re=(r,a,f,u,c=()=>{},w=()=>{})=>{let o,n,p=!1,d=0,i;r.exec("CREATE TABLE IF NOT EXISTS _lunora_alarm (id INTEGER PRIMARY KEY CHECK (id = 0), scheduled_for INTEGER NOT NULL)");const M=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0"),z=r.prepare("INSERT INTO _lunora_alarm (id, scheduled_for) VALUES (0, ?) ON CONFLICT (id) DO UPDATE SET scheduled_for = excluded.scheduled_for"),y=r.prepare("INSERT INTO _lunora_alarm (id, scheduled_for) VALUES (0, ?) ON CONFLICT (id) DO NOTHING"),R=r.prepare("SELECT scheduled_for FROM _lunora_alarm WHERE id = 0"),L=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0 AND scheduled_for = ?"),S=e=>{e===void 0?M.run():z.run(e)},C=e=>y.run(e).changes>0,D=e=>L.run(e).changes>0;let g=!1,m;const E=new Set;let T,t=0;const l=()=>{n!==void 0&&(clearTimeout(n),n=void 0),g=!1},v=e=>{n=setTimeout(()=>{n=void 0,g=!1,e()},O),g=!0},I=()=>{const e=R.get();e!==void 0&&(o=e.scheduled_for,A(e.scheduled_for))},Y=(e,s,_=t)=>{if(!r.open||o!==void 0||_!==t){e();return}if(r.inTransaction){E.add({retry:()=>{k(e,s,_)},settle:e}),T??=setTimeout(x,O);return}if(d+=1,d>W){d=0,e();return}const h=Date.now()+F*2**(d-1);if(C(h)){o=h,A(h),e();return}d=0,I(),e()},k=(e,s,_=t,h=0)=>{const N=d;try{Y(e,s,_)}catch(P){if(d=N,r.open&&h+1<Z){E.add({retry:()=>{k(e,s,_,h+1)},settle:e}),T??=setTimeout(x,F*2**h);return}const U=new Date(s).toISOString();console.error("[@lunora/platform-node] the retry of the alarm due %s on shard %s could not be written after %d attempts, so that alarm is lost",U,u??"(unnamed)",h+1,P),w(`shard ${u??"(unnamed)"}: the retry of the alarm due ${U} could not be written`),e()}},x=()=>{if(T=void 0,r.open&&r.inTransaction){T=setTimeout(x,O);return}const e=[...E];E.clear();for(const s of e)s.retry()},B=(e,s=0)=>{if(p)return;const _=t;if(r.open&&r.inTransaction){v(()=>{B(e,s)});return}if(o=void 0,!r.open)return;try{if(!D(e)){I();return}}catch{o=e,s<W&&(n=setTimeout(()=>{n=void 0,B(e,s+1)},F*2**s));return}let h=()=>{};c(new Promise(N=>{h=N})),h((async()=>{await f?.(),d=0})().catch(async N=>{console.error("[@lunora/platform-node] alarm handler on shard %s threw; retrying with backoff",u??"(unnamed)",N),await new Promise(P=>{k(P,e,_)})}))},A=e=>{if(l(),p)return;const s=Math.max(0,e-Date.now());if(s>K){n=setTimeout(()=>{A(e)},K);return}n=setTimeout(()=>{n=void 0,B(e)},s)},$={delete:()=>{if(!r.open)throw new Error("platform closed: cannot delete an alarm");if(a.assertOwnTurn("delete an alarm"),d=0,S(void 0),a.inside()){i={at:void 0};return}t+=1,o=void 0,l()},get:()=>(i===void 0?o:i.at)??null,set:e=>{if(!r.open)throw new Error("platform closed: cannot set an alarm");a.assertOwnTurn("set an alarm");const s=typeof e=="number"?e:e.getTime();if(d=0,S(s),a.inside()){i={at:s};return}t+=1,o=s,A(s)}},Q=()=>{if(i===void 0)return;const{at:e}=i;if(i=void 0,t+=1,e===void 0){o=void 0,l();return}o=e,A(e)},H=()=>{if(m=void 0,!r.open)return;if(r.inTransaction){m=setTimeout(H,O);return}const e=R.get();e!==void 0&&(n===void 0||g||o!==e.scheduled_for)&&(o=e.scheduled_for,A(e.scheduled_for))},V=()=>{i=void 0,m!==void 0&&clearTimeout(m),H()},q=()=>{l(),m!==void 0&&(clearTimeout(m),m=void 0),T!==void 0&&(clearTimeout(T),T=void 0);for(const e of E)console.error("[@lunora/platform-node] alarm retry on shard %s given up: the database closed while it waited for another transaction to end",u??"(unnamed)"),e.settle();E.clear()};return I(),{alarms:$,commit:Q,dispose:q,rollback:V,suspend:()=>{p=!0,l(),m!==void 0&&(clearTimeout(m),m=void 0)}}},te=(r,a)=>{r.pragma("journal_mode = WAL");const f=new G;let u=!1;const c=t=>{if(u&&f.getStore()!==!0)throw new X("SHARD_UNAVAILABLE",`shard busy: cannot ${t} while another task holds this shard's transaction`)},w=ee(r,c),o=new Set,n=[],{alarms:p,commit:d,dispose:i,suspend:M,rollback:z}=re(r,{assertOwnTurn:c,inside:()=>f.getStore()===!0},a.onAlarm,a.shardKey,t=>{o.add(t),t.then(()=>o.delete(t)).catch(l=>{o.delete(t),console.error("[@lunora/platform-node] an alarm delivery on shard %s failed outside its retry handling",a.shardKey??"(unnamed)",l),n.push(`shard ${a.shardKey??"(unnamed)"}: an alarm delivery failed outside its retry handling`)})},t=>{n.push(t)}),y=new Set,R=new G;let L=Promise.resolve();const S=async t=>{if(R.getStore()===!0)return await t();const l=L;let v=()=>{};L=new Promise(I=>{v=I}),await l;try{return await R.run(!0,t)}finally{v()}},C=t=>S(t),D=async t=>{r.exec("BEGIN"),u=!0;try{const l=await f.run(!0,t);return r.exec("COMMIT"),u=!1,d(),l}catch(l){u=!1;try{r.exec("ROLLBACK")}catch{}throw z(),l}},g=t=>S(async()=>D(t)),m={alarms:p,runSerialized:C,shardKey:a.shardKey,sql:w,transaction:g,waitUntil:t=>{const l=t.catch(v=>{console.error("[@lunora/platform-node] work handed to waitUntil on shard %s failed",a.shardKey??"(unnamed)",v)}).finally(()=>{y.delete(l)});y.add(l)}};return{alarmsSettled:()=>o.size===0?void 0:Promise.allSettled(o),database:r,dispose:()=>{i(),r.open&&r.close()},drain:async()=>{for(;y.size>0||o.size>0;)await Promise.allSettled([...y,...o])},host:m,pendingAlarms:()=>o.size,pendingBackground:()=>y.size,suspendAlarms:M,takeFailures:()=>n.splice(0)}},le=(r={})=>{const a=new j(r.path??":memory:");try{return te(a,r)}catch(f){throw a.close(),f}};export{le as createNodeShardHost};
|