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

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.
@@ -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-CjgGhVoQ.mjs";import{createNodeShardHost as T}from"../packem_shared/createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-BKl1QXiv.mjs";import{createNodeSocketHost as b}from"../packem_shared/createNodeSocketHost-ByOmEGFe.mjs";const P=()=>{const{database:o,dispose:m,host:p}=T(),h=D(o),i=H(),{directory:l}=i,{readFrames:w,restoreSocket:S,simulateRecycle:u,socket:f}=b(o),c=new Set,s=new Map,{dispose:y,scheduler:d,simulateDeadLetter:N}=k(o,{onDispatch:(e,a,t)=>{c.add(t.id),s.set(e,(s.get(e)??0)+1)}}),n=()=>{y(),m(),i.close()};return{capabilities:g,awaitAlarmFired:async e=>{await new Promise(a=>{setTimeout(a,Math.max(0,e-Date.now())+30)})},awaitJobDispatched:async e=>{const t=(await d.list?.())?.find(r=>r.id===e);return t!==void 0&&await new Promise(r=>{setTimeout(r,Math.max(0,t.scheduledFor-Date.now())+30)}),c.has(e)},cleanup:n,cronTicks:e=>s.get(e)??0,directory:l,disposeTerminally:n,kv:h,readFrames:w,restoreSocket:S,scheduler:d,shard:p,simulateDeadLetter:N,simulateRecycle:u,socket:f}};export{P as createNodeConformanceHost};
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};
package/dist/index.d.mts CHANGED
@@ -135,6 +135,42 @@ interface NodeHttpServer {
135
135
  /** The `http://host:port` origin the server answers on. */
136
136
  origin: string;
137
137
  }
138
+ /**
139
+ * The connection fields a Cloudflare `Hyperdrive` binding exposes, and the
140
+ * `HyperdriveLike` shape `@lunora/hyperdrive`'s `createHyperdrive` reads.
141
+ * Declared here structurally so this package does not depend on
142
+ * `@lunora/hyperdrive` for a type.
143
+ */
144
+ interface NodeHyperdriveBinding {
145
+ connectionString: string;
146
+ database: string;
147
+ host: string;
148
+ password: string;
149
+ port: number;
150
+ user: string;
151
+ }
152
+ /**
153
+ * Build the `HYPERDRIVE` binding for a Node host from a database URL, by
154
+ * default `process.env.DATABASE_URL`. Put it on the `env` the worker and shard
155
+ * are built over, under the binding name the app reads (`env.HYPERDRIVE`), and
156
+ * the app's own `.hyperdrive((env) => …)` wiring builds `ctx.sql` from it
157
+ * unchanged.
158
+ *
159
+ * There is no pool or query cache in front of the database here: the driver
160
+ * the app constructs from `connectionString` connects to it directly, so its own
161
+ * pool settings are the only ones that apply.
162
+ * A Postgres URL may name a Unix socket the libpq way: an empty host with the
163
+ * socket directory in a `host` query parameter (`postgres:///db?host=/var/run/postgresql`),
164
+ * which becomes the binding's `host`.
165
+ *
166
+ * A URL with any TLS option other than an explicit off (`sslmode=prefer` or
167
+ * `require`, `ssl=true`, `sslrootcert=…`) gets a binding whose discrete fields
168
+ * throw: they cannot carry it, so a pool built from them would silently connect
169
+ * without TLS. `sslmode=disable` and `ssl=false` keep them. Build the driver
170
+ * from `connectionString`, which keeps every query option.
171
+ * @param url A `postgres://`, `postgresql://`, `mysql://` or `mariadb://` URL; `DATABASE_URL` unless given.
172
+ */
173
+ declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
138
174
  /** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
139
175
  declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
140
176
  /** Options for {@link createNodeQueueHost}. */
@@ -209,6 +245,14 @@ interface NodeQueueHost<Queues extends Record<string, {
209
245
  declare const createNodeQueueHost: <Queues extends Record<string, {
210
246
  isLunoraQueue: true;
211
247
  }>>(database: Database.Database, options: NodeQueueHostOptions<Queues>) => NodeQueueHost<Queues>;
248
+ /** One declared cron job, as {@link NodeSchedulerHost.declareCrons} takes it. */
249
+ interface NodeDeclaredCron {
250
+ args: Record<string, unknown>;
251
+ expression: string;
252
+ functionPath: string;
253
+ /** The job's `cronJobs()` name, unique across the app. Keys its row. */
254
+ name: string;
255
+ }
212
256
  /** Options for {@link createNodeSchedulerHost}. */
213
257
  interface NodeSchedulerHostOptions {
214
258
  /**
@@ -241,6 +285,14 @@ interface NodeSchedulerHostOptions {
241
285
  * TCK's dead-letter legs need.
242
286
  */
243
287
  interface NodeSchedulerHost {
288
+ /**
289
+ * Make `crons` the app's declared cron set: upsert each one, arm it, and
290
+ * delete and disarm any declared row not in the list (a job the app removed
291
+ * or renamed). Every expression is parsed before anything is written, so an
292
+ * invalid one throws and leaves the previous set in place. Throws after
293
+ * `dispose()`.
294
+ */
295
+ declareCrons: (crons: ReadonlyArray<NodeDeclaredCron>) => void;
244
296
  /**
245
297
  * Clear every armed `setTimeout` (one-shot jobs and cron ticks alike) and
246
298
  * put the host into a terminal, closed state: afterwards `schedule()` and
@@ -508,6 +560,13 @@ interface NodeWorkflowHost<Workflows extends Record<string, {
508
560
  declare const createNodeWorkflowHost: <Workflows extends Record<string, {
509
561
  isLunoraWorkflow: true;
510
562
  }>>(options: NodeWorkflowHostOptions<Workflows>) => NodeWorkflowHost<Workflows>;
563
+ /** One entry of the generated `LUNORA_CRONS` map (`_generated/crons.ts`). */
564
+ interface NodeCronJob {
565
+ args?: Record<string, unknown>;
566
+ functionPath?: string;
567
+ name: string;
568
+ workflow?: string;
569
+ }
511
570
  /** Every contract this package provides, composed for one Node process. */
512
571
  interface NodePlatform<Queues extends Record<string, {
513
572
  isLunoraQueue: true;
@@ -643,6 +702,19 @@ type NodePlatformOptions<Queues extends Record<string, {
643
702
  }> = Record<string, never>, Workflows extends Record<string, {
644
703
  isLunoraWorkflow: true;
645
704
  }> = Record<string, never>> = {
705
+ /**
706
+ * The app's declared crons — pass the generated `LUNORA_CRONS` map
707
+ * (`_generated/crons.ts`). Each job is armed on the scheduler and delivered
708
+ * through the same `onDispatch` a scheduled job uses, so it needs `onFetch`
709
+ * (or your own `onDispatch`) to reach a shard; a non-empty map with neither
710
+ * throws. Job names must be unique, every schedule must have a next
711
+ * occurrence, and schedules are read as UTC. The map is the whole declared
712
+ * set: a job declared by an earlier run and absent here is deleted. Omit
713
+ * the option and this process neither fires nor deletes declared jobs, so
714
+ * a script opening the same file leaves a running server's crons alone.
715
+ * Crons registered through `scheduler.cron()` are re-armed either way.
716
+ */
717
+ crons?: Readonly<Record<string, ReadonlyArray<NodeCronJob>>>;
646
718
  /** Secrets for the dispatch route. Omit to leave the route refusing every request. */
647
719
  dispatch?: NodePlatformDispatchOptions;
648
720
  /**
@@ -697,6 +769,28 @@ interface NodeR2BucketOptions {
697
769
  * maps directly onto a file operation.
698
770
  */
699
771
  declare const createNodeR2Bucket: (options: NodeR2BucketOptions) => R2BucketLike;
772
+ /** The shape `ctx.secrets` reads off `env[name]`: a Cloudflare Secrets Store secret binding. */
773
+ interface NodeSecretBinding {
774
+ get: () => Promise<string>;
775
+ }
776
+ /**
777
+ * Build the `ctx.secrets` bindings for a Node host from environment variables:
778
+ * one binding per name, spread into the `env` the worker and shard are built
779
+ * over. `ctx.secrets.get(name)` then reads `source[name]`.
780
+ *
781
+ * Names are listed rather than every variable in `source` being bound, for the
782
+ * same reason a wrangler config lists `secrets_store_secrets[]`: `ctx.secrets`
783
+ * reaches only what was granted to it. It also keeps the bindings off names the
784
+ * env already carries as plain strings (`LUNORA_ADMIN_TOKEN` and the like),
785
+ * which the runtime reads as strings and a binding object would break; a
786
+ * `LUNORA_*` name is refused for that reason.
787
+ *
788
+ * The value is read when `get()` is called, so an unused secret never has to be
789
+ * set. An unset or empty variable rejects the call.
790
+ * @param names The secret names the app reads through `ctx.secrets`.
791
+ * @param source Where values come from; `process.env` unless given.
792
+ */
793
+ declare const createNodeSecretBindings: (names: ReadonlyArray<string>, source?: Readonly<Record<string, string | undefined>>) => Record<string, NodeSecretBinding>;
700
794
  /**
701
795
  * Present the node shard registry as the `ShardNamespaceLike` a worker is built
702
796
  * over (`createWorker({ shardDO })`).
@@ -776,7 +870,7 @@ declare const bindShardSockets: (shard: ShardSocketHooks, inbound: Pick<NodeShar
776
870
  * Pass the result as `createNodeWorkflowHost({ store })`.
777
871
  */
778
872
  declare const createNodeWorkflowStore: (database: Database.Database) => WorkflowStore;
779
- export { NODE_SCHEDULER_DISPATCH_PATH,
873
+ export { NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron,
780
874
  /**
781
875
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
782
876
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -813,7 +907,9 @@ export { NODE_SCHEDULER_DISPATCH_PATH,
813
907
  * registry as the `shardDO` namespace that worker routes to. Also absent are
814
908
  * the Cloudflare product bindings with no local
815
909
  * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
816
- * Engine, Pipelines, Secrets Store, Hyperdrive.
910
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
911
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
912
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
817
913
  *
818
914
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
819
915
  * for `provision` — which reports, once, which declared features this target
@@ -859,7 +955,9 @@ type NodeDispatchInvocation,
859
955
  * registry as the `shardDO` namespace that worker routes to. Also absent are
860
956
  * the Cloudflare product bindings with no local
861
957
  * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
862
- * Engine, Pipelines, Secrets Store, Hyperdrive.
958
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
959
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
960
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
863
961
  *
864
962
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
865
963
  * for `provision` — which reports, once, which declared features this target
@@ -868,4 +966,4 @@ type NodeDispatchInvocation,
868
966
  * server, which is why both statements above hold at once. See
869
967
  * `plans/234-node-host-findings.md`.
870
968
  */
871
- type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore };
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 };
package/dist/index.d.ts CHANGED
@@ -135,6 +135,42 @@ interface NodeHttpServer {
135
135
  /** The `http://host:port` origin the server answers on. */
136
136
  origin: string;
137
137
  }
138
+ /**
139
+ * The connection fields a Cloudflare `Hyperdrive` binding exposes, and the
140
+ * `HyperdriveLike` shape `@lunora/hyperdrive`'s `createHyperdrive` reads.
141
+ * Declared here structurally so this package does not depend on
142
+ * `@lunora/hyperdrive` for a type.
143
+ */
144
+ interface NodeHyperdriveBinding {
145
+ connectionString: string;
146
+ database: string;
147
+ host: string;
148
+ password: string;
149
+ port: number;
150
+ user: string;
151
+ }
152
+ /**
153
+ * Build the `HYPERDRIVE` binding for a Node host from a database URL, by
154
+ * default `process.env.DATABASE_URL`. Put it on the `env` the worker and shard
155
+ * are built over, under the binding name the app reads (`env.HYPERDRIVE`), and
156
+ * the app's own `.hyperdrive((env) => …)` wiring builds `ctx.sql` from it
157
+ * unchanged.
158
+ *
159
+ * There is no pool or query cache in front of the database here: the driver
160
+ * the app constructs from `connectionString` connects to it directly, so its own
161
+ * pool settings are the only ones that apply.
162
+ * A Postgres URL may name a Unix socket the libpq way: an empty host with the
163
+ * socket directory in a `host` query parameter (`postgres:///db?host=/var/run/postgresql`),
164
+ * which becomes the binding's `host`.
165
+ *
166
+ * A URL with any TLS option other than an explicit off (`sslmode=prefer` or
167
+ * `require`, `ssl=true`, `sslrootcert=…`) gets a binding whose discrete fields
168
+ * throw: they cannot carry it, so a pool built from them would silently connect
169
+ * without TLS. `sslmode=disable` and `ssl=false` keep them. Build the driver
170
+ * from `connectionString`, which keeps every query option.
171
+ * @param url A `postgres://`, `postgresql://`, `mysql://` or `mariadb://` URL; `DATABASE_URL` unless given.
172
+ */
173
+ declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
138
174
  /** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
139
175
  declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
140
176
  /** Options for {@link createNodeQueueHost}. */
@@ -209,6 +245,14 @@ interface NodeQueueHost<Queues extends Record<string, {
209
245
  declare const createNodeQueueHost: <Queues extends Record<string, {
210
246
  isLunoraQueue: true;
211
247
  }>>(database: Database.Database, options: NodeQueueHostOptions<Queues>) => NodeQueueHost<Queues>;
248
+ /** One declared cron job, as {@link NodeSchedulerHost.declareCrons} takes it. */
249
+ interface NodeDeclaredCron {
250
+ args: Record<string, unknown>;
251
+ expression: string;
252
+ functionPath: string;
253
+ /** The job's `cronJobs()` name, unique across the app. Keys its row. */
254
+ name: string;
255
+ }
212
256
  /** Options for {@link createNodeSchedulerHost}. */
213
257
  interface NodeSchedulerHostOptions {
214
258
  /**
@@ -241,6 +285,14 @@ interface NodeSchedulerHostOptions {
241
285
  * TCK's dead-letter legs need.
242
286
  */
243
287
  interface NodeSchedulerHost {
288
+ /**
289
+ * Make `crons` the app's declared cron set: upsert each one, arm it, and
290
+ * delete and disarm any declared row not in the list (a job the app removed
291
+ * or renamed). Every expression is parsed before anything is written, so an
292
+ * invalid one throws and leaves the previous set in place. Throws after
293
+ * `dispose()`.
294
+ */
295
+ declareCrons: (crons: ReadonlyArray<NodeDeclaredCron>) => void;
244
296
  /**
245
297
  * Clear every armed `setTimeout` (one-shot jobs and cron ticks alike) and
246
298
  * put the host into a terminal, closed state: afterwards `schedule()` and
@@ -508,6 +560,13 @@ interface NodeWorkflowHost<Workflows extends Record<string, {
508
560
  declare const createNodeWorkflowHost: <Workflows extends Record<string, {
509
561
  isLunoraWorkflow: true;
510
562
  }>>(options: NodeWorkflowHostOptions<Workflows>) => NodeWorkflowHost<Workflows>;
563
+ /** One entry of the generated `LUNORA_CRONS` map (`_generated/crons.ts`). */
564
+ interface NodeCronJob {
565
+ args?: Record<string, unknown>;
566
+ functionPath?: string;
567
+ name: string;
568
+ workflow?: string;
569
+ }
511
570
  /** Every contract this package provides, composed for one Node process. */
512
571
  interface NodePlatform<Queues extends Record<string, {
513
572
  isLunoraQueue: true;
@@ -643,6 +702,19 @@ type NodePlatformOptions<Queues extends Record<string, {
643
702
  }> = Record<string, never>, Workflows extends Record<string, {
644
703
  isLunoraWorkflow: true;
645
704
  }> = Record<string, never>> = {
705
+ /**
706
+ * The app's declared crons — pass the generated `LUNORA_CRONS` map
707
+ * (`_generated/crons.ts`). Each job is armed on the scheduler and delivered
708
+ * through the same `onDispatch` a scheduled job uses, so it needs `onFetch`
709
+ * (or your own `onDispatch`) to reach a shard; a non-empty map with neither
710
+ * throws. Job names must be unique, every schedule must have a next
711
+ * occurrence, and schedules are read as UTC. The map is the whole declared
712
+ * set: a job declared by an earlier run and absent here is deleted. Omit
713
+ * the option and this process neither fires nor deletes declared jobs, so
714
+ * a script opening the same file leaves a running server's crons alone.
715
+ * Crons registered through `scheduler.cron()` are re-armed either way.
716
+ */
717
+ crons?: Readonly<Record<string, ReadonlyArray<NodeCronJob>>>;
646
718
  /** Secrets for the dispatch route. Omit to leave the route refusing every request. */
647
719
  dispatch?: NodePlatformDispatchOptions;
648
720
  /**
@@ -697,6 +769,28 @@ interface NodeR2BucketOptions {
697
769
  * maps directly onto a file operation.
698
770
  */
699
771
  declare const createNodeR2Bucket: (options: NodeR2BucketOptions) => R2BucketLike;
772
+ /** The shape `ctx.secrets` reads off `env[name]`: a Cloudflare Secrets Store secret binding. */
773
+ interface NodeSecretBinding {
774
+ get: () => Promise<string>;
775
+ }
776
+ /**
777
+ * Build the `ctx.secrets` bindings for a Node host from environment variables:
778
+ * one binding per name, spread into the `env` the worker and shard are built
779
+ * over. `ctx.secrets.get(name)` then reads `source[name]`.
780
+ *
781
+ * Names are listed rather than every variable in `source` being bound, for the
782
+ * same reason a wrangler config lists `secrets_store_secrets[]`: `ctx.secrets`
783
+ * reaches only what was granted to it. It also keeps the bindings off names the
784
+ * env already carries as plain strings (`LUNORA_ADMIN_TOKEN` and the like),
785
+ * which the runtime reads as strings and a binding object would break; a
786
+ * `LUNORA_*` name is refused for that reason.
787
+ *
788
+ * The value is read when `get()` is called, so an unused secret never has to be
789
+ * set. An unset or empty variable rejects the call.
790
+ * @param names The secret names the app reads through `ctx.secrets`.
791
+ * @param source Where values come from; `process.env` unless given.
792
+ */
793
+ declare const createNodeSecretBindings: (names: ReadonlyArray<string>, source?: Readonly<Record<string, string | undefined>>) => Record<string, NodeSecretBinding>;
700
794
  /**
701
795
  * Present the node shard registry as the `ShardNamespaceLike` a worker is built
702
796
  * over (`createWorker({ shardDO })`).
@@ -776,7 +870,7 @@ declare const bindShardSockets: (shard: ShardSocketHooks, inbound: Pick<NodeShar
776
870
  * Pass the result as `createNodeWorkflowHost({ store })`.
777
871
  */
778
872
  declare const createNodeWorkflowStore: (database: Database.Database) => WorkflowStore;
779
- export { NODE_SCHEDULER_DISPATCH_PATH,
873
+ export { NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron,
780
874
  /**
781
875
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
782
876
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -813,7 +907,9 @@ export { NODE_SCHEDULER_DISPATCH_PATH,
813
907
  * registry as the `shardDO` namespace that worker routes to. Also absent are
814
908
  * the Cloudflare product bindings with no local
815
909
  * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
816
- * Engine, Pipelines, Secrets Store, Hyperdrive.
910
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
911
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
912
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
817
913
  *
818
914
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
819
915
  * for `provision` — which reports, once, which declared features this target
@@ -859,7 +955,9 @@ type NodeDispatchInvocation,
859
955
  * registry as the `shardDO` namespace that worker routes to. Also absent are
860
956
  * the Cloudflare product bindings with no local
861
957
  * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
862
- * Engine, Pipelines, Secrets Store, Hyperdrive.
958
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
959
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
960
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
863
961
  *
864
962
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
865
963
  * for `provision` — which reports, once, which declared features this target
@@ -868,4 +966,4 @@ type NodeDispatchInvocation,
868
966
  * server, which is why both statements above hold at once. See
869
967
  * `plans/234-node-host-findings.md`.
870
968
  */
871
- type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore };
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 };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{N as r,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 N}from"./packem_shared/createNodeHttpServer-D4YVdhJn.mjs";import{createNodeShardKvStore as m}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodePlatform as S}from"./packem_shared/createNodePlatform-BI6CqDYp.mjs";import{createNodeProfileHandler as H}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as h}from"./packem_shared/createNodeQueueHost-szMV0PBN.mjs";import{createNodeR2Bucket as u}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as D}from"./packem_shared/createNodeSchedulerHost-CjgGhVoQ.mjs";import{createNodeShardHost as P}from"./packem_shared/createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardNamespace as _}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as n}from"./packem_shared/createNodeShardRegistry-BKl1QXiv.mjs";import{bindShardSockets as w,createNodeShardState as A}from"./packem_shared/bindShardSockets-9GvSocBW.mjs";import{createNodeSocketHost as T}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as g}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as y}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{r as NODE_SCHEDULER_DISPATCH_PATH,w as bindShardSockets,t as createNodeDispatchRoute,d as createNodeGlobalStore,N as createNodeHttpServer,S as createNodePlatform,H as createNodeProfileHandler,h as createNodeQueueHost,u as createNodeR2Bucket,D as createNodeSchedulerHost,P as createNodeShardHost,m as createNodeShardKvStore,_ as createNodeShardNamespace,n as createNodeShardRegistry,A as createNodeShardState,T as createNodeSocketHost,c as createNodeSqlExec,g as createNodeWorkflowHost,y as createNodeWorkflowStore};
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};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";const m=/^\//u,R=/^\[(.*)\]$/u,h=new Set(["disable","disabled"]),b=new Set(["0","false"]),A=/[-_]/gu,L=o=>[...o.entries()].filter(([e,t])=>{const r=e.toLowerCase().replaceAll(A,""),a=t.toLowerCase();return r==="sslmode"?!h.has(a):r.startsWith("ssl")&&!(r==="ssl"&&b.has(a))}).map(([e])=>e),O=(o,e)=>{const t=()=>{throw new s("VALIDATION_ERROR",`@lunora/platform-node: the Hyperdrive database URL sets ${e.join(", ")}, which the discrete host/port/user/password/database fields cannot carry, so a driver built from them would connect without TLS — build the driver from connectionString instead`)};return Object.defineProperties({connectionString:o},{database:{enumerable:!0,get:t},host:{enumerable:!0,get:t},password:{enumerable:!0,get:t},port:{enumerable:!0,get:t},user:{enumerable:!0,get:t}})},l=new Set(["postgres:","postgresql:"]),w=/^\d+$/u,f=65535,S=(o,e)=>{if(o.port!=="")return Number(o.port);const t=l.has(o.protocol)?o.searchParams.get("port")??void 0:void 0;if(t===void 0)return e;const r=w.test(t)?Number(t):Number.NaN;if(!(r>=1&&r<=f))throw new s("VALIDATION_ERROR","@lunora/platform-node: the Hyperdrive database URL's port query parameter must be a whole number from 1 to 65535");return r},v={"mariadb:":3306,"mysql:":3306,"postgres:":5432,"postgresql:":5432},y=(o=process.env.DATABASE_URL)=>{if(o===void 0||o==="")throw new s("VALIDATION_ERROR","@lunora/platform-node: Hyperdrive needs a database URL — set DATABASE_URL or pass one to createNodeHyperdrive");let e,t,r,a,n;try{e=new URL(o),t=decodeURIComponent(e.pathname.replace(m,"")),r=decodeURIComponent(e.hostname),a=decodeURIComponent(e.password),n=decodeURIComponent(e.username)}catch{throw new s("VALIDATION_ERROR","@lunora/platform-node: the Hyperdrive database URL is not a valid URL")}const d=v[e.protocol];if(d===void 0)throw new s("VALIDATION_ERROR",`@lunora/platform-node: the Hyperdrive database URL uses "${e.protocol}", but Hyperdrive serves only postgres:, postgresql:, mysql: and mariadb:`);const p=l.has(e.protocol)?e.searchParams.get("host")??"":"",c=r===""?p:r.replace(R,"$1");if(c===""||t==="")throw new s("VALIDATION_ERROR","@lunora/platform-node: the Hyperdrive database URL needs both a host and a database name");const u=S(e,d),i=L(e.searchParams);return i.length>0?O(o,i):{connectionString:o,database:t,host:c,password:a,port:u,user:n}};export{y as createNodeHyperdrive};
@@ -0,0 +1 @@
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};
@@ -0,0 +1,15 @@
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};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";const a="LUNORA_",c=(r,t=process.env)=>{const o=r.filter(e=>e.startsWith(a));if(o.length>0)throw new s("VALIDATION_ERROR",`@lunora/platform-node: ${o.join(", ")} cannot be a ctx.secrets binding — Lunora reads ${a}* env vars as plain strings, and a binding object spread over one would replace it (an admin token would stop working). Keep it a plain env value, or read your own secret under another name`);return Object.fromEntries(r.map(e=>[e,{get:async()=>{const n=Object.hasOwn(t,e)?t[e]:void 0;if(typeof n!="string"||n==="")throw new s("INTERNAL",`ctx.secrets: environment variable "${e}" is not set on this Node host`);return n}}]))};export{c as createNodeSecretBindings};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/platform-node",
3
- "version": "1.0.0-alpha.218",
3
+ "version": "1.0.0-alpha.219",
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",
@@ -50,7 +50,8 @@
50
50
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
51
51
  "@lunora/platform": "1.0.0-alpha.80",
52
52
  "@lunora/queue": "1.0.0-alpha.143",
53
- "@lunora/runtime": "^1.0.0-alpha.276",
53
+ "@lunora/runtime": "^1.0.0-alpha.287",
54
+ "@lunora/scheduler": "^1.0.0-alpha.170",
54
55
  "@lunora/sql-store": "^1.0.0-alpha.234",
55
56
  "@lunora/workflow": "^1.0.0-alpha.111",
56
57
  "@visulima/cron-parser": "2.0.0",
@@ -1 +0,0 @@
1
- import{LunoraError as u}from"@lunora/errors";import{NODE_CAPABILITIES as b}from"@lunora/platform";import{a as A,c as E,i as D,A as R}from"./node-dispatch-route-ByuCR26s.mjs";import{createNodeGlobalStore as y}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as g}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeQueueHost as T}from"./createNodeQueueHost-szMV0PBN.mjs";import{createNodeR2Bucket as F}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as I}from"./createNodeSchedulerHost-CjgGhVoQ.mjs";import{createNodeShardHost as B}from"./createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardRegistry as H}from"./createNodeShardRegistry-BKl1QXiv.mjs";import{createNodeSocketHost as L}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as q}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as O}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const U="__root__",Q=(e,o)=>async(r,c,t)=>{if(D(r,o,U))throw new u("BAD_REQUEST",R);const s=await e({args:c,functionPath:r,id:t.id,identity:void 0,scheduledFor:t.scheduledFor,shardKey:o,traceparent:void 0});if(!s.ok)throw new u("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(s.status)}`)},X=(e={})=>{const o=[],{database:r,dispose:c,drain:t,host:s}=B(e);o.push(c);try{const d=g(r),a=H(e);o.push(()=>{a.close()});const{directory:l}=a,n=A(l,e.onFetch!==void 0),m=E({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:n,schedulerSecret:e.dispatch?.schedulerSecret}),S=e.onFetch===void 0?void 0:Q(n,e.shardKey??"__root__"),{dispose:w,scheduler:v}=I(r,{...e,onDispatch:e.onDispatch??S}),{socket:_}=L(r);o.push(w);const p=e.queues===void 0?void 0:T(r,{onBatch:e.onQueueBatch??(()=>{throw new u("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}),k=e.objectStorageDirectory===void 0?void 0:F({directory:e.objectStorageDirectory}),i=e.globalTablesPath===void 0?void 0:y({path:e.globalTablesPath});i!==void 0&&o.push(()=>{i.dispose()});const N=e.workflows===void 0?void 0:q({store:O(r),workflows:e.workflows}),f=()=>{for(const h of o.toReversed())h()};return{capabilities:b,close:f,directory:l,dispatch:h=>m(h),drain:t,globalTables:i,kv:d,objectStorage:k,queues:p,scheduler:v,shard:s,sockets:_,workflows:N,[Symbol.dispose]:f}}catch(d){for(const a of o.toReversed())try{a()}catch{}throw d}};export{Q as createJobDelivery,X as createNodePlatform};
@@ -1,15 +0,0 @@
1
- import{randomUUID as Z}from"node:crypto";import{deserialize as U,serialize as w}from"node:v8";import{LunoraError as ee}from"@lunora/errors";import{parse as b}from"@visulima/cron-parser/cloudflare";const j={seconds:"optional"},p={backoffMultiplier:2,initialDelayMs:1e3,maxAttempts:5,maxDelayMs:6e4},A=2147483647,N=6e4,F=N/3,te=1e3,re=5,ne=20,O=10,h=6048e5,oe=(o,_)=>{const E=_?.initialDelayMs??p.initialDelayMs,D=_?.backoffMultiplier??p.backoffMultiplier,L=_?.maxDelayMs??p.maxDelayMs;return Math.min(L,E*D**Math.max(0,o-1))},ie=(o,_={})=>{o.exec(`CREATE TABLE IF NOT EXISTS _lunora_scheduler_jobs (
2
- id TEXT PRIMARY KEY,
3
- function_path TEXT NOT NULL,
4
- args BLOB NOT NULL,
5
- scheduled_for INTEGER NOT NULL,
6
- attempts INTEGER NOT NULL DEFAULT 0,
7
- retry BLOB,
8
- state TEXT NOT NULL DEFAULT 'pending'
9
- )`);const E=e=>o.prepare("PRAGMA table_info(_lunora_scheduler_jobs)").all().some(t=>t.name===e),D=e=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},L=e=>{for(let t=0;;t+=1)try{o.exec(`ALTER TABLE _lunora_scheduler_jobs ADD COLUMN ${e} INTEGER`);return}catch(r){if(E(e))return;if(!(r instanceof Error&&"code"in r&&r.code==="SQLITE_BUSY")||t>=re)throw r;D(ne*2**t)}};for(const e of["claimed_at","completed_at"])E(e)||L(e);o.exec("CREATE INDEX IF NOT EXISTS _lunora_scheduler_jobs_state_completed ON _lunora_scheduler_jobs (state, completed_at)"),o.exec(`CREATE TABLE IF NOT EXISTS _lunora_scheduler_crons (
10
- key TEXT PRIMARY KEY,
11
- expression TEXT NOT NULL,
12
- function_path TEXT NOT NULL,
13
- args BLOB NOT NULL
14
- )`);const P=o.prepare("INSERT INTO _lunora_scheduler_jobs (id, function_path, args, scheduled_for, retry) VALUES (?, ?, ?, ?, ?)"),y=o.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE id = ?"),R=o.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE state = ? ORDER BY scheduled_for"),k=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'canceled', completed_at = ? WHERE id = ? AND state = 'pending'"),v=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ?"),g=o.prepare("DELETE FROM _lunora_scheduler_jobs WHERE state IN ('succeeded', 'canceled') AND completed_at <= ?"),B=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'succeeded', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ?"),H=o.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND claimed_at = ? AND state = 'pending'"),J=o.prepare("UPDATE _lunora_scheduler_jobs SET attempts = ?, scheduled_for = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),W=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),X=o.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND state = 'pending' AND scheduled_for <= ? AND (claimed_at IS NULL OR claimed_at < ?) RETURNING *"),Y=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'pending', attempts = 0, completed_at = NULL, scheduled_for = ? WHERE id = ? AND state = 'dead'"),G=o.prepare(`INSERT INTO _lunora_scheduler_crons (key, expression, function_path, args) VALUES (?, ?, ?, ?)
15
- ON CONFLICT (key) DO UPDATE SET expression = excluded.expression, args = excluded.args`),$=o.prepare("SELECT * FROM _lunora_scheduler_crons"),a=()=>o.open,T=()=>o.inTransaction,x=e=>e===null?void 0:U(e);let s=!1;const S=async()=>{s||!a()||!T()||(await new Promise(e=>{setTimeout(e,O).unref()}),await S())},i=new Map,m=new Map,I=e=>({attempts:e.attempts,functionPath:e.function_path,id:e.id,scheduledFor:e.scheduled_for}),M=e=>{const t=i.get(e);t!==void 0&&(clearTimeout(t),i.delete(e))},l=(e,t)=>{M(e);const r=Math.max(0,t-Date.now());if(r>A){const c=setTimeout(()=>{l(e,t)},A);i.set(e,c);return}const n=setTimeout(()=>{K(e).catch(()=>{})},r);i.set(e,n)},V=e=>{const t=y.get(e);!s&&t?.state==="pending"&&l(e,t.claimed_at===null?t.scheduled_for:t.claimed_at+N)},q=(e,t)=>{if(T()){s||l(e,t+O);return}try{const r=X.get(t,e,t,t-N);return r===void 0&&V(e),r}catch{!s&&a()&&l(e,Date.now()+te);return}},z=(e,t)=>{let r=t,n;const c=u=>{n=setTimeout(()=>{if(!a())return;if(T()){c(O);return}const d=Date.now();try{H.run(d,e,r).changes===1&&(r=d)}catch{}c(F)},u),n.unref()};return c(F),{release:()=>{clearTimeout(n)},stamp:()=>r}},K=async e=>{if(i.delete(e),!a())return;const t=Date.now(),r=q(e,t);if(r===void 0)return;const n=r.attempts+1,c=x(r.retry),u=z(e,t);try{if(await _.onDispatch?.(r.function_path,U(r.args),{attempts:n,id:e,scheduledFor:r.scheduled_for}),await S(),a()&&!T()){const d=Date.now();B.run(n,d,e,u.stamp()),g.run(d-h)}}catch{if(await S(),s||!a())return;const d=c?.maxAttempts??p.maxAttempts;if(n>=d){W.run(n,Date.now(),e,u.stamp());return}const C=Date.now()+oe(n,c);J.run(n,C,e,u.stamp()).changes===1&&l(e,C)}finally{u.release()}},f=e=>{const t=m.get(e.key);t!==void 0&&clearTimeout(t);let r;try{r=b(e.expression,j).next().getTime()}catch{return}const n=Math.max(0,r-Date.now());if(n>A){m.set(e.key,setTimeout(()=>{f(e)},A));return}const c=setTimeout(()=>{m.delete(e.key),(async()=>{try{await _.onDispatch?.(e.function_path,U(e.args),{attempts:0,id:`${e.key}:${String(r)}`,scheduledFor:r})}catch{}!s&&a()&&f(e)})().catch(()=>{})},n);m.set(e.key,c)},Q={cancel:async e=>{if(s)return!1;M(e);const t=Date.now(),r=k.run(t,e).changes>0;return g.run(t-h),r},cron:async(e,t,r)=>{if(s)throw new Error("platform closed: cannot register a cron");b(e,j);const n={args:w(r??{}),expression:e,function_path:t,key:`${e} ${t}`};G.run(n.key,n.expression,n.function_path,n.args),f(n)},deadLetter:{list:async()=>s||!a()?[]:R.all("dead").map(e=>I(e)),requeue:async e=>{if(s||!a())return!1;const t=Date.now();return Y.run(t,e).changes===0?!1:(l(e,t),!0)}},get:async e=>{const t=s||!a()?void 0:y.get(e);if(t===void 0||t.completed_at!==null&&t.state!=="dead"&&t.completed_at<=Date.now()-h)return null;const r={canceled:"canceled",dead:"failed",pending:"pending",succeeded:"succeeded"},n=t.state==="pending"&&t.claimed_at!==null&&t.claimed_at>=Date.now()-N,c={...I(t),state:n?"running":r[t.state]};return t.completed_at!==null&&(c.completedAt=t.completed_at),c},list:async()=>s||!a()?[]:R.all("pending").map(e=>I(e)),schedule:async(e,t,r)=>{if(s)throw new Error("platform closed: cannot schedule a job");if(r?.retry?.forever===!0)throw new ee("INVALID_INPUT","retry.forever is not supported by the Node scheduler host; set a finite retry.maxAttempts");const n=`node-job-${Z()}`;let c;return r?.at===void 0?c=Date.now()+(r?.delayMs??0):c=typeof r.at=="number"?r.at:r.at.getTime(),P.run(n,e,w(t),c,r?.retry===void 0?null:w(r.retry)),l(n,c),{id:n,scheduledFor:c}}};g.run(Date.now()-h);for(const e of R.all("pending"))l(e.id,e.scheduled_for);for(const e of $.all())f(e);return{dispose:()=>{for(const e of i.values())clearTimeout(e);for(const e of m.values())clearTimeout(e);i.clear(),m.clear(),s=!0},scheduler:Q,simulateDeadLetter:async e=>{const t=y.get(e);if(t?.state!=="pending")return!1;M(e);const r=x(t.retry);return v.run((r?.maxAttempts??p.maxAttempts)+1,Date.now(),e),!0}}};export{ie as createNodeSchedulerHost};