@lunora/platform-node 1.0.0-alpha.204 → 1.0.0-alpha.205
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/createNodeGlobalStore-CD4DiqeS.mjs +1 -0
- package/dist/packem_shared/{createNodePlatform-CZKUR7EP.mjs → createNodePlatform-CuZZbfWJ.mjs} +1 -1
- package/dist/packem_shared/createNodeSchedulerHost-CiSdzxod.mjs +15 -0
- package/package.json +7 -7
- package/dist/packem_shared/createNodeGlobalStore-DhHyIT8I.mjs +0 -1
- package/dist/packem_shared/createNodeSchedulerHost-Di5cA-fR.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-CiSdzxod.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
|
@@ -56,6 +56,13 @@ type NodeGlobalContextDatabaseOptions = Omit<SqlCtxDbOptions, "dialect" | "exec"
|
|
|
56
56
|
* move a document's mapping while the other's entry was mid-write, leaving an
|
|
57
57
|
* entry no later write or purge could reach. The `sqlite` dialect's contract
|
|
58
58
|
* requires an ordered, atomic `batch` for exactly that reason.
|
|
59
|
+
*
|
|
60
|
+
* `transaction` holds `BEGIN IMMEDIATE` … `COMMIT` open across the awaits of
|
|
61
|
+
* an async `work`, which `better-sqlite3`'s own synchronous `transaction()`
|
|
62
|
+
* cannot. The connection is shared, so while one is open every other statement
|
|
63
|
+
* waits for it to settle: run in between, another writer's statement would land
|
|
64
|
+
* inside it and be rolled back with it. The wait and the statement (or the
|
|
65
|
+
* `BEGIN`) run with no `await` between them, so nothing slips in after the check.
|
|
59
66
|
*/
|
|
60
67
|
declare const createNodeSqlExec: (database: Database.Database) => SqlCtxExec;
|
|
61
68
|
/** Options for {@link createNodeGlobalStore}. */
|
|
@@ -207,7 +214,7 @@ interface NodeSchedulerHostOptions {
|
|
|
207
214
|
* A handler that **throws** marks the delivery failed, which is what drives
|
|
208
215
|
* the retry/dead-letter machinery: the job's `attempts` increments and it is
|
|
209
216
|
* either re-armed with backoff or parked. A handler that resolves marks the
|
|
210
|
-
* job
|
|
217
|
+
* job `succeeded`.
|
|
211
218
|
*
|
|
212
219
|
* Omitting it makes every delivery trivially succeed, which means a caller
|
|
213
220
|
* who forgets to pass one gets a scheduler that quietly drops work — the
|
package/dist/index.d.ts
CHANGED
|
@@ -56,6 +56,13 @@ type NodeGlobalContextDatabaseOptions = Omit<SqlCtxDbOptions, "dialect" | "exec"
|
|
|
56
56
|
* move a document's mapping while the other's entry was mid-write, leaving an
|
|
57
57
|
* entry no later write or purge could reach. The `sqlite` dialect's contract
|
|
58
58
|
* requires an ordered, atomic `batch` for exactly that reason.
|
|
59
|
+
*
|
|
60
|
+
* `transaction` holds `BEGIN IMMEDIATE` … `COMMIT` open across the awaits of
|
|
61
|
+
* an async `work`, which `better-sqlite3`'s own synchronous `transaction()`
|
|
62
|
+
* cannot. The connection is shared, so while one is open every other statement
|
|
63
|
+
* waits for it to settle: run in between, another writer's statement would land
|
|
64
|
+
* inside it and be rolled back with it. The wait and the statement (or the
|
|
65
|
+
* `BEGIN`) run with no `await` between them, so nothing slips in after the check.
|
|
59
66
|
*/
|
|
60
67
|
declare const createNodeSqlExec: (database: Database.Database) => SqlCtxExec;
|
|
61
68
|
/** Options for {@link createNodeGlobalStore}. */
|
|
@@ -207,7 +214,7 @@ interface NodeSchedulerHostOptions {
|
|
|
207
214
|
* A handler that **throws** marks the delivery failed, which is what drives
|
|
208
215
|
* the retry/dead-letter machinery: the job's `attempts` increments and it is
|
|
209
216
|
* either re-armed with backoff or parked. A handler that resolves marks the
|
|
210
|
-
* job
|
|
217
|
+
* job `succeeded`.
|
|
211
218
|
*
|
|
212
219
|
* Omitting it makes every delivery trivially succeed, which means a caller
|
|
213
220
|
* who forgets to pass one gets a scheduler that quietly drops work — the
|
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-C3-wCHPp.mjs";import{createNodeGlobalStore as d,createNodeSqlExec as c}from"./packem_shared/createNodeGlobalStore-
|
|
1
|
+
import{NODE_SCHEDULER_DISPATCH_PATH as r,createNodeDispatchRoute as t}from"./packem_shared/NODE_SCHEDULER_DISPATCH_PATH-C3-wCHPp.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-CuZZbfWJ.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-CiSdzxod.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{sqliteDialect as p}from"@lunora/d1";import{createSqlCtxDb as w,runSqlGlobalTableMigrations as u,runSqlAggregateMigrations as f,runSqlRankMigrations as h,runSqlSearchMigrations as g,backfillSqlSearchIndexes as m,runSqlCdcMigration as d}from"@lunora/sql-store";import S from"better-sqlite3";import{p as l}from"./prepared-statement-3XBQZXtC.mjs";const a={...p,searchBackfillHint:"run the global store's migrate(), which backfills every search index to completion"},s=new WeakMap,y=o=>{const t=s.get(o)??{};s.set(o,t);const r={all:async(e,n)=>l(o,e).all(...n),batch:async e=>{o.transaction(()=>{for(const{params:n,sql:i}of e)l(o,i).run(...n)})()},run:async(e,n)=>({rowsAffected:l(o,e).run(...n).changes})};return{all:async(e,n)=>{for(;t.open!==void 0;)await t.open;return await r.all(e,n)},batch:async e=>{for(;t.open!==void 0;)await t.open;await r.batch?.(e)},run:async(e,n)=>{for(;t.open!==void 0;)await t.open;return await r.run(e,n)},transaction:async e=>{for(;t.open!==void 0;)await t.open;let n=()=>{};t.open=new Promise(c=>{n=c});let i=!1;try{o.exec("BEGIN IMMEDIATE"),i=!0;const c=await e(r);return o.exec("COMMIT"),c}catch(c){throw i&&o.inTransaction&&o.exec("ROLLBACK"),c}finally{t.open=void 0,n()}}}},k=(o={})=>{const t=new S(o.path??":memory:");t.pragma("journal_mode = WAL");const r=y(t);return{database:t,dispose:()=>{t.open&&t.close()},exec:r,migrate:async(e,n={})=>{await u(r,e,a),await f(r,e,a),await h(r,e,a),await g(r,e,a),await m(r,e,a),n.cdc===!0&&await d(r,a)},writer:e=>w({...e,dialect:a,exec:r,provisionScope:r})}};export{k as createNodeGlobalStore,y as createNodeSqlExec};
|
package/dist/packem_shared/{createNodePlatform-CZKUR7EP.mjs → createNodePlatform-CuZZbfWJ.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-C3-wCHPp.mjs";import{createNodeGlobalStore as y}from"./createNodeGlobalStore-
|
|
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};
|
|
@@ -0,0 +1,15 @@
|
|
|
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};
|
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.205",
|
|
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.225",
|
|
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.77",
|
|
52
|
+
"@lunora/queue": "1.0.0-alpha.137",
|
|
53
|
+
"@lunora/runtime": "1.0.0-alpha.264",
|
|
54
|
+
"@lunora/sql-store": "1.0.0-alpha.226",
|
|
55
|
+
"@lunora/workflow": "1.0.0-alpha.104",
|
|
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{sqliteDialect as l}from"@lunora/d1";import{createSqlCtxDb as c,runSqlGlobalTableMigrations as s,runSqlAggregateMigrations as p,runSqlRankMigrations as u,runSqlSearchMigrations as f,backfillSqlSearchIndexes as g,runSqlCdcMigration as m}from"@lunora/sql-store";import S from"better-sqlite3";import{p as n}from"./prepared-statement-3XBQZXtC.mjs";const a={...l,searchBackfillHint:"run the global store's migrate(), which backfills every search index to completion"},d=o=>({all:async(t,r)=>n(o,t).all(...r),batch:async t=>{o.transaction(()=>{for(const{params:r,sql:e}of t)n(o,e).run(...r)})()},run:async(t,r)=>({rowsAffected:n(o,t).run(...r).changes})}),x=(o={})=>{const t=new S(o.path??":memory:");t.pragma("journal_mode = WAL");const r=d(t);return{database:t,dispose:()=>{t.open&&t.close()},exec:r,migrate:async(e,i={})=>{await s(r,e,a),await p(r,e,a),await u(r,e,a),await f(r,e,a),await g(r,e,a),i.cdc===!0&&await m(r,a)},writer:e=>c({...e,dialect:a,exec:r,provisionScope:r})}};export{x as createNodeGlobalStore,d as createNodeSqlExec};
|
|
@@ -1,15 +0,0 @@
|
|
|
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};
|