@lunora/platform-node 1.0.0-alpha.210 → 1.0.0-alpha.211
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 +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/NODE_SCHEDULER_DISPATCH_PATH-RI9fOO8d.mjs +1 -0
- package/dist/packem_shared/createNodePlatform-DJZCR46S.mjs +1 -0
- package/dist/packem_shared/createNodeSchedulerHost-CjgGhVoQ.mjs +15 -0
- package/package.json +7 -7
- package/dist/packem_shared/NODE_SCHEDULER_DISPATCH_PATH-C3-wCHPp.mjs +0 -1
- package/dist/packem_shared/createNodePlatform-CuZZbfWJ.mjs +0 -1
- package/dist/packem_shared/createNodeSchedulerHost-CiSdzxod.mjs +0 -15
|
@@ -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-CjgGhVoQ.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.d.mts
CHANGED
|
@@ -16,6 +16,8 @@ interface NodeDispatchInvocation {
|
|
|
16
16
|
identity?: string;
|
|
17
17
|
userId?: string;
|
|
18
18
|
} | undefined;
|
|
19
|
+
/** The job's due time in epoch-ms, when the sender stamped one. */
|
|
20
|
+
scheduledFor?: number;
|
|
19
21
|
shardKey: string;
|
|
20
22
|
traceparent: string | undefined;
|
|
21
23
|
}
|
|
@@ -221,10 +223,15 @@ interface NodeSchedulerHostOptions {
|
|
|
221
223
|
* precise failure plan 267 caught. Supply one in anything real; the
|
|
222
224
|
* conformance host supplies one purely so the TCK can tell a delivery apart
|
|
223
225
|
* from an expired timer.
|
|
226
|
+
*
|
|
227
|
+
* `job.scheduledFor` is the due time (a cron tick's planned fire time).
|
|
228
|
+
* Forwarding it as the dispatch body's `scheduledFor` is what lets the shard
|
|
229
|
+
* record the `scheduler.lag_ms` metric, as the Worker dispatch path does.
|
|
224
230
|
*/
|
|
225
231
|
onDispatch?: (functionPath: string, args: Record<string, unknown>, job: {
|
|
226
232
|
attempts: number;
|
|
227
233
|
id: string;
|
|
234
|
+
scheduledFor: number;
|
|
228
235
|
}) => Promise<void> | void;
|
|
229
236
|
}
|
|
230
237
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -16,6 +16,8 @@ interface NodeDispatchInvocation {
|
|
|
16
16
|
identity?: string;
|
|
17
17
|
userId?: string;
|
|
18
18
|
} | undefined;
|
|
19
|
+
/** The job's due time in epoch-ms, when the sender stamped one. */
|
|
20
|
+
scheduledFor?: number;
|
|
19
21
|
shardKey: string;
|
|
20
22
|
traceparent: string | undefined;
|
|
21
23
|
}
|
|
@@ -221,10 +223,15 @@ interface NodeSchedulerHostOptions {
|
|
|
221
223
|
* precise failure plan 267 caught. Supply one in anything real; the
|
|
222
224
|
* conformance host supplies one purely so the TCK can tell a delivery apart
|
|
223
225
|
* from an expired timer.
|
|
226
|
+
*
|
|
227
|
+
* `job.scheduledFor` is the due time (a cron tick's planned fire time).
|
|
228
|
+
* Forwarding it as the dispatch body's `scheduledFor` is what lets the shard
|
|
229
|
+
* record the `scheduler.lag_ms` metric, as the Worker dispatch path does.
|
|
224
230
|
*/
|
|
225
231
|
onDispatch?: (functionPath: string, args: Record<string, unknown>, job: {
|
|
226
232
|
attempts: number;
|
|
227
233
|
id: string;
|
|
234
|
+
scheduledFor: number;
|
|
228
235
|
}) => Promise<void> | void;
|
|
229
236
|
}
|
|
230
237
|
/**
|
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-
|
|
1
|
+
import{NODE_SCHEDULER_DISPATCH_PATH as r,createNodeDispatchRoute as t}from"./packem_shared/NODE_SCHEDULER_DISPATCH_PATH-RI9fOO8d.mjs";import{createNodeGlobalStore as d,createNodeSqlExec as c}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.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-DJZCR46S.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-D_jsnenX.mjs";import{createNodeSchedulerHost as D}from"./packem_shared/createNodeSchedulerHost-CjgGhVoQ.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{toErrorResponse as h,resolveShard as u}from"@lunora/runtime";import{s as l}from"./hmac-url-Bogwm7I6.mjs";const f=async(e,t)=>{if(!e.body)return"";const n=e.body.getReader(),a=new TextDecoder;let r=0,o="";for(;;){const{done:s,value:d}=await n.read();if(s)break;if(d){if(r+=d.byteLength,r>t)return await n.cancel().catch(()=>{}),null;o+=a.decode(d,{stream:!0})}}return o+=a.decode(),o},c=(e,t)=>{const n=Math.max(e.length,t.length);let a=e.length^t.length;for(let r=0;r<n;r+=1){const o=r<e.length?e.charCodeAt(r):0,s=r<t.length?t.charCodeAt(r):0;a|=o^s}return a===0},y="/_lunora/scheduler/dispatch",g="__lunora_relation__:",p=e=>e.startsWith(g),_=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[a,...r]=n.split(" ");return a?.toLowerCase()!=="bearer"?!1:c(t,r.join(" ").trim())},w=async(e,t,n)=>{const a=e.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:r}=n;return a!==null&&a.length>0&&r!==void 0&&r.length>0?c(await l(r,t),a):_(e,n.adminToken)},E="x-lunora-paywall",S="1",A="x-lunora-scheduled-for",T=({forwardedIdentity:e,mutationId:t,scheduledFor:n,traceparent:a})=>{const r={"content-type":"application/json",[E]:S,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),a!==void 0&&a.length>0&&(r.traceparent=a),n!==void 0&&Number.isFinite(n)&&(r[A]=String(Math.trunc(n))),r},D=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},m=1048576,P=async e=>{const t=await f(e,m);if(t===null)throw new i("PAYLOAD_TOO_LARGE","Scheduler dispatch body is too large");return t},R=async(e,t)=>{if(e.method!=="POST")throw new i("METHOD_NOT_ALLOWED","Scheduler dispatch endpoint requires POST",{status:405});const n=await P(e);if(!await w(e,n,{adminToken:t.adminToken,schedulerSecret:t.schedulerSecret}))throw new i("DISPATCH_UNAUTHENTICATED","Scheduler dispatch requires a valid signature or admin bearer");let r;try{r=JSON.parse(n)}catch{throw new i("BAD_REQUEST","Scheduler dispatch body must be valid JSON")}const o=r??{};if(typeof o.workflow=="string"||o.pool!==void 0)throw new i("SERVICE_UNAVAILABLE","Scheduler dispatch for a workflow or pool target is not served by the Node dispatch route");if(typeof o.functionPath!="string"||o.functionPath.length===0)throw new i("BAD_REQUEST","Scheduler dispatch is missing `functionPath`");if(p(o.functionPath))throw new i("FORBIDDEN","`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard");const s=typeof o.shardKey=="string"&&o.shardKey.length>0?o.shardKey:t.defaultShardKey;return t.invoke({args:o.args??{},functionPath:o.functionPath,id:typeof o.id=="string"&&o.id.length>0?o.id:void 0,identity:D(e),scheduledFor:typeof o.scheduledFor=="number"?o.scheduledFor:void 0,shardKey:s,traceparent:e.headers.get("traceparent")??void 0})},O=(e,t)=>n=>{if(!t)throw new i("SERVICE_UNAVAILABLE","@lunora/platform-node: the dispatch route needs `onFetch` to run a function; without it a shard only echoes its key");const a=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n.args,functionPath:n.functionPath}),headers:T({forwardedIdentity:n.identity,mutationId:n.id,scheduledFor:n.scheduledFor,traceparent:n.traceparent}),method:"POST"});return u(e,n.shardKey).fetch(a)},N=e=>async t=>{try{return await R(t,e)}catch(n){return h(n)}},C=y;export{C as NODE_SCHEDULER_DISPATCH_PATH,N as createNodeDispatchRoute,O as createShardInvoke};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as n}from"@lunora/errors";import{NODE_CAPABILITIES as y}from"@lunora/platform";import{createShardInvoke as g,createNodeDispatchRoute as _}from"./NODE_SCHEDULER_DISPATCH_PATH-RI9fOO8d.mjs";import{createNodeGlobalStore as R}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as D}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeQueueHost as I}from"./createNodeQueueHost-CttDb5sY.mjs";import{createNodeR2Bucket as A}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as E}from"./createNodeSchedulerHost-CjgGhVoQ.mjs";import{createNodeShardHost as T}from"./createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardRegistry as q}from"./createNodeShardRegistry-BKl1QXiv.mjs";import{createNodeSocketHost as B}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as H}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as L}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const F=(e,o)=>async(r,c,t)=>{const s=await e({args:c,functionPath:r,id:t.id,identity:void 0,scheduledFor:t.scheduledFor,shardKey:o,traceparent:void 0});if(!s.ok)throw new n("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(s.status)}`)},z=(e={})=>{const o=[],{database:r,dispose:c,drain:t,host:s}=T(e);o.push(c);try{const d=D(r),a=q(e);o.push(()=>{a.close()});const{directory:u}=a,l=g(u,e.onFetch!==void 0),f=_({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:l,schedulerSecret:e.dispatch?.schedulerSecret}),v=e.onFetch===void 0?void 0:F(l,e.shardKey??"__root__"),{dispose:w,scheduler:p}=E(r,{...e,onDispatch:e.onDispatch??v}),{socket:S}=B(r);o.push(w);const k=e.queues===void 0?void 0:I(r,{onBatch:e.onQueueBatch??(()=>{throw new n("VALIDATION_ERROR","@lunora/platform-node: createNodePlatform was given `queues` without `onQueueBatch`, so a delivered batch has nowhere to go — pass the worker's queue export from createWorker")}),queues:e.queues}),b=e.objectStorageDirectory===void 0?void 0:A({directory:e.objectStorageDirectory}),i=e.globalTablesPath===void 0?void 0:R({path:e.globalTablesPath});i!==void 0&&o.push(()=>{i.dispose()});const N=e.workflows===void 0?void 0:H({store:L(r),workflows:e.workflows}),m=()=>{for(const h of o.toReversed())h()};return{capabilities:y,close:m,directory:u,dispatch:h=>f(h),drain:t,globalTables:i,kv:d,objectStorage:b,queues:k,scheduler:p,shard:s,sockets:S,workflows:N,[Symbol.dispose]:m}}catch(d){for(const a of o.toReversed())try{a()}catch{}throw d}};export{z as createNodePlatform};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{randomUUID as Z}from"node:crypto";import{deserialize as U,serialize as w}from"node:v8";import{LunoraError as ee}from"@lunora/errors";import{parse as b}from"@visulima/cron-parser/cloudflare";const j={seconds:"optional"},p={backoffMultiplier:2,initialDelayMs:1e3,maxAttempts:5,maxDelayMs:6e4},A=2147483647,N=6e4,F=N/3,te=1e3,re=5,ne=20,O=10,h=6048e5,oe=(o,_)=>{const E=_?.initialDelayMs??p.initialDelayMs,D=_?.backoffMultiplier??p.backoffMultiplier,L=_?.maxDelayMs??p.maxDelayMs;return Math.min(L,E*D**Math.max(0,o-1))},ie=(o,_={})=>{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=e=>o.prepare("PRAGMA table_info(_lunora_scheduler_jobs)").all().some(t=>t.name===e),D=e=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},L=e=>{for(let t=0;;t+=1)try{o.exec(`ALTER TABLE _lunora_scheduler_jobs ADD COLUMN ${e} INTEGER`);return}catch(r){if(E(e))return;if(!(r instanceof Error&&"code"in r&&r.code==="SQLITE_BUSY")||t>=re)throw r;D(ne*2**t)}};for(const e of["claimed_at","completed_at"])E(e)||L(e);o.exec("CREATE INDEX IF NOT EXISTS _lunora_scheduler_jobs_state_completed ON _lunora_scheduler_jobs (state, completed_at)"),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 P=o.prepare("INSERT INTO _lunora_scheduler_jobs (id, function_path, args, scheduled_for, retry) VALUES (?, ?, ?, ?, ?)"),y=o.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE id = ?"),R=o.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE state = ? ORDER BY scheduled_for"),k=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'canceled', completed_at = ? WHERE id = ? AND state = 'pending'"),v=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ?"),g=o.prepare("DELETE FROM _lunora_scheduler_jobs WHERE state IN ('succeeded', 'canceled') AND completed_at <= ?"),B=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'succeeded', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ?"),H=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 = ? AND state = 'pending'"),W=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),X=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 *"),Y=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'pending', attempts = 0, completed_at = NULL, scheduled_for = ? WHERE id = ? AND state = 'dead'"),G=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`),$=o.prepare("SELECT * FROM _lunora_scheduler_crons"),a=()=>o.open,T=()=>o.inTransaction,x=e=>e===null?void 0:U(e);let s=!1;const S=async()=>{s||!a()||!T()||(await new Promise(e=>{setTimeout(e,O).unref()}),await S())},i=new Map,m=new Map,I=e=>({attempts:e.attempts,functionPath:e.function_path,id:e.id,scheduledFor:e.scheduled_for}),M=e=>{const t=i.get(e);t!==void 0&&(clearTimeout(t),i.delete(e))},l=(e,t)=>{M(e);const r=Math.max(0,t-Date.now());if(r>A){const c=setTimeout(()=>{l(e,t)},A);i.set(e,c);return}const n=setTimeout(()=>{K(e).catch(()=>{})},r);i.set(e,n)},V=e=>{const t=y.get(e);!s&&t?.state==="pending"&&l(e,t.claimed_at===null?t.scheduled_for:t.claimed_at+N)},q=(e,t)=>{if(T()){s||l(e,t+O);return}try{const r=X.get(t,e,t,t-N);return r===void 0&&V(e),r}catch{!s&&a()&&l(e,Date.now()+te);return}},z=(e,t)=>{let r=t,n;const c=u=>{n=setTimeout(()=>{if(!a())return;if(T()){c(O);return}const d=Date.now();try{H.run(d,e,r).changes===1&&(r=d)}catch{}c(F)},u),n.unref()};return c(F),{release:()=>{clearTimeout(n)},stamp:()=>r}},K=async e=>{if(i.delete(e),!a())return;const t=Date.now(),r=q(e,t);if(r===void 0)return;const n=r.attempts+1,c=x(r.retry),u=z(e,t);try{if(await _.onDispatch?.(r.function_path,U(r.args),{attempts:n,id:e,scheduledFor:r.scheduled_for}),await S(),a()&&!T()){const d=Date.now();B.run(n,d,e,u.stamp()),g.run(d-h)}}catch{if(await S(),s||!a())return;const d=c?.maxAttempts??p.maxAttempts;if(n>=d){W.run(n,Date.now(),e,u.stamp());return}const C=Date.now()+oe(n,c);J.run(n,C,e,u.stamp()).changes===1&&l(e,C)}finally{u.release()}},f=e=>{const t=m.get(e.key);t!==void 0&&clearTimeout(t);let r;try{r=b(e.expression,j).next().getTime()}catch{return}const n=Math.max(0,r-Date.now());if(n>A){m.set(e.key,setTimeout(()=>{f(e)},A));return}const c=setTimeout(()=>{m.delete(e.key),(async()=>{try{await _.onDispatch?.(e.function_path,U(e.args),{attempts:0,id:`${e.key}:${String(r)}`,scheduledFor:r})}catch{}!s&&a()&&f(e)})().catch(()=>{})},n);m.set(e.key,c)},Q={cancel:async e=>{if(s)return!1;M(e);const t=Date.now(),r=k.run(t,e).changes>0;return g.run(t-h),r},cron:async(e,t,r)=>{if(s)throw new Error("platform closed: cannot register a cron");b(e,j);const n={args:w(r??{}),expression:e,function_path:t,key:`${e} ${t}`};G.run(n.key,n.expression,n.function_path,n.args),f(n)},deadLetter:{list:async()=>s||!a()?[]:R.all("dead").map(e=>I(e)),requeue:async e=>{if(s||!a())return!1;const t=Date.now();return Y.run(t,e).changes===0?!1:(l(e,t),!0)}},get:async e=>{const t=s||!a()?void 0:y.get(e);if(t===void 0||t.completed_at!==null&&t.state!=="dead"&&t.completed_at<=Date.now()-h)return null;const r={canceled:"canceled",dead:"failed",pending:"pending",succeeded:"succeeded"},n=t.state==="pending"&&t.claimed_at!==null&&t.claimed_at>=Date.now()-N,c={...I(t),state:n?"running":r[t.state]};return t.completed_at!==null&&(c.completedAt=t.completed_at),c},list:async()=>s||!a()?[]:R.all("pending").map(e=>I(e)),schedule:async(e,t,r)=>{if(s)throw new Error("platform closed: cannot schedule a job");if(r?.retry?.forever===!0)throw new ee("INVALID_INPUT","retry.forever is not supported by the Node scheduler host; set a finite retry.maxAttempts");const n=`node-job-${Z()}`;let c;return r?.at===void 0?c=Date.now()+(r?.delayMs??0):c=typeof r.at=="number"?r.at:r.at.getTime(),P.run(n,e,w(t),c,r?.retry===void 0?null:w(r.retry)),l(n,c),{id:n,scheduledFor:c}}};g.run(Date.now()-h);for(const e of R.all("pending"))l(e.id,e.scheduled_for);for(const e of $.all())f(e);return{dispose:()=>{for(const e of i.values())clearTimeout(e);for(const e of m.values())clearTimeout(e);i.clear(),m.clear(),s=!0},scheduler:Q,simulateDeadLetter:async e=>{const t=y.get(e);if(t?.state!=="pending")return!1;M(e);const r=x(t.retry);return v.run((r?.maxAttempts??p.maxAttempts)+1,Date.now(),e),!0}}};export{ie as createNodeSchedulerHost};
|
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.211",
|
|
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.229",
|
|
50
50
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
51
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
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.
|
|
51
|
+
"@lunora/platform": "1.0.0-alpha.78",
|
|
52
|
+
"@lunora/queue": "1.0.0-alpha.140",
|
|
53
|
+
"@lunora/runtime": "1.0.0-alpha.270",
|
|
54
|
+
"@lunora/sql-store": "1.0.0-alpha.230",
|
|
55
|
+
"@lunora/workflow": "1.0.0-alpha.108",
|
|
56
56
|
"@visulima/cron-parser": "2.0.0",
|
|
57
57
|
"@visulima/workflow": "4.0.0",
|
|
58
58
|
"better-sqlite3": "^13.0.3",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{toErrorResponse as h,resolveShard as u}from"@lunora/runtime";import{s as l}from"./hmac-url-Bogwm7I6.mjs";const f=async(t,e)=>{if(!t.body)return"";const n=t.body.getReader(),r=new TextDecoder;let a=0,o="";for(;;){const{done:s,value:d}=await n.read();if(s)break;if(d){if(a+=d.byteLength,a>e)return await n.cancel().catch(()=>{}),null;o+=r.decode(d,{stream:!0})}}return o+=r.decode(),o},c=(t,e)=>{const n=Math.max(t.length,e.length);let r=t.length^e.length;for(let a=0;a<n;a+=1){const o=a<t.length?t.charCodeAt(a):0,s=a<e.length?e.charCodeAt(a):0;r|=o^s}return r===0},y="/_lunora/scheduler/dispatch",g="__lunora_relation__:",p=t=>t.startsWith(g),w=(t,e)=>{if(!e||e.length===0)return!1;const n=t.headers.get("authorization");if(!n)return!1;const[r,...a]=n.split(" ");return r?.toLowerCase()!=="bearer"?!1:c(e,a.join(" ").trim())},_=async(t,e,n)=>{const r=t.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:a}=n;return r!==null&&r.length>0&&a!==void 0&&a.length>0?c(await l(a,e),r):w(t,n.adminToken)},A="x-lunora-paywall",S="1",E=({forwardedIdentity:t,mutationId:e,traceparent:n})=>{const r={"content-type":"application/json",[A]:S,"x-lunora-system":"1"};return t?.userId!==void 0&&t.userId.length>0&&(r["x-lunora-userid"]=t.userId),t?.identity!==void 0&&t.identity.length>0&&(r["x-lunora-identity"]=t.identity),e!==void 0&&e.length>0&&(r["x-lunora-mutation-id"]=e),n!==void 0&&n.length>0&&(r.traceparent=n),r},T=t=>{const e=t.headers.get("x-lunora-userid"),n=t.headers.get("x-lunora-identity");if(!(e===null&&n===null))return{...n===null?{}:{identity:n},...e===null?{}:{userId:e}}},P=1048576,m=async t=>{const e=await f(t,P);if(e===null)throw new i("PAYLOAD_TOO_LARGE","Scheduler dispatch body is too large");return e},D=async(t,e)=>{if(t.method!=="POST")throw new i("METHOD_NOT_ALLOWED","Scheduler dispatch endpoint requires POST",{status:405});const n=await m(t);if(!await _(t,n,{adminToken:e.adminToken,schedulerSecret:e.schedulerSecret}))throw new i("DISPATCH_UNAUTHENTICATED","Scheduler dispatch requires a valid signature or admin bearer");let a;try{a=JSON.parse(n)}catch{throw new i("BAD_REQUEST","Scheduler dispatch body must be valid JSON")}const o=a??{};if(typeof o.workflow=="string"||o.pool!==void 0)throw new i("SERVICE_UNAVAILABLE","Scheduler dispatch for a workflow or pool target is not served by the Node dispatch route");if(typeof o.functionPath!="string"||o.functionPath.length===0)throw new i("BAD_REQUEST","Scheduler dispatch is missing `functionPath`");if(p(o.functionPath))throw new i("FORBIDDEN","`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard");const s=typeof o.shardKey=="string"&&o.shardKey.length>0?o.shardKey:e.defaultShardKey;return e.invoke({args:o.args??{},functionPath:o.functionPath,id:typeof o.id=="string"&&o.id.length>0?o.id:void 0,identity:T(t),shardKey:s,traceparent:t.headers.get("traceparent")??void 0})},L=(t,e)=>n=>{if(!e)throw new i("SERVICE_UNAVAILABLE","@lunora/platform-node: the dispatch route needs `onFetch` to run a function; without it a shard only echoes its key");const r=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n.args,functionPath:n.functionPath}),headers:E({forwardedIdentity:n.identity,mutationId:n.id,traceparent:n.traceparent}),method:"POST"});return u(t,n.shardKey).fetch(r)},O=t=>async e=>{try{return await D(e,t)}catch(n){return h(n)}},N=y;export{N as NODE_SCHEDULER_DISPATCH_PATH,O as createNodeDispatchRoute,L as createShardInvoke};
|
|
@@ -1 +0,0 @@
|
|
|
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-C3-wCHPp.mjs";import{createNodeGlobalStore as y}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as R}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeQueueHost as T}from"./createNodeQueueHost-CttDb5sY.mjs";import{createNodeR2Bucket as q}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as I}from"./createNodeSchedulerHost-CiSdzxod.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};
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import{randomUUID as Q}from"node:crypto";import{deserialize as U,serialize as w}from"node:v8";import{parse as b}from"@visulima/cron-parser";const p={backoffMultiplier:2,initialDelayMs:1e3,maxAttempts:5,maxDelayMs:6e4},A=2147483647,h=6e4,j=h/3,Z=1e3,ee=5,te=20,x=10,N=6048e5,ne=(o,_)=>{const E=_?.initialDelayMs??p.initialDelayMs,D=_?.backoffMultiplier??p.backoffMultiplier,L=_?.maxDelayMs??p.maxDelayMs;return Math.min(L,E*D**Math.max(0,o-1))},ae=(o,_={})=>{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=e=>o.prepare("PRAGMA table_info(_lunora_scheduler_jobs)").all().some(t=>t.name===e),D=e=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},L=e=>{for(let t=0;;t+=1)try{o.exec(`ALTER TABLE _lunora_scheduler_jobs ADD COLUMN ${e} INTEGER`);return}catch(n){if(E(e))return;if(!(n instanceof Error&&"code"in n&&n.code==="SQLITE_BUSY")||t>=ee)throw n;D(te*2**t)}};for(const e of["claimed_at","completed_at"])E(e)||L(e);o.exec("CREATE INDEX IF NOT EXISTS _lunora_scheduler_jobs_state_completed ON _lunora_scheduler_jobs (state, completed_at)"),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 k=o.prepare("INSERT INTO _lunora_scheduler_jobs (id, function_path, args, scheduled_for, retry) VALUES (?, ?, ?, ?, ?)"),R=o.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE id = ?"),y=o.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE state = ? ORDER BY scheduled_for"),F=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'canceled', completed_at = ? WHERE id = ? AND state = 'pending'"),B=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ?"),g=o.prepare("DELETE FROM _lunora_scheduler_jobs WHERE state IN ('succeeded', 'canceled') AND completed_at <= ?"),P=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'succeeded', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ?"),v=o.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND claimed_at = ? AND state = 'pending'"),H=o.prepare("UPDATE _lunora_scheduler_jobs SET attempts = ?, scheduled_for = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),J=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),W=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 *"),X=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'pending', attempts = 0, completed_at = NULL, scheduled_for = ? WHERE id = ? AND state = 'dead'"),Y=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`),G=o.prepare("SELECT * FROM _lunora_scheduler_crons"),s=()=>o.open,T=()=>o.inTransaction,O=e=>e===null?void 0:U(e);let a=!1;const S=async()=>{a||!s()||!T()||(await new Promise(e=>{setTimeout(e,x).unref()}),await S())},i=new Map,m=new Map,M=e=>({attempts:e.attempts,functionPath:e.function_path,id:e.id,scheduledFor:e.scheduled_for}),I=e=>{const t=i.get(e);t!==void 0&&(clearTimeout(t),i.delete(e))},l=(e,t)=>{I(e);const n=Math.max(0,t-Date.now());if(n>A){const c=setTimeout(()=>{l(e,t)},A);i.set(e,c);return}const r=setTimeout(()=>{K(e).catch(()=>{})},n);i.set(e,r)},$=e=>{const t=R.get(e);!a&&t?.state==="pending"&&l(e,t.claimed_at===null?t.scheduled_for:t.claimed_at+h)},q=(e,t)=>{if(T()){a||l(e,t+x);return}try{const n=W.get(t,e,t,t-h);return n===void 0&&$(e),n}catch{!a&&s()&&l(e,Date.now()+Z);return}},z=(e,t)=>{let n=t,r;const c=u=>{r=setTimeout(()=>{if(!s())return;if(T()){c(x);return}const d=Date.now();try{v.run(d,e,n).changes===1&&(n=d)}catch{}c(j)},u),r.unref()};return c(j),{release:()=>{clearTimeout(r)},stamp:()=>n}},K=async e=>{if(i.delete(e),!s())return;const t=Date.now(),n=q(e,t);if(n===void 0)return;const r=n.attempts+1,c=O(n.retry),u=z(e,t);try{if(await _.onDispatch?.(n.function_path,U(n.args),{attempts:r,id:e}),await S(),s()&&!T()){const d=Date.now();P.run(r,d,e,u.stamp()),g.run(d-N)}}catch{if(await S(),a||!s())return;const d=c?.maxAttempts??p.maxAttempts;if(r>=d){J.run(r,Date.now(),e,u.stamp());return}const C=Date.now()+ne(r,c);H.run(r,C,e,u.stamp()).changes===1&&l(e,C)}finally{u.release()}},f=e=>{const t=m.get(e.key);t!==void 0&&clearTimeout(t);let n;try{n=b(e.expression).next().getTime()}catch{return}const r=Math.max(0,n-Date.now());if(r>A){m.set(e.key,setTimeout(()=>{f(e)},A));return}const c=setTimeout(()=>{m.delete(e.key),(async()=>{try{await _.onDispatch?.(e.function_path,U(e.args),{attempts:0,id:e.key})}catch{}!a&&s()&&f(e)})().catch(()=>{})},r);m.set(e.key,c)},V={cancel:async e=>{if(a)return!1;I(e);const t=Date.now(),n=F.run(t,e).changes>0;return g.run(t-N),n},cron:async(e,t,n)=>{if(a)throw new Error("platform closed: cannot register a cron");b(e);const r={args:w(n??{}),expression:e,function_path:t,key:`${e} ${t}`};Y.run(r.key,r.expression,r.function_path,r.args),f(r)},deadLetter:{list:async()=>a||!s()?[]:y.all("dead").map(e=>M(e)),requeue:async e=>{if(a||!s())return!1;const t=Date.now();return X.run(t,e).changes===0?!1:(l(e,t),!0)}},get:async e=>{const t=a||!s()?void 0:R.get(e);if(t===void 0||t.completed_at!==null&&t.state!=="dead"&&t.completed_at<=Date.now()-N)return null;const n={canceled:"canceled",dead:"failed",pending:"pending",succeeded:"succeeded"},r=t.state==="pending"&&t.claimed_at!==null&&t.claimed_at>=Date.now()-h,c={...M(t),state:r?"running":n[t.state]};return t.completed_at!==null&&(c.completedAt=t.completed_at),c},list:async()=>a||!s()?[]:y.all("pending").map(e=>M(e)),schedule:async(e,t,n)=>{if(a)throw new Error("platform closed: cannot schedule a job");const r=`node-job-${Q()}`;let c;return n?.at===void 0?c=Date.now()+(n?.delayMs??0):c=typeof n.at=="number"?n.at:n.at.getTime(),k.run(r,e,w(t),c,n?.retry===void 0?null:w(n.retry)),l(r,c),{id:r,scheduledFor:c}}};g.run(Date.now()-N);for(const e of y.all("pending"))l(e.id,e.scheduled_for);for(const e of G.all())f(e);return{dispose:()=>{for(const e of i.values())clearTimeout(e);for(const e of m.values())clearTimeout(e);i.clear(),m.clear(),a=!0},scheduler:V,simulateDeadLetter:async e=>{const t=R.get(e);if(t?.state!=="pending")return!1;I(e);const n=O(t.retry);return B.run((n?.maxAttempts??p.maxAttempts)+1,Date.now(),e),!0}}};export{ae as createNodeSchedulerHost};
|