@lunora/platform-node 1.0.0-alpha.226 → 1.0.0-alpha.228
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +42 -12
- package/dist/index.d.ts +42 -12
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{checkNodeAppHost-tF2DzWaY.mjs → checkNodeAppHost-BW69Ja4_.mjs} +1 -1
- package/dist/packem_shared/createNodeHttpServer-CKwkBmRI.mjs +4 -0
- package/dist/packem_shared/{createNodeMailHost-DrUo8de-.mjs → createNodeMailHost-AOATqXEM.mjs} +1 -1
- package/dist/packem_shared/{createNodePlatform-wUZZ-3Eb.mjs → createNodePlatform-Dr9tUfyX.mjs} +1 -1
- package/dist/packem_shared/createNodeQueueHost--kuV6C8-.mjs +17 -0
- package/dist/packem_shared/createNodeShardKvStore-Bh6oQZgs.mjs +1 -0
- package/dist/packem_shared/{createNodeShardRegistry-D1r6M8Rg.mjs → createNodeShardRegistry-DEn0kYmG.mjs} +1 -1
- package/dist/packem_shared/{createNodeSocketHost-ByOmEGFe.mjs → createNodeSocketHost-BJf5HOHr.mjs} +1 -1
- package/dist/packem_shared/node-socket-pair-BsiTm62u.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/createNodeHttpServer-cUx4J9Z9.mjs +0 -4
- package/dist/packem_shared/createNodeQueueHost-glQ8GNCA.mjs +0 -17
- package/dist/packem_shared/createNodeShardKvStore-DVi1OsvH.mjs +0 -1
- package/dist/packem_shared/node-socket-pair-0baNnoFw.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NODE_CAPABILITIES as g}from"@lunora/platform";import{createNodeShardKvStore as D}from"../packem_shared/createNodeShardKvStore-
|
|
1
|
+
import{NODE_CAPABILITIES as g}from"@lunora/platform";import{createNodeShardKvStore as D}from"../packem_shared/createNodeShardKvStore-Bh6oQZgs.mjs";import{createNodeSchedulerHost as k}from"../packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as T}from"../packem_shared/createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-DEn0kYmG.mjs";import{createNodeSocketHost as b}from"../packem_shared/createNodeSocketHost-BJf5HOHr.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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, SocketHandle, SocketHost,
|
|
1
|
+
import { QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, ShardKvListOptions, ShardKvStore, SocketHandle, SocketHost, DirectShardDirectory, PlatformCapabilities, R2BucketLike } from '@lunora/platform';
|
|
2
2
|
import { SchemaLike } from '@lunora/shard-engine';
|
|
3
3
|
import { SqlCtxDbOptions, SqlCtxExec, createSqlCtxDb } from '@lunora/sql-store';
|
|
4
4
|
import Database from 'better-sqlite3';
|
|
@@ -293,9 +293,11 @@ interface NodeQueueHost<Queues extends Record<string, {
|
|
|
293
293
|
/** The caller's `env` plus one `QUEUE_<EXPORT>` binding per queue. */
|
|
294
294
|
readonly env: Record<string, unknown>;
|
|
295
295
|
/**
|
|
296
|
-
* Deliver
|
|
297
|
-
*
|
|
298
|
-
*
|
|
296
|
+
* Deliver the batches currently due, queue by queue, and return how many
|
|
297
|
+
* batches were delivered. Each queue gets at least one batch, then further
|
|
298
|
+
* ones while the poll is inside its time budget. Drives the consumer —
|
|
299
|
+
* nothing here runs on a timer, because this host has no dev server to own
|
|
300
|
+
* one yet.
|
|
299
301
|
*/
|
|
300
302
|
poll: (now?: number) => Promise<number>;
|
|
301
303
|
}
|
|
@@ -503,10 +505,42 @@ interface NodeShardHostParts {
|
|
|
503
505
|
takeFailures: () => string[];
|
|
504
506
|
}
|
|
505
507
|
declare const createNodeShardHost: (options?: NodeShardHostOptions) => NodeShardHostParts;
|
|
508
|
+
/**
|
|
509
|
+
* `ShardKvListOptions` plus the paging options `DurableObjectStorage.list` has. The contract leaves
|
|
510
|
+
* them out on purpose (Cloudflare's `ShardKvStore` would spend a `limit` on hidden secret records);
|
|
511
|
+
* the Node storage bridge emulates `state.storage`, whose callers pass them, so this store serves them
|
|
512
|
+
* with Cloudflare's meanings. A key it does not know throws rather than being ignored.
|
|
513
|
+
*/
|
|
514
|
+
interface NodeShardKvListOptions extends ShardKvListOptions {
|
|
515
|
+
/** Only keys below this one. Exclusive, in either direction. */
|
|
516
|
+
end?: string;
|
|
517
|
+
/** At most this many keys, counted from the end the listing starts at. A positive integer. */
|
|
518
|
+
limit?: number;
|
|
519
|
+
/** List in descending key order. `start`, `startAfter` and `end` keep their meaning. */
|
|
520
|
+
reverse?: boolean;
|
|
521
|
+
/** Only keys at or above this one. Not together with `startAfter`. */
|
|
522
|
+
start?: string;
|
|
523
|
+
/** Only keys above this one. Not together with `start`. */
|
|
524
|
+
startAfter?: string;
|
|
525
|
+
}
|
|
526
|
+
/** A `ShardKvStore` whose `list` also takes the paging options. Keys always come back in key order. */
|
|
527
|
+
interface NodeShardKvStore extends ShardKvStore {
|
|
528
|
+
list: <T = unknown>(options?: NodeShardKvListOptions) => Promise<Map<string, T>>;
|
|
529
|
+
}
|
|
530
|
+
/** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
|
|
531
|
+
declare const createNodeShardKvStore: (database: Database.Database) => NodeShardKvStore;
|
|
532
|
+
/** Every frame type a `SocketHandle` may be handed. `ws` sends each of them, a Blob by its `size`. */
|
|
533
|
+
type OutboundFrame = Parameters<SocketHandle["send"]>[0];
|
|
506
534
|
/** The end a shard accepts. Its `send` and `close` are what the socket host calls through its handle. */
|
|
507
535
|
interface NodeServerEnd {
|
|
536
|
+
/**
|
|
537
|
+
* Outbound bytes not yet on the wire: the attached transport's own buffer, or before the handshake
|
|
538
|
+
* the frames still queued. A getter, so the socket host's adopted handle (this very object) stays
|
|
539
|
+
* live; the engine's drain wait reads it before each frame it streams.
|
|
540
|
+
*/
|
|
541
|
+
readonly bufferedAmount: number;
|
|
508
542
|
close: (code?: number, reason?: string) => void;
|
|
509
|
-
send: (data:
|
|
543
|
+
send: (data: OutboundFrame) => void;
|
|
510
544
|
}
|
|
511
545
|
/**
|
|
512
546
|
* The socket-host half of a Node platform instance, plus the test-only hooks
|
|
@@ -553,7 +587,7 @@ interface NodeShard {
|
|
|
553
587
|
*/
|
|
554
588
|
inbound: Pick<NodeSocketHost, "onClose" | "onMessage">;
|
|
555
589
|
/** Durable key-value storage on this shard's database. */
|
|
556
|
-
kv:
|
|
590
|
+
kv: NodeShardKvStore;
|
|
557
591
|
/** Single-writer execution, local SQL, transactions, durable alarms. */
|
|
558
592
|
shard: ShardHost;
|
|
559
593
|
/** The key this shard serves. */
|
|
@@ -1061,8 +1095,6 @@ interface NodeHyperdriveBinding {
|
|
|
1061
1095
|
* @param url A `postgres://`, `postgresql://`, `mysql://` or `mariadb://` URL; `DATABASE_URL` unless given.
|
|
1062
1096
|
*/
|
|
1063
1097
|
declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
|
|
1064
|
-
/** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
|
|
1065
|
-
declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
|
|
1066
1098
|
interface NodeProfileHandlerOptions {
|
|
1067
1099
|
/** The bearer a caller must present. Required and non-empty: an empty token would make the endpoint open to anyone. */
|
|
1068
1100
|
token: string;
|
|
@@ -1138,9 +1170,7 @@ interface NodeShardState {
|
|
|
1138
1170
|
deleteAlarm: () => Promise<void>;
|
|
1139
1171
|
get: <T = unknown>(key: string) => Promise<T | undefined>;
|
|
1140
1172
|
getAlarm: () => Promise<number | null>;
|
|
1141
|
-
list: <T = unknown>(options?:
|
|
1142
|
-
prefix?: string;
|
|
1143
|
-
}) => Promise<Map<string, T>>;
|
|
1173
|
+
list: <T = unknown>(options?: NodeShardKvListOptions) => Promise<Map<string, T>>;
|
|
1144
1174
|
put: (key: string, value: unknown) => Promise<void>;
|
|
1145
1175
|
setAlarm: (scheduledTime: Date | number) => Promise<void>;
|
|
1146
1176
|
sql: {
|
|
@@ -1402,4 +1432,4 @@ type DrainTimer,
|
|
|
1402
1432
|
* plane to deploy to and no `wrangler`-equivalent to shell out to, which is why
|
|
1403
1433
|
* the deploy stops at a build context. See `plans/234-node-host-findings.md`.
|
|
1404
1434
|
*/
|
|
1405
|
-
type Drainable, type MailParkReason, NODE_SCHEDULER_DISPATCH_PATH, type NodeAppDurableObjectBinding, type NodeAppHost, type NodeAppHostOptions, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeDurableObjectClass, type NodeDurableObjectInstance, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodeMailHost, type NodeMailHostOptions, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformMailOptions, 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, checkNodeAppHost, createNodeAppHost, createNodeDispatchRoute, createNodeDurableObjectFactory, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodeMailHost, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore, drainTogether };
|
|
1435
|
+
type Drainable, type MailParkReason, NODE_SCHEDULER_DISPATCH_PATH, type NodeAppDurableObjectBinding, type NodeAppHost, type NodeAppHostOptions, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeDurableObjectClass, type NodeDurableObjectInstance, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodeMailHost, type NodeMailHostOptions, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformMailOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardKvListOptions, type NodeShardKvStore, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, checkNodeAppHost, createNodeAppHost, createNodeDispatchRoute, createNodeDurableObjectFactory, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodeMailHost, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore, drainTogether };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, SocketHandle, SocketHost,
|
|
1
|
+
import { QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, ShardKvListOptions, ShardKvStore, SocketHandle, SocketHost, DirectShardDirectory, PlatformCapabilities, R2BucketLike } from '@lunora/platform';
|
|
2
2
|
import { SchemaLike } from '@lunora/shard-engine';
|
|
3
3
|
import { SqlCtxDbOptions, SqlCtxExec, createSqlCtxDb } from '@lunora/sql-store';
|
|
4
4
|
import Database from 'better-sqlite3';
|
|
@@ -293,9 +293,11 @@ interface NodeQueueHost<Queues extends Record<string, {
|
|
|
293
293
|
/** The caller's `env` plus one `QUEUE_<EXPORT>` binding per queue. */
|
|
294
294
|
readonly env: Record<string, unknown>;
|
|
295
295
|
/**
|
|
296
|
-
* Deliver
|
|
297
|
-
*
|
|
298
|
-
*
|
|
296
|
+
* Deliver the batches currently due, queue by queue, and return how many
|
|
297
|
+
* batches were delivered. Each queue gets at least one batch, then further
|
|
298
|
+
* ones while the poll is inside its time budget. Drives the consumer —
|
|
299
|
+
* nothing here runs on a timer, because this host has no dev server to own
|
|
300
|
+
* one yet.
|
|
299
301
|
*/
|
|
300
302
|
poll: (now?: number) => Promise<number>;
|
|
301
303
|
}
|
|
@@ -503,10 +505,42 @@ interface NodeShardHostParts {
|
|
|
503
505
|
takeFailures: () => string[];
|
|
504
506
|
}
|
|
505
507
|
declare const createNodeShardHost: (options?: NodeShardHostOptions) => NodeShardHostParts;
|
|
508
|
+
/**
|
|
509
|
+
* `ShardKvListOptions` plus the paging options `DurableObjectStorage.list` has. The contract leaves
|
|
510
|
+
* them out on purpose (Cloudflare's `ShardKvStore` would spend a `limit` on hidden secret records);
|
|
511
|
+
* the Node storage bridge emulates `state.storage`, whose callers pass them, so this store serves them
|
|
512
|
+
* with Cloudflare's meanings. A key it does not know throws rather than being ignored.
|
|
513
|
+
*/
|
|
514
|
+
interface NodeShardKvListOptions extends ShardKvListOptions {
|
|
515
|
+
/** Only keys below this one. Exclusive, in either direction. */
|
|
516
|
+
end?: string;
|
|
517
|
+
/** At most this many keys, counted from the end the listing starts at. A positive integer. */
|
|
518
|
+
limit?: number;
|
|
519
|
+
/** List in descending key order. `start`, `startAfter` and `end` keep their meaning. */
|
|
520
|
+
reverse?: boolean;
|
|
521
|
+
/** Only keys at or above this one. Not together with `startAfter`. */
|
|
522
|
+
start?: string;
|
|
523
|
+
/** Only keys above this one. Not together with `start`. */
|
|
524
|
+
startAfter?: string;
|
|
525
|
+
}
|
|
526
|
+
/** A `ShardKvStore` whose `list` also takes the paging options. Keys always come back in key order. */
|
|
527
|
+
interface NodeShardKvStore extends ShardKvStore {
|
|
528
|
+
list: <T = unknown>(options?: NodeShardKvListOptions) => Promise<Map<string, T>>;
|
|
529
|
+
}
|
|
530
|
+
/** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
|
|
531
|
+
declare const createNodeShardKvStore: (database: Database.Database) => NodeShardKvStore;
|
|
532
|
+
/** Every frame type a `SocketHandle` may be handed. `ws` sends each of them, a Blob by its `size`. */
|
|
533
|
+
type OutboundFrame = Parameters<SocketHandle["send"]>[0];
|
|
506
534
|
/** The end a shard accepts. Its `send` and `close` are what the socket host calls through its handle. */
|
|
507
535
|
interface NodeServerEnd {
|
|
536
|
+
/**
|
|
537
|
+
* Outbound bytes not yet on the wire: the attached transport's own buffer, or before the handshake
|
|
538
|
+
* the frames still queued. A getter, so the socket host's adopted handle (this very object) stays
|
|
539
|
+
* live; the engine's drain wait reads it before each frame it streams.
|
|
540
|
+
*/
|
|
541
|
+
readonly bufferedAmount: number;
|
|
508
542
|
close: (code?: number, reason?: string) => void;
|
|
509
|
-
send: (data:
|
|
543
|
+
send: (data: OutboundFrame) => void;
|
|
510
544
|
}
|
|
511
545
|
/**
|
|
512
546
|
* The socket-host half of a Node platform instance, plus the test-only hooks
|
|
@@ -553,7 +587,7 @@ interface NodeShard {
|
|
|
553
587
|
*/
|
|
554
588
|
inbound: Pick<NodeSocketHost, "onClose" | "onMessage">;
|
|
555
589
|
/** Durable key-value storage on this shard's database. */
|
|
556
|
-
kv:
|
|
590
|
+
kv: NodeShardKvStore;
|
|
557
591
|
/** Single-writer execution, local SQL, transactions, durable alarms. */
|
|
558
592
|
shard: ShardHost;
|
|
559
593
|
/** The key this shard serves. */
|
|
@@ -1061,8 +1095,6 @@ interface NodeHyperdriveBinding {
|
|
|
1061
1095
|
* @param url A `postgres://`, `postgresql://`, `mysql://` or `mariadb://` URL; `DATABASE_URL` unless given.
|
|
1062
1096
|
*/
|
|
1063
1097
|
declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
|
|
1064
|
-
/** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
|
|
1065
|
-
declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
|
|
1066
1098
|
interface NodeProfileHandlerOptions {
|
|
1067
1099
|
/** The bearer a caller must present. Required and non-empty: an empty token would make the endpoint open to anyone. */
|
|
1068
1100
|
token: string;
|
|
@@ -1138,9 +1170,7 @@ interface NodeShardState {
|
|
|
1138
1170
|
deleteAlarm: () => Promise<void>;
|
|
1139
1171
|
get: <T = unknown>(key: string) => Promise<T | undefined>;
|
|
1140
1172
|
getAlarm: () => Promise<number | null>;
|
|
1141
|
-
list: <T = unknown>(options?:
|
|
1142
|
-
prefix?: string;
|
|
1143
|
-
}) => Promise<Map<string, T>>;
|
|
1173
|
+
list: <T = unknown>(options?: NodeShardKvListOptions) => Promise<Map<string, T>>;
|
|
1144
1174
|
put: (key: string, value: unknown) => Promise<void>;
|
|
1145
1175
|
setAlarm: (scheduledTime: Date | number) => Promise<void>;
|
|
1146
1176
|
sql: {
|
|
@@ -1402,4 +1432,4 @@ type DrainTimer,
|
|
|
1402
1432
|
* plane to deploy to and no `wrangler`-equivalent to shell out to, which is why
|
|
1403
1433
|
* the deploy stops at a build context. See `plans/234-node-host-findings.md`.
|
|
1404
1434
|
*/
|
|
1405
|
-
type Drainable, type MailParkReason, NODE_SCHEDULER_DISPATCH_PATH, type NodeAppDurableObjectBinding, type NodeAppHost, type NodeAppHostOptions, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeDurableObjectClass, type NodeDurableObjectInstance, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodeMailHost, type NodeMailHostOptions, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformMailOptions, 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, checkNodeAppHost, createNodeAppHost, createNodeDispatchRoute, createNodeDurableObjectFactory, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodeMailHost, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore, drainTogether };
|
|
1435
|
+
type Drainable, type MailParkReason, NODE_SCHEDULER_DISPATCH_PATH, type NodeAppDurableObjectBinding, type NodeAppHost, type NodeAppHostOptions, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeDurableObjectClass, type NodeDurableObjectInstance, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodeMailHost, type NodeMailHostOptions, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformMailOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardKvListOptions, type NodeShardKvStore, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, checkNodeAppHost, createNodeAppHost, createNodeDispatchRoute, createNodeDurableObjectFactory, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodeMailHost, 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{DEFAULT_DRAIN_TIMEOUT_MS as o,drainTogether as t}from"./packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{checkNodeAppHost as c,createNodeAppHost as d}from"./packem_shared/checkNodeAppHost-
|
|
1
|
+
import{DEFAULT_DRAIN_TIMEOUT_MS as o,drainTogether as t}from"./packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{checkNodeAppHost as c,createNodeAppHost as d}from"./packem_shared/checkNodeAppHost-BW69Ja4_.mjs";import{N,c as f}from"./packem_shared/node-dispatch-route-DjQWVUkP.mjs";import{createNodeDurableObjectFactory as x}from"./packem_shared/createNodeDurableObjectFactory-hAwJt_pN.mjs";import{createNodeGlobalStore as s,createNodeSqlExec as H}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeHttpServer as h}from"./packem_shared/createNodeHttpServer-CKwkBmRI.mjs";import{createNodeHyperdrive as D}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as u}from"./packem_shared/createNodeShardKvStore-Bh6oQZgs.mjs";import{createNodeMailHost as E}from"./packem_shared/createNodeMailHost-AOATqXEM.mjs";import{createNodePlatform as _}from"./packem_shared/createNodePlatform-Dr9tUfyX.mjs";import{createNodeProfileHandler as R}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as P}from"./packem_shared/createNodeQueueHost--kuV6C8-.mjs";import{createNodeR2Bucket as v}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as I}from"./packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeSecretBindings as O}from"./packem_shared/createNodeSecretBindings-C7wh0fOm.mjs";import{createNodeShardHost as w}from"./packem_shared/createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardNamespace as C}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as L}from"./packem_shared/createNodeShardRegistry-DEn0kYmG.mjs";import{bindShardSockets as j,createNodeShardState as q}from"./packem_shared/bindShardSockets-DjLmRlIA.mjs";import{createNodeSocketHost as K}from"./packem_shared/createNodeSocketHost-BJf5HOHr.mjs";import{createNodeWorkflowHost as z}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as V}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{o as DEFAULT_DRAIN_TIMEOUT_MS,N as NODE_SCHEDULER_DISPATCH_PATH,j as bindShardSockets,c as checkNodeAppHost,d as createNodeAppHost,f as createNodeDispatchRoute,x as createNodeDurableObjectFactory,s as createNodeGlobalStore,h as createNodeHttpServer,D as createNodeHyperdrive,E as createNodeMailHost,_ as createNodePlatform,R as createNodeProfileHandler,P as createNodeQueueHost,v as createNodeR2Bucket,I as createNodeSchedulerHost,O as createNodeSecretBindings,w as createNodeShardHost,u as createNodeShardKvStore,C as createNodeShardNamespace,L as createNodeShardRegistry,q as createNodeShardState,K as createNodeSocketHost,H as createNodeSqlExec,z as createNodeWorkflowHost,V as createNodeWorkflowStore,t as drainTogether};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as p,existsSync as m,realpathSync as h,lstatSync as g}from"node:fs";import{join as f,relative as y,isAbsolute as O}from"node:path";import{LunoraError as i}from"@lunora/errors";import{drainTimeoutMs as k,drainTogether as A,startDrainDeadline as R,settlesBefore as D}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeDurableObjectFactory as $}from"./createNodeDurableObjectFactory-hAwJt_pN.mjs";import{walkDeclaredCrons as N,createNodePlatform as v}from"./createNodePlatform-
|
|
1
|
+
import{mkdirSync as p,existsSync as m,realpathSync as h,lstatSync as g}from"node:fs";import{join as f,relative as y,isAbsolute as O}from"node:path";import{LunoraError as i}from"@lunora/errors";import{drainTimeoutMs as k,drainTogether as A,startDrainDeadline as R,settlesBefore as D}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeDurableObjectFactory as $}from"./createNodeDurableObjectFactory-hAwJt_pN.mjs";import{walkDeclaredCrons as N,createNodePlatform as v}from"./createNodePlatform-Dr9tUfyX.mjs";import{createNodeShardNamespace as I}from"./createNodeShardNamespace-BgQjDv7V.mjs";const w=e=>{const r=new Set;let a=0;const t=()=>{const n=a===0?[]:[`${String(a)} ${e.label} failed`];return a=0,n},o=()=>r.size===0?[]:[`${String(r.size)} ${e.label}`];return{drain:async n=>{const c=R(n);try{for(;r.size>0;)if(!await D(Promise.all(r),c))return{failed:t(),pending:o(),timedOut:!0};return{failed:t(),pending:[],timedOut:!1}}finally{c.cancel()}},idle:()=>r.size===0,pending:o,track:n=>{const c=Promise.resolve(n).then(()=>{},d=>{e.reportFailures&&(a+=1,console.error("[@lunora/platform-node] work handed to waitUntil failed:",d))}).finally(()=>r.delete(c));r.add(c)}}},b=e=>{const r=[];for(const a of e)try{a.close({force:!0})}catch(t){r.push(t)}if(r.length>0)throw new AggregateError(r,`@lunora/platform-node: ${String(r.length)} platform(s) failed to close`)},S=e=>typeof e=="object"&&e!==null&&typeof e.fetch=="function",j=(e,r,a,t)=>{const o=$(r.worker[e.className],a);return v({crons:e.name===t?r.crons??{}:void 0,directory:r.dataDirectory===void 0?void 0:f(r.dataDirectory,e.name),onAlarm:async n=>{n!==void 0&&await(await o(n)).alarm?.()},onFetch:async(n,c)=>(await o(c)).fetch(n),path:r.dataDirectory===void 0?void 0:f(r.dataDirectory,`${e.name}.platform.sqlite3`)})},E=/^[A-Za-z_$][\w$]*$/u,L=(e,r)=>{const a=y(e,r);return a!==""&&!a.startsWith("..")&&!O(a)},T=(e,r)=>{if(!E.test(e))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${JSON.stringify(e)} is not a valid binding name (a JavaScript identifier such as SHARD), and its name becomes a directory under the data directory`);if(r===void 0||!m(r))return;const a=h(r);for(const t of[f(r,e),f(r,`${e}.platform.sqlite3`)]){let o;try{o=g(t)}catch{continue}if(o.isSymbolicLink()&&!m(t))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${e} would store data outside ${r}: ${t} is a link to nothing, which SQLite would follow`);if(!L(a,h(t)))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${e} would store data outside ${r}: ${t} links out of it`)}},_=e=>{const r=new Map;for(const{name:a}of e){const t=r.get(a.toLowerCase());if(t!==void 0)throw new i("VALIDATION_ERROR",t===a?`@lunora/platform-node: Durable Object binding ${a} is declared twice, and both would share one shard directory and platform database`:`@lunora/platform-node: Durable Object bindings ${t} and ${a} differ only in case, so on a case-insensitive volume they would share one shard directory and platform database — rename one`);r.set(a.toLowerCase(),a)}},P=e=>{if(typeof e!="function")return!1;try{return Reflect.construct(String,[],e),!0}catch{return!1}},x=e=>{if(!S(e.worker.default))throw new i("VALIDATION_ERROR","@lunora/platform-node: the worker module has no default export with a `fetch` handler");_(e.durableObjects);for(const t of e.durableObjects){T(t.name,e.dataDirectory);const o=Object.hasOwn(e.worker,t.className)?e.worker[t.className]:void 0;if(o===void 0)throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${t.name} names class ${t.className}, which the worker module does not export`);if(!P(o))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${t.name} names ${t.className}, which the worker module exports as something \`new\` cannot construct`)}const r=e.shardBinding??"SHARD";if(N(e.crons??{}).length>0&&!e.durableObjects.some(t=>t.name===r))throw new i("VALIDATION_ERROR",`@lunora/platform-node: the app declares crons, but no Durable Object binding is named ${r} to run them on`)},M=e=>{x(e);const r=e.worker.default,a={...e.env},t=[],o=w({label:"worker waitUntil task(s)",reportFailures:!0}),n=w({label:"worker request(s)",reportFailures:!1}),c=e.shardBinding??"SHARD";e.dataDirectory!==void 0&&p(e.dataDirectory,{recursive:!0});try{for(const s of e.durableObjects){const l=j(s,e,a,c);t.push(l),Object.defineProperty(a,s.name,{configurable:!0,enumerable:!0,value:I(l.directory),writable:!0})}}catch(s){try{b(t.splice(0))}catch(l){console.error("[@lunora/platform-node] closing the platforms of a host that failed to compose failed:",l)}throw s}const d={passThroughOnException:()=>{},waitUntil:o.track};let u;return{close:async s=>(k(s),u??=(async()=>{try{return await A([n,o,...t],s)}finally{b(t.splice(0))}})(),u),fetch:async s=>{const l=Promise.resolve(r.fetch(s,a,d));return n.track(l),l},rearmPersistedAlarms:()=>t.flatMap(s=>s.rearmPersistedAlarms())}};export{x as checkNodeAppHost,M as createNodeAppHost};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{once as A}from"node:events";import{createServer as U}from"node:http";import{WebSocketServer as B}from"ws";import{startDrainDeadline as H,settlesBefore as _}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{t as x}from"./node-socket-pair-BsiTm62u.mjs";const R=e=>e.includes(":")&&!e.startsWith("[")?`[${e}]`:e,C=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},D=/^(?:127\.\d+\.\d+\.\d+|::1|localhost)$/,O=1048576,P=5e3,q=(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,P),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>O){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=q(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]??"/"}`,M=e=>(e.headers.get("content-type")??"").toLowerCase().startsWith("text/event-stream"),N=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),M(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()},Y=65536,T=async(e,t,c=0)=>{const s=await e.read();if(s.done)return t;const o=Y-c;return s.value.byteLength>=o?(t.push(s.value.subarray(0,o)),await e.cancel().catch(()=>{}),t):(t.push(s.value),T(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 T(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]))},G=4*1024*1024,J=async e=>{const t=e.host??"127.0.0.1",c=e.origin===void 0?void 0:C(e.origin);if(c===void 0&&!D.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 B({maxPayload:G,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=>N(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 $=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=x(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)=>{$(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=>A(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=H(i);f=!0,b().catch(()=>{}),n.closeIdleConnections();const d=new Map(l),p=await _(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};
|
package/dist/packem_shared/{createNodeMailHost-DrUo8de-.mjs → createNodeMailHost-AOATqXEM.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{AsyncLocalStorage as te}from"node:async_hooks";import{createHash as re}from"node:crypto";import{LunoraError as O}from"@lunora/errors";import{shouldCaptureMail as ne,createMailerFromEnv as ie,createMailer as V,assertValidIdempotencyKey as oe,consumeQueuedSend as ae,MailSendError as se,isRetryableMailError as le,isOutcomeUnknownMailError as Y}from"@lunora/mail";import{defineQueue as _e}from"@lunora/queue";import{createNodeQueueHost as ce,allowReservedQueueName as ue,RESERVED_MAIL_QUEUE_NAME as Ee,preparedSendOf as de}from"./createNodeQueueHost
|
|
1
|
+
import{AsyncLocalStorage as te}from"node:async_hooks";import{createHash as re}from"node:crypto";import{LunoraError as O}from"@lunora/errors";import{shouldCaptureMail as ne,createMailerFromEnv as ie,createMailer as V,assertValidIdempotencyKey as oe,consumeQueuedSend as ae,MailSendError as se,isRetryableMailError as le,isOutcomeUnknownMailError as Y}from"@lunora/mail";import{defineQueue as _e}from"@lunora/queue";import{createNodeQueueHost as ce,allowReservedQueueName as ue,RESERVED_MAIL_QUEUE_NAME as Ee,preparedSendOf as de}from"./createNodeQueueHost--kuV6C8-.mjs";const A=Ee,G=10,M=3,pe=30,k=6e4,U=G*(k+4*1e4)+6e4,Q=180,h=15*864e5,H="CASE WHEN content_type = 'json' AND json_valid(CAST(body AS TEXT)) THEN json_extract(CAST(body AS TEXT), '$.idempotencyKey') END",C=h,me=3,J=(e,t=0)=>e instanceof Error?{message:e.message,name:e.name,stack:e.stack,...e.cause!==void 0&&t<me&&{cause:J(e.cause,t+1)}}:{message:String(e)},T=(e,t,r,i)=>{const _=JSON.stringify({attempts:r,error:J(i),event:t,queue:A});console[e](`[@lunora/platform-node] ${_}`)},Te="sending ",j="failed ",b=6e4,Ne=(e,t,r)=>{e.exec("CREATE TABLE IF NOT EXISTS _lunora_mail_sent (key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER NOT NULL)"),e.exec("CREATE INDEX IF NOT EXISTS _lunora_mail_sent_expires ON _lunora_mail_sent (expires_at)");const i=e.prepare("SELECT value FROM _lunora_mail_sent WHERE key = ? AND expires_at > ?"),_=e.prepare("INSERT INTO _lunora_mail_sent (key, value, expires_at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at"),y=e.prepare("DELETE FROM _lunora_mail_sent WHERE expires_at <= ?"),N=e.prepare("DELETE FROM _lunora_mail_sent WHERE key = ?"),S=e.transaction((l,E,m)=>{_.run(l,E,m),r(l)}),L=e.transaction((l,E,m)=>{_.run(l,"failed",m),N.run(E)});let p=Number.NEGATIVE_INFINITY;return{get:async l=>i.get(l,t())?.value,put:async(l,E,{expirationTtl:m})=>{const f=t();if(E==="failed"&&l.startsWith(j)){const D=l.slice(j.length),x=`${Te}${D}`,R=Number.parseInt(D,10);try{L(l,x,f+m*1e3)}catch(v){T("warn","lunora.mail.attempt_mark_failed",R,v);try{N.run(x)}catch(g){T("error","lunora.mail.attempt_mark_orphaned",R,g)}}return}f-p>=b&&(y.run(f),p=f),l.includes(" ")?_.run(l,E,f+m*1e3):S.immediate(l,E,f+m*1e3)}}},$=e=>Array.isArray(e)?`[${e.map(t=>$(t)).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,r])=>r!==void 0).toSorted(([r],[i])=>r<i?-1:1).map(([r,i])=>`${JSON.stringify(r)}:${$(i)}`).join(",")}}`:JSON.stringify(e),F=e=>{const t=typeof e=="string"?[e]:e;return Array.isArray(t)&&t.length===0?void 0:t},fe=(e,t)=>{const r=e!==null&&typeof e=="object"?e:{};return re("sha256").update($({bcc:F(r.bcc),cc:F(r.cc),from:r.from??t,headers:r.headers,html:r.html,replyTo:r.replyTo,subject:r.subject,text:r.text,to:F(r.to)})).digest("hex")},Ae=(e,t,r)=>{e.exec("CREATE TABLE IF NOT EXISTS _lunora_mail_claims (key TEXT PRIMARY KEY, message_id TEXT NOT NULL, expires_at INTEGER NOT NULL)"),e.exec("CREATE INDEX IF NOT EXISTS _lunora_mail_claims_expires ON _lunora_mail_claims (expires_at)"),e.exec("CREATE TABLE IF NOT EXISTS _lunora_mail_keys (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, expires_at INTEGER NOT NULL)"),e.exec("CREATE INDEX IF NOT EXISTS _lunora_mail_keys_expires ON _lunora_mail_keys (expires_at)"),e.exec("CREATE TABLE IF NOT EXISTS _lunora_mail_deliveries (key TEXT PRIMARY KEY, delivery INTEGER NOT NULL, first_at INTEGER NOT NULL, expires_at INTEGER NOT NULL)"),e.exec("CREATE INDEX IF NOT EXISTS _lunora_mail_deliveries_expires ON _lunora_mail_deliveries (expires_at)");const i=e.prepare(`INSERT INTO _lunora_mail_claims (key, message_id, expires_at) VALUES (?, ?, ?)
|
|
2
2
|
ON CONFLICT (key) DO UPDATE SET message_id = excluded.message_id, expires_at = excluded.expires_at
|
|
3
3
|
WHERE _lunora_mail_claims.expires_at <= ? OR _lunora_mail_claims.message_id = excluded.message_id`),_=e.prepare("DELETE FROM _lunora_mail_claims WHERE key = ? AND message_id = ?"),y=e.prepare("SELECT fingerprint FROM _lunora_mail_keys WHERE key = ? AND expires_at > ?"),N=e.prepare("INSERT INTO _lunora_mail_keys (key, fingerprint, expires_at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET fingerprint = excluded.fingerprint, expires_at = excluded.expires_at"),S=e.prepare("DELETE FROM _lunora_mail_claims WHERE expires_at <= ?"),L=e.prepare("DELETE FROM _lunora_mail_keys WHERE expires_at <= ?"),p=`EXISTS (SELECT 1 FROM _lunora_queue_messages WHERE queue = '${A}' AND state IN ('pending', 'dead') AND ${H} = _lunora_mail_deliveries.key AND id <> @excluded AND enqueued_at < _lunora_mail_deliveries.expires_at)`;let l,E;const m=n=>{l??=e.prepare(`DELETE FROM _lunora_mail_deliveries WHERE NOT ${p} AND expires_at <= @now`),l.run({excluded:"",now:n})},f=(n,a,c,u)=>{const s=`_lunora_mail_deliveries.expires_at <= @now AND @enqueued >= _lunora_mail_deliveries.expires_at AND NOT ${p}`;return E??=e.prepare(`INSERT INTO _lunora_mail_deliveries (key, delivery, first_at, expires_at) VALUES (@key, 1, @now, @expires)
|
|
4
4
|
ON CONFLICT (key) DO UPDATE SET
|
package/dist/packem_shared/{createNodePlatform-wUZZ-3Eb.mjs → createNodePlatform-Dr9tUfyX.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readdirSync as j,lstatSync as X,readlinkSync as Y,statSync as $,realpathSync as F}from"node:fs";import{join as m,dirname as p,basename as M,resolve as N}from"node:path";import{LunoraError as d}from"@lunora/errors";import{NODE_CAPABILITIES as z}from"@lunora/platform";import Z from"better-sqlite3";import{a as ee,c as te,i as re,A as oe}from"./node-dispatch-route-DjQWVUkP.mjs";import{startDrainDeadline as P,settlesBefore as D,drainTimeoutMs as ae,drainTogether as se}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeGlobalStore as ne}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as ie}from"./createNodeShardKvStore-
|
|
1
|
+
import{readdirSync as j,lstatSync as X,readlinkSync as Y,statSync as $,realpathSync as F}from"node:fs";import{join as m,dirname as p,basename as M,resolve as N}from"node:path";import{LunoraError as d}from"@lunora/errors";import{NODE_CAPABILITIES as z}from"@lunora/platform";import Z from"better-sqlite3";import{a as ee,c as te,i as re,A as oe}from"./node-dispatch-route-DjQWVUkP.mjs";import{startDrainDeadline as P,settlesBefore as D,drainTimeoutMs as ae,drainTogether as se}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeGlobalStore as ne}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as ie}from"./createNodeShardKvStore-Bh6oQZgs.mjs";import{createNodeMailHost as de}from"./createNodeMailHost-AOATqXEM.mjs";import{createNodeQueueHost as le}from"./createNodeQueueHost--kuV6C8-.mjs";import{createNodeR2Bucket as ce}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as he}from"./createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as ue}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardRegistry as fe,SHARD_FILE_SUFFIX as k}from"./createNodeShardRegistry-DEn0kYmG.mjs";import{createNodeSocketHost as me}from"./createNodeSocketHost-BJf5HOHr.mjs";import{createNodeWorkflowHost as pe}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as we}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const ge="__root__",ye=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>{if(o.functionPath===void 0)throw new d("VALIDATION_ERROR",o.workflow===void 0?`@lunora/platform-node: cron job "${o.name}" has neither a function target nor a workflow target`:`@lunora/platform-node: cron job "${o.name}" starts workflow "${o.workflow}", which this host cannot do from a cron tick — schedule a function that calls ctx.workflows.get(name).create() instead`);return{args:o.args??{},expression:t,functionPath:o.functionPath,name:o.name}})),ve=(e,t)=>{const r=ye(e);if(r.length>0&&!t)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},w=(e,{databaseFile:t})=>{const r=N(t?e.trim():e);try{return F(r)}catch{try{return m(F(p(r)),M(r))}catch{return r}}},V=40,Re=e=>{let t=N(e.trim());const r=[t];for(let o=0;o<=V;o+=1){let i;try{i=X(t).isSymbolicLink()}catch(a){if(a.code==="ENOENT")return r;throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" could not be resolved — pass a path it can check`,{cause:a})}if(!i)return r;try{t=N(p(t),Y(t)),r.push(t)}catch(a){throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a symlink whose target could not be read`,{cause:a})}}throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a chain of more than ${String(V)} symlinks (a loop?) — pass the file itself`)},H=(e,t)=>{try{const r=$(e.trim(),{bigint:!0}),o=$(t.trim(),{bigint:!0});return r.dev===o.dev&&r.ino===o.ino}catch{return w(e,{databaseFile:!0}).toLowerCase()===w(t,{databaseFile:!0}).toLowerCase()}},Se=e=>{const t=e.trim();if(t===""||t===":memory:")throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is not durable — the mail queue and its sent ledger must survive a restart, so give mail a database file`);if(t.toLowerCase().startsWith("file:"))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is a file: URI — pass a plain filesystem path instead (better-sqlite3 does not read URIs, and would open a file by that literal name)`)},Ae=e=>({drain:async t=>{const r=P(t);try{return await D(e.drain(),r)?{failed:[],pending:[],timedOut:!1}:(console.error("[@lunora/platform-node] platform drain deadline passed with a mail poll still running"),{failed:[],pending:["a mail poll"],timedOut:!0})}finally{r.cancel()}},idle:()=>e.idle(),pending:()=>e.idle()?[]:["a mail poll"]}),be=(e,t)=>{const r=Re(e),o=r.at(-1)??e,i=[["the shard database (`path`)",t.path],["the .global() store (`globalTablesPath`)",t.globalTablesPath]];for(const[l,s]of i)if(s!==void 0&&s!==":memory:"&&s!==""&&H(s,o))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is ${l} "${s}" — give mail a database file of its own`);const{directory:a}=t;if(a===void 0)return;const u=w(a,{databaseFile:!1});if(r.some(l=>{const s=m(w(p(l),{databaseFile:!1}),M(l));return s.endsWith(k)&&p(s)===u}))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a ${k} file inside the shard registry's directory "${a}", which would open it as a shard — move it out of that directory`);let f;try{f=j(a).filter(l=>l.endsWith(k))}catch{return}const h=f.find(l=>H(m(a,l),o));if(h!==void 0)throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is the same file as the shard registry's shard "${m(a,h)}" — give mail a database file of its own`)},_e=(e,t)=>{if(e===void 0)return;const{path:r,...o}=e;Se(r),be(r,t);const i=new Z(r);try{return{close:()=>{i.close()},mail:de(i,o)}}catch(a){throw i.close(),a}},ke=(e,t)=>async(r,o,i)=>{if(re(r,t,ge))throw new d("BAD_REQUEST",oe);const a=await e({args:o,functionPath:r,id:i.id,identity:void 0,scheduledFor:i.scheduledFor,shardKey:t,traceparent:void 0});if(!a.ok)throw new d("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(a.status)}`)},Ke=(e={})=>{const t=[],{database:r,dispose:o,drain:i,host:a,pendingAlarms:u,pendingBackground:g,suspendAlarms:f,takeFailures:h}=ue(e);t.push(o);try{const l=ie(r),s=fe(e);t.push(n=>{s.close(n)});const{directory:O}=s,I=ee(O,e.onFetch!==void 0),B=te({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:I,schedulerSecret:e.dispatch?.schedulerSecret}),C=e.onFetch===void 0?void 0:ke(I,e.shardKey??"__root__"),{declareCrons:U,dispose:q,pendingDispatches:y,scheduler:W,suspend:J}=he(r,{...e,onDispatch:e.onDispatch??C}),{socket:K}=me(r);t.push(q),e.crons!==void 0&&U(ve(e.crons,e.onDispatch!==void 0||e.onFetch!==void 0));const Q=e.queues===void 0?void 0:le(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}),v=_e(e.mail,e);v!==void 0&&t.push(v.close);const R=v?.mail,x=e.objectStorageDirectory===void 0?void 0:ce({directory:e.objectStorageDirectory}),S=e.globalTablesPath===void 0?void 0:ne({path:e.globalTablesPath});S!==void 0&&t.push(()=>{S.dispose()});const G=e.workflows===void 0?void 0:pe({store:we(r),workflows:e.workflows}),E=n=>{const c=[];for(const b of t.toReversed())try{b(n)}catch(_){c.push(_)}if(c.length>0)throw new AggregateError(c,`@lunora/platform-node: ${String(c.length)} resource(s) failed to close`)},T=()=>[...g()>0||u()>0?["waitUntil work on the platform host"]:[],...y().labels],A=[{drain:async n=>{const c=P(n);try{const[b,_]=await Promise.all([D(i(),c),D(Promise.allSettled(y().waits),c)]);if(b&&_)return{failed:h(),pending:[],timedOut:!1};const L=T();return console.error("[@lunora/platform-node] platform drain deadline passed with work still running: %s",L.join(", ")),{failed:h(),pending:L,timedOut:!0}}finally{c.cancel()}},idle:()=>g()===0&&u()===0&&y().waits.length===0,pending:T},s,...R===void 0?[]:[Ae(R)]];return{capabilities:z,close:E,directory:O,dispatch:n=>B(n),idle:()=>A.every(n=>n.idle()),pending:()=>A.flatMap(n=>n.pending()),drain:async n=>(ae(n),J(),f(),s.suspendAlarms(),se(A,n)),globalTables:S,kv:l,mail:R,objectStorage:x,rearmPersistedAlarms:()=>s.rearmPersistedAlarms(),queues:Q,scheduler:W,shard:a,sockets:K,workflows:G,[Symbol.dispose]:()=>{E()}}}catch(l){for(const s of t.toReversed())try{s()}catch{}throw l}};export{ke as createJobDelivery,Ke as createNodePlatform,ye as walkDeclaredCrons};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{randomUUID as G}from"node:crypto";import{deserialize as j,serialize as J}from"node:v8";import{LunoraError as d}from"@lunora/errors";import{isQueueDefinition as K,queueDefaultName as Z,queueBindingName as ee}from"@lunora/queue";const y={maxBatchSize:10,maxBatchTimeoutSeconds:5,maxRetries:3,retryDelaySeconds:0,visibilityTimeoutMs:3e4},te=1e3,ne=100,oe=86400,w=131072,b=262144,re=(e,i)=>{switch(i){case"bytes":{if(e instanceof ArrayBuffer)return Buffer.from(e);if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);throw new d("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "bytes" needs an ArrayBuffer or a typed array')}case"text":{if(typeof e!="string")throw new d("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "text" needs a string');return Buffer.from(e,"utf8")}case"v8":return J(e);default:return Buffer.from(JSON.stringify(e??null),"utf8")}},U=(e,i,_)=>{const T=re(e,i);if(T.byteLength>w)throw new d("VALIDATION_ERROR",`@lunora/platform-node: a message for queue "${_}" encodes to ${String(T.byteLength)} bytes, over the Cloudflare Queues ceiling of ${String(w)} (128 KiB) per message — store the payload and enqueue a reference to it`);return T},g=(e,i)=>{switch(i){case"bytes":return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);case"text":return e.toString("utf8");case"v8":return j(e);default:return JSON.parse(e.toString("utf8"))}},se=e=>{try{return g(e.body,e.content_type)}catch{return}},N=e=>e===void 0||!Number.isFinite(e)?0:Math.min(Math.max(0,Math.ceil(e)),oe)*1e3,k=new WeakMap,de=(e,i)=>{const _=k.get(e)?.get(i);if(_===void 0)throw new d("INTERNAL",`@lunora/platform-node: no queue "${i}" on this host`);return _},x="lunora-mail",F=new WeakSet,le=e=>(F.add(e),e),C=new WeakMap,me=(e,i)=>{e.pragma("journal_mode = WAL"),e.exec(`CREATE TABLE IF NOT EXISTS _lunora_queue_messages (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
queue TEXT NOT NULL,
|
|
4
|
+
body BLOB NOT NULL,
|
|
5
|
+
content_type TEXT NOT NULL,
|
|
6
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
visible_at INTEGER NOT NULL,
|
|
8
|
+
enqueued_at INTEGER NOT NULL,
|
|
9
|
+
state TEXT NOT NULL DEFAULT 'pending'
|
|
10
|
+
)`),e.exec("CREATE INDEX IF NOT EXISTS _lunora_queue_messages_due ON _lunora_queue_messages (queue, state, visible_at)");const _=e.prepare("INSERT INTO _lunora_queue_messages (id, queue, body, content_type, visible_at, enqueued_at) VALUES (?, ?, ?, ?, ?, ?)"),T=e.prepare(`UPDATE _lunora_queue_messages
|
|
11
|
+
SET attempts = attempts + 1, visible_at = ?
|
|
12
|
+
WHERE id IN (
|
|
13
|
+
SELECT id FROM _lunora_queue_messages
|
|
14
|
+
WHERE queue = ? AND state = 'pending' AND visible_at <= ?
|
|
15
|
+
ORDER BY visible_at, enqueued_at LIMIT ?
|
|
16
|
+
)
|
|
17
|
+
RETURNING *`),H=e.prepare("UPDATE _lunora_queue_messages SET visible_at = ? WHERE id = ?"),S=e.prepare("DELETE FROM _lunora_queue_messages WHERE id = ?"),Q=e.prepare("UPDATE _lunora_queue_messages SET state = 'dead' WHERE id = ?"),W=e.prepare("SELECT enqueued_at FROM _lunora_queue_messages WHERE queue = ? AND state = 'pending' AND visible_at <= ? ORDER BY enqueued_at LIMIT 1"),$=e.prepare("SELECT COUNT(*) AS n FROM (SELECT 1 FROM _lunora_queue_messages WHERE queue = ? AND state = 'pending' AND visible_at <= ? LIMIT ?)"),V=e.prepare("SELECT * FROM _lunora_queue_messages WHERE queue = ? AND state = 'dead' ORDER BY enqueued_at"),X=e.prepare("UPDATE _lunora_queue_messages SET state = 'pending', attempts = 0, visible_at = ? WHERE id = ? AND state = 'dead' AND queue IN (SELECT value FROM json_each(?))"),R=Object.entries(i.queues).map(([t,n])=>{if(!K(n))throw new d("VALIDATION_ERROR",`@lunora/platform-node: "${t}" is not a defineQueue result`);return{definition:n,exportName:t,name:n.name??Z(t)}}),h=new Set(R.map(t=>t.name));if(h.has(x)&&!F.has(i))throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue name "${x}" is reserved for the mail host, which would otherwise share its rows with this queue — give the queue another name`);const L=C.get(e)??new Set,O=[...h].find(t=>L.has(t));if(O!==void 0)throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue "${O}" is already declared by another host on this database connection, and both would claim its rows — give it another name, or a connection of its own`);const P=JSON.stringify([...h]);for(const t of R){const n=t.definition.deadLetterQueue;if(n!==void 0){if(n===t.name)throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue "${t.name}" names itself as its own deadLetterQueue, which would redeliver forever`);if(!h.has(n))throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue "${t.name}" names deadLetterQueue "${n}", which no declared queue provides — its dead letters would be unreachable`)}}const Y=i.visibilityTimeoutMs??y.visibilityTimeoutMs,p=i.now??Date.now,A=(t,n,u,a,r)=>{_.run(G(),t,n,u,r+a,r)},z=(t,n,u,a,r)=>{if(u==="ack")return S.run(t.id),!1;const s=n.definition.maxRetries??y.maxRetries;if(t.attempts>s){const m=n.definition.deadLetterQueue;return m===void 0?Q.run(t.id):(A(m,t.body,t.content_type,0,r),S.run(t.id)),!1}const l=N(a??n.definition.retryDelay??y.retryDelaySeconds);return H.run(r+l,t.id),l===0},D={},v={...i.env},q=new Map;for(const t of R){const n=(a,r)=>{const s=r?.contentType??"json",l=U(a,s,t.name),m=N(r?.delaySeconds);let f;return{insert:()=>{A(t.name,l,s,m,p())},get stored(){return f??={value:g(l,s)},f.value}}};q.set(t.exportName,n);const u={send:async(a,r)=>{n(a,r).insert()},sendBatch:async(a,r)=>{const s=p(),l=N(r?.delaySeconds),m=[...a].map(c=>{const o=c.contentType??"json";return{contentType:o,delay:c.delaySeconds===void 0?l:N(c.delaySeconds),encoded:U(c.body,o,t.name)}}),f=m.reduce((c,o)=>c+o.encoded.byteLength,0);if(f>b)throw new d("VALIDATION_ERROR",`@lunora/platform-node: a sendBatch for queue "${t.name}" encodes to ${String(f)} bytes, over the Cloudflare Queues ceiling of ${String(b)} (256 KiB) per batch — split it across more calls`);e.transaction(()=>{for(const c of m)A(t.name,c.encoded,c.contentType,c.delay,s)})()}};D[t.exportName]=u,v[ee(t.exportName)]=u}const I=async(t,n)=>{const u=Math.min(Math.max(1,t.definition.maxBatchSize??y.maxBatchSize),100),a=$.get(t.name,n,u)?.n??0;if(a===0)return"none";if(a<u){const o=W.get(t.name,n)?.enqueued_at,E=Math.min(Math.max(0,t.definition.maxBatchTimeout??y.maxBatchTimeoutSeconds),60)*1e3;if(o!==void 0&&n-o<E)return"none"}const r=e.transaction(()=>T.all(n+Y,t.name,n,u)).immediate();if(r.length===0)return"none";const s=new Map,l=r.map(o=>({ack:()=>{s.set(o.id,{outcome:"ack"})},attempts:o.attempts,body:g(o.body,o.content_type),id:o.id,retry:E=>{s.set(o.id,{delaySeconds:E?.delaySeconds,outcome:"retry"})},timestamp:new Date(o.enqueued_at)})),m={ackAll:()=>{for(const o of r)s.set(o.id,{outcome:"ack"})},messages:l,queue:t.name,retryAll:o=>{for(const E of r)s.set(E.id,{delaySeconds:o?.delaySeconds,outcome:"retry"})}};let f="ack";try{await i.onBatch(m)}catch{f="retry"}return e.transaction(()=>{let o=!1;for(const E of r){const B=s.get(E.id);o=z(E,t,B?.outcome??f,B?.delaySeconds,n)||o}return o})()||r.length<u?"last":"more"},M={bindings:D,deadLetters:{list:t=>V.all(t).map(n=>({attempts:n.attempts,body:se(n),id:n.id})),requeue:t=>X.run(p(),t,P).changes>0},env:v,poll:async(t=p())=>{const n=p();let u=0;for(const a of R){if(a.definition.mode==="pull")continue;let r=0;for(let s=await I(a,t);s!=="none"&&(u+=1,r+=1,!(s==="last"||r>=ne||p()-n>=te));s=await I(a,t));}return u}};k.set(M,q);for(const t of h)L.add(t);return C.set(e,L),M};export{x as RESERVED_MAIL_QUEUE_NAME,le as allowReservedQueueName,me as createNodeQueueHost,de as preparedSendOf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{serialize as p,deserialize as d}from"node:v8";const h=new Set(["end","limit","prefix","reverse","start","startAfter"]),v=new RegExp("\\p{Cs}","u"),g=1114111,E=e=>{let t=e;for(;t.length>0&&t.codePointAt(t.length-2)===g;)t=t.slice(0,-2);const n=t.length>=2&&(t.codePointAt(t.length-2)??0)>65535?t.codePointAt(t.length-2):t.codePointAt(t.length-1);if(n===void 0)return;const s=n>65535?2:1;return t.slice(0,-s)+String.fromCodePoint(n===55295?57344:n+1)},m=e=>{if(e==="")return{};if(!v.test(e))return{lower:e,upper:E(e)};const t=e.slice(0,-1),n=e.codePointAt(e.length-1)??0;if(n<55296||n>56319||v.test(t))return;const s=(n-55296)*1024+65536+1023;return{lower:`${e}\uDC00`,upper:E(`${t}${String.fromCodePoint(s)}`)}},w=e=>{const t=Object.keys(e).filter(s=>!h.has(s));if(t.length>0)throw new TypeError(`@lunora/platform-node: list does not support the option(s) ${t.join(", ")}`);if(e.start!==void 0&&e.startAfter!==void 0)throw new TypeError("@lunora/platform-node: list takes start or startAfter, not both");const{limit:n}=e;if(n!==void 0&&(!Number.isSafeInteger(n)||n<1))throw new RangeError(`@lunora/platform-node: list limit must be a positive integer, got ${String(n)}`);for(const s of["end","prefix","start","startAfter"])if(e[s]!==void 0&&typeof e[s]!="string")throw new TypeError(`@lunora/platform-node: list ${s} must be a string`);if(e.reverse!==void 0&&typeof e.reverse!="boolean")throw new TypeError("@lunora/platform-node: list reverse must be a boolean")},y=e=>{e.exec("CREATE TABLE IF NOT EXISTS _lunora_kv (key TEXT PRIMARY KEY, value BLOB NOT NULL)");const t=e.prepare("SELECT value FROM _lunora_kv WHERE key = ?"),n=e.prepare("INSERT INTO _lunora_kv (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value"),s=e.prepare("DELETE FROM _lunora_kv WHERE key = ?"),c=new Map,f=r=>{const o=m(r.prefix??"");if(o===void 0)return[];const l=[];o.lower!==void 0&&l.push([">=",o.lower]),o.upper!==void 0&&l.push(["<",o.upper]),r.start!==void 0&&l.push([">=",r.start]),r.startAfter!==void 0&&l.push([">",r.startAfter]),r.end!==void 0&&l.push(["<",r.end]);const a=`SELECT key, value FROM _lunora_kv${l.length===0?"":` WHERE ${l.map(([u])=>`key ${u} ?`).join(" AND ")}`} ORDER BY key ${r.reverse===!0?"DESC":"ASC"} LIMIT ?`;let i=c.get(a);return i===void 0&&(i=e.prepare(a),c.set(a,i)),i.all(...l.map(([,u])=>u),r.limit??-1)};return{delete:async r=>s.run(r).changes>0,get:async r=>{const o=t.get(r);return o===void 0?void 0:d(o.value)},list:async(r={})=>(w(r),new Map(f(r).map(o=>[o.key,d(o.value)]))),put:async(r,o)=>{n.run(r,p(o))}}};export{y as createNodeShardKvStore};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as P,readdirSync as W}from"node:fs";import{join as b}from"node:path";import{LunoraError as U}from"@lunora/errors";import x from"better-sqlite3";import{startDrainDeadline as z,settlesBefore as K}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeShardKvStore as T}from"./createNodeShardKvStore-
|
|
1
|
+
import{mkdirSync as P,readdirSync as W}from"node:fs";import{join as b}from"node:path";import{LunoraError as U}from"@lunora/errors";import x from"better-sqlite3";import{startDrainDeadline as z,settlesBefore as K}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeShardKvStore as T}from"./createNodeShardKvStore-Bh6oQZgs.mjs";import{createNodeShardHost as V}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeSocketHost as X}from"./createNodeSocketHost-BJf5HOHr.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("")),G=n=>decodeURIComponent(n),J=(n,s)=>{const d=s.slice(0,-v.length),l=b(n,s);let u;try{u=G(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(u)}${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 "${u}", 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}" "${b(n,f)}"`);return u},Q=(n,s)=>{let d;try{return d=new x(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()}},k=(n,s,d)=>n===0?"":`${String(n)} ${n===1?s:d}`,Y=(n,s)=>{const d=[k(s.requests,"request in flight","requests in flight"),k(s.alarms,"alarm running","alarms running"),k(s.background,"waitUntil task","waitUntil tasks"),s.closing?"a socket close handler running":""].filter(l=>l!=="");return`shard ${n}: ${d.join(", ")}`},ie=(n={})=>{const s=new Map;let d="open",l=!1;const u=()=>{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,h=new Set,E=[];if(n.directory!==void 0){P(n.directory,{recursive:!0});for(const e of W(n.directory))e.endsWith(v)&&S.add(J(n.directory,e))}const $=e=>{f();const t=s.get(e);if(t!==void 0)return t.shard;const r=n.directory===void 0?void 0:b(n.directory,`${F(e)}${v}`);let o;const{alarmsSettled:a,database:i,dispose:c,drain:g,host:w,pendingAlarms:_,pendingBackground:j,suspendAlarms:L,takeFailures:C}=V({onAlarm:()=>n.onAlarm?.(o),path:r,shardKey:e});let A;try{A=X(i),o={inbound:A,kv:T(i),shard:w,shardKey:e,sockets:A.socket}}catch(O){throw c(),O}return s.set(e,{alarmsSettled:a,dispose:c,drain:A.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=$(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 c=i.drain(),g=i.pendingBackground(),w=i.pendingAlarms();c!==void 0&&(t(a).closing=!0,r.push(c)),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])=>Y(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)},y=(e,t)=>{const r=N(e,t);if(r.length>0){Promise.allSettled(r).then(()=>{h.has(e)&&s.get(e)===t&&y(e,t)}).catch(()=>{});return}h.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?h.delete(e):r&&!h.has(e)&&(h.add(e),y(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=[];u();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 c=D(o,a,i.length>0);c!==void 0&&r.push({error:c,key:o})}else h.has(o)||(h.add(o),y(o,a))}R(),M(t,r)},drain:async e=>{const t=z(e);try{for(let r=p();r.waits.length>0;r=p())if(!await K(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)&&Q(b(e,`${F(r)}${v}`),r))try{$(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:$,suspendAlarms:u}};export{v as SHARD_FILE_SUFFIX,ie as createNodeShardRegistry};
|
package/dist/packem_shared/{createNodeSocketHost-ByOmEGFe.mjs → createNodeSocketHost-BJf5HOHr.mjs}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{deserialize as D,serialize as m}from"node:v8";import{LunoraError as F}from"@lunora/errors";import{findSocketTagBudgetViolation as L}from"@lunora/platform";import{N as M,u as P,c as U}from"./node-socket-pair-
|
|
1
|
+
import{deserialize as D,serialize as m}from"node:v8";import{LunoraError as F}from"@lunora/errors";import{findSocketTagBudgetViolation as L}from"@lunora/platform";import{N as M,u as P,c as U}from"./node-socket-pair-BsiTm62u.mjs";import{t as y}from"./to-array-buffer-DVyXU4Ep.mjs";const u=r=>typeof r=="object"&&r!==null||typeof r=="function",J=r=>{r.exec("CREATE TABLE IF NOT EXISTS _lunora_sockets (id TEXT PRIMARY KEY, attachment BLOB, tags TEXT NOT NULL DEFAULT '[]')");const E=r.prepare(`INSERT INTO _lunora_sockets (id, attachment, tags) VALUES (?, ?, ?)
|
|
2
2
|
ON CONFLICT (id) DO UPDATE SET attachment = excluded.attachment, tags = excluded.tags`),R=r.prepare("UPDATE _lunora_sockets SET attachment = ? WHERE id = ?"),_=r.prepare("UPDATE _lunora_sockets SET tags = ? WHERE id = ?"),A=r.prepare("SELECT attachment, tags FROM _lunora_sockets WHERE id = ?"),N=r.prepare("DELETE FROM _lunora_sockets WHERE id = ?"),a=new Map,l=new WeakMap;let p=new WeakMap;const T=(t,e)=>{r.open&&R.run(e===void 0?null:m(e),t)},v=(t,e)=>{r.open&&_.run(JSON.stringify([...e]),t)},g=t=>{const e=t;e.closed=!0,a.delete(e.id),u(e.raw)&&p.delete(e.raw),r.open&&N.run(e.id)},w=(t,e)=>{const o=t;return o.handle=e,l.set(e,o.id),e},O=(t,e)=>{const o=t,n=e,s=typeof n.close=="function"?n.close.bind(e):void 0;return typeof n.send!="function"&&(n.send=c=>{o.received.push(typeof c=="string"?c:y(c))}),n.close=(c,i)=>{g(o),s?.(c,i)},n.deserializeAttachment=()=>o.attachment,n.serializeAttachment=c=>{o.attachment=c,T(o.id,c)},w(o,e)},S=t=>{const e=t;return w(e,{close:(n,s)=>{g(e)},deserializeAttachment:()=>e.attachment,send:n=>{e.received.push(typeof n=="string"?n:y(n))},serializeAttachment:n=>{e.attachment=n,T(e.id,n)}})},f={},h=new Set,k=()=>h.size===0?void 0:Promise.all(h).then(()=>k()),C={close:(t,e,o,n)=>{let s;try{s=f.close?.(t,e,o,n)}catch(d){s=Promise.reject(d instanceof Error?d:new Error(String(d)))}const c=()=>{const d=p.get(t);d!==void 0&&g(d)},i=Promise.resolve(s).then(c,c).catch(()=>{}).finally(()=>{h.delete(i)});h.add(i)},message:(t,e)=>{try{f.message?.(t,e)}catch(o){console.error("[@lunora/platform-node] socket message handler threw",o)}}};return{drain:k,onClose:t=>{f.close=t},onMessage:t=>{f.message=t},readFrames:t=>(a.get(l.get(t)??"")?.received??[]).filter(e=>typeof e=="string"),restoreSocket:(t,e)=>{const o=r.open?A.get(t):void 0,n=o?.attachment===null?void 0:o?.attachment,s={attachment:n===void 0?e:D(n),closed:!1,handle:void 0,id:t,raw:void 0,received:[],tags:new Set(o===void 0?[]:JSON.parse(o.tags))};return a.set(t,s),o===void 0&&r.open&&E.run(t,s.attachment===void 0?null:m(s.attachment),JSON.stringify([...s.tags])),S(s)},simulateRecycle:()=>{a.clear(),p=new WeakMap},socket:{newPair:()=>U(C),upgradeResponse:t=>{if(!(t instanceof M))throw new TypeError("@lunora/platform-node: upgradeResponse called with a client end this host did not open");return P(t)},accept:(t,e,o)=>{if(!r.open)throw new Error("platform closed: cannot accept a socket");const n=L(o);if(n!==void 0)throw new F("SOCKET_TAG_BUDGET_EXCEEDED",n);const s=crypto.randomUUID(),c=new Set(o);E.run(s,e===void 0?null:m(e),JSON.stringify([...c]));const i={attachment:e,closed:!1,handle:void 0,id:s,raw:t,received:[],tags:c};return a.set(s,i),u(t)?(p.set(t,i),O(i,t)):S(i)},getSockets:t=>{const e=[...a.values()];return(t===void 0?e:e.filter(n=>n.tags.has(t))).map(n=>n.handle)},handleFor:t=>u(t)?p.get(t)?.handle:void 0,idFor:t=>{const e=l.get(t);if(e===void 0)throw new Error("@lunora/platform-node: idFor called with a handle this host never issued");return e},removeTag:(t,e)=>{if(!r.open)throw new Error("platform closed: cannot remove a tag");const o=a.get(l.get(t)??"");o!==void 0&&(e===void 0?o.tags.clear():o.tags.delete(e),v(o.id,o.tags))},setTag:(t,e)=>{if(!r.open)throw new Error("platform closed: cannot set a tag");const o=a.get(l.get(t)??"");o!==void 0&&(o.tags.add(e),v(o.id,o.tags))}}}};export{J as createNodeSocketHost};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{t as A}from"./to-array-buffer-DVyXU4Ep.mjs";const m=16*1024*1024,k=256,v="lunora-ping",y="lunora-pong",_=new TextDecoder,E=o=>typeof o=="string"?Buffer.byteLength(o,"utf8"):o instanceof Blob?o.size:o.byteLength;class b{#e;#t;constructor(e,r){this.#t=e,this.#e=r}attach(e){this.#t(e)}abandon(){this.#e()}}const B=o=>{let e,r=!1,d=!1;const l=[];let c=0;const u=(t,n,i,a)=>{d||(d=!0,o.close(t,n,i,a))},h=(t,n)=>t>0&&t+E(n)>m,s={get bufferedAmount(){return r?0:e===void 0?c:e.bufferedAmount},close:(t,n)=>{r||(r=!0,e===void 0?u(s,t??1e3,n??"",!0):e.close(t,n))},send:t=>{if(!r){if(e!==void 0){if(h(e.bufferedAmount,t)){r=!0,u(s,1013,"client is not reading",!1),e.terminate();return}e.send(t);return}if(l.length>=k){r=!0,u(s,1011,"handshake stalled",!1);return}if(h(c,t)){r=!0,u(s,1013,"too much queued before the handshake",!1);return}l.push(t),c+=E(t)}}};return{client:new b(t=>{if(r){t.close(1001,"connection closed before the handshake completed");return}if(e!==void 0)throw new g("INTERNAL","a Node socket pair attaches to exactly one live transport");e=t;for(const n of l.splice(0))t.send(n);c=0,t.on("message",(n,i)=>{if(r||Array.isArray(n))return;const a=i?void 0:_.decode(n);if(a===v){s.send(y);return}o.message(s,a??A(n))}),t.on("error",()=>{}),t.on("close",(n,i)=>{r=!0,u(s,n,i.toString("utf8"),n===1e3||n===1005)})},()=>{e===void 0&&(r=!0,u(s,1006,"handshake did not complete",!1))}),server:s}},p="x-lunora-node-upgrade",N=3e4,f=new Map,L=o=>{const e=crypto.randomUUID();return f.set(e,o),setTimeout(()=>{f.delete(e)&&o.abandon()},N).unref(),new Response(null,{headers:{[p]:e},status:200})},P=o=>{const e=o.headers.get(p);if(e===null)return;const r=f.get(e);return f.delete(e),r};export{b as N,B as c,P as t,L as u};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/platform-node",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.228",
|
|
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",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"@lunora/d1": "^1.0.0-alpha.238",
|
|
50
50
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
51
51
|
"@lunora/mail": "^1.0.0-alpha.140",
|
|
52
|
-
"@lunora/platform": "^1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "^1.0.0-alpha.84",
|
|
53
53
|
"@lunora/queue": "^1.0.0-alpha.146",
|
|
54
54
|
"@lunora/runtime": "^1.0.0-alpha.305",
|
|
55
55
|
"@lunora/scheduler": "^1.0.0-alpha.175",
|
|
@@ -1,4 +0,0 @@
|
|
|
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};
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{randomUUID as P}from"node:crypto";import{deserialize as z,serialize as j}from"node:v8";import{LunoraError as d}from"@lunora/errors";import{isQueueDefinition as G,queueDefaultName as J,queueBindingName as K}from"@lunora/queue";const h={maxBatchSize:10,maxBatchTimeoutSeconds:5,maxRetries:3,retryDelaySeconds:0,visibilityTimeoutMs:3e4},Z=86400,I=131072,B=262144,ee=(e,s)=>{switch(s){case"bytes":{if(e instanceof ArrayBuffer)return Buffer.from(e);if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);throw new d("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "bytes" needs an ArrayBuffer or a typed array')}case"text":{if(typeof e!="string")throw new d("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "text" needs a string');return Buffer.from(e,"utf8")}case"v8":return j(e);default:return Buffer.from(JSON.stringify(e??null),"utf8")}},M=(e,s,E)=>{const p=ee(e,s);if(p.byteLength>I)throw new d("VALIDATION_ERROR",`@lunora/platform-node: a message for queue "${E}" encodes to ${String(p.byteLength)} bytes, over the Cloudflare Queues ceiling of ${String(I)} (128 KiB) per message — store the payload and enqueue a reference to it`);return p},A=(e,s)=>{switch(s){case"bytes":return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);case"text":return e.toString("utf8");case"v8":return z(e);default:return JSON.parse(e.toString("utf8"))}},te=e=>{try{return A(e.body,e.content_type)}catch{return}},R=e=>e===void 0||!Number.isFinite(e)?0:Math.min(Math.max(0,Math.ceil(e)),Z)*1e3,U=new WeakMap,ae=(e,s)=>{const E=U.get(e)?.get(s);if(E===void 0)throw new d("INTERNAL",`@lunora/platform-node: no queue "${s}" on this host`);return E},w="lunora-mail",x=new WeakSet,ie=e=>(x.add(e),e),b=new WeakMap,ue=(e,s)=>{e.pragma("journal_mode = WAL"),e.exec(`CREATE TABLE IF NOT EXISTS _lunora_queue_messages (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
queue TEXT NOT NULL,
|
|
4
|
-
body BLOB NOT NULL,
|
|
5
|
-
content_type TEXT NOT NULL,
|
|
6
|
-
attempts INTEGER NOT NULL DEFAULT 0,
|
|
7
|
-
visible_at INTEGER NOT NULL,
|
|
8
|
-
enqueued_at INTEGER NOT NULL,
|
|
9
|
-
state TEXT NOT NULL DEFAULT 'pending'
|
|
10
|
-
)`),e.exec("CREATE INDEX IF NOT EXISTS _lunora_queue_messages_due ON _lunora_queue_messages (queue, state, visible_at)");const E=e.prepare("INSERT INTO _lunora_queue_messages (id, queue, body, content_type, visible_at, enqueued_at) VALUES (?, ?, ?, ?, ?, ?)"),p=e.prepare(`UPDATE _lunora_queue_messages
|
|
11
|
-
SET attempts = attempts + 1, visible_at = ?
|
|
12
|
-
WHERE id IN (
|
|
13
|
-
SELECT id FROM _lunora_queue_messages
|
|
14
|
-
WHERE queue = ? AND state = 'pending' AND visible_at <= ?
|
|
15
|
-
ORDER BY visible_at, enqueued_at LIMIT ?
|
|
16
|
-
)
|
|
17
|
-
RETURNING *`),C=e.prepare("UPDATE _lunora_queue_messages SET visible_at = ? WHERE id = ?"),S=e.prepare("DELETE FROM _lunora_queue_messages WHERE id = ?"),W=e.prepare("UPDATE _lunora_queue_messages SET state = 'dead' WHERE id = ?"),$=e.prepare("SELECT enqueued_at FROM _lunora_queue_messages WHERE queue = ? AND state = 'pending' AND visible_at <= ? ORDER BY enqueued_at LIMIT 1"),k=e.prepare("SELECT COUNT(*) AS n FROM _lunora_queue_messages WHERE queue = ? AND state = 'pending' AND visible_at <= ?"),F=e.prepare("SELECT * FROM _lunora_queue_messages WHERE queue = ? AND state = 'dead' ORDER BY enqueued_at"),H=e.prepare("UPDATE _lunora_queue_messages SET state = 'pending', attempts = 0, visible_at = ? WHERE id = ? AND state = 'dead' AND queue IN (SELECT value FROM json_each(?))"),T=Object.entries(s.queues).map(([t,n])=>{if(!G(n))throw new d("VALIDATION_ERROR",`@lunora/platform-node: "${t}" is not a defineQueue result`);return{definition:n,exportName:t,name:n.name??J(t)}}),_=new Set(T.map(t=>t.name));if(_.has(w)&&!x.has(s))throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue name "${w}" is reserved for the mail host, which would otherwise share its rows with this queue — give the queue another name`);const N=b.get(e)??new Set,L=[..._].find(t=>N.has(t));if(L!==void 0)throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue "${L}" is already declared by another host on this database connection, and both would claim its rows — give it another name, or a connection of its own`);const Q=JSON.stringify([..._]);for(const t of T){const n=t.definition.deadLetterQueue;if(n!==void 0){if(n===t.name)throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue "${t.name}" names itself as its own deadLetterQueue, which would redeliver forever`);if(!_.has(n))throw new d("VALIDATION_ERROR",`@lunora/platform-node: queue "${t.name}" names deadLetterQueue "${n}", which no declared queue provides — its dead letters would be unreachable`)}}const V=s.visibilityTimeoutMs??h.visibilityTimeoutMs,y=s.now??Date.now,g=(t,n,u,c,r)=>{E.run(P(),t,n,u,r+c,r)},X=(t,n,u,c,r)=>{if(u==="ack"){S.run(t.id);return}const a=n.definition.maxRetries??h.maxRetries;if(t.attempts>a){const l=n.definition.deadLetterQueue;l===void 0?W.run(t.id):(g(l,t.body,t.content_type,0,r),S.run(t.id));return}const m=R(c??n.definition.retryDelay??h.retryDelaySeconds);C.run(r+m,t.id)},O={},v={...s.env},D=new Map;for(const t of T){const n=(c,r)=>{const a=r?.contentType??"json",m=M(c,a,t.name),l=R(r?.delaySeconds);let f;return{insert:()=>{g(t.name,m,a,l,y())},get stored(){return f??={value:A(m,a)},f.value}}};D.set(t.exportName,n);const u={send:async(c,r)=>{n(c,r).insert()},sendBatch:async(c,r)=>{const a=y(),m=R(r?.delaySeconds),l=[...c].map(o=>{const i=o.contentType??"json";return{contentType:i,delay:o.delaySeconds===void 0?m:R(o.delaySeconds),encoded:M(o.body,i,t.name)}}),f=l.reduce((o,i)=>o+i.encoded.byteLength,0);if(f>B)throw new d("VALIDATION_ERROR",`@lunora/platform-node: a sendBatch for queue "${t.name}" encodes to ${String(f)} bytes, over the Cloudflare Queues ceiling of ${String(B)} (256 KiB) per batch — split it across more calls`);e.transaction(()=>{for(const o of l)g(t.name,o.encoded,o.contentType,o.delay,a)})()}};O[t.exportName]=u,v[K(t.exportName)]=u}const Y=async(t,n)=>{const u=Math.min(Math.max(1,t.definition.maxBatchSize??h.maxBatchSize),100),c=k.get(t.name,n)?.n??0;if(c===0)return!1;if(c<u){const o=$.get(t.name,n)?.enqueued_at,i=Math.min(Math.max(0,t.definition.maxBatchTimeout??h.maxBatchTimeoutSeconds),60)*1e3;if(o!==void 0&&n-o<i)return!1}const r=e.transaction(()=>p.all(n+V,t.name,n,u)).immediate();if(r.length===0)return!1;const a=new Map,m=r.map(o=>({ack:()=>{a.set(o.id,{outcome:"ack"})},attempts:o.attempts,body:A(o.body,o.content_type),id:o.id,retry:i=>{a.set(o.id,{delaySeconds:i?.delaySeconds,outcome:"retry"})},timestamp:new Date(o.enqueued_at)})),l={ackAll:()=>{for(const o of r)a.set(o.id,{outcome:"ack"})},messages:m,queue:t.name,retryAll:o=>{for(const i of r)a.set(i.id,{delaySeconds:o?.delaySeconds,outcome:"retry"})}};let f="ack";try{await s.onBatch(l)}catch{f="retry"}return e.transaction(()=>{for(const o of r){const i=a.get(o.id);X(o,t,i?.outcome??f,i?.delaySeconds,n)}})(),!0},q={bindings:O,deadLetters:{list:t=>F.all(t).map(n=>({attempts:n.attempts,body:te(n),id:n.id})),requeue:t=>H.run(y(),t,Q).changes>0},env:v,poll:async(t=y())=>{let n=0;for(const u of T)u.definition.mode!=="pull"&&await Y(u,t)&&(n+=1);return n}};U.set(q,D);for(const t of _)N.add(t);return b.set(e,N),q};export{w as RESERVED_MAIL_QUEUE_NAME,ie as allowReservedQueueName,ue as createNodeQueueHost,ae as preparedSendOf};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{serialize as v,deserialize as u}from"node:v8";const T=r=>{r.exec("CREATE TABLE IF NOT EXISTS _lunora_kv (key TEXT PRIMARY KEY, value BLOB NOT NULL)");const l=r.prepare("SELECT value FROM _lunora_kv WHERE key = ?"),s=r.prepare("INSERT INTO _lunora_kv (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value"),a=r.prepare("DELETE FROM _lunora_kv WHERE key = ?"),E=r.prepare("SELECT key, value FROM _lunora_kv");return{delete:async e=>a.run(e).changes>0,get:async e=>{const t=l.get(e);return t===void 0?void 0:u(t.value)},list:async e=>{const t=e?.prefix??"",c=E.all(),o=new Map;for(const n of c)n.key.startsWith(t)&&o.set(n.key,u(n.value));return o},put:async(e,t)=>{s.run(e,v(t))}}};export{T as createNodeShardKvStore};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{t as p}from"./to-array-buffer-DVyXU4Ep.mjs";const E=256,g="lunora-ping",m="lunora-pong";class A{#e;#t;constructor(e,o){this.#t=e,this.#e=o}attach(e){this.#t(e)}abandon(){this.#e()}}const P=r=>{let e,o=!1,u=!1;const d=[],c=(n,t,s,i)=>{u||(u=!0,r.close(n,t,s,i))},a={close:(n,t)=>{o||(o=!0,e===void 0?c(a,n??1e3,t??"",!0):e.close(n,t))},send:n=>{if(!o){if(e!==void 0){e.send(n);return}if(d.length>=E){o=!0,c(a,1011,"handshake stalled",!1);return}d.push(n)}}};return{client:new A(n=>{if(o){n.close(1001,"connection closed before the handshake completed");return}if(e!==void 0)throw new h("INTERNAL","a Node socket pair attaches to exactly one live transport");e={close:(t,s)=>{n.close(t,s)},send:t=>{n.send(t)}};for(const t of d.splice(0))n.send(t);n.on("message",(t,s)=>{if(o||Array.isArray(t))return;const i=s?void 0:new TextDecoder().decode(t);if(i===g){n.send(m);return}r.message(a,i??p(t))}),n.on("error",()=>{}),n.on("close",(t,s)=>{o=!0,c(a,t,s.toString("utf8"),t===1e3||t===1005)})},()=>{e===void 0&&(o=!0,c(a,1006,"handshake did not complete",!1))}),server:a}},f="x-lunora-node-upgrade",k=3e4,l=new Map,T=r=>{const e=crypto.randomUUID();return l.set(e,r),setTimeout(()=>{l.delete(e)&&r.abandon()},k).unref(),new Response(null,{headers:{[f]:e},status:200})},U=r=>{const e=r.headers.get(f);if(e===null)return;const o=l.get(e);return l.delete(e),o};export{A as N,P as c,U as t,T as u};
|