@lunora/platform-node 1.0.0-alpha.176 → 1.0.0-alpha.177
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.mjs +1 -1
- package/dist/packem_shared/{createNodePlatform-B9Wb06Ds.mjs → createNodePlatform-C07qb5Aq.mjs} +1 -1
- package/dist/packem_shared/createNodeSchedulerHost-Di5cA-fR.mjs +15 -0
- package/dist/packem_shared/createNodeShardHost-Bhbm4txQ.mjs +1 -0
- package/dist/packem_shared/{createNodeShardRegistry-BQTmTR31.mjs → createNodeShardRegistry-BKl1QXiv.mjs} +1 -1
- package/package.json +6 -6
- package/dist/packem_shared/createNodeSchedulerHost-BIJ4H38-.mjs +0 -15
- package/dist/packem_shared/createNodeShardHost-CrZcfv6X.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NODE_CAPABILITIES as g}from"@lunora/platform";import{createNodeShardKvStore as D}from"../packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeSchedulerHost as k}from"../packem_shared/createNodeSchedulerHost-
|
|
1
|
+
import{NODE_CAPABILITIES as g}from"@lunora/platform";import{createNodeShardKvStore as D}from"../packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeSchedulerHost as k}from"../packem_shared/createNodeSchedulerHost-Di5cA-fR.mjs";import{createNodeShardHost as T}from"../packem_shared/createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-BKl1QXiv.mjs";import{createNodeSocketHost as b}from"../packem_shared/createNodeSocketHost-ByOmEGFe.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{NODE_SCHEDULER_DISPATCH_PATH as r,createNodeDispatchRoute as t}from"./packem_shared/NODE_SCHEDULER_DISPATCH_PATH-CNBAtztq.mjs";import{createNodeGlobalStore as d,createNodeSqlExec as c}from"./packem_shared/createNodeGlobalStore-DhHyIT8I.mjs";import{createNodeHttpServer as p}from"./packem_shared/createNodeHttpServer-D4YVdhJn.mjs";import{createNodeShardKvStore as m}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodePlatform as S}from"./packem_shared/createNodePlatform-
|
|
1
|
+
import{NODE_SCHEDULER_DISPATCH_PATH as r,createNodeDispatchRoute as t}from"./packem_shared/NODE_SCHEDULER_DISPATCH_PATH-CNBAtztq.mjs";import{createNodeGlobalStore as d,createNodeSqlExec as c}from"./packem_shared/createNodeGlobalStore-DhHyIT8I.mjs";import{createNodeHttpServer as p}from"./packem_shared/createNodeHttpServer-D4YVdhJn.mjs";import{createNodeShardKvStore as m}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodePlatform as S}from"./packem_shared/createNodePlatform-C07qb5Aq.mjs";import{createNodeProfileHandler as l}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as h}from"./packem_shared/createNodeQueueHost-CttDb5sY.mjs";import{createNodeR2Bucket as u}from"./packem_shared/createNodeR2Bucket-6I2HobcB.mjs";import{createNodeSchedulerHost as D}from"./packem_shared/createNodeSchedulerHost-Di5cA-fR.mjs";import{createNodeShardHost as P}from"./packem_shared/createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardNamespace as _}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as n}from"./packem_shared/createNodeShardRegistry-BKl1QXiv.mjs";import{bindShardSockets as w,createNodeShardState as A}from"./packem_shared/bindShardSockets-9GvSocBW.mjs";import{createNodeSocketHost as T}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as g}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as y}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{r as NODE_SCHEDULER_DISPATCH_PATH,w as bindShardSockets,t as createNodeDispatchRoute,d as createNodeGlobalStore,p as createNodeHttpServer,S as createNodePlatform,l as createNodeProfileHandler,h as createNodeQueueHost,u as createNodeR2Bucket,D as createNodeSchedulerHost,P as createNodeShardHost,m as createNodeShardKvStore,_ as createNodeShardNamespace,n as createNodeShardRegistry,A as createNodeShardState,T as createNodeSocketHost,c as createNodeSqlExec,g as createNodeWorkflowHost,y as createNodeWorkflowStore};
|
package/dist/packem_shared/{createNodePlatform-B9Wb06Ds.mjs → createNodePlatform-C07qb5Aq.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as k}from"@lunora/errors";import{NODE_CAPABILITIES as N}from"@lunora/platform";import{createNodeDispatchRoute as b,createShardInvoke as g}from"./NODE_SCHEDULER_DISPATCH_PATH-CNBAtztq.mjs";import{createNodeGlobalStore as y}from"./createNodeGlobalStore-DhHyIT8I.mjs";import{createNodeShardKvStore as R}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeQueueHost as T}from"./createNodeQueueHost-CttDb5sY.mjs";import{createNodeR2Bucket as q}from"./createNodeR2Bucket-6I2HobcB.mjs";import{createNodeSchedulerHost as I}from"./createNodeSchedulerHost-
|
|
1
|
+
import{LunoraError as k}from"@lunora/errors";import{NODE_CAPABILITIES as N}from"@lunora/platform";import{createNodeDispatchRoute as b,createShardInvoke as g}from"./NODE_SCHEDULER_DISPATCH_PATH-CNBAtztq.mjs";import{createNodeGlobalStore as y}from"./createNodeGlobalStore-DhHyIT8I.mjs";import{createNodeShardKvStore as R}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeQueueHost as T}from"./createNodeQueueHost-CttDb5sY.mjs";import{createNodeR2Bucket as q}from"./createNodeR2Bucket-6I2HobcB.mjs";import{createNodeSchedulerHost as I}from"./createNodeSchedulerHost-Di5cA-fR.mjs";import{createNodeShardHost as _}from"./createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardRegistry as B}from"./createNodeShardRegistry-BKl1QXiv.mjs";import{createNodeSocketHost as D}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as H}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as P}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const z=(e={})=>{const o=[],{database:r,dispose:i,drain:u,host:m}=_(e);o.push(i);try{const c=R(r),t=B(e);o.push(()=>{t.close()});const{directory:d}=t,l=b({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:g(d,e.onFetch!==void 0),schedulerSecret:e.dispatch?.schedulerSecret}),{socket:f}=D(r),{dispose:n,scheduler:p}=I(r,e);o.push(n);const S=e.queues===void 0?void 0:T(r,{onBatch:e.onQueueBatch??(()=>{throw new k("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.objectStorageDirectory===void 0?void 0:q({directory:e.objectStorageDirectory}),a=e.globalTablesPath===void 0?void 0:y({path:e.globalTablesPath});a!==void 0&&o.push(()=>{a.dispose()});const w=e.workflows===void 0?void 0:H({store:P(r),workflows:e.workflows}),h=()=>{for(const s of o.toReversed())s()};return{capabilities:N,close:h,directory:d,dispatch:s=>l(s),drain:u,globalTables:a,kv:c,objectStorage:v,queues:S,scheduler:p,shard:m,sockets:f,workflows:w,[Symbol.dispose]:h}}catch(c){for(const t of o.toReversed())try{t()}catch{}throw c}};export{z as createNodePlatform};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{randomUUID as K}from"node:crypto";import{deserialize as D,serialize as M}from"node:v8";import{parse as C}from"@visulima/cron-parser";const d={backoffMultiplier:2,initialDelayMs:1e3,maxAttempts:5,maxDelayMs:6e4},h=2147483647,g=6e4,w=g/3,V=1e3,Q=5,Z=20,S=10,ee=(o,m)=>{const E=m?.initialDelayMs??d.initialDelayMs,A=m?.backoffMultiplier??d.backoffMultiplier,L=m?.maxDelayMs??d.maxDelayMs;return Math.min(L,E*A**Math.max(0,o-1))},oe=(o,m={})=>{o.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 E=()=>o.prepare("PRAGMA table_info(_lunora_scheduler_jobs)").all().some(e=>e.name==="claimed_at"),A=e=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},L=()=>{for(let e=0;;e+=1)try{o.exec("ALTER TABLE _lunora_scheduler_jobs ADD COLUMN claimed_at INTEGER");return}catch(t){if(E())return;if(!(t instanceof Error&&"code"in t&&t.code==="SQLITE_BUSY")||e>=Q)throw t;A(Z*2**e)}};E()||L(),o.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 b=o.prepare("INSERT INTO _lunora_scheduler_jobs (id, function_path, args, scheduled_for, retry) VALUES (?, ?, ?, ?, ?)"),I=o.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE id = ?"),N=o.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE state = ? ORDER BY scheduled_for"),j=o.prepare("DELETE FROM _lunora_scheduler_jobs WHERE id = ? AND state = 'pending'"),k=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, claimed_at = NULL WHERE id = ?"),F=o.prepare("DELETE FROM _lunora_scheduler_jobs WHERE id = ? AND claimed_at = ?"),B=o.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND claimed_at = ? AND state = 'pending'"),J=o.prepare("UPDATE _lunora_scheduler_jobs SET attempts = ?, scheduled_for = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ?"),P=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ?"),v=o.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 *"),H=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'pending', attempts = 0, scheduled_for = ? WHERE id = ? AND state = 'dead'"),W=o.prepare(`INSERT INTO _lunora_scheduler_crons (key, expression, function_path, args) VALUES (?, ?, ?, ?)
|
|
15
|
+
ON CONFLICT (key) DO UPDATE SET expression = excluded.expression, args = excluded.args`),Y=o.prepare("SELECT * FROM _lunora_scheduler_crons"),c=()=>o.open,T=()=>o.inTransaction,U=e=>e===null?void 0:D(e);let a=!1;const y=async()=>{a||!c()||!T()||(await new Promise(e=>{setTimeout(e,S).unref()}),await y())},l=new Map,_=new Map,x=e=>({attempts:e.attempts,functionPath:e.function_path,id:e.id,scheduledFor:e.scheduled_for}),R=e=>{const t=l.get(e);t!==void 0&&(clearTimeout(t),l.delete(e))},i=(e,t)=>{R(e);const r=Math.max(0,t-Date.now());if(r>h){const s=setTimeout(()=>{i(e,t)},h);l.set(e,s);return}const n=setTimeout(()=>{q(e).catch(()=>{})},r);l.set(e,n)},X=e=>{const t=I.get(e);!a&&t?.state==="pending"&&i(e,t.claimed_at===null?t.scheduled_for:t.claimed_at+g)},G=(e,t)=>{if(T()){a||i(e,t+S);return}try{const r=v.get(t,e,t,t-g);return r===void 0&&X(e),r}catch{!a&&c()&&i(e,Date.now()+V);return}},$=(e,t)=>{let r=t,n;const s=u=>{n=setTimeout(()=>{if(!c())return;if(T()){s(S);return}const f=Date.now();try{B.run(f,e,r).changes===1&&(r=f)}catch{}s(w)},u),n.unref()};return s(w),{release:()=>{clearTimeout(n)},stamp:()=>r}},q=async e=>{if(l.delete(e),!c())return;const t=Date.now(),r=G(e,t);if(r===void 0)return;const n=r.attempts+1,s=U(r.retry),u=$(e,t);try{await m.onDispatch?.(r.function_path,D(r.args),{attempts:n,id:e}),await y(),c()&&!T()&&F.run(e,u.stamp())}catch{if(await y(),a||!c())return;const f=s?.maxAttempts??d.maxAttempts;if(n>=f){P.run(n,e,u.stamp());return}const O=Date.now()+ee(n,s);J.run(n,O,e,u.stamp()).changes===1&&i(e,O)}finally{u.release()}},p=e=>{const t=_.get(e.key);t!==void 0&&clearTimeout(t);let r;try{r=C(e.expression).next().getTime()}catch{return}const n=Math.max(0,r-Date.now());if(n>h){_.set(e.key,setTimeout(()=>{p(e)},h));return}const s=setTimeout(()=>{_.delete(e.key),(async()=>{try{await m.onDispatch?.(e.function_path,D(e.args),{attempts:0,id:e.key})}catch{}!a&&c()&&p(e)})().catch(()=>{})},n);_.set(e.key,s)},z={cancel:async e=>a?!1:(R(e),j.run(e).changes>0),cron:async(e,t,r)=>{if(a)throw new Error("platform closed: cannot register a cron");C(e);const n={args:M(r??{}),expression:e,function_path:t,key:`${e} ${t}`};W.run(n.key,n.expression,n.function_path,n.args),p(n)},deadLetter:{list:async()=>a||!c()?[]:N.all("dead").map(e=>x(e)),requeue:async e=>{if(a||!c())return!1;const t=Date.now();return H.run(t,e).changes===0?!1:(i(e,t),!0)}},list:async()=>a||!c()?[]:N.all("pending").map(e=>x(e)),schedule:async(e,t,r)=>{if(a)throw new Error("platform closed: cannot schedule a job");const n=`node-job-${K()}`;let s;return r?.at===void 0?s=Date.now()+(r?.delayMs??0):s=typeof r.at=="number"?r.at:r.at.getTime(),b.run(n,e,M(t),s,r?.retry===void 0?null:M(r.retry)),i(n,s),{id:n,scheduledFor:s}}};for(const e of N.all("pending"))i(e.id,e.scheduled_for);for(const e of Y.all())p(e);return{dispose:()=>{for(const e of l.values())clearTimeout(e);for(const e of _.values())clearTimeout(e);l.clear(),_.clear(),a=!0},scheduler:z,simulateDeadLetter:async e=>{const t=I.get(e);if(t?.state!=="pending")return!1;R(e);const r=U(t.retry);return k.run((r?.maxAttempts??d.maxAttempts)+1,e),!0}}};export{oe as createNodeSchedulerHost};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AsyncLocalStorage as N}from"node:async_hooks";import{LunoraError as B}from"@lunora/errors";import F from"better-sqlite3";import{p as H}from"./prepared-statement-3XBQZXtC.mjs";const I=2147483647,O=6,M=100,C=10,U=r=>r===void 0?null:r,k=(r,n)=>({get databaseSize(){const u=r.pragma("page_count",{simple:!0}),o=r.pragma("page_size",{simple:!0});return u*o},exec:(u,...o)=>{n("run SQL");const t=H(r,u),s=o.map(i=>U(i)),c=t.reader&&t.readonly;let p;const T=()=>(p===void 0&&(n("run SQL"),t.reader?p=t.all(...s):(t.run(...s),p=[])),p);c||T();const y=function*(){n("run SQL"),t.raw(!0);try{yield*t.iterate(...s)}finally{t.raw(!1)}};return{get columnNames(){return t.reader?t.columns().map(i=>i.name):void 0},[Symbol.iterator]:()=>T()[Symbol.iterator](),one:()=>{const i=T();if(i.length!==1)throw new Error(`expected exactly one row, got ${String(i.length)}`);return i[0]},...c?{raw:y}:{},toArray:()=>[...T()]}}}),G=(r,n,u)=>{let o,t,s=0,c;r.exec("CREATE TABLE IF NOT EXISTS _lunora_alarm (id INTEGER PRIMARY KEY CHECK (id = 0), scheduled_for INTEGER NOT NULL)");const p=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0"),T=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"),i=r.prepare("SELECT scheduled_for FROM _lunora_alarm WHERE id = 0"),A=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0 AND scheduled_for = ?"),_=e=>{e===void 0?p.run():T.run(e)},w=e=>y.run(e).changes>0,v=e=>A.run(e).changes>0;let E=!1,m;const h=()=>{t!==void 0&&(clearTimeout(t),t=void 0),E=!1},g=e=>{t=setTimeout(()=>{t=void 0,E=!1,e()},C),E=!0},S=()=>{const e=i.get();e!==void 0&&(o=e.scheduled_for,f(e.scheduled_for))},a=()=>{if(!r.open||o!==void 0)return;if(r.inTransaction){g(a);return}if(s+=1,s>O){s=0;return}const e=Date.now()+M*2**(s-1);if(w(e)){o=e,f(e);return}s=0,S()},l=(e,d=0)=>{if(r.open&&r.inTransaction){g(()=>{l(e,d)});return}if(o=void 0,!!r.open){try{if(!v(e)){S();return}}catch{o=e,d<O&&(t=setTimeout(()=>{t=void 0,l(e,d+1)},M*2**d));return}(async()=>{await u?.(),s=0})().catch(()=>{a()})}},f=e=>{h();const d=Math.max(0,e-Date.now());if(d>I){t=setTimeout(()=>{f(e)},I);return}t=setTimeout(()=>{t=void 0,l(e)},d)},R={delete:()=>{if(!r.open)throw new Error("platform closed: cannot delete an alarm");if(n.assertOwnTurn("delete an alarm"),s=0,_(void 0),n.inside()){c={at:void 0};return}o=void 0,h()},get:()=>(c===void 0?o:c.at)??null,set:e=>{if(!r.open)throw new Error("platform closed: cannot set an alarm");n.assertOwnTurn("set an alarm");const d=typeof e=="number"?e:e.getTime();if(s=0,_(d),n.inside()){c={at:d};return}o=d,f(d)}},D=()=>{if(c===void 0)return;const{at:e}=c;if(c=void 0,e===void 0){o=void 0,h();return}o=e,f(e)},L=()=>{if(m=void 0,!r.open)return;if(r.inTransaction){m=setTimeout(L,C);return}const e=i.get();e!==void 0&&(t===void 0||E||o!==e.scheduled_for)&&(o=e.scheduled_for,f(e.scheduled_for))},x=()=>{c=void 0,m!==void 0&&clearTimeout(m),L()},z=()=>{h(),m!==void 0&&(clearTimeout(m),m=void 0)};return S(),{alarms:R,commit:D,dispose:z,rollback:x}},Q=(r={})=>{const n=new F(r.path??":memory:");n.pragma("journal_mode = WAL");const u=new N;let o=!1;const t=a=>{if(o&&u.getStore()!==!0)throw new B("SHARD_UNAVAILABLE",`shard busy: cannot ${a} while another task holds this shard's transaction`)},s=k(n,t),{alarms:c,commit:p,dispose:T,rollback:y}=G(n,{assertOwnTurn:t,inside:()=>u.getStore()===!0},r.onAlarm),i=new Set,A=new N;let _=Promise.resolve();const w=async a=>{if(A.getStore()===!0)return await a();const l=_;let f=()=>{};_=new Promise(R=>{f=R}),await l;try{return await A.run(!0,a)}finally{f()}},v=a=>w(a),E=async a=>{n.exec("BEGIN"),o=!0;try{const l=await u.run(!0,a);return n.exec("COMMIT"),o=!1,p(),l}catch(l){o=!1;try{n.exec("ROLLBACK")}catch{}throw y(),l}},m=a=>w(async()=>E(a)),h={alarms:c,runSerialized:v,shardKey:r.shardKey,sql:s,transaction:m,waitUntil:a=>{const l=a.catch(()=>{}).finally(()=>{i.delete(l)});i.add(l)}};return{database:n,dispose:()=>{T(),n.open&&n.close()},drain:async()=>{for(;i.size>0;)await Promise.all(i)},host:h}};export{Q as createNodeShardHost};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as S,readdirSync as v}from"node:fs";import{join as l}from"node:path";import{LunoraError as f}from"@lunora/errors";import{createNodeShardKvStore as w}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeShardHost as g}from"./createNodeShardHost-
|
|
1
|
+
import{mkdirSync as S,readdirSync as v}from"node:fs";import{join as l}from"node:path";import{LunoraError as f}from"@lunora/errors";import{createNodeShardKvStore as w}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeShardHost as g}from"./createNodeShardHost-Bhbm4txQ.mjs";import{createNodeSocketHost as A}from"./createNodeSocketHost-ByOmEGFe.mjs";const c=".sqlite3",u=r=>r.replaceAll(/[^\da-z._-]/gu,t=>[...Buffer.from(t,"utf8")].map(o=>`%${o.toString(16).padStart(2,"0").toUpperCase()}`).join("")),b=r=>decodeURIComponent(r),$=(r,t)=>{const o=t.slice(0,-c.length),s=l(r,t);let d;try{d=b(o)}catch{throw new f("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${s}" has a basename that is not valid percent-encoding, so the shard key it holds cannot be recovered. Rename or remove the file.`)}const e=`${u(d)}${c}`;if(e!==t)throw new f("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${s}" was written under an older shard-key encoding. It decodes to shard key "${d}", which this build stores as "${e}" — so the key would be listed for fan-out while every read opened a new, empty database. Rename it: mv "${s}" "${l(r,e)}"`);return d},I=(r={})=>{const t=new Map,o=new Set;if(r.directory!==void 0){S(r.directory,{recursive:!0});for(const e of v(r.directory))e.endsWith(c)&&o.add($(r.directory,e))}const s=e=>{const a=t.get(e);if(a!==void 0)return a.shard;const i=r.directory===void 0?void 0:l(r.directory,`${u(e)}${c}`);let n;const{database:m,dispose:p,host:y}=g({onAlarm:()=>r.onAlarm?.(n),path:i,shardKey:e}),h=A(m);return n={inbound:h,kv:w(m),shard:y,shardKey:e,sockets:h.socket},t.set(e,{dispose:p,drain:h.drain,shard:n}),o.add(e),n},d=e=>({fetch:async a=>{const i=s(e);return r.onFetch===void 0?new Response(e):r.onFetch(a,i)}});return{close:()=>{for(const e of t.values()){const a=e.drain();a===void 0?e.dispose():a.finally(e.dispose).catch(()=>{})}t.clear()},directory:{get:e=>d(String(e)),getByName:e=>d(e),idForName:e=>e},listShardKeys:()=>[...o],shardFor:s}};export{I 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.177",
|
|
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",
|
|
@@ -46,13 +46,13 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/d1": "1.0.0-alpha.
|
|
49
|
+
"@lunora/d1": "1.0.0-alpha.205",
|
|
50
50
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
51
51
|
"@lunora/platform": "1.0.0-alpha.74",
|
|
52
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
53
|
-
"@lunora/runtime": "1.0.0-alpha.
|
|
54
|
-
"@lunora/sql-store": "1.0.0-alpha.
|
|
55
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
52
|
+
"@lunora/queue": "1.0.0-alpha.126",
|
|
53
|
+
"@lunora/runtime": "1.0.0-alpha.236",
|
|
54
|
+
"@lunora/sql-store": "1.0.0-alpha.206",
|
|
55
|
+
"@lunora/workflow": "1.0.0-alpha.94",
|
|
56
56
|
"@visulima/cron-parser": "2.0.0",
|
|
57
57
|
"@visulima/workflow": "3.0.0",
|
|
58
58
|
"better-sqlite3": "^13.0.3",
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import{randomUUID as j}from"node:crypto";import{deserialize as L,serialize as N}from"node:v8";import{parse as R}from"@visulima/cron-parser";const E={backoffMultiplier:2,initialDelayMs:1e3,maxAttempts:5,maxDelayMs:6e4},d=2147483647,F=(s,i)=>{const _=i?.initialDelayMs??E.initialDelayMs,m=i?.backoffMultiplier??E.backoffMultiplier,p=i?.maxDelayMs??E.maxDelayMs;return Math.min(p,_*m**Math.max(0,s-1))},H=(s,i={})=>{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
|
-
)`),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 _=s.prepare("INSERT INTO _lunora_scheduler_jobs (id, function_path, args, scheduled_for, retry) VALUES (?, ?, ?, ?, ?)"),m=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE id = ?"),p=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE state = ? ORDER BY scheduled_for"),x=s.prepare("DELETE FROM _lunora_scheduler_jobs WHERE id = ?"),M=s.prepare("DELETE FROM _lunora_scheduler_jobs WHERE id = ? AND state = 'pending'"),O=s.prepare("UPDATE _lunora_scheduler_jobs SET attempts = ?, scheduled_for = ? WHERE id = ?"),g=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ? WHERE id = ?"),U=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'pending', attempts = 0, scheduled_for = ? WHERE id = ? AND state = 'dead'"),S=s.prepare(`INSERT INTO _lunora_scheduler_crons (key, expression, function_path, args) VALUES (?, ?, ?, ?)
|
|
15
|
-
ON CONFLICT (key) DO UPDATE SET expression = excluded.expression, args = excluded.args`),b=s.prepare("SELECT * FROM _lunora_scheduler_crons"),c=()=>s.open,A=e=>e===null?void 0:L(e);let a=!1;const l=new Map,u=new Map,D=e=>({attempts:e.attempts,functionPath:e.function_path,id:e.id,scheduledFor:e.scheduled_for}),h=e=>{const t=l.get(e);t!==void 0&&(clearTimeout(t),l.delete(e))},T=(e,t)=>{h(e);const r=Math.max(0,t-Date.now());if(r>d){const o=setTimeout(()=>{T(e,t)},d);l.set(e,o);return}const n=setTimeout(()=>{k(e).catch(()=>{})},r);l.set(e,n)},k=async e=>{if(l.delete(e),!c())return;const t=m.get(e);if(t?.state!=="pending")return;const r=t.attempts+1,n=A(t.retry);try{await i.onDispatch?.(t.function_path,L(t.args),{attempts:r,id:e}),c()&&x.run(e)}catch{if(a||!c())return;const o=n?.maxAttempts??E.maxAttempts;if(r>=o){g.run(r,e);return}const y=Date.now()+F(r,n);O.run(r,y,e),T(e,y)}},f=e=>{const t=u.get(e.key);t!==void 0&&clearTimeout(t);let r;try{r=R(e.expression).next().getTime()}catch{return}const n=Math.max(0,r-Date.now());if(n>d){u.set(e.key,setTimeout(()=>{f(e)},d));return}const o=setTimeout(()=>{u.delete(e.key),(async()=>{try{await i.onDispatch?.(e.function_path,L(e.args),{attempts:0,id:e.key})}catch{}!a&&c()&&f(e)})().catch(()=>{})},n);u.set(e.key,o)},I={cancel:async e=>a?!1:(h(e),M.run(e).changes>0),cron:async(e,t,r)=>{if(a)throw new Error("platform closed: cannot register a cron");R(e);const n={args:N(r??{}),expression:e,function_path:t,key:`${e} ${t}`};S.run(n.key,n.expression,n.function_path,n.args),f(n)},deadLetter:{list:async()=>a||!c()?[]:p.all("dead").map(e=>D(e)),requeue:async e=>{if(a||!c())return!1;const t=Date.now();return U.run(t,e).changes===0?!1:(T(e,t),!0)}},list:async()=>a||!c()?[]:p.all("pending").map(e=>D(e)),schedule:async(e,t,r)=>{if(a)throw new Error("platform closed: cannot schedule a job");const n=`node-job-${j()}`;let o;return r?.at===void 0?o=Date.now()+(r?.delayMs??0):o=typeof r.at=="number"?r.at:r.at.getTime(),_.run(n,e,N(t),o,r?.retry===void 0?null:N(r.retry)),T(n,o),{id:n,scheduledFor:o}}};for(const e of p.all("pending"))T(e.id,e.scheduled_for);for(const e of b.all())f(e);return{dispose:()=>{for(const e of l.values())clearTimeout(e);for(const e of u.values())clearTimeout(e);l.clear(),u.clear(),a=!0},scheduler:I,simulateDeadLetter:async e=>{const t=m.get(e);if(t?.state!=="pending")return!1;h(e);const r=A(t.retry);return g.run((r?.maxAttempts??E.maxAttempts)+1,e),!0}}};export{H as createNodeSchedulerHost};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{AsyncLocalStorage as S}from"node:async_hooks";import{LunoraError as v}from"@lunora/errors";import L from"better-sqlite3";import{p as R}from"./prepared-statement-3XBQZXtC.mjs";const A=2147483647,I=6,M=100,N=r=>r===void 0?null:r,O=(r,t)=>({get databaseSize(){const u=r.pragma("page_count",{simple:!0}),o=r.pragma("page_size",{simple:!0});return u*o},exec:(u,...o)=>{t("run SQL");const e=R(r,u),s=o.map(a=>N(a)),i=e.reader&&e.readonly;let c;const d=()=>(c===void 0&&(t("run SQL"),e.reader?c=e.all(...s):(e.run(...s),c=[])),c);i||d();const m=function*(){t("run SQL"),e.raw(!0);try{yield*e.iterate(...s)}finally{e.raw(!1)}};return{get columnNames(){return e.reader?e.columns().map(a=>a.name):void 0},[Symbol.iterator]:()=>d()[Symbol.iterator](),one:()=>{const a=d();if(a.length!==1)throw new Error(`expected exactly one row, got ${String(a.length)}`);return a[0]},...i?{raw:m}:{},toArray:()=>[...d()]}}}),x=(r,t,u)=>{let o,e,s=0,i;r.exec("CREATE TABLE IF NOT EXISTS _lunora_alarm (id INTEGER PRIMARY KEY CHECK (id = 0), scheduled_for INTEGER NOT NULL)");const c=n=>{n===void 0?r.prepare("DELETE FROM _lunora_alarm WHERE id = 0").run():r.prepare("INSERT INTO _lunora_alarm (id, scheduled_for) VALUES (0, ?) ON CONFLICT (id) DO UPDATE SET scheduled_for = excluded.scheduled_for").run(n)},d=()=>{e!==void 0&&(clearTimeout(e),e=void 0)},m=n=>{d();const p=Math.max(0,n-Date.now());if(p>A){e=setTimeout(()=>{m(n)},A);return}e=setTimeout(()=>{o=void 0,e=void 0,r.open&&(c(void 0),(async()=>{await u?.(),s=0})().catch(()=>{if(!r.open||o!==void 0)return;if(s+=1,s>I){s=0;return}const E=Date.now()+M*2**(s-1);o=E,c(E),m(E)}))},p)},a={delete:()=>{if(!r.open)throw new Error("platform closed: cannot delete an alarm");if(t.assertOwnTurn("delete an alarm"),s=0,c(void 0),t.inside()){i={at:void 0};return}o=void 0,d()},get:()=>(i===void 0?o:i.at)??null,set:n=>{if(!r.open)throw new Error("platform closed: cannot set an alarm");t.assertOwnTurn("set an alarm");const p=typeof n=="number"?n:n.getTime();if(s=0,c(p),t.inside()){i={at:p};return}o=p,m(p)}},h=()=>{if(i===void 0)return;const{at:n}=i;if(i=void 0,n===void 0){o=void 0,d();return}o=n,m(n)},y=()=>{i=void 0},w=r.prepare("SELECT scheduled_for FROM _lunora_alarm WHERE id = 0").get();return w!==void 0&&(o=w.scheduled_for,m(w.scheduled_for)),{alarms:a,commit:h,dispose:d,rollback:y}},H=(r={})=>{const t=new L(r.path??":memory:");t.pragma("journal_mode = WAL");const u=new S;let o=!1;const e=l=>{if(o&&u.getStore()!==!0)throw new v("SHARD_UNAVAILABLE",`shard busy: cannot ${l} while another task holds this shard's transaction`)},s=O(t,e),{alarms:i,commit:c,dispose:d,rollback:m}=x(t,{assertOwnTurn:e,inside:()=>u.getStore()===!0},r.onAlarm),a=new Set,h=new S;let y=Promise.resolve();const w=async l=>{if(h.getStore()===!0)return await l();const f=y;let T=()=>{};y=new Promise(g=>{T=g}),await f;try{return await h.run(!0,l)}finally{T()}},n=l=>w(l),p=async l=>{t.exec("BEGIN"),o=!0;try{const f=await u.run(!0,l);return t.exec("COMMIT"),o=!1,c(),f}catch(f){o=!1,m();try{t.exec("ROLLBACK")}catch{}throw f}},E=l=>w(async()=>p(l)),_={alarms:i,runSerialized:n,shardKey:r.shardKey,sql:s,transaction:E,waitUntil:l=>{const f=l.catch(()=>{}).finally(()=>{a.delete(f)});a.add(f)}};return{database:t,dispose:()=>{d(),t.open&&t.close()},drain:async()=>{for(;a.size>0;)await Promise.all(a)},host:_}};export{H as createNodeShardHost};
|