@lunora/platform-node 1.0.0-alpha.219 → 1.0.0-alpha.220

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/README.md CHANGED
@@ -16,7 +16,7 @@ Portability was a claim, not a construction check — `PLATFORM_MATRICES` held e
16
16
 
17
17
  ## Scope
18
18
 
19
- This is a **spike**, not a production target: it is not wired into `lunora dev`, has no deploy driver, and several capabilities are honestly rated `emulated`/`unsupported` in its capability matrix entry (see `@lunora/platform`'s `NODE_CAPABILITIES`). Wiring it into the dev server is the payoff and a follow-up, not this change.
19
+ This is a **spike**, not a production target: it is not wired into `lunora dev`, deploys only as the container build context `lunora deploy --target node` writes, and several capabilities are honestly rated `emulated`/`unsupported` in its capability matrix entry (see `@lunora/platform`'s `NODE_CAPABILITIES`). Wiring it into the dev server is the payoff and a follow-up, not this change.
20
20
 
21
21
  ## On-demand profiling
22
22
 
@@ -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-DY6TOmXg.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};
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-BQPmMWJ7.mjs";import{createNodeShardHost as T}from"../packem_shared/createNodeShardHost-VU8MPeba.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-BHzxHBx1.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
@@ -5,6 +5,51 @@ import { ShardKvStore, QueueBindingLike, MessageBatchLike, SchedulerHost, ShardH
5
5
  import { WorkflowBindingLike } from '@lunora/workflow';
6
6
  import { WorkflowRuntime, WorkflowStore } from '@visulima/workflow';
7
7
  import { ShardNamespaceLike } from '@lunora/runtime';
8
+ /**
9
+ * The deadline every `drain()` in this package runs under. A shutdown that waits for work without a bound is held open by the
10
+ * one request or background task that never settles, until the supervisor's kill skips the database close the drain exists to
11
+ * reach. Each drain returns what was still pending when its deadline passed, so the caller can log it and close anyway.
12
+ */
13
+ /**
14
+ * Arms `onExpire` to run after `ms` and returns a function that disarms it. Injectable so a test drives the deadline by hand
15
+ * rather than waiting for a clock.
16
+ */
17
+ type DrainTimer = (ms: number, onExpire: () => void) => () => void;
18
+ /** Options every `drain()` accepts. */
19
+ interface DrainOptions {
20
+ /** Stop waiting after this many milliseconds. Defaults to {@link DEFAULT_DRAIN_TIMEOUT_MS}. */
21
+ timeoutMs?: number;
22
+ /** The clock the deadline runs on. Defaults to `setTimeout`, which keeps the process alive until the drain settles or expires. */
23
+ timer?: DrainTimer;
24
+ }
25
+ /** How a `drain()` ended. */
26
+ interface DrainResult {
27
+ /**
28
+ * Work that failed while the drain waited for it (an alarm retry that could not be written), one readable entry each. Each
29
+ * was also logged with its cause when it happened. A failure never stops the drain waiting for the rest.
30
+ */
31
+ failed: string[];
32
+ /** What was still running when the deadline passed, one human-readable entry each. Empty when the drain completed. */
33
+ pending: string[];
34
+ /** `true` when the deadline passed before the work settled. */
35
+ timedOut: boolean;
36
+ }
37
+ /** Long enough for an ordinary request or background write to finish; short enough that a stuck one cannot stall a shutdown. */
38
+ declare const DEFAULT_DRAIN_TIMEOUT_MS = 3e4;
39
+ /** Something that drains and can say, synchronously, whether it is idle: a registry, a platform. */
40
+ interface Drainable {
41
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
42
+ idle: () => boolean;
43
+ /** What is running right now, re-read when the deadline passes: a part that drained early can have gained work since. */
44
+ pending: () => string[];
45
+ }
46
+ /**
47
+ * Drain several parts under one deadline until a pass that began with every part idle also ends with every part idle. Work
48
+ * on one part can start work on another after that one finished draining (a request handed between registries), and a
49
+ * failure can be recorded after a part's own drain returned; the pass that begins idle collects it, and is held to the same
50
+ * deadline as any other.
51
+ */
52
+ declare const drainTogether: (parts: ReadonlyArray<Drainable>, options?: DrainOptions) => Promise<DrainResult>;
8
53
  /** One function call the route has authenticated and parsed. */
9
54
  interface NodeDispatchInvocation {
10
55
  args: Record<string, unknown>;
@@ -132,6 +177,14 @@ interface NodeHttpServerOptions {
132
177
  interface NodeHttpServer {
133
178
  /** Stop accepting connections and end every open one, streams included. */
134
179
  close: () => Promise<void>;
180
+ /**
181
+ * Stop accepting connections, then wait until every HTTP response that was in progress when the drain began has been written
182
+ * to the end or its client has gone, or until the deadline passes (`timeoutMs`, 30 s by default). A request that still
183
+ * arrives on an open connection is answered with keep-alive off and is not waited for. Event streams (`text/event-stream`)
184
+ * and WebSockets are endless by design and are not waited for; {@link NodeHttpServer.close} ends them. Resolves with what was
185
+ * still unfinished when the deadline passed, which it also logs.
186
+ */
187
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
135
188
  /** The `http://host:port` origin the server answers on. */
136
189
  origin: string;
137
190
  }
@@ -306,6 +359,14 @@ interface NodeSchedulerHost {
306
359
  * left uncleared.
307
360
  */
308
361
  dispose: () => void;
362
+ /**
363
+ * Deliveries running now, one-shot jobs and cron ticks alike, each from its timer firing until the scheduler has
364
+ * recorded the outcome, labelled by job. A drain waits for these before the database the scheduler writes to is closed.
365
+ */
366
+ pendingDispatches: () => {
367
+ labels: string[];
368
+ waits: Promise<unknown>[];
369
+ };
309
370
  scheduler: SchedulerHost;
310
371
  /**
311
372
  * Drive a pending job straight to its dead-letter state without waiting out
@@ -314,6 +375,12 @@ interface NodeSchedulerHost {
314
375
  * while how many failures it takes to get there is host policy.
315
376
  */
316
377
  simulateDeadLetter: (id: string) => Promise<boolean>;
378
+ /**
379
+ * Stop firing: clear every armed timer and arm none from then on, while rows are still written and kept. A shutdown calls
380
+ * it before draining, so no job or cron tick starts after the drain checked for running work; each then re-arms from its
381
+ * row after a restart. A delivery already running finishes. One-way; `dispose()` still ends the host.
382
+ */
383
+ suspend: () => void;
317
384
  }
318
385
  /** Build a durable, SQLite-backed scheduler over `database`. */
319
386
  declare const createNodeSchedulerHost: (database: Database.Database, options?: NodeSchedulerHostOptions) => NodeSchedulerHost;
@@ -413,10 +480,18 @@ interface NodeShardHostOptions {
413
480
  * connection are always retired together.
414
481
  */
415
482
  declare const createNodeShardHost: (options?: NodeShardHostOptions) => {
483
+ /** Settles once every alarm delivery running now (its handler and any retry write) has; `undefined` when none is. */
484
+ alarmsSettled: () => Promise<unknown> | undefined;
416
485
  database: Database.Database;
417
486
  dispose: () => void;
418
487
  drain: () => Promise<void>;
419
488
  host: ShardHost;
489
+ pendingAlarms: () => number;
490
+ pendingBackground: () => number;
491
+ /** Stop arming and claiming alarms, leaving the durable row for a restart. One-way: a closing registry calls it. */
492
+ suspendAlarms: () => void;
493
+ /** The failures recorded since the last call, which a drain reports in its result; each is also logged when it happens. */
494
+ takeFailures: () => string[];
420
495
  };
421
496
  /** The end a shard accepts. Its `send` and `close` are what the socket host calls through its handle. */
422
497
  interface NodeServerEnd {
@@ -502,10 +577,32 @@ interface NodeShardRegistryOptions {
502
577
  }
503
578
  /** An in-process shard registry: placement, hosting, and the fan-out key set. */
504
579
  interface NodeShardRegistry {
505
- /** Dispose every live shard. Safe to call more than once. */
506
- close: () => void;
580
+ /**
581
+ * Dispose every live shard, and refuse new work from then on: `shardFor`, a stub's `fetch` and `rearmPersistedAlarms`
582
+ * throw once this is called, so nothing reopens a shard. Safe to call more than once. A shard that a request or a socket
583
+ * close handler is still using is disposed once that work settles, unless `force` is set: then it is disposed now and
584
+ * named in a log line. A shard whose dispose fails stays live; a failure after close() returned is logged and reported by
585
+ * the next `drain()`, and the next `close()` retries it. A shutdown passes `force` after its drain has finished or
586
+ * reached its deadline, so work that never settles cannot keep a database open at exit.
587
+ */
588
+ close: (options?: {
589
+ force?: boolean;
590
+ }) => void;
507
591
  /** The `ShardDirectory` to hand the runtime. */
508
592
  directory: DirectShardDirectory;
593
+ /**
594
+ * Wait until every shard is idle: no `onFetch` or `onAlarm` call in flight (a cron or scheduled job's delivery is one), no
595
+ * promise handed to a shard's `waitUntil` pending, and no socket close handler still running, across every live shard,
596
+ * including one opened while draining. Work that starts more work is waited for too. Bounded by `timeoutMs` (30 s by
597
+ * default); resolves with what was still running when it passed, which it also logs. A graceful shutdown awaits this, then
598
+ * calls {@link NodeShardRegistry.close}; `close()` alone does not wait for any of it.
599
+ */
600
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
601
+ /**
602
+ * Whether every shard is idle right now (nothing a {@link NodeShardRegistry.drain} would wait for). Synchronous, so a caller
603
+ * that drained several things can confirm all of them are still idle at one instant before it closes anything.
604
+ */
605
+ idle: () => boolean;
509
606
  /**
510
607
  * Every shard key this registry knows about — the set `@lunora/runtime`'s
511
608
  * query coordinator fans out over.
@@ -518,8 +615,22 @@ interface NodeShardRegistry {
518
615
  * cost of visiting shards that had nothing to say.
519
616
  */
520
617
  listShardKeys: (table?: string) => ReadonlyArray<string>;
618
+ /** What is running right now, one label per shard with its counts, as a drain that timed out would report it. */
619
+ pending: () => string[];
620
+ /**
621
+ * Open every stored shard that has a persisted alarm, so the alarm is re-armed now rather than when something next sends
622
+ * that shard a request: after a restart an alarm would otherwise never fire on a shard nobody calls. Shards without one stay
623
+ * closed. Returns the keys it opened. A process serving the registry calls this once, before it takes traffic.
624
+ */
625
+ rearmPersistedAlarms: () => string[];
521
626
  /** Materialize (or reuse) the shard serving `key`. */
522
627
  shardFor: (key: string) => NodeShard;
628
+ /**
629
+ * Stop arming and claiming alarms on every shard, including one opened afterwards, leaving each durable row to re-arm after
630
+ * a restart. A shutdown calls it before draining, so no alarm starts after the drain checked for running work. One-way;
631
+ * `close()` does it too.
632
+ */
633
+ suspendAlarms: () => void;
523
634
  }
524
635
  /** Build the in-process shard registry. */
525
636
  declare const createNodeShardRegistry: (options?: NodeShardRegistryOptions) => NodeShardRegistry;
@@ -603,8 +714,14 @@ interface NodePlatform<Queues extends Record<string, {
603
714
  * any runtime socket map or durable row. A no-op instead of a throw would
604
715
  * be indistinguishable from a working call — exactly the silent-vanishing
605
716
  * this lifecycle exists to end.
717
+ *
718
+ * `force` is for a shutdown whose drain has finished or reached its deadline:
719
+ * a shard whose socket close handler is still running is disposed now (and
720
+ * logged) instead of once the handler settles. See `NodeShardRegistry.close`.
606
721
  */
607
- close: () => void;
722
+ close: (options?: {
723
+ force?: boolean;
724
+ }) => void;
608
725
  /** In-process shard directory (see `createNodeShardRegistry` for what it can and cannot do). */
609
726
  directory: ShardDirectory;
610
727
  /**
@@ -618,14 +735,24 @@ interface NodePlatform<Queues extends Record<string, {
618
735
  */
619
736
  dispatch: (request: Request) => Promise<Response>;
620
737
  /**
621
- * Wait for every promise handed to `shard.waitUntil` to settle.
738
+ * Wait for every promise handed to `shard.waitUntil` to settle, and for the
739
+ * registry's shards to go idle (`NodeShardRegistry.drain`): in-flight
740
+ * `onFetch` and `onAlarm` calls, including cron and scheduled-job
741
+ * deliveries, and each shard's own `waitUntil` work.
622
742
  *
623
743
  * Separate from `close()` because the two answer different questions:
624
744
  * `close()` releases handles and stays synchronous (it backs
625
745
  * `Symbol.dispose`), while draining is inherently awaitable. A graceful
626
- * shutdown is `await platform.drain()` then `platform.close()`.
746
+ * shutdown is `await platform.drain()` then `platform.close()`. Bounded by
747
+ * `timeoutMs` (30 s by default); resolves with what was still running when
748
+ * it passed.
749
+ *
750
+ * Draining is the start of shutdown: it first stops the scheduler's job and
751
+ * cron timers and every alarm timer, so nothing new starts once the drain
752
+ * has found the platform idle. Their rows are kept and re-armed after a
753
+ * restart.
627
754
  */
628
- drain: () => Promise<void>;
755
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
629
756
  /**
630
757
  * The `.global()` backend, or `undefined` when the caller named no database
631
758
  * file for it. There is no default path, because a global store silently
@@ -644,10 +771,17 @@ interface NodePlatform<Queues extends Record<string, {
644
771
  * round-trips a row through exactly that object.
645
772
  */
646
773
  globalTables?: NodeGlobalStore;
774
+ /**
775
+ * Whether nothing a {@link NodePlatform.drain} would wait for is running right now. Synchronous, so a caller draining
776
+ * several platforms or registries together can confirm they are all idle at one instant.
777
+ */
778
+ idle: () => boolean;
647
779
  /** Durable key-value storage backed by the same `better-sqlite3` database as `shard`. */
648
780
  kv: ShardKvStore;
649
781
  /** The local-filesystem bucket, or `undefined` when the caller named no bucket directory. */
650
782
  objectStorage?: R2BucketLike;
783
+ /** What is running right now (host work, scheduler deliveries, each shard's work), as a timed-out drain would report it. */
784
+ pending: () => string[];
651
785
  /**
652
786
  * The declared queues, or `undefined` when the caller declared none.
653
787
  *
@@ -656,6 +790,8 @@ interface NodePlatform<Queues extends Record<string, {
656
790
  * works when no queue exists to send to.
657
791
  */
658
792
  queues?: NodeQueueHost<Queues>;
793
+ /** Open every stored shard with a persisted alarm, so it is re-armed before traffic arrives. See `NodeShardRegistry.rearmPersistedAlarms`. */
794
+ rearmPersistedAlarms: () => string[];
659
795
  /** Delayed jobs and crons, persisted to the same database and re-armed on construction. */
660
796
  scheduler: SchedulerHost;
661
797
  /** Single-writer execution, local SQL, transactions, durable alarms. */
@@ -870,7 +1006,7 @@ declare const bindShardSockets: (shard: ShardSocketHooks, inbound: Pick<NodeShar
870
1006
  * Pass the result as `createNodeWorkflowHost({ store })`.
871
1007
  */
872
1008
  declare const createNodeWorkflowStore: (database: Database.Database) => WorkflowStore;
873
- export { NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron,
1009
+ export { DEFAULT_DRAIN_TIMEOUT_MS,
874
1010
  /**
875
1011
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
876
1012
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -911,6 +1047,10 @@ export { NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron,
911
1047
  * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
912
1048
  * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
913
1049
  *
1050
+ * `lunora deploy --target node` bundles an app into a container build context
1051
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1052
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1053
+ *
914
1054
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
915
1055
  * for `provision` — which reports, once, which declared features this target
916
1056
  * cannot serve, and writes nothing: there is no hosted control plane to deploy
@@ -918,7 +1058,7 @@ export { NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron,
918
1058
  * server, which is why both statements above hold at once. See
919
1059
  * `plans/234-node-host-findings.md`.
920
1060
  */
921
- type NodeDispatchInvocation,
1061
+ type DrainOptions,
922
1062
  /**
923
1063
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
924
1064
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -959,6 +1099,114 @@ type NodeDispatchInvocation,
959
1099
  * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
960
1100
  * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
961
1101
  *
1102
+ * `lunora deploy --target node` bundles an app into a container build context
1103
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1104
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1105
+ *
1106
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1107
+ * for `provision` — which reports, once, which declared features this target
1108
+ * cannot serve, and writes nothing: there is no hosted control plane to deploy
1109
+ * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1110
+ * server, which is why both statements above hold at once. See
1111
+ * `plans/234-node-host-findings.md`.
1112
+ */
1113
+ type DrainResult,
1114
+ /**
1115
+ * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
1116
+ * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
1117
+ * `SchedulerHost`) over `better-sqlite3` and an in-process socket/directory/
1118
+ * scheduler registry.
1119
+ *
1120
+ * Promoted from `@lunora/platform`'s `node:sqlite` reference host
1121
+ * (`src/conformance/reference-host.ts`) under plan 234, then hardened until the
1122
+ * durability half of each contract actually holds: alarms and scheduler jobs
1123
+ * are persisted **and re-armed on construction**, socket attachments and tags
1124
+ * live in SQLite rather than a `Map`, and `.global()` tables run the real
1125
+ * `@lunora/sql-store` core (`./node-global-store`). Each of those is pinned by
1126
+ * a restart test — a second host over the same database file — not only by the
1127
+ * TCK's simulated recycle.
1128
+ *
1129
+ * Three suites run against this package: `@lunora/platform/conformance`'s host
1130
+ * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
1131
+ * lifecycle/global-store tests.
1132
+ *
1133
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1134
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1135
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1136
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1137
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1138
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1139
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1140
+ * is the one combination that fails at runtime with no diagnostic before it.
1141
+ *
1142
+ * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1143
+ * nothing here owns a timer, so queue delivery is driven by an explicit
1144
+ * `poll()`. What exists is the listener a dev server would sit on:
1145
+ * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1146
+ * streaming the response body, and `createNodeShardNamespace` presents the
1147
+ * registry as the `shardDO` namespace that worker routes to. Also absent are
1148
+ * the Cloudflare product bindings with no local
1149
+ * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1150
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
1151
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
1152
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
1153
+ *
1154
+ * `lunora deploy --target node` bundles an app into a container build context
1155
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1156
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1157
+ *
1158
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1159
+ * for `provision` — which reports, once, which declared features this target
1160
+ * cannot serve, and writes nothing: there is no hosted control plane to deploy
1161
+ * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1162
+ * server, which is why both statements above hold at once. See
1163
+ * `plans/234-node-host-findings.md`.
1164
+ */
1165
+ type DrainTimer,
1166
+ /**
1167
+ * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
1168
+ * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
1169
+ * `SchedulerHost`) over `better-sqlite3` and an in-process socket/directory/
1170
+ * scheduler registry.
1171
+ *
1172
+ * Promoted from `@lunora/platform`'s `node:sqlite` reference host
1173
+ * (`src/conformance/reference-host.ts`) under plan 234, then hardened until the
1174
+ * durability half of each contract actually holds: alarms and scheduler jobs
1175
+ * are persisted **and re-armed on construction**, socket attachments and tags
1176
+ * live in SQLite rather than a `Map`, and `.global()` tables run the real
1177
+ * `@lunora/sql-store` core (`./node-global-store`). Each of those is pinned by
1178
+ * a restart test — a second host over the same database file — not only by the
1179
+ * TCK's simulated recycle.
1180
+ *
1181
+ * Three suites run against this package: `@lunora/platform/conformance`'s host
1182
+ * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
1183
+ * lifecycle/global-store tests.
1184
+ *
1185
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1186
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1187
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1188
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1189
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1190
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1191
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1192
+ * is the one combination that fails at runtime with no diagnostic before it.
1193
+ *
1194
+ * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1195
+ * nothing here owns a timer, so queue delivery is driven by an explicit
1196
+ * `poll()`. What exists is the listener a dev server would sit on:
1197
+ * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1198
+ * streaming the response body, and `createNodeShardNamespace` presents the
1199
+ * registry as the `shardDO` namespace that worker routes to. Also absent are
1200
+ * the Cloudflare product bindings with no local
1201
+ * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1202
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
1203
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
1204
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
1205
+ *
1206
+ * `lunora deploy --target node` bundles an app into a container build context
1207
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1208
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1209
+ *
962
1210
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
963
1211
  * for `provision` — which reports, once, which declared features this target
964
1212
  * cannot serve, and writes nothing: there is no hosted control plane to deploy
@@ -966,4 +1214,4 @@ type NodeDispatchInvocation,
966
1214
  * server, which is why both statements above hold at once. See
967
1215
  * `plans/234-node-host-findings.md`.
968
1216
  */
969
- type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore };
1217
+ type Drainable, NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore, drainTogether };
package/dist/index.d.ts CHANGED
@@ -5,6 +5,51 @@ import { ShardKvStore, QueueBindingLike, MessageBatchLike, SchedulerHost, ShardH
5
5
  import { WorkflowBindingLike } from '@lunora/workflow';
6
6
  import { WorkflowRuntime, WorkflowStore } from '@visulima/workflow';
7
7
  import { ShardNamespaceLike } from '@lunora/runtime';
8
+ /**
9
+ * The deadline every `drain()` in this package runs under. A shutdown that waits for work without a bound is held open by the
10
+ * one request or background task that never settles, until the supervisor's kill skips the database close the drain exists to
11
+ * reach. Each drain returns what was still pending when its deadline passed, so the caller can log it and close anyway.
12
+ */
13
+ /**
14
+ * Arms `onExpire` to run after `ms` and returns a function that disarms it. Injectable so a test drives the deadline by hand
15
+ * rather than waiting for a clock.
16
+ */
17
+ type DrainTimer = (ms: number, onExpire: () => void) => () => void;
18
+ /** Options every `drain()` accepts. */
19
+ interface DrainOptions {
20
+ /** Stop waiting after this many milliseconds. Defaults to {@link DEFAULT_DRAIN_TIMEOUT_MS}. */
21
+ timeoutMs?: number;
22
+ /** The clock the deadline runs on. Defaults to `setTimeout`, which keeps the process alive until the drain settles or expires. */
23
+ timer?: DrainTimer;
24
+ }
25
+ /** How a `drain()` ended. */
26
+ interface DrainResult {
27
+ /**
28
+ * Work that failed while the drain waited for it (an alarm retry that could not be written), one readable entry each. Each
29
+ * was also logged with its cause when it happened. A failure never stops the drain waiting for the rest.
30
+ */
31
+ failed: string[];
32
+ /** What was still running when the deadline passed, one human-readable entry each. Empty when the drain completed. */
33
+ pending: string[];
34
+ /** `true` when the deadline passed before the work settled. */
35
+ timedOut: boolean;
36
+ }
37
+ /** Long enough for an ordinary request or background write to finish; short enough that a stuck one cannot stall a shutdown. */
38
+ declare const DEFAULT_DRAIN_TIMEOUT_MS = 3e4;
39
+ /** Something that drains and can say, synchronously, whether it is idle: a registry, a platform. */
40
+ interface Drainable {
41
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
42
+ idle: () => boolean;
43
+ /** What is running right now, re-read when the deadline passes: a part that drained early can have gained work since. */
44
+ pending: () => string[];
45
+ }
46
+ /**
47
+ * Drain several parts under one deadline until a pass that began with every part idle also ends with every part idle. Work
48
+ * on one part can start work on another after that one finished draining (a request handed between registries), and a
49
+ * failure can be recorded after a part's own drain returned; the pass that begins idle collects it, and is held to the same
50
+ * deadline as any other.
51
+ */
52
+ declare const drainTogether: (parts: ReadonlyArray<Drainable>, options?: DrainOptions) => Promise<DrainResult>;
8
53
  /** One function call the route has authenticated and parsed. */
9
54
  interface NodeDispatchInvocation {
10
55
  args: Record<string, unknown>;
@@ -132,6 +177,14 @@ interface NodeHttpServerOptions {
132
177
  interface NodeHttpServer {
133
178
  /** Stop accepting connections and end every open one, streams included. */
134
179
  close: () => Promise<void>;
180
+ /**
181
+ * Stop accepting connections, then wait until every HTTP response that was in progress when the drain began has been written
182
+ * to the end or its client has gone, or until the deadline passes (`timeoutMs`, 30 s by default). A request that still
183
+ * arrives on an open connection is answered with keep-alive off and is not waited for. Event streams (`text/event-stream`)
184
+ * and WebSockets are endless by design and are not waited for; {@link NodeHttpServer.close} ends them. Resolves with what was
185
+ * still unfinished when the deadline passed, which it also logs.
186
+ */
187
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
135
188
  /** The `http://host:port` origin the server answers on. */
136
189
  origin: string;
137
190
  }
@@ -306,6 +359,14 @@ interface NodeSchedulerHost {
306
359
  * left uncleared.
307
360
  */
308
361
  dispose: () => void;
362
+ /**
363
+ * Deliveries running now, one-shot jobs and cron ticks alike, each from its timer firing until the scheduler has
364
+ * recorded the outcome, labelled by job. A drain waits for these before the database the scheduler writes to is closed.
365
+ */
366
+ pendingDispatches: () => {
367
+ labels: string[];
368
+ waits: Promise<unknown>[];
369
+ };
309
370
  scheduler: SchedulerHost;
310
371
  /**
311
372
  * Drive a pending job straight to its dead-letter state without waiting out
@@ -314,6 +375,12 @@ interface NodeSchedulerHost {
314
375
  * while how many failures it takes to get there is host policy.
315
376
  */
316
377
  simulateDeadLetter: (id: string) => Promise<boolean>;
378
+ /**
379
+ * Stop firing: clear every armed timer and arm none from then on, while rows are still written and kept. A shutdown calls
380
+ * it before draining, so no job or cron tick starts after the drain checked for running work; each then re-arms from its
381
+ * row after a restart. A delivery already running finishes. One-way; `dispose()` still ends the host.
382
+ */
383
+ suspend: () => void;
317
384
  }
318
385
  /** Build a durable, SQLite-backed scheduler over `database`. */
319
386
  declare const createNodeSchedulerHost: (database: Database.Database, options?: NodeSchedulerHostOptions) => NodeSchedulerHost;
@@ -413,10 +480,18 @@ interface NodeShardHostOptions {
413
480
  * connection are always retired together.
414
481
  */
415
482
  declare const createNodeShardHost: (options?: NodeShardHostOptions) => {
483
+ /** Settles once every alarm delivery running now (its handler and any retry write) has; `undefined` when none is. */
484
+ alarmsSettled: () => Promise<unknown> | undefined;
416
485
  database: Database.Database;
417
486
  dispose: () => void;
418
487
  drain: () => Promise<void>;
419
488
  host: ShardHost;
489
+ pendingAlarms: () => number;
490
+ pendingBackground: () => number;
491
+ /** Stop arming and claiming alarms, leaving the durable row for a restart. One-way: a closing registry calls it. */
492
+ suspendAlarms: () => void;
493
+ /** The failures recorded since the last call, which a drain reports in its result; each is also logged when it happens. */
494
+ takeFailures: () => string[];
420
495
  };
421
496
  /** The end a shard accepts. Its `send` and `close` are what the socket host calls through its handle. */
422
497
  interface NodeServerEnd {
@@ -502,10 +577,32 @@ interface NodeShardRegistryOptions {
502
577
  }
503
578
  /** An in-process shard registry: placement, hosting, and the fan-out key set. */
504
579
  interface NodeShardRegistry {
505
- /** Dispose every live shard. Safe to call more than once. */
506
- close: () => void;
580
+ /**
581
+ * Dispose every live shard, and refuse new work from then on: `shardFor`, a stub's `fetch` and `rearmPersistedAlarms`
582
+ * throw once this is called, so nothing reopens a shard. Safe to call more than once. A shard that a request or a socket
583
+ * close handler is still using is disposed once that work settles, unless `force` is set: then it is disposed now and
584
+ * named in a log line. A shard whose dispose fails stays live; a failure after close() returned is logged and reported by
585
+ * the next `drain()`, and the next `close()` retries it. A shutdown passes `force` after its drain has finished or
586
+ * reached its deadline, so work that never settles cannot keep a database open at exit.
587
+ */
588
+ close: (options?: {
589
+ force?: boolean;
590
+ }) => void;
507
591
  /** The `ShardDirectory` to hand the runtime. */
508
592
  directory: DirectShardDirectory;
593
+ /**
594
+ * Wait until every shard is idle: no `onFetch` or `onAlarm` call in flight (a cron or scheduled job's delivery is one), no
595
+ * promise handed to a shard's `waitUntil` pending, and no socket close handler still running, across every live shard,
596
+ * including one opened while draining. Work that starts more work is waited for too. Bounded by `timeoutMs` (30 s by
597
+ * default); resolves with what was still running when it passed, which it also logs. A graceful shutdown awaits this, then
598
+ * calls {@link NodeShardRegistry.close}; `close()` alone does not wait for any of it.
599
+ */
600
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
601
+ /**
602
+ * Whether every shard is idle right now (nothing a {@link NodeShardRegistry.drain} would wait for). Synchronous, so a caller
603
+ * that drained several things can confirm all of them are still idle at one instant before it closes anything.
604
+ */
605
+ idle: () => boolean;
509
606
  /**
510
607
  * Every shard key this registry knows about — the set `@lunora/runtime`'s
511
608
  * query coordinator fans out over.
@@ -518,8 +615,22 @@ interface NodeShardRegistry {
518
615
  * cost of visiting shards that had nothing to say.
519
616
  */
520
617
  listShardKeys: (table?: string) => ReadonlyArray<string>;
618
+ /** What is running right now, one label per shard with its counts, as a drain that timed out would report it. */
619
+ pending: () => string[];
620
+ /**
621
+ * Open every stored shard that has a persisted alarm, so the alarm is re-armed now rather than when something next sends
622
+ * that shard a request: after a restart an alarm would otherwise never fire on a shard nobody calls. Shards without one stay
623
+ * closed. Returns the keys it opened. A process serving the registry calls this once, before it takes traffic.
624
+ */
625
+ rearmPersistedAlarms: () => string[];
521
626
  /** Materialize (or reuse) the shard serving `key`. */
522
627
  shardFor: (key: string) => NodeShard;
628
+ /**
629
+ * Stop arming and claiming alarms on every shard, including one opened afterwards, leaving each durable row to re-arm after
630
+ * a restart. A shutdown calls it before draining, so no alarm starts after the drain checked for running work. One-way;
631
+ * `close()` does it too.
632
+ */
633
+ suspendAlarms: () => void;
523
634
  }
524
635
  /** Build the in-process shard registry. */
525
636
  declare const createNodeShardRegistry: (options?: NodeShardRegistryOptions) => NodeShardRegistry;
@@ -603,8 +714,14 @@ interface NodePlatform<Queues extends Record<string, {
603
714
  * any runtime socket map or durable row. A no-op instead of a throw would
604
715
  * be indistinguishable from a working call — exactly the silent-vanishing
605
716
  * this lifecycle exists to end.
717
+ *
718
+ * `force` is for a shutdown whose drain has finished or reached its deadline:
719
+ * a shard whose socket close handler is still running is disposed now (and
720
+ * logged) instead of once the handler settles. See `NodeShardRegistry.close`.
606
721
  */
607
- close: () => void;
722
+ close: (options?: {
723
+ force?: boolean;
724
+ }) => void;
608
725
  /** In-process shard directory (see `createNodeShardRegistry` for what it can and cannot do). */
609
726
  directory: ShardDirectory;
610
727
  /**
@@ -618,14 +735,24 @@ interface NodePlatform<Queues extends Record<string, {
618
735
  */
619
736
  dispatch: (request: Request) => Promise<Response>;
620
737
  /**
621
- * Wait for every promise handed to `shard.waitUntil` to settle.
738
+ * Wait for every promise handed to `shard.waitUntil` to settle, and for the
739
+ * registry's shards to go idle (`NodeShardRegistry.drain`): in-flight
740
+ * `onFetch` and `onAlarm` calls, including cron and scheduled-job
741
+ * deliveries, and each shard's own `waitUntil` work.
622
742
  *
623
743
  * Separate from `close()` because the two answer different questions:
624
744
  * `close()` releases handles and stays synchronous (it backs
625
745
  * `Symbol.dispose`), while draining is inherently awaitable. A graceful
626
- * shutdown is `await platform.drain()` then `platform.close()`.
746
+ * shutdown is `await platform.drain()` then `platform.close()`. Bounded by
747
+ * `timeoutMs` (30 s by default); resolves with what was still running when
748
+ * it passed.
749
+ *
750
+ * Draining is the start of shutdown: it first stops the scheduler's job and
751
+ * cron timers and every alarm timer, so nothing new starts once the drain
752
+ * has found the platform idle. Their rows are kept and re-armed after a
753
+ * restart.
627
754
  */
628
- drain: () => Promise<void>;
755
+ drain: (options?: DrainOptions) => Promise<DrainResult>;
629
756
  /**
630
757
  * The `.global()` backend, or `undefined` when the caller named no database
631
758
  * file for it. There is no default path, because a global store silently
@@ -644,10 +771,17 @@ interface NodePlatform<Queues extends Record<string, {
644
771
  * round-trips a row through exactly that object.
645
772
  */
646
773
  globalTables?: NodeGlobalStore;
774
+ /**
775
+ * Whether nothing a {@link NodePlatform.drain} would wait for is running right now. Synchronous, so a caller draining
776
+ * several platforms or registries together can confirm they are all idle at one instant.
777
+ */
778
+ idle: () => boolean;
647
779
  /** Durable key-value storage backed by the same `better-sqlite3` database as `shard`. */
648
780
  kv: ShardKvStore;
649
781
  /** The local-filesystem bucket, or `undefined` when the caller named no bucket directory. */
650
782
  objectStorage?: R2BucketLike;
783
+ /** What is running right now (host work, scheduler deliveries, each shard's work), as a timed-out drain would report it. */
784
+ pending: () => string[];
651
785
  /**
652
786
  * The declared queues, or `undefined` when the caller declared none.
653
787
  *
@@ -656,6 +790,8 @@ interface NodePlatform<Queues extends Record<string, {
656
790
  * works when no queue exists to send to.
657
791
  */
658
792
  queues?: NodeQueueHost<Queues>;
793
+ /** Open every stored shard with a persisted alarm, so it is re-armed before traffic arrives. See `NodeShardRegistry.rearmPersistedAlarms`. */
794
+ rearmPersistedAlarms: () => string[];
659
795
  /** Delayed jobs and crons, persisted to the same database and re-armed on construction. */
660
796
  scheduler: SchedulerHost;
661
797
  /** Single-writer execution, local SQL, transactions, durable alarms. */
@@ -870,7 +1006,7 @@ declare const bindShardSockets: (shard: ShardSocketHooks, inbound: Pick<NodeShar
870
1006
  * Pass the result as `createNodeWorkflowHost({ store })`.
871
1007
  */
872
1008
  declare const createNodeWorkflowStore: (database: Database.Database) => WorkflowStore;
873
- export { NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron,
1009
+ export { DEFAULT_DRAIN_TIMEOUT_MS,
874
1010
  /**
875
1011
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
876
1012
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -911,6 +1047,10 @@ export { NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron,
911
1047
  * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
912
1048
  * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
913
1049
  *
1050
+ * `lunora deploy --target node` bundles an app into a container build context
1051
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1052
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1053
+ *
914
1054
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
915
1055
  * for `provision` — which reports, once, which declared features this target
916
1056
  * cannot serve, and writes nothing: there is no hosted control plane to deploy
@@ -918,7 +1058,7 @@ export { NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron,
918
1058
  * server, which is why both statements above hold at once. See
919
1059
  * `plans/234-node-host-findings.md`.
920
1060
  */
921
- type NodeDispatchInvocation,
1061
+ type DrainOptions,
922
1062
  /**
923
1063
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
924
1064
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -959,6 +1099,114 @@ type NodeDispatchInvocation,
959
1099
  * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
960
1100
  * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
961
1101
  *
1102
+ * `lunora deploy --target node` bundles an app into a container build context
1103
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1104
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1105
+ *
1106
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1107
+ * for `provision` — which reports, once, which declared features this target
1108
+ * cannot serve, and writes nothing: there is no hosted control plane to deploy
1109
+ * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1110
+ * server, which is why both statements above hold at once. See
1111
+ * `plans/234-node-host-findings.md`.
1112
+ */
1113
+ type DrainResult,
1114
+ /**
1115
+ * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
1116
+ * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
1117
+ * `SchedulerHost`) over `better-sqlite3` and an in-process socket/directory/
1118
+ * scheduler registry.
1119
+ *
1120
+ * Promoted from `@lunora/platform`'s `node:sqlite` reference host
1121
+ * (`src/conformance/reference-host.ts`) under plan 234, then hardened until the
1122
+ * durability half of each contract actually holds: alarms and scheduler jobs
1123
+ * are persisted **and re-armed on construction**, socket attachments and tags
1124
+ * live in SQLite rather than a `Map`, and `.global()` tables run the real
1125
+ * `@lunora/sql-store` core (`./node-global-store`). Each of those is pinned by
1126
+ * a restart test — a second host over the same database file — not only by the
1127
+ * TCK's simulated recycle.
1128
+ *
1129
+ * Three suites run against this package: `@lunora/platform/conformance`'s host
1130
+ * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
1131
+ * lifecycle/global-store tests.
1132
+ *
1133
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1134
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1135
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1136
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1137
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1138
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1139
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1140
+ * is the one combination that fails at runtime with no diagnostic before it.
1141
+ *
1142
+ * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1143
+ * nothing here owns a timer, so queue delivery is driven by an explicit
1144
+ * `poll()`. What exists is the listener a dev server would sit on:
1145
+ * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1146
+ * streaming the response body, and `createNodeShardNamespace` presents the
1147
+ * registry as the `shardDO` namespace that worker routes to. Also absent are
1148
+ * the Cloudflare product bindings with no local
1149
+ * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1150
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
1151
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
1152
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
1153
+ *
1154
+ * `lunora deploy --target node` bundles an app into a container build context
1155
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1156
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1157
+ *
1158
+ * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
1159
+ * for `provision` — which reports, once, which declared features this target
1160
+ * cannot serve, and writes nothing: there is no hosted control plane to deploy
1161
+ * to and no `wrangler`-equivalent to shell out to. A deploy driver is not a dev
1162
+ * server, which is why both statements above hold at once. See
1163
+ * `plans/234-node-host-findings.md`.
1164
+ */
1165
+ type DrainTimer,
1166
+ /**
1167
+ * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
1168
+ * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
1169
+ * `SchedulerHost`) over `better-sqlite3` and an in-process socket/directory/
1170
+ * scheduler registry.
1171
+ *
1172
+ * Promoted from `@lunora/platform`'s `node:sqlite` reference host
1173
+ * (`src/conformance/reference-host.ts`) under plan 234, then hardened until the
1174
+ * durability half of each contract actually holds: alarms and scheduler jobs
1175
+ * are persisted **and re-armed on construction**, socket attachments and tags
1176
+ * live in SQLite rather than a `Map`, and `.global()` tables run the real
1177
+ * `@lunora/sql-store` core (`./node-global-store`). Each of those is pinned by
1178
+ * a restart test — a second host over the same database file — not only by the
1179
+ * TCK's simulated recycle.
1180
+ *
1181
+ * Three suites run against this package: `@lunora/platform/conformance`'s host
1182
+ * TCK, `@lunora/shard-engine/conformance`'s engine suite, and its own
1183
+ * lifecycle/global-store tests.
1184
+ *
1185
+ * **Emulated here**, and rated accordingly in `NODE_CAPABILITIES`
1186
+ * (`@lunora/platform`): queues over a durable table (`./node-queue-host`), R2
1187
+ * buckets over the local filesystem (`./node-r2-bucket`), workflows over the
1188
+ * `@visulima/workflow` engine (`./node-workflow-host`), and cross-shard fan-out
1189
+ * via `@lunora/runtime`'s query coordinator over the in-process shard registry.
1190
+ * `createNodePlatform` binds all three declarations (`queues`, `workflows`,
1191
+ * `objectStorageDirectory`) — a capability rated `emulated` with nothing bound
1192
+ * is the one combination that fails at runtime with no diagnostic before it.
1193
+ *
1194
+ * **Still missing:** a dev server. There is no `lunora dev --target node`, and
1195
+ * nothing here owns a timer, so queue delivery is driven by an explicit
1196
+ * `poll()`. What exists is the listener a dev server would sit on:
1197
+ * `createNodeHttpServer` serves an app worker's `fetch` over `node:http`,
1198
+ * streaming the response body, and `createNodeShardNamespace` presents the
1199
+ * registry as the `shardDO` namespace that worker routes to. Also absent are
1200
+ * the Cloudflare product bindings with no local
1201
+ * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
1202
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
1203
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
1204
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
1205
+ *
1206
+ * `lunora deploy --target node` bundles an app into a container build context
1207
+ * whose generated entry composes this package (crons, `ctx.secrets`,
1208
+ * Hyperdrive from `DATABASE_URL`) and serves it with `createNodeHttpServer`.
1209
+ *
962
1210
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
963
1211
  * for `provision` — which reports, once, which declared features this target
964
1212
  * cannot serve, and writes nothing: there is no hosted control plane to deploy
@@ -966,4 +1214,4 @@ type NodeDispatchInvocation,
966
1214
  * server, which is why both statements above hold at once. See
967
1215
  * `plans/234-node-host-findings.md`.
968
1216
  */
969
- type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore };
1217
+ type Drainable, NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore, drainTogether };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{N as o,c as t}from"./packem_shared/node-dispatch-route-ByuCR26s.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{createNodeHyperdrive as m}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as S}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodePlatform as H}from"./packem_shared/createNodePlatform-Cgr4hQvw.mjs";import{createNodeProfileHandler as h}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as k}from"./packem_shared/createNodeQueueHost-szMV0PBN.mjs";import{createNodeR2Bucket as n}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as E}from"./packem_shared/createNodeSchedulerHost-DY6TOmXg.mjs";import{createNodeSecretBindings as R}from"./packem_shared/createNodeSecretBindings-C7wh0fOm.mjs";import{createNodeShardHost as _}from"./packem_shared/createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardNamespace as g}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as y}from"./packem_shared/createNodeShardRegistry-BKl1QXiv.mjs";import{bindShardSockets as B,createNodeShardState as C}from"./packem_shared/bindShardSockets-9GvSocBW.mjs";import{createNodeSocketHost as W}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as G}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as K}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{o as NODE_SCHEDULER_DISPATCH_PATH,B as bindShardSockets,t as createNodeDispatchRoute,d as createNodeGlobalStore,p as createNodeHttpServer,m as createNodeHyperdrive,H as createNodePlatform,h as createNodeProfileHandler,k as createNodeQueueHost,n as createNodeR2Bucket,E as createNodeSchedulerHost,R as createNodeSecretBindings,_ as createNodeShardHost,S as createNodeShardKvStore,g as createNodeShardNamespace,y as createNodeShardRegistry,C as createNodeShardState,W as createNodeSocketHost,c as createNodeSqlExec,G as createNodeWorkflowHost,K as createNodeWorkflowStore};
1
+ import{DEFAULT_DRAIN_TIMEOUT_MS as o,drainTogether as t}from"./packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{N as d,c}from"./packem_shared/node-dispatch-route-ByuCR26s.mjs";import{createNodeGlobalStore as p,createNodeSqlExec as N}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeHttpServer as x}from"./packem_shared/createNodeHttpServer-cUx4J9Z9.mjs";import{createNodeHyperdrive as s}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as h}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodePlatform as i}from"./packem_shared/createNodePlatform-C5LvauTf.mjs";import{createNodeProfileHandler as E}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as _}from"./packem_shared/createNodeQueueHost-szMV0PBN.mjs";import{createNodeR2Bucket as n}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as R}from"./packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeSecretBindings as P}from"./packem_shared/createNodeSecretBindings-C7wh0fOm.mjs";import{createNodeShardHost as v}from"./packem_shared/createNodeShardHost-VU8MPeba.mjs";import{createNodeShardNamespace as U}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as w}from"./packem_shared/createNodeShardRegistry-BHzxHBx1.mjs";import{bindShardSockets as B,createNodeShardState as C}from"./packem_shared/bindShardSockets-9GvSocBW.mjs";import{createNodeSocketHost as M}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as W}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as F}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{o as DEFAULT_DRAIN_TIMEOUT_MS,d as NODE_SCHEDULER_DISPATCH_PATH,B as bindShardSockets,c as createNodeDispatchRoute,p as createNodeGlobalStore,x as createNodeHttpServer,s as createNodeHyperdrive,i as createNodePlatform,E as createNodeProfileHandler,_ as createNodeQueueHost,n as createNodeR2Bucket,R as createNodeSchedulerHost,P as createNodeSecretBindings,v as createNodeShardHost,h as createNodeShardKvStore,U as createNodeShardNamespace,w as createNodeShardRegistry,C as createNodeShardState,M as createNodeSocketHost,N as createNodeSqlExec,W as createNodeWorkflowHost,F as createNodeWorkflowStore,t as drainTogether};
@@ -0,0 +1 @@
1
+ const T=3e4,m=(e,t)=>{const n=setTimeout(t,e);return()=>{clearTimeout(n)}};const u=(e={})=>{const t=e.timeoutMs??3e4;if(!Number.isInteger(t)||t<0||t>2147483647)throw new RangeError(`@lunora/platform-node: a drain timeoutMs must be a whole number of milliseconds from 0 to ${String(2147483647)}, and it is ${String(t)}`);return t},f=(e={})=>{const t=u(e);let n=()=>{};const i=new Promise(s=>{n=s});return{cancel:(e.timer??m)(t,()=>{n()}),expired:i}},M=e=>(t,n)=>{let i=!0;return(async()=>{await e.expired,i&&n()})().catch(()=>{}),()=>{i=!1}},_=async(e,t)=>{const n=f(t),i=M(n),a=[];try{for(let s=!1;;){const l=await Promise.all(e.map(async r=>r.drain({timer:i})));if(a.push(...l.flatMap(r=>r.failed)),l.some(r=>r.timedOut)){const r=await Promise.all(e.filter((o,d)=>l[d]?.timedOut!==!0).map(async o=>o.drain({timer:i})));return a.push(...r.flatMap(o=>o.failed)),{failed:a,pending:e.flatMap(o=>o.pending()),timedOut:!0}}const c=e.every(r=>r.idle());if(s&&c)return{failed:a,pending:[],timedOut:!1};s=c}}finally{n.cancel()}},p=async(e,t)=>Promise.race([e.then(()=>!0,()=>!0),t.expired.then(()=>!1)]);export{T as DEFAULT_DRAIN_TIMEOUT_MS,u as drainTimeoutMs,_ as drainTogether,p as settlesBefore,f as startDrainDeadline,M as timerBoundTo};
@@ -0,0 +1,4 @@
1
+ import{once as H}from"node:events";import{createServer as U}from"node:http";import{WebSocketServer as A}from"ws";import{startDrainDeadline as C,settlesBefore as x}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{t as B}from"./node-socket-pair-0baNnoFw.mjs";const R=e=>e.includes(":")&&!e.startsWith("[")?`[${e}]`:e,D=e=>{const t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new RangeError(`origin must be an http or https URL, got scheme ${t.protocol}`);return t.origin},O=/^(?:127\.\d+\.\d+\.\d+|::1|localhost)$/,P=1048576,q=5e3,_=(e,t)=>{const c=e[Symbol.asyncIterator]();return new ReadableStream({cancel(){if(t.headersSent){e.destroy();return}if(e.complete){e.resume();return}let s=0,o=!1;const n=()=>{if(!e.complete){if(o=!0,t.writableFinished){e.destroy();return}e.removeAllListeners("readable"),e.pause()}},l=setTimeout(n,q),f=()=>{clearTimeout(l)};t.once("finish",()=>{o&&e.destroy()}),e.once("end",f),e.once("close",f),e.removeAllListeners("readable"),e.on("readable",()=>{let a=e.read();for(;a!==null;){if(s+=a.byteLength,s>P){n();return}a=e.read()}})},async pull(s){const o=await c.next();o.done?s.close():s.enqueue(o.value)}})},F=(e,t)=>{const c=new URL(e??"/",t),s=new URL(t);return s.pathname=c.pathname,s.search=c.search,s},E=(e,t,c,s)=>{const o=new Headers;for(const[f,a]of Object.entries(e.headers))if(Array.isArray(a))for(const b of a)o.append(f,b);else a!==void 0&&o.set(f,a);const n=e.method??"GET",l={headers:o,method:n,signal:c};return n!=="GET"&&n!=="HEAD"&&s!==void 0&&(l.body=_(e,s),l.duplex="half"),new Request(F(e.url,t),l)},I=e=>e.destroyed,L=e=>`${e.method??"GET"} ${(e.url??"/").split("?",1)[0]??"/"}`,Y=e=>(e.headers.get("content-type")??"").toLowerCase().startsWith("text/event-stream"),M=async(e,t,c)=>{if(t.on("error",()=>{t.destroy()}),I(t)){await e.body?.cancel().catch(()=>{});return}const s={};e.headers.forEach((f,a)=>{a!=="set-cookie"&&(s[a]=f)});const o=e.headers.getSetCookie();if(o.length>0&&(s["set-cookie"]=o),t.writeHead(e.status,s),Y(e)&&c(),e.body===null){t.end();return}const n=e.body.getReader();t.once("close",()=>{n.cancel().catch(()=>{})});let l=await n.read();for(;!l.done&&!t.destroyed;)t.write(l.value)||await new Promise(f=>{const a=()=>{t.off("drain",a),t.off("close",a),f()};t.on("drain",a),t.on("close",a)}),l=await n.read();t.end()},N=65536,$=async(e,t,c=0)=>{const s=await e.read();if(s.done)return t;const o=N-c;return s.value.byteLength>=o?(t.push(s.value.subarray(0,o)),await e.cancel().catch(()=>{}),t):(t.push(s.value),$(e,t,c+s.value.byteLength))},W=async(e,t)=>{const c=e.body?.getReader(),s=()=>{c?.cancel().catch(()=>{})};if(t.destroyed){s();return}t.once("close",s);const o=c===void 0?[]:await $(c,[]);if(t.off("close",s),!t.writable)return;const n=Buffer.concat(o),l=[`HTTP/1.1 ${String(e.status)} ${e.statusText||"Refused"}`,"connection: close",`content-length: ${String(n.byteLength)}`];e.headers.forEach((f,a)=>{a!=="content-length"&&a!=="connection"&&l.push(`${a}: ${f}`)}),t.end(Buffer.concat([Buffer.from(`${l.join(`\r
2
+ `)}\r
3
+ \r
4
+ `),n]))},J=async e=>{const t=e.host??"127.0.0.1",c=e.origin===void 0?void 0:D(e.origin);if(c===void 0&&!O.test(t))throw new Error(`createNodeHttpServer: host "${t}" is not a loopback address, so set origin to the public URL (e.g. https://app.example). Without it, browser requests fail the CSRF origin check and signed URLs point at the bound address.`);const s=new A({noServer:!0}),o=new Set,n=U(),l=new Map;let f=!1,a;const b=async()=>(a??=new Promise((i,r)=>{n.close(d=>{d===void 0?i():r(d)})}),a);let v=0;const S=()=>c??`http://${R(t)}:${String(v)}`;n.on("request",(i,r)=>{const d=S(),p=new AbortController;let h=()=>{};const u=new Promise(y=>{h=y});f?r.setHeader("connection","close"):(l.set(u,L(i)),u.then(()=>l.delete(u)).catch(()=>{})),r.once("finish",h),r.once("close",h),r.once("close",()=>{r.writableFinished||p.abort()});let w;try{w=E(i,d,p.signal,r)}catch{r.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),r.end("Bad Request");return}Promise.resolve().then(()=>e.fetch(w)).then(y=>M(y,r,h),y=>{console.error("[@lunora/platform-node] the fetch handler threw for %s; answered 500",L(i),y),r.headersSent||r.writeHead(500,{"content-type":"text/plain; charset=utf-8"}),r.end("Internal Server Error")}).catch(()=>{r.destroy()})});const T=async(i,r,d)=>{const p=new AbortController,h={closed:!1};o.add(r),r.on("error",()=>{r.destroy()}),r.once("close",()=>{h.closed=!0,o.delete(r),p.abort()});const u=await e.fetch(E(i,S(),p.signal)),w=B(u);if(w===void 0){await W(u,r);return}if(h.closed){w.abandon();return}r.once("close",()=>{w.abandon()}),s.handleUpgrade(i,r,d,y=>{w.attach(y)})};n.on("upgrade",(i,r,d)=>{T(i,r,d).catch(()=>{r.destroy()})}),await new Promise((i,r)=>{n.once("error",r),n.listen(e.port??0,t,()=>{n.off("error",r),i()})});const{port:m}=n.address();return v=m,{close:async()=>{const i=[...s.clients].map(async d=>H(d,"close"));for(const d of s.clients)d.terminate();for(const d of o)d.destroy();s.close();const r=b();n.closeAllConnections(),await r,await Promise.all(i)},drain:async i=>{const r=C(i);f=!0,b().catch(()=>{}),n.closeIdleConnections();const d=new Map(l),p=await x(Promise.all(d.keys()),r);if(r.cancel(),p)return{failed:[],pending:[],timedOut:!1};const h=[...d].filter(([u])=>l.has(u)).map(([,u])=>u);return console.error("[@lunora/platform-node] HTTP drain deadline passed with %d response(s) unfinished: %s",h.length,h.join(", ")),{failed:[],pending:h,timedOut:!0}},origin:`http://${R(t)}:${String(m)}`}};export{J as createNodeHttpServer};
@@ -0,0 +1 @@
1
+ import{LunoraError as d}from"@lunora/errors";import{NODE_CAPABILITIES as H}from"@lunora/platform";import{a as q,c as U,i as $,A as C}from"./node-dispatch-route-ByuCR26s.mjs";import{startDrainDeadline as V,settlesBefore as N,drainTimeoutMs as Q,drainTogether as x}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeGlobalStore as G}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as K}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeQueueHost as M}from"./createNodeQueueHost-szMV0PBN.mjs";import{createNodeR2Bucket as W}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as J}from"./createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as j}from"./createNodeShardHost-VU8MPeba.mjs";import{createNodeShardRegistry as Y}from"./createNodeShardRegistry-BHzxHBx1.mjs";import{createNodeSocketHost as z}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as X}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as Z}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const ee="__root__",re=e=>Object.entries(e).flatMap(([o,r])=>r.map(t=>{if(t.functionPath===void 0)throw new d("VALIDATION_ERROR",t.workflow===void 0?`@lunora/platform-node: cron job "${t.name}" has neither a function target nor a workflow target`:`@lunora/platform-node: cron job "${t.name}" starts workflow "${t.workflow}", which this host cannot do from a cron tick — schedule a function that calls ctx.workflows.get(name).create() instead`);return{args:t.args??{},expression:o,functionPath:t.functionPath,name:t.name}})),oe=(e,o)=>{const r=re(e);if(r.length>0&&!o)throw new d("VALIDATION_ERROR","@lunora/platform-node: `crons` declares jobs but nothing can deliver them — pass `onFetch` (to run them on the shard) or `onDispatch`");return r},te=(e,o)=>async(r,t,c)=>{if($(r,o,ee))throw new d("BAD_REQUEST",C);const i=await e({args:t,functionPath:r,id:c.id,identity:void 0,scheduledFor:c.scheduledFor,shardKey:o,traceparent:void 0});if(!i.ok)throw new d("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(i.status)}`)},Se=(e={})=>{const o=[],{database:r,dispose:t,drain:c,host:i,pendingAlarms:p,pendingBackground:g,suspendAlarms:R,takeFailures:S}=j(e);o.push(t);try{const l=K(r),s=Y(e);o.push(a=>{s.close(a)});const{directory:v}=s,k=q(v,e.onFetch!==void 0),y=U({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:k,schedulerSecret:e.dispatch?.schedulerSecret}),E=e.onFetch===void 0?void 0:te(k,e.shardKey??"__root__"),{declareCrons:b,dispose:T,pendingDispatches:h,scheduler:I,suspend:F}=J(r,{...e,onDispatch:e.onDispatch??E}),{socket:O}=z(r);o.push(T),e.crons!==void 0&&b(oe(e.crons,e.onDispatch!==void 0||e.onFetch!==void 0));const P=e.queues===void 0?void 0:M(r,{onBatch:e.onQueueBatch??(()=>{throw new d("VALIDATION_ERROR","@lunora/platform-node: createNodePlatform was given `queues` without `onQueueBatch`, so a delivered batch has nowhere to go — pass the worker's queue export from createWorker")}),queues:e.queues}),B=e.objectStorageDirectory===void 0?void 0:W({directory:e.objectStorageDirectory}),u=e.globalTablesPath===void 0?void 0:G({path:e.globalTablesPath});u!==void 0&&o.push(()=>{u.dispose()});const L=e.workflows===void 0?void 0:X({store:Z(r),workflows:e.workflows}),A=a=>{const n=[];for(const m of o.toReversed())try{m(a)}catch(w){n.push(w)}if(n.length>0)throw new AggregateError(n,`@lunora/platform-node: ${String(n.length)} resource(s) failed to close`)},_=()=>[...g()>0||p()>0?["waitUntil work on the platform host"]:[],...h().labels],f={drain:async a=>{const n=V(a);try{const[m,w]=await Promise.all([N(c(),n),N(Promise.allSettled(h().waits),n)]);if(m&&w)return{failed:S(),pending:[],timedOut:!1};const D=_();return console.error("[@lunora/platform-node] platform drain deadline passed with work still running: %s",D.join(", ")),{failed:S(),pending:D,timedOut:!0}}finally{n.cancel()}},idle:()=>g()===0&&p()===0&&h().waits.length===0,pending:_};return{capabilities:H,close:A,directory:v,dispatch:a=>y(a),idle:()=>f.idle()&&s.idle(),pending:()=>[...f.pending(),...s.pending()],drain:async a=>(Q(a),F(),R(),s.suspendAlarms(),x([f,s],a)),globalTables:u,kv:l,objectStorage:B,rearmPersistedAlarms:()=>s.rearmPersistedAlarms(),queues:P,scheduler:I,shard:i,sockets:O,workflows:L,[Symbol.dispose]:()=>{A()}}}catch(l){for(const s of o.toReversed())try{s()}catch{}throw l}};export{te as createJobDelivery,Se as createNodePlatform};
@@ -0,0 +1,15 @@
1
+ import{randomUUID as me}from"node:crypto";import{serialize as D,deserialize as F}from"node:v8";import{LunoraError as W}from"@lunora/errors";import _e from"@lunora/scheduler/validate";import{parse as fe}from"@visulima/cron-parser/cloudflare";const Ee={seconds:"optional",tz:"UTC"},T={backoffMultiplier:2,initialDelayMs:1e3,maxAttempts:5,maxDelayMs:6e4},L=2147483647,I=6e4,V=I/3,he=1e3,Te=5,ye=20,P=10,g=6048e5,q=(s,p)=>{if(!_e(s))throw new W("VALIDATION_ERROR",`@lunora/platform-node: ${p} has cron expression "${s}", which is invalid or never occurs`)},h="declared:",S=s=>s.key.startsWith(h)?`job "${s.key.slice(h.length)}" (${s.function_path})`:`"${s.expression}" (${s.function_path})`,Ae=(s,p)=>{const E=p?.initialDelayMs??T.initialDelayMs,y=p?.backoffMultiplier??T.backoffMultiplier,A=p?.maxDelayMs??T.maxDelayMs;return Math.min(A,E*y**Math.max(0,s-1))},Se=(s,p={})=>{const E=new Map,y=(e,t)=>{const r=t.then(()=>{},()=>{});E.set(r,e),r.finally(()=>E.delete(r)).catch(()=>{})};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
+ )`);const A=e=>s.prepare("PRAGMA table_info(_lunora_scheduler_jobs)").all().some(t=>t.name===e),z=e=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},K=e=>{for(let t=0;;t+=1)try{s.exec(`ALTER TABLE _lunora_scheduler_jobs ADD COLUMN ${e} INTEGER`);return}catch(r){if(A(e))return;if(!(r instanceof Error&&"code"in r&&r.code==="SQLITE_BUSY")||t>=Te)throw r;z(ye*2**t)}};for(const e of["claimed_at","completed_at"])A(e)||K(e);s.exec("CREATE INDEX IF NOT EXISTS _lunora_scheduler_jobs_state_completed ON _lunora_scheduler_jobs (state, completed_at)"),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 Q=s.prepare("INSERT INTO _lunora_scheduler_jobs (id, function_path, args, scheduled_for, retry) VALUES (?, ?, ?, ?, ?)"),k=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE id = ?"),w=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE state = ? ORDER BY scheduled_for"),Z=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'canceled', completed_at = ? WHERE id = ? AND state = 'pending'"),ee=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ?"),x=s.prepare("DELETE FROM _lunora_scheduler_jobs WHERE state IN ('succeeded', 'canceled') AND completed_at <= ?"),te=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'succeeded', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ?"),ne=s.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND claimed_at = ? AND state = 'pending'"),re=s.prepare("UPDATE _lunora_scheduler_jobs SET attempts = ?, scheduled_for = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),oe=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),se=s.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 *"),ae=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'pending', attempts = 0, completed_at = NULL, scheduled_for = ? WHERE id = ? AND state = 'dead'"),B=s.prepare(`INSERT INTO _lunora_scheduler_crons (key, expression, function_path, args) VALUES (?, ?, ?, ?)
15
+ ON CONFLICT (key) DO UPDATE SET expression = excluded.expression, function_path = excluded.function_path, args = excluded.args`),H=s.prepare("SELECT * FROM _lunora_scheduler_crons"),J=s.prepare("SELECT * FROM _lunora_scheduler_crons WHERE key = ?"),ce=s.prepare("DELETE FROM _lunora_scheduler_crons WHERE key = ?"),i=()=>s.open,N=()=>s.inTransaction,X=e=>e===null?void 0:F(e);let c=!1,M=!1;const O=async()=>{c||!i()||!N()||(await new Promise(e=>{setTimeout(e,P).unref()}),await O())},_=new Map,u=new Map,b=new Set;let U=new Set;const C=e=>({attempts:e.attempts,functionPath:e.function_path,id:e.id,scheduledFor:e.scheduled_for}),v=e=>{const t=_.get(e);t!==void 0&&(clearTimeout(t),_.delete(e))},m=(e,t)=>{if(v(e),M)return;const r=Math.max(0,t-Date.now());if(r>L){const n=setTimeout(()=>{m(e,t)},L);_.set(e,n);return}const o=setTimeout(()=>{const n={label:`scheduled job ${e}`};y(n,ue(e,a=>{n.label=a}).catch(()=>{}))},r);_.set(e,o)},le=e=>{const t=k.get(e);!c&&t?.state==="pending"&&m(e,t.claimed_at===null?t.scheduled_for:t.claimed_at+I)},ie=(e,t)=>{if(N()){c||m(e,t+P);return}try{const r=se.get(t,e,t,t-I);return r===void 0&&le(e),r}catch{!c&&i()&&m(e,Date.now()+he);return}},de=(e,t)=>{let r=t,o;const n=a=>{o=setTimeout(()=>{if(!i())return;if(N()){n(P);return}const l=Date.now();try{ne.run(l,e,r).changes===1&&(r=l)}catch{}n(V)},a),o.unref()};return n(V),{release:()=>{clearTimeout(o)},stamp:()=>r}},ue=async(e,t)=>{if(_.delete(e),!i())return;const r=Date.now(),o=ie(e,r);if(o===void 0)return;t?.(`scheduled job ${o.function_path} (${e})`);const n=o.attempts+1,a=X(o.retry),l=de(e,r);try{if(await p.onDispatch?.(o.function_path,F(o.args),{attempts:n,id:e,scheduledFor:o.scheduled_for}),await O(),i()&&!N()){const d=Date.now();te.run(n,d,e,l.stamp()),x.run(d-g)}}catch(d){if(await O(),console.error("[@lunora/platform-node] scheduled job %s (%s) failed on attempt %d",o.function_path,e,n,d),c||!i())return;const $=a?.maxAttempts??T.maxAttempts;if(n>=$){oe.run(n,Date.now(),e,l.stamp());return}const G=Date.now()+Ae(n,a);re.run(n,G,e,l.stamp()).changes===1&&m(e,G)}finally{l.release()}};let j,R;const f=e=>{if(b.has(e.key))return;const t=u.get(e.key);if(t!==void 0&&(clearTimeout(t),u.delete(e.key)),M)return;let r;try{r=fe(e.expression,Ee).next().getTime()}catch{return}const o=Math.max(0,r-Date.now());if(o>L)return u.set(e.key,setTimeout(()=>{f(e)},L)),r;const n=setTimeout(()=>{if(u.delete(e.key),c||!i())return;let a;try{a=J.get(e.key)}catch(d){R(e,`could not read its row before the tick due ${new Date(r).toISOString()}, so that tick was skipped`,d);return}if(a===void 0){j(e,r,void 0);return}if(a.expression!==e.expression){f(a);return}const l=a;b.add(e.key),y({label:`cron ${S(l)}`},(async()=>{let d;try{await p.onDispatch?.(l.function_path,F(l.args),{attempts:0,id:`${e.key}:${String(r)}`,scheduledFor:r})}catch($){d={error:$}}finally{b.delete(e.key)}j(l,r,d)})().catch(d=>{R(l,"failed to settle its tick",d)}))},o);return u.set(e.key,n),r};R=(e,t,r)=>{const o=c||!i()?void 0:f(e),n=o===void 0?"none scheduled, the scheduler is closed":new Date(o).toISOString();return console.error(`[@lunora/platform-node] cron ${S(e)} ${t}; re-armed from its last known definition, next run: ${n}`,r),o},j=(e,t,r)=>{let o;if(!c&&i()){let n,a=!1;try{n=J.get(e.key)}catch(l){a=!0,o=R(e,"could not read its row after its tick",l)}n!==void 0?o=f(n):!a&&U.has(e.key)&&(U.delete(e.key),console.warn(`[@lunora/platform-node] declared cron ${S(e)} was removed from the database by another process passing \`crons\`; it stops firing here`))}if(r!==void 0){const n=o===void 0?"none scheduled":new Date(o).toISOString();console.error(`[@lunora/platform-node] cron ${S(e)} tick due ${new Date(t).toISOString()} failed; next run: ${n}`,r.error)}};const pe={cancel:async e=>{if(c)return!1;v(e);const t=Date.now(),r=Z.run(t,e).changes>0;return x.run(t-g),r},cron:async(e,t,r)=>{if(c)throw new Error("platform closed: cannot register a cron");q(e,`cron for ${t}`);const o={args:D(r??{}),expression:e,function_path:t,key:`${e} ${t}`};B.run(o.key,o.expression,o.function_path,o.args),f(o)},deadLetter:{list:async()=>c||!i()?[]:w.all("dead").map(e=>C(e)),requeue:async e=>{if(c||!i())return!1;const t=Date.now();return ae.run(t,e).changes===0?!1:(m(e,t),!0)}},get:async e=>{const t=c||!i()?void 0:k.get(e);if(t===void 0||t.completed_at!==null&&t.state!=="dead"&&t.completed_at<=Date.now()-g)return null;const r={canceled:"canceled",dead:"failed",pending:"pending",succeeded:"succeeded"},o=t.state==="pending"&&t.claimed_at!==null&&t.claimed_at>=Date.now()-I,n={...C(t),state:o?"running":r[t.state]};return t.completed_at!==null&&(n.completedAt=t.completed_at),n},list:async()=>c||!i()?[]:w.all("pending").map(e=>C(e)),schedule:async(e,t,r)=>{if(c)throw new Error("platform closed: cannot schedule a job");if(r?.retry?.forever===!0)throw new W("INVALID_INPUT","retry.forever is not supported by the Node scheduler host; set a finite retry.maxAttempts");const o=`node-job-${me()}`;let n;return r?.at===void 0?n=Date.now()+(r?.delayMs??0):n=typeof r.at=="number"?r.at:r.at.getTime(),Q.run(o,e,D(t),n,r?.retry===void 0?null:D(r.retry)),m(o,n),{id:o,scheduledFor:n}}};x.run(Date.now()-g);for(const e of w.all("pending"))m(e.id,e.scheduled_for);for(const e of H.all())e.key.startsWith(h)||f(e);const Y=()=>{for(const e of _.values())clearTimeout(e);for(const e of u.values())clearTimeout(e);_.clear(),u.clear()};return{pendingDispatches:()=>({labels:[...E.values()].map(e=>e.label),waits:[...E.keys()]}),declareCrons:e=>{if(c)throw new Error("platform closed: cannot declare crons");const t=new Set;for(const n of e){if(t.has(n.name))throw new W("VALIDATION_ERROR",`@lunora/platform-node: two declared cron jobs are named "${n.name}"; cron job names must be unique`);t.add(n.name),q(n.expression,`cron job "${n.name}"`)}const r=e.map(n=>({args:D(n.args),expression:n.expression,function_path:n.functionPath,key:`${h}${n.name}`})),o=new Set(r.map(n=>n.key));s.transaction(()=>{for(const n of H.all())n.key.startsWith(h)&&!o.has(n.key)&&ce.run(n.key);for(const n of r)B.run(n.key,n.expression,n.function_path,n.args)}).immediate();for(const[n,a]of u)n.startsWith(h)&&!o.has(n)&&(clearTimeout(a),u.delete(n));U=o;for(const n of r)f(n)},dispose:()=>{Y(),c=!0},scheduler:pe,simulateDeadLetter:async e=>{const t=k.get(e);if(t?.state!=="pending")return!1;v(e);const r=X(t.retry);return ee.run((r?.maxAttempts??T.maxAttempts)+1,Date.now(),e),!0},suspend:()=>{M=!0,Y()}}};export{Se as createNodeSchedulerHost};
@@ -0,0 +1 @@
1
+ import{AsyncLocalStorage as H}from"node:async_hooks";import{LunoraError as X}from"@lunora/errors";import j from"better-sqlite3";import{p as J}from"./prepared-statement-3XBQZXtC.mjs";const G=2147483647,K=6,F=100,Z=4,N=10,b=r=>r===void 0?null:r,ee=(r,s)=>({get databaseSize(){const p=r.pragma("page_count",{simple:!0}),u=r.pragma("page_size",{simple:!0});return p*u},exec:(p,...u)=>{s("run SQL");const c=J(r,p),y=u.map(i=>b(i)),o=c.reader&&c.readonly;let n;const f=()=>(n===void 0&&(s("run SQL"),c.reader?n=c.all(...y):(c.run(...y),n=[])),n);o||f();const d=function*(){s("run SQL"),c.raw(!0);try{yield*c.iterate(...y)}finally{c.raw(!1)}};return{get columnNames(){return c.reader?c.columns().map(i=>i.name):void 0},[Symbol.iterator]:()=>f()[Symbol.iterator](),one:()=>{const i=f();if(i.length!==1)throw new Error(`expected exactly one row, got ${String(i.length)}`);return i[0]},...o?{raw:d}:{},toArray:()=>[...f()]}}}),re=(r,s,p,u,c=()=>{},y=()=>{})=>{let o,n,f=!1,d=0,i;r.exec("CREATE TABLE IF NOT EXISTS _lunora_alarm (id INTEGER PRIMARY KEY CHECK (id = 0), scheduled_for INTEGER NOT NULL)");const O=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0"),M=r.prepare("INSERT INTO _lunora_alarm (id, scheduled_for) VALUES (0, ?) ON CONFLICT (id) DO UPDATE SET scheduled_for = excluded.scheduled_for"),w=r.prepare("INSERT INTO _lunora_alarm (id, scheduled_for) VALUES (0, ?) ON CONFLICT (id) DO NOTHING"),R=r.prepare("SELECT scheduled_for FROM _lunora_alarm WHERE id = 0"),L=r.prepare("DELETE FROM _lunora_alarm WHERE id = 0 AND scheduled_for = ?"),S=e=>{e===void 0?O.run():M.run(e)},z=e=>w.run(e).changes>0,C=e=>L.run(e).changes>0;let g=!1,m;const E=new Set;let T,t=0;const l=()=>{n!==void 0&&(clearTimeout(n),n=void 0),g=!1},v=e=>{n=setTimeout(()=>{n=void 0,g=!1,e()},N),g=!0},I=()=>{const e=R.get();e!==void 0&&(o=e.scheduled_for,A(e.scheduled_for))},W=(e,a,_=t)=>{if(!r.open||o!==void 0||_!==t){e();return}if(r.inTransaction){E.add({retry:()=>{D(e,a,_)},settle:e}),T??=setTimeout(k,N);return}if(d+=1,d>K){d=0,e();return}const h=Date.now()+F*2**(d-1);if(z(h)){o=h,A(h),e();return}d=0,I(),e()},D=(e,a,_=t,h=0)=>{const B=d;try{W(e,a,_)}catch(q){if(d=B,r.open&&h+1<Z){E.add({retry:()=>{D(e,a,_,h+1)},settle:e}),T??=setTimeout(k,F*2**h);return}const U=new Date(a).toISOString();console.error("[@lunora/platform-node] the retry of the alarm due %s on shard %s could not be written after %d attempts, so that alarm is lost",U,u??"(unnamed)",h+1,q),y(`shard ${u??"(unnamed)"}: the retry of the alarm due ${U} could not be written`),e()}},k=()=>{if(T=void 0,r.open&&r.inTransaction){T=setTimeout(k,N);return}const e=[...E];E.clear();for(const a of e)a.retry()},x=(e,a=0)=>{if(f)return;const _=t;if(r.open&&r.inTransaction){v(()=>{x(e,a)});return}if(o=void 0,!!r.open){try{if(!C(e)){I();return}}catch{o=e,a<K&&(n=setTimeout(()=>{n=void 0,x(e,a+1)},F*2**a));return}c((async()=>{await p?.(),d=0})().catch(async h=>{console.error("[@lunora/platform-node] alarm handler on shard %s threw; retrying with backoff",u??"(unnamed)",h),await new Promise(B=>{D(B,e,_)})}))}},A=e=>{if(l(),f)return;const a=Math.max(0,e-Date.now());if(a>G){n=setTimeout(()=>{A(e)},G);return}n=setTimeout(()=>{n=void 0,x(e)},a)},Y={delete:()=>{if(!r.open)throw new Error("platform closed: cannot delete an alarm");if(s.assertOwnTurn("delete an alarm"),d=0,S(void 0),s.inside()){i={at:void 0};return}t+=1,o=void 0,l()},get:()=>(i===void 0?o:i.at)??null,set:e=>{if(!r.open)throw new Error("platform closed: cannot set an alarm");s.assertOwnTurn("set an alarm");const a=typeof e=="number"?e:e.getTime();if(d=0,S(a),s.inside()){i={at:a};return}t+=1,o=a,A(a)}},$=()=>{if(i===void 0)return;const{at:e}=i;if(i=void 0,t+=1,e===void 0){o=void 0,l();return}o=e,A(e)},P=()=>{if(m=void 0,!r.open)return;if(r.inTransaction){m=setTimeout(P,N);return}const e=R.get();e!==void 0&&(n===void 0||g||o!==e.scheduled_for)&&(o=e.scheduled_for,A(e.scheduled_for))},Q=()=>{i=void 0,m!==void 0&&clearTimeout(m),P()},V=()=>{l(),m!==void 0&&(clearTimeout(m),m=void 0),T!==void 0&&(clearTimeout(T),T=void 0);for(const e of E)console.error("[@lunora/platform-node] alarm retry on shard %s given up: the database closed while it waited for another transaction to end",u??"(unnamed)"),e.settle();E.clear()};return I(),{alarms:Y,commit:$,dispose:V,rollback:Q,suspend:()=>{f=!0,l(),m!==void 0&&(clearTimeout(m),m=void 0)}}},ie=(r={})=>{const s=new j(r.path??":memory:");s.pragma("journal_mode = WAL");const p=new H;let u=!1;const c=t=>{if(u&&p.getStore()!==!0)throw new X("SHARD_UNAVAILABLE",`shard busy: cannot ${t} while another task holds this shard's transaction`)},y=ee(s,c),o=new Set,n=[],{alarms:f,commit:d,dispose:i,suspend:O,rollback:M}=re(s,{assertOwnTurn:c,inside:()=>p.getStore()===!0},r.onAlarm,r.shardKey,t=>{o.add(t),t.then(()=>o.delete(t)).catch(l=>{o.delete(t),console.error("[@lunora/platform-node] an alarm delivery on shard %s failed outside its retry handling",r.shardKey??"(unnamed)",l),n.push(`shard ${r.shardKey??"(unnamed)"}: an alarm delivery failed outside its retry handling`)})},t=>{n.push(t)}),w=new Set,R=new H;let L=Promise.resolve();const S=async t=>{if(R.getStore()===!0)return await t();const l=L;let v=()=>{};L=new Promise(I=>{v=I}),await l;try{return await R.run(!0,t)}finally{v()}},z=t=>S(t),C=async t=>{s.exec("BEGIN"),u=!0;try{const l=await p.run(!0,t);return s.exec("COMMIT"),u=!1,d(),l}catch(l){u=!1;try{s.exec("ROLLBACK")}catch{}throw M(),l}},g=t=>S(async()=>C(t)),m={alarms:f,runSerialized:z,shardKey:r.shardKey,sql:y,transaction:g,waitUntil:t=>{const l=t.catch(v=>{console.error("[@lunora/platform-node] work handed to waitUntil on shard %s failed",r.shardKey??"(unnamed)",v)}).finally(()=>{w.delete(l)});w.add(l)}};return{alarmsSettled:()=>o.size===0?void 0:Promise.allSettled(o),database:s,dispose:()=>{i(),s.open&&s.close()},drain:async()=>{for(;w.size>0||o.size>0;)await Promise.allSettled([...w,...o])},host:m,pendingAlarms:()=>o.size,pendingBackground:()=>w.size,suspendAlarms:O,takeFailures:()=>n.splice(0)}};export{ie as createNodeShardHost};
@@ -0,0 +1 @@
1
+ import{mkdirSync as O,readdirSync as P}from"node:fs";import{join as A}from"node:path";import{LunoraError as U}from"@lunora/errors";import W from"better-sqlite3";import{startDrainDeadline as x,settlesBefore as z}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeShardKvStore as K}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeShardHost as T}from"./createNodeShardHost-VU8MPeba.mjs";import{createNodeSocketHost as V}from"./createNodeSocketHost-ByOmEGFe.mjs";const v=".sqlite3",F=n=>n.replaceAll(/[^\da-z._-]/gu,s=>[...Buffer.from(s,"utf8")].map(d=>`%${d.toString(16).padStart(2,"0").toUpperCase()}`).join("")),X=n=>decodeURIComponent(n),G=(n,s)=>{const d=s.slice(0,-v.length),l=A(n,s);let c;try{c=X(d)}catch{throw new U("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${l}" has a basename that is not valid percent-encoding, so the shard key it holds cannot be recovered. Rename or remove the file.`)}const f=`${F(c)}${v}`;if(f!==s)throw new U("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${l}" was written under an older shard-key encoding. It decodes to shard key "${c}", which this build stores as "${f}" — so the key would be listed for fan-out while every read opened a new, empty database. Rename it: mv "${l}" "${A(n,f)}"`);return c},J=(n,s)=>{let d;try{return d=new W(n,{fileMustExist:!0,readonly:!0}),d.prepare("SELECT 1 FROM _lunora_alarm LIMIT 1").get()!==void 0}catch(l){return console.error("[@lunora/platform-node] could not check shard %s for a persisted alarm, so it is opened to re-arm any",s,l),!0}finally{d?.close()}},y=(n,s,d)=>n===0?"":`${String(n)} ${n===1?s:d}`,Q=(n,s)=>{const d=[y(s.requests,"request in flight","requests in flight"),y(s.alarms,"alarm running","alarms running"),y(s.background,"waitUntil task","waitUntil tasks"),s.closing?"a socket close handler running":""].filter(l=>l!=="");return`shard ${n}: ${d.join(", ")}`},ae=(n={})=>{const s=new Map;let d="open",l=!1;const c=()=>{l=!0;for(const e of s.values())e.suspendAlarms()},f=()=>{if(d!=="open")throw new Error(`@lunora/platform-node: the shard registry is ${d}, so it opens no shard and takes no request`)},m=new Map,B=async(e,t)=>{const r=Promise.resolve().then(t),o=r.then(()=>{},()=>{});let a=m.get(e);return a===void 0&&(a=new Set,m.set(e,a)),a.add(o),o.finally(()=>{a.delete(o),a.size===0&&m.get(e)===a&&m.delete(e)}).catch(()=>{}),r},S=new Set,u=new Set,E=[];if(n.directory!==void 0){O(n.directory,{recursive:!0});for(const e of P(n.directory))e.endsWith(v)&&S.add(G(n.directory,e))}const b=e=>{f();const t=s.get(e);if(t!==void 0)return t.shard;const r=n.directory===void 0?void 0:A(n.directory,`${F(e)}${v}`);let o;const{alarmsSettled:a,database:i,dispose:h,drain:g,host:w,pendingAlarms:_,pendingBackground:j,suspendAlarms:L,takeFailures:C}=T({onAlarm:()=>n.onAlarm?.(o),path:r,shardKey:e}),k=V(i);return o={inbound:k,kv:K(i),shard:w,shardKey:e,sockets:k.socket},s.set(e,{alarmsSettled:a,dispose:h,drain:k.drain,drainHost:g,pendingAlarms:_,pendingBackground:j,shard:o,suspendAlarms:L,takeFailures:C}),S.add(e),l&&L(),o},H=e=>({fetch:async t=>{const r=b(e),{onFetch:o}=n;return o===void 0?new Response(e):B(e,()=>o(t,r))}}),I=()=>[...E.splice(0),...[...s.values()].flatMap(e=>e.takeFailures())],p=()=>{const e=new Map,t=a=>{let i=e.get(a);return i===void 0&&(i={alarms:0,background:0,closing:!1,requests:0},e.set(a,i)),i},r=[];for(const[a,i]of m)r.push(...i),t(a).requests+=i.size;for(const[a,i]of s){const h=i.drain(),g=i.pendingBackground(),w=i.pendingAlarms();h!==void 0&&(t(a).closing=!0,r.push(h)),g>0&&(t(a).background=g),w>0&&(t(a).alarms=w),(g>0||w>0)&&r.push(i.drainHost())}return{labels:[...e].map(([a,i])=>Q(a,i)),waits:r}},N=(e,t)=>{const r=t.drain(),o=t.alarmsSettled();return[...m.get(e)??[],...o===void 0?[]:[o],...r===void 0?[]:[r]]},R=()=>{d!=="open"&&s.size===0&&(d="closed")},q=(e,t)=>{try{t.dispose()}catch(r){return r??new Error(`shard ${e} failed to close`)}s.delete(e)},$=(e,t)=>{const r=N(e,t);if(r.length>0){Promise.allSettled(r).then(()=>{u.has(e)&&s.get(e)===t&&$(e,t)}).catch(()=>{});return}u.delete(e);const o=q(e,t);o!==void 0&&(console.error("[@lunora/platform-node] shard %s failed to close after the work using it settled",e,o),E.push(`shard ${e} failed to close after the work using it settled`)),R()},D=(e,t,r)=>{const o=q(e,t);return o===void 0?u.delete(e):r&&!u.has(e)&&(u.add(e),$(e,t)),o},M=(e,t)=>{e.length>0&&console.error("[@lunora/platform-node] closed %d shard(s) with a request, alarm handler or socket close handler still running: %s",e.length,e.join(", "));for(const{error:r,key:o}of t)console.error("[@lunora/platform-node] shard %s failed to close",o,r);if(t.length>0)throw new AggregateError(t.map(({error:r})=>r),`@lunora/platform-node: ${String(t.length)} shard(s) failed to close: ${t.map(({key:r})=>r).join(", ")}`)};return{close:e=>{d==="open"&&(d="closing");const t=[],r=[];c();for(const[o,a]of s){const i=N(o,a);if(i.length===0||e?.force===!0){i.length>0&&t.push(o);const h=D(o,a,i.length>0);h!==void 0&&r.push({error:h,key:o})}else u.has(o)||(u.add(o),$(o,a))}R(),M(t,r)},drain:async e=>{const t=x(e);try{for(let r=p();r.waits.length>0;r=p())if(!await z(Promise.allSettled(r.waits),t)){const o=p().labels;return console.error("[@lunora/platform-node] shard drain deadline passed with work still running: %s",o.join(", ")),{failed:I(),pending:o,timedOut:!0}}return{failed:I(),pending:[],timedOut:!1}}finally{t.cancel()}},directory:{get:e=>H(String(e)),getByName:e=>H(e),idForName:e=>e},idle:()=>p().waits.length===0,pending:()=>p().labels,rearmPersistedAlarms:()=>{f();const{directory:e}=n;if(e===void 0)return[];const t=[];for(const r of S)if(!s.has(r)&&J(A(e,`${F(r)}${v}`),r))try{b(r),t.push(r)}catch(o){console.error("[@lunora/platform-node] could not open shard %s to re-arm its persisted alarm",r,o)}return t},listShardKeys:()=>[...S],shardFor:b,suspendAlarms:c}};export{ae as createNodeShardRegistry};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/platform-node",
3
- "version": "1.0.0-alpha.219",
3
+ "version": "1.0.0-alpha.220",
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,12 +46,12 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/d1": "^1.0.0-alpha.233",
49
+ "@lunora/d1": "^1.0.0-alpha.237",
50
50
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
51
- "@lunora/platform": "1.0.0-alpha.80",
52
- "@lunora/queue": "1.0.0-alpha.143",
53
- "@lunora/runtime": "^1.0.0-alpha.287",
54
- "@lunora/scheduler": "^1.0.0-alpha.170",
51
+ "@lunora/platform": "^1.0.0-alpha.81",
52
+ "@lunora/queue": "^1.0.0-alpha.144",
53
+ "@lunora/runtime": "^1.0.0-alpha.292",
54
+ "@lunora/scheduler": "^1.0.0-alpha.171",
55
55
  "@lunora/sql-store": "^1.0.0-alpha.234",
56
56
  "@lunora/workflow": "^1.0.0-alpha.111",
57
57
  "@visulima/cron-parser": "2.0.0",
@@ -1,4 +0,0 @@
1
- import{once as R}from"node:events";import{createServer as m}from"node:http";import{WebSocketServer as E}from"ws";import{t as L}from"./node-socket-pair-0baNnoFw.mjs";const y=e=>e.includes(":")&&!e.startsWith("[")?`[${e}]`:e,$=e=>{const t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new RangeError(`origin must be an http or https URL, got scheme ${t.protocol}`);return t.origin},U=/^(?:127\.\d+\.\d+\.\d+|::1|localhost)$/,A=1048576,T=5e3,H=(e,t)=>{const o=e[Symbol.asyncIterator]();return new ReadableStream({cancel(){if(t.headersSent){e.destroy();return}if(e.complete){e.resume();return}let s=0,n=!1;const a=()=>{if(!e.complete){if(n=!0,t.writableFinished){e.destroy();return}e.removeAllListeners("readable"),e.pause()}},d=setTimeout(a,T),c=()=>{clearTimeout(d)};t.once("finish",()=>{n&&e.destroy()}),e.once("end",c),e.once("close",c),e.removeAllListeners("readable"),e.on("readable",()=>{let l=e.read();for(;l!==null;){if(s+=l.byteLength,s>A){a();return}l=e.read()}})},async pull(s){const n=await o.next();n.done?s.close():s.enqueue(n.value)}})},x=(e,t)=>{const o=new URL(e??"/",t),s=new URL(t);return s.pathname=o.pathname,s.search=o.search,s},b=(e,t,o,s)=>{const n=new Headers;for(const[c,l]of Object.entries(e.headers))if(Array.isArray(l))for(const i of l)n.append(c,i);else l!==void 0&&n.set(c,l);const a=e.method??"GET",d={headers:n,method:a,signal:o};return a!=="GET"&&a!=="HEAD"&&s!==void 0&&(d.body=H(e,s),d.duplex="half"),new Request(x(e.url,t),d)},B=e=>e.destroyed,C=async(e,t)=>{if(t.on("error",()=>{t.destroy()}),B(t)){await e.body?.cancel().catch(()=>{});return}const o={};e.headers.forEach((d,c)=>{c!=="set-cookie"&&(o[c]=d)});const s=e.headers.getSetCookie();if(s.length>0&&(o["set-cookie"]=s),t.writeHead(e.status,o),e.body===null){t.end();return}const n=e.body.getReader();t.once("close",()=>{n.cancel().catch(()=>{})});let a=await n.read();for(;!a.done&&!t.destroyed;)t.write(a.value)||await new Promise(d=>{const c=()=>{t.off("drain",c),t.off("close",c),d()};t.on("drain",c),t.on("close",c)}),a=await n.read();t.end()},_=65536,v=async(e,t,o=0)=>{const s=await e.read();if(s.done)return t;const n=_-o;return s.value.byteLength>=n?(t.push(s.value.subarray(0,n)),await e.cancel().catch(()=>{}),t):(t.push(s.value),v(e,t,o+s.value.byteLength))},q=async(e,t)=>{const o=e.body?.getReader(),s=()=>{o?.cancel().catch(()=>{})};if(t.destroyed){s();return}t.once("close",s);const n=o===void 0?[]:await v(o,[]);if(t.off("close",s),!t.writable)return;const a=Buffer.concat(n),d=[`HTTP/1.1 ${String(e.status)} ${e.statusText||"Refused"}`,"connection: close",`content-length: ${String(a.byteLength)}`];e.headers.forEach((c,l)=>{l!=="content-length"&&l!=="connection"&&d.push(`${l}: ${c}`)}),t.end(Buffer.concat([Buffer.from(`${d.join(`\r
2
- `)}\r
3
- \r
4
- `),a]))},I=async e=>{const t=e.host??"127.0.0.1",o=e.origin===void 0?void 0:$(e.origin);if(o===void 0&&!U.test(t))throw new Error(`createNodeHttpServer: host "${t}" is not a loopback address, so set origin to the public URL (e.g. https://app.example). Without it, browser requests fail the CSRF origin check and signed URLs point at the bound address.`);const s=new E({noServer:!0}),n=new Set,a=m(),d=()=>o??`http://${y(t)}:${String(a.address().port)}`;a.on("request",(i,r)=>{const h=d(),f=new AbortController;r.once("close",()=>{r.writableFinished||f.abort()});let u;try{u=b(i,h,f.signal,r)}catch{r.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),r.end("Bad Request");return}Promise.resolve().then(()=>e.fetch(u)).then(w=>C(w,r),()=>{r.headersSent||r.writeHead(500,{"content-type":"text/plain; charset=utf-8"}),r.end("Internal Server Error")}).catch(()=>{r.destroy()})});const c=async(i,r,h)=>{const f=new AbortController,u={closed:!1};n.add(r),r.on("error",()=>{r.destroy()}),r.once("close",()=>{u.closed=!0,n.delete(r),f.abort()});const w=await e.fetch(b(i,d(),f.signal)),p=L(w);if(p===void 0){await q(w,r);return}if(u.closed){p.abandon();return}r.once("close",()=>{p.abandon()}),s.handleUpgrade(i,r,h,S=>{p.attach(S)})};a.on("upgrade",(i,r,h)=>{c(i,r,h).catch(()=>{r.destroy()})}),await new Promise((i,r)=>{a.once("error",r),a.listen(e.port??0,t,()=>{a.off("error",r),i()})});const{port:l}=a.address();return{close:async()=>{const i=[...s.clients].map(async r=>R(r,"close"));for(const r of s.clients)r.terminate();for(const r of n)r.destroy();s.close(),a.closeAllConnections(),await new Promise((r,h)=>{a.close(f=>{f===void 0?r():h(f)})}),await Promise.all(i)},origin:`http://${y(t)}:${String(l)}`}};export{I as createNodeHttpServer};
@@ -1 +0,0 @@
1
- import{LunoraError as a}from"@lunora/errors";import{NODE_CAPABILITIES as R}from"@lunora/platform";import{a as g,c as D,i as E,A as b}from"./node-dispatch-route-ByuCR26s.mjs";import{createNodeGlobalStore as y}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as T}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeQueueHost as I}from"./createNodeQueueHost-szMV0PBN.mjs";import{createNodeR2Bucket as F}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as O}from"./createNodeSchedulerHost-DY6TOmXg.mjs";import{createNodeShardHost as L}from"./createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardRegistry as B}from"./createNodeShardRegistry-BKl1QXiv.mjs";import{createNodeSocketHost as H}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as q}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as P}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const C="__root__",U=e=>Object.entries(e).flatMap(([r,o])=>o.map(t=>{if(t.functionPath===void 0)throw new a("VALIDATION_ERROR",t.workflow===void 0?`@lunora/platform-node: cron job "${t.name}" has neither a function target nor a workflow target`:`@lunora/platform-node: cron job "${t.name}" starts workflow "${t.workflow}", which this host cannot do from a cron tick — schedule a function that calls ctx.workflows.get(name).create() instead`);return{args:t.args??{},expression:r,functionPath:t.functionPath,name:t.name}})),V=(e,r)=>{const o=U(e);if(o.length>0&&!r)throw new a("VALIDATION_ERROR","@lunora/platform-node: `crons` declares jobs but nothing can deliver them — pass `onFetch` (to run them on the shard) or `onDispatch`");return o},$=(e,r)=>async(o,t,c)=>{if(E(o,r,C))throw new a("BAD_REQUEST",b);const s=await e({args:t,functionPath:o,id:c.id,identity:void 0,scheduledFor:c.scheduledFor,shardKey:r,traceparent:void 0});if(!s.ok)throw new a("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${o} was refused with status ${String(s.status)}`)},oe=(e={})=>{const r=[],{database:o,dispose:t,drain:c,host:s}=L(e);r.push(t);try{const n=T(o),d=B(e);r.push(()=>{d.close()});const{directory:l}=d,u=g(l,e.onFetch!==void 0),m=D({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:u,schedulerSecret:e.dispatch?.schedulerSecret}),w=e.onFetch===void 0?void 0:$(u,e.shardKey??"__root__"),{declareCrons:v,dispose:S,scheduler:p}=O(o,{...e,onDispatch:e.onDispatch??w}),{socket:k}=H(o);r.push(S),e.crons!==void 0&&v(V(e.crons,e.onDispatch!==void 0||e.onFetch!==void 0));const _=e.queues===void 0?void 0:I(o,{onBatch:e.onQueueBatch??(()=>{throw new a("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}),A=e.objectStorageDirectory===void 0?void 0:F({directory:e.objectStorageDirectory}),i=e.globalTablesPath===void 0?void 0:y({path:e.globalTablesPath});i!==void 0&&r.push(()=>{i.dispose()});const N=e.workflows===void 0?void 0:q({store:P(o),workflows:e.workflows}),f=()=>{for(const h of r.toReversed())h()};return{capabilities:R,close:f,directory:l,dispatch:h=>m(h),drain:c,globalTables:i,kv:n,objectStorage:A,queues:_,scheduler:p,shard:s,sockets:k,workflows:N,[Symbol.dispose]:f}}catch(n){for(const d of r.toReversed())try{d()}catch{}throw n}};export{$ as createJobDelivery,oe as createNodePlatform};
@@ -1,15 +0,0 @@
1
- import{randomUUID as ie}from"node:crypto";import{serialize as N,deserialize as v}from"node:v8";import{LunoraError as F}from"@lunora/errors";import le from"@lunora/scheduler/validate";import{parse as de}from"@visulima/cron-parser/cloudflare";const ue={seconds:"optional",tz:"UTC"},T={backoffMultiplier:2,initialDelayMs:1e3,maxAttempts:5,maxDelayMs:6e4},R=2147483647,L=6e4,J=L/3,me=1e3,pe=5,_e=20,j=10,D=6048e5,X=(s,u)=>{if(!le(s))throw new F("VALIDATION_ERROR",`@lunora/platform-node: ${u} has cron expression "${s}", which is invalid or never occurs`)},E="declared:",$=s=>s.key.startsWith(E)?`job "${s.key.slice(E.length)}" (${s.function_path})`:`"${s.expression}" (${s.function_path})`,fe=(s,u)=>{const h=u?.initialDelayMs??T.initialDelayMs,g=u?.backoffMultiplier??T.backoffMultiplier,S=u?.maxDelayMs??T.maxDelayMs;return Math.min(S,h*g**Math.max(0,s-1))},Ne=(s,u={})=>{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
- )`);const h=e=>s.prepare("PRAGMA table_info(_lunora_scheduler_jobs)").all().some(t=>t.name===e),g=e=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},S=e=>{for(let t=0;;t+=1)try{s.exec(`ALTER TABLE _lunora_scheduler_jobs ADD COLUMN ${e} INTEGER`);return}catch(r){if(h(e))return;if(!(r instanceof Error&&"code"in r&&r.code==="SQLITE_BUSY")||t>=pe)throw r;g(_e*2**t)}};for(const e of["claimed_at","completed_at"])h(e)||S(e);s.exec("CREATE INDEX IF NOT EXISTS _lunora_scheduler_jobs_state_completed ON _lunora_scheduler_jobs (state, completed_at)"),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 Y=s.prepare("INSERT INTO _lunora_scheduler_jobs (id, function_path, args, scheduled_for, retry) VALUES (?, ?, ?, ?, ?)"),I=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE id = ?"),w=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE state = ? ORDER BY scheduled_for"),G=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'canceled', completed_at = ? WHERE id = ? AND state = 'pending'"),V=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ?"),x=s.prepare("DELETE FROM _lunora_scheduler_jobs WHERE state IN ('succeeded', 'canceled') AND completed_at <= ?"),q=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'succeeded', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ?"),z=s.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND claimed_at = ? AND state = 'pending'"),K=s.prepare("UPDATE _lunora_scheduler_jobs SET attempts = ?, scheduled_for = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),Q=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),Z=s.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 *"),ee=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'pending', attempts = 0, completed_at = NULL, scheduled_for = ? WHERE id = ? AND state = 'dead'"),P=s.prepare(`INSERT INTO _lunora_scheduler_crons (key, expression, function_path, args) VALUES (?, ?, ?, ?)
15
- ON CONFLICT (key) DO UPDATE SET expression = excluded.expression, function_path = excluded.function_path, args = excluded.args`),W=s.prepare("SELECT * FROM _lunora_scheduler_crons"),B=s.prepare("SELECT * FROM _lunora_scheduler_crons WHERE key = ?"),te=s.prepare("DELETE FROM _lunora_scheduler_crons WHERE key = ?"),l=()=>s.open,y=()=>s.inTransaction,H=e=>e===null?void 0:v(e);let c=!1;const k=async()=>{c||!l()||!y()||(await new Promise(e=>{setTimeout(e,j).unref()}),await k())},_=new Map,m=new Map,M=new Set;let O=new Set;const U=e=>({attempts:e.attempts,functionPath:e.function_path,id:e.id,scheduledFor:e.scheduled_for}),C=e=>{const t=_.get(e);t!==void 0&&(clearTimeout(t),_.delete(e))},p=(e,t)=>{C(e);const r=Math.max(0,t-Date.now());if(r>R){const n=setTimeout(()=>{p(e,t)},R);_.set(e,n);return}const o=setTimeout(()=>{se(e).catch(()=>{})},r);_.set(e,o)},re=e=>{const t=I.get(e);!c&&t?.state==="pending"&&p(e,t.claimed_at===null?t.scheduled_for:t.claimed_at+L)},ne=(e,t)=>{if(y()){c||p(e,t+j);return}try{const r=Z.get(t,e,t,t-L);return r===void 0&&re(e),r}catch{!c&&l()&&p(e,Date.now()+me);return}},oe=(e,t)=>{let r=t,o;const n=a=>{o=setTimeout(()=>{if(!l())return;if(y()){n(j);return}const i=Date.now();try{z.run(i,e,r).changes===1&&(r=i)}catch{}n(J)},a),o.unref()};return n(J),{release:()=>{clearTimeout(o)},stamp:()=>r}},se=async e=>{if(_.delete(e),!l())return;const t=Date.now(),r=ne(e,t);if(r===void 0)return;const o=r.attempts+1,n=H(r.retry),a=oe(e,t);try{if(await u.onDispatch?.(r.function_path,v(r.args),{attempts:o,id:e,scheduledFor:r.scheduled_for}),await k(),l()&&!y()){const i=Date.now();q.run(o,i,e,a.stamp()),x.run(i-D)}}catch{if(await k(),c||!l())return;const i=n?.maxAttempts??T.maxAttempts;if(o>=i){Q.run(o,Date.now(),e,a.stamp());return}const d=Date.now()+fe(o,n);K.run(o,d,e,a.stamp()).changes===1&&p(e,d)}finally{a.release()}};let b,A;const f=e=>{if(M.has(e.key))return;const t=m.get(e.key);t!==void 0&&clearTimeout(t);let r;try{r=de(e.expression,ue).next().getTime()}catch{return}const o=Math.max(0,r-Date.now());if(o>R)return m.set(e.key,setTimeout(()=>{f(e)},R)),r;const n=setTimeout(()=>{if(m.delete(e.key),c||!l())return;let a;try{a=B.get(e.key)}catch(d){A(e,`could not read its row before the tick due ${new Date(r).toISOString()}, so that tick was skipped`,d);return}if(a===void 0){b(e,r,void 0);return}if(a.expression!==e.expression){f(a);return}const i=a;M.add(e.key),(async()=>{let d;try{await u.onDispatch?.(i.function_path,v(i.args),{attempts:0,id:`${e.key}:${String(r)}`,scheduledFor:r})}catch(ce){d={error:ce}}finally{M.delete(e.key)}b(i,r,d)})().catch(d=>{A(i,"failed to settle its tick",d)})},o);return m.set(e.key,n),r};A=(e,t,r)=>{const o=c||!l()?void 0:f(e),n=o===void 0?"none scheduled, the scheduler is closed":new Date(o).toISOString();return console.error(`[@lunora/platform-node] cron ${$(e)} ${t}; re-armed from its last known definition, next run: ${n}`,r),o},b=(e,t,r)=>{let o;if(!c&&l()){let n,a=!1;try{n=B.get(e.key)}catch(i){a=!0,o=A(e,"could not read its row after its tick",i)}n!==void 0?o=f(n):!a&&O.has(e.key)&&(O.delete(e.key),console.warn(`[@lunora/platform-node] declared cron ${$(e)} was removed from the database by another process passing \`crons\`; it stops firing here`))}if(r!==void 0){const n=o===void 0?"none scheduled":new Date(o).toISOString();console.error(`[@lunora/platform-node] cron ${$(e)} tick due ${new Date(t).toISOString()} failed; next run: ${n}`,r.error)}};const ae={cancel:async e=>{if(c)return!1;C(e);const t=Date.now(),r=G.run(t,e).changes>0;return x.run(t-D),r},cron:async(e,t,r)=>{if(c)throw new Error("platform closed: cannot register a cron");X(e,`cron for ${t}`);const o={args:N(r??{}),expression:e,function_path:t,key:`${e} ${t}`};P.run(o.key,o.expression,o.function_path,o.args),f(o)},deadLetter:{list:async()=>c||!l()?[]:w.all("dead").map(e=>U(e)),requeue:async e=>{if(c||!l())return!1;const t=Date.now();return ee.run(t,e).changes===0?!1:(p(e,t),!0)}},get:async e=>{const t=c||!l()?void 0:I.get(e);if(t===void 0||t.completed_at!==null&&t.state!=="dead"&&t.completed_at<=Date.now()-D)return null;const r={canceled:"canceled",dead:"failed",pending:"pending",succeeded:"succeeded"},o=t.state==="pending"&&t.claimed_at!==null&&t.claimed_at>=Date.now()-L,n={...U(t),state:o?"running":r[t.state]};return t.completed_at!==null&&(n.completedAt=t.completed_at),n},list:async()=>c||!l()?[]:w.all("pending").map(e=>U(e)),schedule:async(e,t,r)=>{if(c)throw new Error("platform closed: cannot schedule a job");if(r?.retry?.forever===!0)throw new F("INVALID_INPUT","retry.forever is not supported by the Node scheduler host; set a finite retry.maxAttempts");const o=`node-job-${ie()}`;let n;return r?.at===void 0?n=Date.now()+(r?.delayMs??0):n=typeof r.at=="number"?r.at:r.at.getTime(),Y.run(o,e,N(t),n,r?.retry===void 0?null:N(r.retry)),p(o,n),{id:o,scheduledFor:n}}};x.run(Date.now()-D);for(const e of w.all("pending"))p(e.id,e.scheduled_for);for(const e of W.all())e.key.startsWith(E)||f(e);return{declareCrons:e=>{if(c)throw new Error("platform closed: cannot declare crons");const t=new Set;for(const n of e){if(t.has(n.name))throw new F("VALIDATION_ERROR",`@lunora/platform-node: two declared cron jobs are named "${n.name}"; cron job names must be unique`);t.add(n.name),X(n.expression,`cron job "${n.name}"`)}const r=e.map(n=>({args:N(n.args),expression:n.expression,function_path:n.functionPath,key:`${E}${n.name}`})),o=new Set(r.map(n=>n.key));s.transaction(()=>{for(const n of W.all())n.key.startsWith(E)&&!o.has(n.key)&&te.run(n.key);for(const n of r)P.run(n.key,n.expression,n.function_path,n.args)}).immediate();for(const[n,a]of m)n.startsWith(E)&&!o.has(n)&&(clearTimeout(a),m.delete(n));O=o;for(const n of r)f(n)},dispose:()=>{for(const e of _.values())clearTimeout(e);for(const e of m.values())clearTimeout(e);_.clear(),m.clear(),c=!0},scheduler:ae,simulateDeadLetter:async e=>{const t=I.get(e);if(t?.state!=="pending")return!1;C(e);const r=H(t.retry);return V.run((r?.maxAttempts??T.maxAttempts)+1,Date.now(),e),!0}}};export{Ne as createNodeSchedulerHost};
@@ -1 +0,0 @@
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 +0,0 @@
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};