@lunora/platform-node 1.0.0-alpha.220 → 1.0.0-alpha.221
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 +126 -14
- package/dist/index.d.ts +126 -14
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/createNodeMailHost-DrUo8de-.mjs +8 -0
- package/dist/packem_shared/createNodePlatform-BqtVmQqS.mjs +1 -0
- package/dist/packem_shared/createNodeQueueHost-glQ8GNCA.mjs +17 -0
- package/dist/packem_shared/{createNodeShardRegistry-BHzxHBx1.mjs → createNodeShardRegistry-C1SRJQhd.mjs} +1 -1
- package/package.json +2 -1
- package/dist/packem_shared/createNodePlatform-C5LvauTf.mjs +0 -1
- package/dist/packem_shared/createNodeQueueHost-szMV0PBN.mjs +0 -17
|
@@ -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-BQPmMWJ7.mjs";import{createNodeShardHost as T}from"../packem_shared/createNodeShardHost-VU8MPeba.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-
|
|
1
|
+
import{NODE_CAPABILITIES as g}from"@lunora/platform";import{createNodeShardKvStore as D}from"../packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeSchedulerHost as k}from"../packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as T}from"../packem_shared/createNodeShardHost-VU8MPeba.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-C1SRJQhd.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
|
@@ -2,6 +2,7 @@ import { SchemaLike } from '@lunora/shard-engine';
|
|
|
2
2
|
import { SqlCtxDbOptions, SqlCtxExec, createSqlCtxDb } from '@lunora/sql-store';
|
|
3
3
|
import Database from 'better-sqlite3';
|
|
4
4
|
import { ShardKvStore, QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, SocketHandle, SocketHost, DirectShardDirectory, PlatformCapabilities, ShardDirectory, R2BucketLike } from '@lunora/platform';
|
|
5
|
+
import { Mailer, QueueLike, MailEnv, MailTransport } from '@lunora/mail';
|
|
5
6
|
import { WorkflowBindingLike } from '@lunora/workflow';
|
|
6
7
|
import { WorkflowRuntime, WorkflowStore } from '@visulima/workflow';
|
|
7
8
|
import { ShardNamespaceLike } from '@lunora/runtime';
|
|
@@ -226,6 +227,79 @@ interface NodeHyperdriveBinding {
|
|
|
226
227
|
declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
|
|
227
228
|
/** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
|
|
228
229
|
declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
|
|
230
|
+
/** Options for {@link createNodeMailHost}. */
|
|
231
|
+
interface NodeMailHostOptions {
|
|
232
|
+
/**
|
|
233
|
+
* Where `MAIL_FROM`, `RESEND_API_KEY` and the capture switches
|
|
234
|
+
* (`LUNORA_MAIL_CAPTURE`, `WORKER_ENV`, …) are read, once, at construction.
|
|
235
|
+
* `process.env` unless given.
|
|
236
|
+
*/
|
|
237
|
+
env?: MailEnv;
|
|
238
|
+
/** The host clock, shared with the queue host so a retry delay and `poll(now)` agree. Defaults to `Date.now`. */
|
|
239
|
+
now?: () => number;
|
|
240
|
+
/**
|
|
241
|
+
* Deliver through this, an SMTP client, another provider or a test double.
|
|
242
|
+
* It wins over `RESEND_API_KEY`, which is only read without it. Ignored while
|
|
243
|
+
* the env selects capture, as `createMailerFromEnv` ignores a transport then.
|
|
244
|
+
*/
|
|
245
|
+
transport?: MailTransport;
|
|
246
|
+
}
|
|
247
|
+
/** Queued mail delivery for one Node process. */
|
|
248
|
+
/**
|
|
249
|
+
* Why a send sits in `deadLetters`: its retries ran out (`retries_exhausted`); its idempotency key
|
|
250
|
+
* belongs to other content (`idempotency_key_conflict`); an earlier delivery may have been sent
|
|
251
|
+
* and the provider no longer drops a repeat (`outcome_unknown`), so the provider's logs decide;
|
|
252
|
+
* or that may be so and the record of it has expired (`evidence_expired`). `unknown` is a row
|
|
253
|
+
* parked with no reason recorded (by a build before reasons, or a process that stopped first),
|
|
254
|
+
* which may be any of these, so treat it as `outcome_unknown` until the provider's logs say.
|
|
255
|
+
*/
|
|
256
|
+
type MailParkReason = "evidence_expired" | "idempotency_key_conflict" | "outcome_unknown" | "retries_exhausted" | "unknown";
|
|
257
|
+
interface NodeMailHost {
|
|
258
|
+
/** Sends that failed past the queue's retries, parked by the queue host rather than dropped. */
|
|
259
|
+
deadLetters: {
|
|
260
|
+
/** Each parked send, with why it was parked, so an operator can decide whether to requeue it. */
|
|
261
|
+
list: () => {
|
|
262
|
+
attempts: number;
|
|
263
|
+
body: unknown;
|
|
264
|
+
id: string;
|
|
265
|
+
reason: MailParkReason;
|
|
266
|
+
}[];
|
|
267
|
+
/**
|
|
268
|
+
* Return a parked send to the queue for one more delivery. Its attempt
|
|
269
|
+
* count is kept, so a send an earlier attempt may have delivered is
|
|
270
|
+
* refused once the provider no longer dedupes it. `false` when no mail
|
|
271
|
+
* send with that id is parked. Throws for one queued 15 or more days ago,
|
|
272
|
+
* whose attempt record in the sent ledger has expired.
|
|
273
|
+
*/
|
|
274
|
+
requeue: (id: string) => boolean;
|
|
275
|
+
};
|
|
276
|
+
/** Wait for every `poll()` in flight. `createNodePlatform`'s `drain()` calls it before the database can close. */
|
|
277
|
+
drain: () => Promise<void>;
|
|
278
|
+
/** Whether no `poll()` is in flight: what `createNodePlatform`'s `drain()` checks to end its passes. */
|
|
279
|
+
idle: () => boolean;
|
|
280
|
+
/** `queue()` enqueues onto {@link NodeMailHost.queue}; `send()` delivers now through the same transport. */
|
|
281
|
+
mailer: Mailer;
|
|
282
|
+
/** Deliver the queued sends that are due, and return how many batches went out. Nothing here runs on a timer. */
|
|
283
|
+
poll: (now?: number) => Promise<number>;
|
|
284
|
+
/**
|
|
285
|
+
* The producer: pass it as `createMailerFromEnv(env, { queue })` in your own
|
|
286
|
+
* module. A queued body needs an `idempotencyKey`, which `mailer.queue()` mints.
|
|
287
|
+
*/
|
|
288
|
+
queue: QueueLike;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Create queued mail delivery over `database`: a durable `lunora-mail` queue, a
|
|
292
|
+
* mailer whose `queue()` writes to it, and `poll()` to drain it through the given
|
|
293
|
+
* `transport` or, without one, Resend (`RESEND_API_KEY`). In a dev environment
|
|
294
|
+
* the mailer captures instead, exactly as `createMailerFromEnv` decides on
|
|
295
|
+
* Cloudflare. Throws when `MAIL_FROM` is unset or nothing can deliver.
|
|
296
|
+
*
|
|
297
|
+
* Give it a connection nothing else opens a transaction on, ideally a file of
|
|
298
|
+
* its own, as `createNodePlatform({ mail: { path } })` does: on a shard host's
|
|
299
|
+
* connection, a poll during `shard.transaction()` writes inside it, and that
|
|
300
|
+
* transaction's rollback would undo the acks and sent records and resend.
|
|
301
|
+
*/
|
|
302
|
+
declare const createNodeMailHost: (database: Database.Database, options?: NodeMailHostOptions) => NodeMailHost;
|
|
229
303
|
/** Options for {@link createNodeQueueHost}. */
|
|
230
304
|
interface NodeQueueHostOptions<Queues extends Record<string, {
|
|
231
305
|
isLunoraQueue: true;
|
|
@@ -279,7 +353,7 @@ interface NodeQueueHost<Queues extends Record<string, {
|
|
|
279
353
|
body: unknown;
|
|
280
354
|
id: string;
|
|
281
355
|
}[];
|
|
282
|
-
/** Return a parked message to its queue with `attempts` reset. `false` when no
|
|
356
|
+
/** Return a parked message to its queue with `attempts` reset. `false` when no message of a queue this host declared is parked under that id. */
|
|
283
357
|
requeue: (id: string) => boolean;
|
|
284
358
|
};
|
|
285
359
|
/** The caller's `env` plus one `QUEUE_<EXPORT>` binding per queue. */
|
|
@@ -735,10 +809,11 @@ interface NodePlatform<Queues extends Record<string, {
|
|
|
735
809
|
*/
|
|
736
810
|
dispatch: (request: Request) => Promise<Response>;
|
|
737
811
|
/**
|
|
738
|
-
* Wait for every promise handed to `shard.waitUntil` to settle,
|
|
739
|
-
* registry's shards to go idle
|
|
740
|
-
* `onFetch` and `onAlarm` calls,
|
|
741
|
-
* deliveries, and each shard's own
|
|
812
|
+
* Wait for every promise handed to `shard.waitUntil` to settle, for every
|
|
813
|
+
* `mail.poll()` in flight, and for the registry's shards to go idle
|
|
814
|
+
* (`NodeShardRegistry.drain`): in-flight `onFetch` and `onAlarm` calls,
|
|
815
|
+
* including cron and scheduled-job deliveries, and each shard's own
|
|
816
|
+
* `waitUntil` work.
|
|
742
817
|
*
|
|
743
818
|
* Separate from `close()` because the two answer different questions:
|
|
744
819
|
* `close()` releases handles and stays synchronous (it backs
|
|
@@ -778,6 +853,14 @@ interface NodePlatform<Queues extends Record<string, {
|
|
|
778
853
|
idle: () => boolean;
|
|
779
854
|
/** Durable key-value storage backed by the same `better-sqlite3` database as `shard`. */
|
|
780
855
|
kv: ShardKvStore;
|
|
856
|
+
/**
|
|
857
|
+
* Queued mail delivery, or `undefined` when the caller passed no `mail`.
|
|
858
|
+
* Its queue, sent ledger and key records live in `mail.path`, a database file
|
|
859
|
+
* of its own on its own connection, never the shard's: construction refuses a
|
|
860
|
+
* path that is the shard's file, the `globalTablesPath` file, or a `.sqlite3`
|
|
861
|
+
* file in the shard registry's `directory`.
|
|
862
|
+
*/
|
|
863
|
+
mail?: NodeMailHost;
|
|
781
864
|
/** The local-filesystem bucket, or `undefined` when the caller named no bucket directory. */
|
|
782
865
|
objectStorage?: R2BucketLike;
|
|
783
866
|
/** What is running right now (host work, scheduler deliveries, each shard's work), as a timed-out drain would report it. */
|
|
@@ -805,6 +888,18 @@ interface NodePlatform<Queues extends Record<string, {
|
|
|
805
888
|
*/
|
|
806
889
|
workflows?: NodeWorkflowHost<Workflows>;
|
|
807
890
|
}
|
|
891
|
+
/**
|
|
892
|
+
* `createNodePlatform`'s `mail` option: the {@link NodeMailHostOptions} plus the
|
|
893
|
+
* database file the mail host keeps its queue, sent ledger and key records in.
|
|
894
|
+
*
|
|
895
|
+
* Its own file, never the shard's, and there is no default: a shard transaction
|
|
896
|
+
* holds the shard file across awaits, and mail written inside it would be rolled
|
|
897
|
+
* back with it (see `composeMail`). The same reason `globalTablesPath` has none.
|
|
898
|
+
*/
|
|
899
|
+
type NodePlatformMailOptions = NodeMailHostOptions & {
|
|
900
|
+
/** The mail database file, for example `./.lunora/mail.sqlite3`. */
|
|
901
|
+
path: string;
|
|
902
|
+
};
|
|
808
903
|
/**
|
|
809
904
|
* The secrets the dispatch route authenticates with. With neither, the route
|
|
810
905
|
* refuses everything.
|
|
@@ -860,6 +955,15 @@ type NodePlatformOptions<Queues extends Record<string, {
|
|
|
860
955
|
* default, for the same reason the bucket has none.
|
|
861
956
|
*/
|
|
862
957
|
globalTablesPath?: string;
|
|
958
|
+
/**
|
|
959
|
+
* Deliver `@lunora/mail` sends: a durable `lunora-mail` queue drained
|
|
960
|
+
* through the given `transport` or, without one, Resend (`RESEND_API_KEY`), exposed as
|
|
961
|
+
* `platform.mail`. Its queue, sent ledger and key records live in `path`, a
|
|
962
|
+
* database file of their own (see {@link NodePlatformMailOptions}). Omit when
|
|
963
|
+
* the app sends no mail. Throws here, not on the first send, when `MAIL_FROM`
|
|
964
|
+
* is unset or nothing can deliver.
|
|
965
|
+
*/
|
|
966
|
+
mail?: NodePlatformMailOptions;
|
|
863
967
|
/**
|
|
864
968
|
* Directory the object-storage bucket keeps its objects in, one file per
|
|
865
969
|
* key. Omit when the app declares no buckets — there is no default,
|
|
@@ -1044,8 +1148,10 @@ export { DEFAULT_DRAIN_TIMEOUT_MS,
|
|
|
1044
1148
|
* the Cloudflare product bindings with no local
|
|
1045
1149
|
* equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
|
|
1046
1150
|
* Engine, Pipelines. `ctx.secrets` reads environment variables through
|
|
1047
|
-
* `createNodeSecretBindings` (`./node-secrets`),
|
|
1048
|
-
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`)
|
|
1151
|
+
* `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
|
|
1152
|
+
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
|
|
1153
|
+
* `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
|
|
1154
|
+
* (`./node-mail-host`) through Resend or a caller-supplied transport.
|
|
1049
1155
|
*
|
|
1050
1156
|
* `lunora deploy --target node` bundles an app into a container build context
|
|
1051
1157
|
* whose generated entry composes this package (crons, `ctx.secrets`,
|
|
@@ -1096,8 +1202,10 @@ type DrainOptions,
|
|
|
1096
1202
|
* the Cloudflare product bindings with no local
|
|
1097
1203
|
* equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
|
|
1098
1204
|
* Engine, Pipelines. `ctx.secrets` reads environment variables through
|
|
1099
|
-
* `createNodeSecretBindings` (`./node-secrets`),
|
|
1100
|
-
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`)
|
|
1205
|
+
* `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
|
|
1206
|
+
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
|
|
1207
|
+
* `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
|
|
1208
|
+
* (`./node-mail-host`) through Resend or a caller-supplied transport.
|
|
1101
1209
|
*
|
|
1102
1210
|
* `lunora deploy --target node` bundles an app into a container build context
|
|
1103
1211
|
* whose generated entry composes this package (crons, `ctx.secrets`,
|
|
@@ -1148,8 +1256,10 @@ type DrainResult,
|
|
|
1148
1256
|
* the Cloudflare product bindings with no local
|
|
1149
1257
|
* equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
|
|
1150
1258
|
* Engine, Pipelines. `ctx.secrets` reads environment variables through
|
|
1151
|
-
* `createNodeSecretBindings` (`./node-secrets`),
|
|
1152
|
-
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`)
|
|
1259
|
+
* `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
|
|
1260
|
+
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
|
|
1261
|
+
* `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
|
|
1262
|
+
* (`./node-mail-host`) through Resend or a caller-supplied transport.
|
|
1153
1263
|
*
|
|
1154
1264
|
* `lunora deploy --target node` bundles an app into a container build context
|
|
1155
1265
|
* whose generated entry composes this package (crons, `ctx.secrets`,
|
|
@@ -1200,8 +1310,10 @@ type DrainTimer,
|
|
|
1200
1310
|
* the Cloudflare product bindings with no local
|
|
1201
1311
|
* equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
|
|
1202
1312
|
* Engine, Pipelines. `ctx.secrets` reads environment variables through
|
|
1203
|
-
* `createNodeSecretBindings` (`./node-secrets`),
|
|
1204
|
-
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`)
|
|
1313
|
+
* `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
|
|
1314
|
+
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
|
|
1315
|
+
* `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
|
|
1316
|
+
* (`./node-mail-host`) through Resend or a caller-supplied transport.
|
|
1205
1317
|
*
|
|
1206
1318
|
* `lunora deploy --target node` bundles an app into a container build context
|
|
1207
1319
|
* whose generated entry composes this package (crons, `ctx.secrets`,
|
|
@@ -1214,4 +1326,4 @@ type DrainTimer,
|
|
|
1214
1326
|
* server, which is why both statements above hold at once. See
|
|
1215
1327
|
* `plans/234-node-host-findings.md`.
|
|
1216
1328
|
*/
|
|
1217
|
-
type Drainable, NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore, drainTogether };
|
|
1329
|
+
type Drainable, type MailParkReason, NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type 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, createNodeDispatchRoute, 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
|
@@ -2,6 +2,7 @@ import { SchemaLike } from '@lunora/shard-engine';
|
|
|
2
2
|
import { SqlCtxDbOptions, SqlCtxExec, createSqlCtxDb } from '@lunora/sql-store';
|
|
3
3
|
import Database from 'better-sqlite3';
|
|
4
4
|
import { ShardKvStore, QueueBindingLike, MessageBatchLike, SchedulerHost, ShardHost, SocketHandle, SocketHost, DirectShardDirectory, PlatformCapabilities, ShardDirectory, R2BucketLike } from '@lunora/platform';
|
|
5
|
+
import { Mailer, QueueLike, MailEnv, MailTransport } from '@lunora/mail';
|
|
5
6
|
import { WorkflowBindingLike } from '@lunora/workflow';
|
|
6
7
|
import { WorkflowRuntime, WorkflowStore } from '@visulima/workflow';
|
|
7
8
|
import { ShardNamespaceLike } from '@lunora/runtime';
|
|
@@ -226,6 +227,79 @@ interface NodeHyperdriveBinding {
|
|
|
226
227
|
declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
|
|
227
228
|
/** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
|
|
228
229
|
declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
|
|
230
|
+
/** Options for {@link createNodeMailHost}. */
|
|
231
|
+
interface NodeMailHostOptions {
|
|
232
|
+
/**
|
|
233
|
+
* Where `MAIL_FROM`, `RESEND_API_KEY` and the capture switches
|
|
234
|
+
* (`LUNORA_MAIL_CAPTURE`, `WORKER_ENV`, …) are read, once, at construction.
|
|
235
|
+
* `process.env` unless given.
|
|
236
|
+
*/
|
|
237
|
+
env?: MailEnv;
|
|
238
|
+
/** The host clock, shared with the queue host so a retry delay and `poll(now)` agree. Defaults to `Date.now`. */
|
|
239
|
+
now?: () => number;
|
|
240
|
+
/**
|
|
241
|
+
* Deliver through this, an SMTP client, another provider or a test double.
|
|
242
|
+
* It wins over `RESEND_API_KEY`, which is only read without it. Ignored while
|
|
243
|
+
* the env selects capture, as `createMailerFromEnv` ignores a transport then.
|
|
244
|
+
*/
|
|
245
|
+
transport?: MailTransport;
|
|
246
|
+
}
|
|
247
|
+
/** Queued mail delivery for one Node process. */
|
|
248
|
+
/**
|
|
249
|
+
* Why a send sits in `deadLetters`: its retries ran out (`retries_exhausted`); its idempotency key
|
|
250
|
+
* belongs to other content (`idempotency_key_conflict`); an earlier delivery may have been sent
|
|
251
|
+
* and the provider no longer drops a repeat (`outcome_unknown`), so the provider's logs decide;
|
|
252
|
+
* or that may be so and the record of it has expired (`evidence_expired`). `unknown` is a row
|
|
253
|
+
* parked with no reason recorded (by a build before reasons, or a process that stopped first),
|
|
254
|
+
* which may be any of these, so treat it as `outcome_unknown` until the provider's logs say.
|
|
255
|
+
*/
|
|
256
|
+
type MailParkReason = "evidence_expired" | "idempotency_key_conflict" | "outcome_unknown" | "retries_exhausted" | "unknown";
|
|
257
|
+
interface NodeMailHost {
|
|
258
|
+
/** Sends that failed past the queue's retries, parked by the queue host rather than dropped. */
|
|
259
|
+
deadLetters: {
|
|
260
|
+
/** Each parked send, with why it was parked, so an operator can decide whether to requeue it. */
|
|
261
|
+
list: () => {
|
|
262
|
+
attempts: number;
|
|
263
|
+
body: unknown;
|
|
264
|
+
id: string;
|
|
265
|
+
reason: MailParkReason;
|
|
266
|
+
}[];
|
|
267
|
+
/**
|
|
268
|
+
* Return a parked send to the queue for one more delivery. Its attempt
|
|
269
|
+
* count is kept, so a send an earlier attempt may have delivered is
|
|
270
|
+
* refused once the provider no longer dedupes it. `false` when no mail
|
|
271
|
+
* send with that id is parked. Throws for one queued 15 or more days ago,
|
|
272
|
+
* whose attempt record in the sent ledger has expired.
|
|
273
|
+
*/
|
|
274
|
+
requeue: (id: string) => boolean;
|
|
275
|
+
};
|
|
276
|
+
/** Wait for every `poll()` in flight. `createNodePlatform`'s `drain()` calls it before the database can close. */
|
|
277
|
+
drain: () => Promise<void>;
|
|
278
|
+
/** Whether no `poll()` is in flight: what `createNodePlatform`'s `drain()` checks to end its passes. */
|
|
279
|
+
idle: () => boolean;
|
|
280
|
+
/** `queue()` enqueues onto {@link NodeMailHost.queue}; `send()` delivers now through the same transport. */
|
|
281
|
+
mailer: Mailer;
|
|
282
|
+
/** Deliver the queued sends that are due, and return how many batches went out. Nothing here runs on a timer. */
|
|
283
|
+
poll: (now?: number) => Promise<number>;
|
|
284
|
+
/**
|
|
285
|
+
* The producer: pass it as `createMailerFromEnv(env, { queue })` in your own
|
|
286
|
+
* module. A queued body needs an `idempotencyKey`, which `mailer.queue()` mints.
|
|
287
|
+
*/
|
|
288
|
+
queue: QueueLike;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Create queued mail delivery over `database`: a durable `lunora-mail` queue, a
|
|
292
|
+
* mailer whose `queue()` writes to it, and `poll()` to drain it through the given
|
|
293
|
+
* `transport` or, without one, Resend (`RESEND_API_KEY`). In a dev environment
|
|
294
|
+
* the mailer captures instead, exactly as `createMailerFromEnv` decides on
|
|
295
|
+
* Cloudflare. Throws when `MAIL_FROM` is unset or nothing can deliver.
|
|
296
|
+
*
|
|
297
|
+
* Give it a connection nothing else opens a transaction on, ideally a file of
|
|
298
|
+
* its own, as `createNodePlatform({ mail: { path } })` does: on a shard host's
|
|
299
|
+
* connection, a poll during `shard.transaction()` writes inside it, and that
|
|
300
|
+
* transaction's rollback would undo the acks and sent records and resend.
|
|
301
|
+
*/
|
|
302
|
+
declare const createNodeMailHost: (database: Database.Database, options?: NodeMailHostOptions) => NodeMailHost;
|
|
229
303
|
/** Options for {@link createNodeQueueHost}. */
|
|
230
304
|
interface NodeQueueHostOptions<Queues extends Record<string, {
|
|
231
305
|
isLunoraQueue: true;
|
|
@@ -279,7 +353,7 @@ interface NodeQueueHost<Queues extends Record<string, {
|
|
|
279
353
|
body: unknown;
|
|
280
354
|
id: string;
|
|
281
355
|
}[];
|
|
282
|
-
/** Return a parked message to its queue with `attempts` reset. `false` when no
|
|
356
|
+
/** Return a parked message to its queue with `attempts` reset. `false` when no message of a queue this host declared is parked under that id. */
|
|
283
357
|
requeue: (id: string) => boolean;
|
|
284
358
|
};
|
|
285
359
|
/** The caller's `env` plus one `QUEUE_<EXPORT>` binding per queue. */
|
|
@@ -735,10 +809,11 @@ interface NodePlatform<Queues extends Record<string, {
|
|
|
735
809
|
*/
|
|
736
810
|
dispatch: (request: Request) => Promise<Response>;
|
|
737
811
|
/**
|
|
738
|
-
* Wait for every promise handed to `shard.waitUntil` to settle,
|
|
739
|
-
* registry's shards to go idle
|
|
740
|
-
* `onFetch` and `onAlarm` calls,
|
|
741
|
-
* deliveries, and each shard's own
|
|
812
|
+
* Wait for every promise handed to `shard.waitUntil` to settle, for every
|
|
813
|
+
* `mail.poll()` in flight, and for the registry's shards to go idle
|
|
814
|
+
* (`NodeShardRegistry.drain`): in-flight `onFetch` and `onAlarm` calls,
|
|
815
|
+
* including cron and scheduled-job deliveries, and each shard's own
|
|
816
|
+
* `waitUntil` work.
|
|
742
817
|
*
|
|
743
818
|
* Separate from `close()` because the two answer different questions:
|
|
744
819
|
* `close()` releases handles and stays synchronous (it backs
|
|
@@ -778,6 +853,14 @@ interface NodePlatform<Queues extends Record<string, {
|
|
|
778
853
|
idle: () => boolean;
|
|
779
854
|
/** Durable key-value storage backed by the same `better-sqlite3` database as `shard`. */
|
|
780
855
|
kv: ShardKvStore;
|
|
856
|
+
/**
|
|
857
|
+
* Queued mail delivery, or `undefined` when the caller passed no `mail`.
|
|
858
|
+
* Its queue, sent ledger and key records live in `mail.path`, a database file
|
|
859
|
+
* of its own on its own connection, never the shard's: construction refuses a
|
|
860
|
+
* path that is the shard's file, the `globalTablesPath` file, or a `.sqlite3`
|
|
861
|
+
* file in the shard registry's `directory`.
|
|
862
|
+
*/
|
|
863
|
+
mail?: NodeMailHost;
|
|
781
864
|
/** The local-filesystem bucket, or `undefined` when the caller named no bucket directory. */
|
|
782
865
|
objectStorage?: R2BucketLike;
|
|
783
866
|
/** What is running right now (host work, scheduler deliveries, each shard's work), as a timed-out drain would report it. */
|
|
@@ -805,6 +888,18 @@ interface NodePlatform<Queues extends Record<string, {
|
|
|
805
888
|
*/
|
|
806
889
|
workflows?: NodeWorkflowHost<Workflows>;
|
|
807
890
|
}
|
|
891
|
+
/**
|
|
892
|
+
* `createNodePlatform`'s `mail` option: the {@link NodeMailHostOptions} plus the
|
|
893
|
+
* database file the mail host keeps its queue, sent ledger and key records in.
|
|
894
|
+
*
|
|
895
|
+
* Its own file, never the shard's, and there is no default: a shard transaction
|
|
896
|
+
* holds the shard file across awaits, and mail written inside it would be rolled
|
|
897
|
+
* back with it (see `composeMail`). The same reason `globalTablesPath` has none.
|
|
898
|
+
*/
|
|
899
|
+
type NodePlatformMailOptions = NodeMailHostOptions & {
|
|
900
|
+
/** The mail database file, for example `./.lunora/mail.sqlite3`. */
|
|
901
|
+
path: string;
|
|
902
|
+
};
|
|
808
903
|
/**
|
|
809
904
|
* The secrets the dispatch route authenticates with. With neither, the route
|
|
810
905
|
* refuses everything.
|
|
@@ -860,6 +955,15 @@ type NodePlatformOptions<Queues extends Record<string, {
|
|
|
860
955
|
* default, for the same reason the bucket has none.
|
|
861
956
|
*/
|
|
862
957
|
globalTablesPath?: string;
|
|
958
|
+
/**
|
|
959
|
+
* Deliver `@lunora/mail` sends: a durable `lunora-mail` queue drained
|
|
960
|
+
* through the given `transport` or, without one, Resend (`RESEND_API_KEY`), exposed as
|
|
961
|
+
* `platform.mail`. Its queue, sent ledger and key records live in `path`, a
|
|
962
|
+
* database file of their own (see {@link NodePlatformMailOptions}). Omit when
|
|
963
|
+
* the app sends no mail. Throws here, not on the first send, when `MAIL_FROM`
|
|
964
|
+
* is unset or nothing can deliver.
|
|
965
|
+
*/
|
|
966
|
+
mail?: NodePlatformMailOptions;
|
|
863
967
|
/**
|
|
864
968
|
* Directory the object-storage bucket keeps its objects in, one file per
|
|
865
969
|
* key. Omit when the app declares no buckets — there is no default,
|
|
@@ -1044,8 +1148,10 @@ export { DEFAULT_DRAIN_TIMEOUT_MS,
|
|
|
1044
1148
|
* the Cloudflare product bindings with no local
|
|
1045
1149
|
* equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
|
|
1046
1150
|
* Engine, Pipelines. `ctx.secrets` reads environment variables through
|
|
1047
|
-
* `createNodeSecretBindings` (`./node-secrets`),
|
|
1048
|
-
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`)
|
|
1151
|
+
* `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
|
|
1152
|
+
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
|
|
1153
|
+
* `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
|
|
1154
|
+
* (`./node-mail-host`) through Resend or a caller-supplied transport.
|
|
1049
1155
|
*
|
|
1050
1156
|
* `lunora deploy --target node` bundles an app into a container build context
|
|
1051
1157
|
* whose generated entry composes this package (crons, `ctx.secrets`,
|
|
@@ -1096,8 +1202,10 @@ type DrainOptions,
|
|
|
1096
1202
|
* the Cloudflare product bindings with no local
|
|
1097
1203
|
* equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
|
|
1098
1204
|
* Engine, Pipelines. `ctx.secrets` reads environment variables through
|
|
1099
|
-
* `createNodeSecretBindings` (`./node-secrets`),
|
|
1100
|
-
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`)
|
|
1205
|
+
* `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
|
|
1206
|
+
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
|
|
1207
|
+
* `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
|
|
1208
|
+
* (`./node-mail-host`) through Resend or a caller-supplied transport.
|
|
1101
1209
|
*
|
|
1102
1210
|
* `lunora deploy --target node` bundles an app into a container build context
|
|
1103
1211
|
* whose generated entry composes this package (crons, `ctx.secrets`,
|
|
@@ -1148,8 +1256,10 @@ type DrainResult,
|
|
|
1148
1256
|
* the Cloudflare product bindings with no local
|
|
1149
1257
|
* equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
|
|
1150
1258
|
* Engine, Pipelines. `ctx.secrets` reads environment variables through
|
|
1151
|
-
* `createNodeSecretBindings` (`./node-secrets`),
|
|
1152
|
-
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`)
|
|
1259
|
+
* `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
|
|
1260
|
+
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
|
|
1261
|
+
* `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
|
|
1262
|
+
* (`./node-mail-host`) through Resend or a caller-supplied transport.
|
|
1153
1263
|
*
|
|
1154
1264
|
* `lunora deploy --target node` bundles an app into a container build context
|
|
1155
1265
|
* whose generated entry composes this package (crons, `ctx.secrets`,
|
|
@@ -1200,8 +1310,10 @@ type DrainTimer,
|
|
|
1200
1310
|
* the Cloudflare product bindings with no local
|
|
1201
1311
|
* equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
|
|
1202
1312
|
* Engine, Pipelines. `ctx.secrets` reads environment variables through
|
|
1203
|
-
* `createNodeSecretBindings` (`./node-secrets`),
|
|
1204
|
-
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`)
|
|
1313
|
+
* `createNodeSecretBindings` (`./node-secrets`), the Hyperdrive binding is
|
|
1314
|
+
* built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`), and
|
|
1315
|
+
* `@lunora/mail` sends are queued and delivered by `createNodeMailHost`
|
|
1316
|
+
* (`./node-mail-host`) through Resend or a caller-supplied transport.
|
|
1205
1317
|
*
|
|
1206
1318
|
* `lunora deploy --target node` bundles an app into a container build context
|
|
1207
1319
|
* whose generated entry composes this package (crons, `ctx.secrets`,
|
|
@@ -1214,4 +1326,4 @@ type DrainTimer,
|
|
|
1214
1326
|
* server, which is why both statements above hold at once. See
|
|
1215
1327
|
* `plans/234-node-host-findings.md`.
|
|
1216
1328
|
*/
|
|
1217
|
-
type Drainable, NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore, drainTogether };
|
|
1329
|
+
type Drainable, type MailParkReason, NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron, type NodeDispatchInvocation, type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type 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, createNodeDispatchRoute, 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{N as d,c}from"./packem_shared/node-dispatch-route-ByuCR26s.mjs";import{createNodeGlobalStore as p,createNodeSqlExec as N}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeHttpServer as x}from"./packem_shared/createNodeHttpServer-cUx4J9Z9.mjs";import{createNodeHyperdrive as s}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as
|
|
1
|
+
import{DEFAULT_DRAIN_TIMEOUT_MS as o,drainTogether as t}from"./packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{N as d,c}from"./packem_shared/node-dispatch-route-ByuCR26s.mjs";import{createNodeGlobalStore as p,createNodeSqlExec as N}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeHttpServer as x}from"./packem_shared/createNodeHttpServer-cUx4J9Z9.mjs";import{createNodeHyperdrive as s}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as l}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeMailHost as i}from"./packem_shared/createNodeMailHost-DrUo8de-.mjs";import{createNodePlatform as E}from"./packem_shared/createNodePlatform-BqtVmQqS.mjs";import{createNodeProfileHandler as _}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as n}from"./packem_shared/createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as R}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as P}from"./packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeSecretBindings as v}from"./packem_shared/createNodeSecretBindings-C7wh0fOm.mjs";import{createNodeShardHost as M}from"./packem_shared/createNodeShardHost-VU8MPeba.mjs";import{createNodeShardNamespace as b}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as y}from"./packem_shared/createNodeShardRegistry-C1SRJQhd.mjs";import{bindShardSockets as C,createNodeShardState as L}from"./packem_shared/bindShardSockets-9GvSocBW.mjs";import{createNodeSocketHost as W}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as F}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as K}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{o as DEFAULT_DRAIN_TIMEOUT_MS,d as NODE_SCHEDULER_DISPATCH_PATH,C as bindShardSockets,c as createNodeDispatchRoute,p as createNodeGlobalStore,x as createNodeHttpServer,s as createNodeHyperdrive,i as createNodeMailHost,E as createNodePlatform,_ as createNodeProfileHandler,n as createNodeQueueHost,R as createNodeR2Bucket,P as createNodeSchedulerHost,v as createNodeSecretBindings,M as createNodeShardHost,l as createNodeShardKvStore,b as createNodeShardNamespace,y as createNodeShardRegistry,L as createNodeShardState,W as createNodeSocketHost,N as createNodeSqlExec,F as createNodeWorkflowHost,K as createNodeWorkflowStore,t as drainTogether};
|
|
@@ -0,0 +1,8 @@
|
|
|
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-glQ8GNCA.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
|
+
ON CONFLICT (key) DO UPDATE SET message_id = excluded.message_id, expires_at = excluded.expires_at
|
|
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
|
+
ON CONFLICT (key) DO UPDATE SET
|
|
5
|
+
delivery = CASE WHEN ${s} THEN 1 ELSE _lunora_mail_deliveries.delivery + 1 END,
|
|
6
|
+
first_at = CASE WHEN ${s} THEN excluded.first_at ELSE _lunora_mail_deliveries.first_at END,
|
|
7
|
+
expires_at = excluded.expires_at
|
|
8
|
+
RETURNING delivery, first_at`),E.get({enqueued:u,excluded:c,expires:a+h,key:n,now:a})},D=e.prepare("SELECT first_at FROM _lunora_mail_deliveries WHERE key = ?"),x=e.prepare("UPDATE _lunora_mail_keys SET expires_at = max(expires_at, ?) WHERE key = ?");let R=Number.NEGATIVE_INFINITY,v;const g=n=>(v??=e.prepare(`SELECT body FROM _lunora_queue_messages WHERE queue = '${A}' AND state IN ('pending', 'dead') AND ${H} = ? ORDER BY enqueued_at LIMIT 1`),v.get(n)),I=(n,a)=>{const c=y.get(n,a)?.fingerprint;if(c!==void 0)return{fingerprint:c,recorded:!0};const u=g(n);return u===void 0?void 0:{fingerprint:r(JSON.parse(u.body.toString("utf8"))),recorded:!1}},w=n=>{n-R>=b&&(S.run(n),L.run(n),m(n),R=n)},o=e.transaction((n,a,c)=>{const u=t();w(u);const s=I(n,u);return s!==void 0&&s.fingerprint!==a?"conflict":(s?.recorded!==!0&&N.run(n,a,u+C),c(),"queued")}),d=e.transaction((n,a,c,u)=>{const s=t();w(s);const P=I(n,s);if(P!==void 0&&P.fingerprint!==a)return{outcome:"conflict"};if(i.run(n,c,s+U,s).changes===0)return{outcome:"busy"};N.run(n,a,Math.max(s+C,s+U));const K=f(n,s,c,u);return{delivery:K?.delivery??1,firstDeliveredAt:K?.first_at??s,outcome:"taken"}});return{firstDeliveredAt:n=>D.get(n)?.first_at,keepContent:n=>{x.run(t()+C,n)},release:(n,a)=>{_.run(n,a)},reserve:(n,a,c)=>o.immediate(n,a,c),take:(n,a,c,u)=>d.immediate(n,a,c,u)}},X=e=>{const t=e!==null&&typeof e=="object"?e.idempotencyKey:void 0;return typeof t=="string"&&t!==""?t:void 0},q=86400,ye=e=>{if(e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0||e>q))throw new O("VALIDATION_ERROR",`@lunora/platform-node: \`delaySeconds\` must be a whole number of seconds from 0 to ${String(q)} (24 hours), as on Cloudflare Queues, got ${typeof e=="number"?String(e):JSON.stringify(e)}`)},z=new Set(["0","1","false","true"]),Re=e=>{const t=e.LUNORA_MAIL_CAPTURE;return typeof t=="string"&&z.has(t.toLowerCase())?`LUNORA_MAIL_CAPTURE=${t}`:["CF_ENV","ENVIRONMENT","NODE_ENV","WORKER_ENV"].flatMap(r=>typeof e[r]=="string"&&e[r]!==""?[`${r}=${e[r]}`]:[]).join(", ")},Ie=e=>{const t=e.LUNORA_MAIL_CAPTURE;return typeof t=="string"&&t!==""&&!z.has(t.toLowerCase())?`; LUNORA_MAIL_CAPTURE=${t} was ignored, as only 1, true, 0 or false are read`:""},Oe=e=>{const r=e.SHARD!==void 0&&typeof e.LUNORA_ADMIN_TOKEN=="string"?"recorded in the studio's Mail inbox":"DISCARDED, because there is no SHARD namespace and LUNORA_ADMIN_TOKEN on env to record it with";console.warn(`[@lunora/platform-node] mail is captured, not sent (${Re(e)} selects dev capture${Ie(e)}): every send is ${r}. Set LUNORA_MAIL_CAPTURE=0 to deliver.`)},Se=(e,t,r)=>{const i=e.MAIL_FROM;if(typeof i!="string"||i==="")throw new O("VALIDATION_ERROR","@lunora/platform-node: mail needs MAIL_FROM, the default sender");if(ne(e))return Oe(e),ie(e,{queue:t,sendTimeoutMs:k});if(r!==void 0)return V({from:i,queue:t,sendTimeoutMs:k,transport:r});const _=e.RESEND_API_KEY;if(typeof _!="string"||_==="")throw new O("VALIDATION_ERROR","@lunora/platform-node: mail has nothing to deliver through — set RESEND_API_KEY or pass `transport` (Cloudflare Email Workers' send_email binding does not exist on Node)");return V({apiKey:_,from:i,queue:t,sendTimeoutMs:k})},W=(e,t,r)=>{e.parking.getStore()?.set(t.id,{attempts:t.attempts,reason:r}),t.retry({delaySeconds:q})},Z=(e,t,r)=>{t.attempts>M&&e.parking.getStore()?.set(t.id,{attempts:t.attempts,reason:"retries_exhausted"}),t.retry({delaySeconds:r})},ee=(e,t,r)=>{if(!le(r)){if(Y(r)){T("error","lunora.mail.send_outcome_unknown",t.attempts,r),W(e,t,"outcome_unknown");return}T("error","lunora.mail.send_refused",t.attempts,r),t.ack();return}t.attempts>M?T("error","lunora.mail.send_dead_lettered",t.attempts,r):T("warn","lunora.mail.send_retry",t.attempts,r),Z(e,t,Y(r)?Q:pe*2**(t.attempts-1))},Le=(e,t,r)=>{const i=new Error(`another delivery of idempotency key "${r}" is in flight`);T(t.attempts>M?"error":"warn",t.attempts>M?"lunora.mail.send_dead_lettered":"lunora.mail.send_key_busy",t.attempts,i),Z(e,t,Q)},De=(e,t,r)=>{if(r===void 0)return{delivery:t.attempts,firstDeliveredAt:t.timestamp.getTime(),outcome:"taken"};try{return e.claims.take(r,e.fingerprint(t.body),t.id,t.timestamp.getTime())}catch(i){ee(e,t,new se({cause:i,message:`@lunora/mail: could not claim idempotency key "${r}"`,retryable:!0}));return}},B=(e,t,r)=>{try{r()}catch(i){T("error",t,e.attempts,i)}},xe=async(e,t)=>{const r=X(t.body),i=De(e,t,r);if(i===void 0)return;if(i.outcome==="conflict"){T("error","lunora.mail.idempotency_key_conflict",t.attempts,new Error(`idempotency key "${String(r)}" belongs to different content; this send is parked in deadLetters, not sent`)),W(e,t,"idempotency_key_conflict");return}if(i.outcome==="busy"){Le(e,t,String(r));return}const _=i.firstDeliveredAt;if(i.delivery>1&&e.clock()-_>=h){r!==void 0&&B(t,"lunora.mail.claim_release_failed",()=>{e.claims.release(r,t.id)}),T("error","lunora.mail.send_evidence_expired",t.attempts,new Error("an earlier delivery of this key may have been sent, and its record in the sent ledger has expired")),W(e,t,"evidence_expired");return}const y=new Date(Date.now()-(e.clock()-_));try{try{await ae(e.mailer,t.body,{attempts:i.delivery,enqueuedAt:y,sent:e.sent,sentTtlSeconds:h/1e3})}catch(N){ee(e,t,N);return}t.ack()}finally{r!==void 0&&B(t,"lunora.mail.claim_release_failed",()=>{e.claims.release(r,t.id)})}},ve=(e,t)=>({...e,retry:r=>{e.retry({delaySeconds:(r?.delaySeconds??0)+t()})}}),Me=async(e,t)=>{const r=e.clock(),i=()=>Math.ceil(Math.max(0,e.clock()-r)/1e3);for(const _ of t.messages)await xe(e,ve(_,i))},Ue=(e,t={})=>{const r=t.env??{...process.env},i=t.now??Date.now,_={send:async(o,d)=>{const{delaySeconds:n,...a}=d??{};if(Object.keys(a).length>0)throw new O("VALIDATION_ERROR",`@lunora/platform-node: the mail queue takes only a \`delaySeconds\` option, got ${Object.keys(a).join(", ")}`);ye(n);const{insert:c,stored:u}=de(l,"mail")(o,n===void 0?void 0:{delaySeconds:n});oe(u?.idempotencyKey);const s=X(u);if(s===void 0)throw new O("VALIDATION_ERROR","@lunora/platform-node: a queued mail body needs an `idempotencyKey` (a non-empty string) — queue through `mailer.queue()`, which mints one");if(p.claims.reserve(s,p.fingerprint(u),c)==="conflict")throw new O("VALIDATION_ERROR",`@lunora/platform-node: idempotency key "${s}" was already queued with different content — a key names one message, so use a new key for new content`)}},y=Se(r,_,t.transport),N=r.MAIL_FROM,S=o=>fe(o,typeof N=="string"?N:void 0),L=Ae(e,i,S),p={claims:L,clock:i,fingerprint:S,mailer:y,sent:Ne(e,i,o=>{L.keepContent(o)}),parking:new te},l=ce(e,ue({now:i,onBatch:async o=>{await Me(p,o)},queues:{mail:_e({handler:()=>{},maxBatchSize:G,maxBatchTimeout:0,maxRetries:M,name:A})},visibilityTimeoutMs:U}));e.exec(`CREATE INDEX IF NOT EXISTS _lunora_mail_row_keys ON _lunora_queue_messages ((${H}), enqueued_at) WHERE queue = '${A}'`);const E=e.prepare(`UPDATE _lunora_queue_messages SET state = 'dead' WHERE id = ? AND queue = '${A}' AND state = 'pending' AND attempts = ?`);e.exec("CREATE TABLE IF NOT EXISTS _lunora_mail_parked (id TEXT PRIMARY KEY, reason TEXT NOT NULL)");const m=e.prepare("INSERT OR REPLACE INTO _lunora_mail_parked (id, reason) SELECT ?, ? WHERE EXISTS (SELECT 1 FROM _lunora_queue_messages WHERE id = ? AND queue = ? AND state = 'dead' AND attempts = ?)"),f=e.prepare("SELECT reason FROM _lunora_mail_parked WHERE id = ?"),D=e.prepare("DELETE FROM _lunora_mail_parked WHERE id = ?"),x=e.transaction((o,d,n)=>{n<=M&&E.run(o,n),m.run(o,d,o,A,n)}),R=e.prepare("UPDATE _lunora_queue_messages SET state = 'pending', visible_at = ? WHERE id = ? AND queue = ? AND state = 'dead'"),v=e.prepare("SELECT body, enqueued_at FROM _lunora_queue_messages WHERE id = ? AND queue = ? AND state = 'dead'"),g=e.transaction(o=>R.run(i(),o,A).changes===0?!1:(D.run(o),!0)),I=new Set;return{deadLetters:{list:()=>l.deadLetters.list(A).map(o=>({...o,reason:f.get(o.id)?.reason??"unknown"})),requeue:o=>{const d=v.get(o,A);if(d===void 0)return!1;const n=X(JSON.parse(d.body.toString("utf8"))),a=(n===void 0?void 0:p.claims.firstDeliveredAt(n))??d.enqueued_at;if(i()-a>=h)throw new O("VALIDATION_ERROR",`@lunora/platform-node: parked mail ${o} was first attempted 15 or more days ago, so the record of whether an earlier attempt was sent has expired — check the provider's logs and queue it again if it never arrived`);return g.immediate(o)}},drain:async()=>{await Promise.allSettled(I)},idle:()=>I.size===0,mailer:y,poll:async o=>{const d=new Map,n=p.parking.run(d,async()=>await l.poll(o)).finally(()=>{for(const[a,{attempts:c,reason:u}]of d)try{x.immediate(a,u,c)}catch(s){T("error","lunora.mail.park_failed",c,s)}});I.add(n);try{return await n}finally{I.delete(n)}},queue:_}};export{Ue as createNodeMailHost};
|
|
@@ -0,0 +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-ByuCR26s.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-DVi1OsvH.mjs";import{createNodeMailHost as de}from"./createNodeMailHost-DrUo8de-.mjs";import{createNodeQueueHost as le}from"./createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as ce}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as he}from"./createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as ue}from"./createNodeShardHost-VU8MPeba.mjs";import{createNodeShardRegistry as fe,SHARD_FILE_SUFFIX as k}from"./createNodeShardRegistry-C1SRJQhd.mjs";import{createNodeSocketHost as me}from"./createNodeSocketHost-ByOmEGFe.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};
|
|
@@ -0,0 +1,17 @@
|
|
|
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 +1 @@
|
|
|
1
|
-
import{mkdirSync as O,readdirSync as P}from"node:fs";import{join as A}from"node:path";import{LunoraError as U}from"@lunora/errors";import W from"better-sqlite3";import{startDrainDeadline as x,settlesBefore as z}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeShardKvStore as K}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeShardHost as T}from"./createNodeShardHost-VU8MPeba.mjs";import{createNodeSocketHost as V}from"./createNodeSocketHost-ByOmEGFe.mjs";const v=".sqlite3",F=n=>n.replaceAll(/[^\da-z._-]/gu,s=>[...Buffer.from(s,"utf8")].map(d=>`%${d.toString(16).padStart(2,"0").toUpperCase()}`).join("")),X=n=>decodeURIComponent(n),G=(n,s)=>{const d=s.slice(0,-v.length),l=A(n,s);let c;try{c=X(d)}catch{throw new U("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${l}" has a basename that is not valid percent-encoding, so the shard key it holds cannot be recovered. Rename or remove the file.`)}const f=`${F(c)}${v}`;if(f!==s)throw new U("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${l}" was written under an older shard-key encoding. It decodes to shard key "${c}", which this build stores as "${f}" — so the key would be listed for fan-out while every read opened a new, empty database. Rename it: mv "${l}" "${A(n,f)}"`);return c},J=(n,s)=>{let d;try{return d=new W(n,{fileMustExist:!0,readonly:!0}),d.prepare("SELECT 1 FROM _lunora_alarm LIMIT 1").get()!==void 0}catch(l){return console.error("[@lunora/platform-node] could not check shard %s for a persisted alarm, so it is opened to re-arm any",s,l),!0}finally{d?.close()}},y=(n,s,d)=>n===0?"":`${String(n)} ${n===1?s:d}`,Q=(n,s)=>{const d=[y(s.requests,"request in flight","requests in flight"),y(s.alarms,"alarm running","alarms running"),y(s.background,"waitUntil task","waitUntil tasks"),s.closing?"a socket close handler running":""].filter(l=>l!=="");return`shard ${n}: ${d.join(", ")}`},ae=(n={})=>{const s=new Map;let d="open",l=!1;const c=()=>{l=!0;for(const e of s.values())e.suspendAlarms()},f=()=>{if(d!=="open")throw new Error(`@lunora/platform-node: the shard registry is ${d}, so it opens no shard and takes no request`)},m=new Map,B=async(e,t)=>{const r=Promise.resolve().then(t),o=r.then(()=>{},()=>{});let a=m.get(e);return a===void 0&&(a=new Set,m.set(e,a)),a.add(o),o.finally(()=>{a.delete(o),a.size===0&&m.get(e)===a&&m.delete(e)}).catch(()=>{}),r},S=new Set,u=new Set,E=[];if(n.directory!==void 0){O(n.directory,{recursive:!0});for(const e of P(n.directory))e.endsWith(v)&&S.add(G(n.directory,e))}const b=e=>{f();const t=s.get(e);if(t!==void 0)return t.shard;const r=n.directory===void 0?void 0:A(n.directory,`${F(e)}${v}`);let o;const{alarmsSettled:a,database:i,dispose:h,drain:g,host:w,pendingAlarms:_,pendingBackground:j,suspendAlarms:L,takeFailures:C}=T({onAlarm:()=>n.onAlarm?.(o),path:r,shardKey:e}),k=V(i);return o={inbound:k,kv:K(i),shard:w,shardKey:e,sockets:k.socket},s.set(e,{alarmsSettled:a,dispose:h,drain:k.drain,drainHost:g,pendingAlarms:_,pendingBackground:j,shard:o,suspendAlarms:L,takeFailures:C}),S.add(e),l&&L(),o},H=e=>({fetch:async t=>{const r=b(e),{onFetch:o}=n;return o===void 0?new Response(e):B(e,()=>o(t,r))}}),I=()=>[...E.splice(0),...[...s.values()].flatMap(e=>e.takeFailures())],p=()=>{const e=new Map,t=a=>{let i=e.get(a);return i===void 0&&(i={alarms:0,background:0,closing:!1,requests:0},e.set(a,i)),i},r=[];for(const[a,i]of m)r.push(...i),t(a).requests+=i.size;for(const[a,i]of s){const h=i.drain(),g=i.pendingBackground(),w=i.pendingAlarms();h!==void 0&&(t(a).closing=!0,r.push(h)),g>0&&(t(a).background=g),w>0&&(t(a).alarms=w),(g>0||w>0)&&r.push(i.drainHost())}return{labels:[...e].map(([a,i])=>Q(a,i)),waits:r}},N=(e,t)=>{const r=t.drain(),o=t.alarmsSettled();return[...m.get(e)??[],...o===void 0?[]:[o],...r===void 0?[]:[r]]},R=()=>{d!=="open"&&s.size===0&&(d="closed")},q=(e,t)=>{try{t.dispose()}catch(r){return r??new Error(`shard ${e} failed to close`)}s.delete(e)},$=(e,t)=>{const r=N(e,t);if(r.length>0){Promise.allSettled(r).then(()=>{u.has(e)&&s.get(e)===t&&$(e,t)}).catch(()=>{});return}u.delete(e);const o=q(e,t);o!==void 0&&(console.error("[@lunora/platform-node] shard %s failed to close after the work using it settled",e,o),E.push(`shard ${e} failed to close after the work using it settled`)),R()},D=(e,t,r)=>{const o=q(e,t);return o===void 0?u.delete(e):r&&!u.has(e)&&(u.add(e),$(e,t)),o},M=(e,t)=>{e.length>0&&console.error("[@lunora/platform-node] closed %d shard(s) with a request, alarm handler or socket close handler still running: %s",e.length,e.join(", "));for(const{error:r,key:o}of t)console.error("[@lunora/platform-node] shard %s failed to close",o,r);if(t.length>0)throw new AggregateError(t.map(({error:r})=>r),`@lunora/platform-node: ${String(t.length)} shard(s) failed to close: ${t.map(({key:r})=>r).join(", ")}`)};return{close:e=>{d==="open"&&(d="closing");const t=[],r=[];c();for(const[o,a]of s){const i=N(o,a);if(i.length===0||e?.force===!0){i.length>0&&t.push(o);const h=D(o,a,i.length>0);h!==void 0&&r.push({error:h,key:o})}else u.has(o)||(u.add(o),$(o,a))}R(),M(t,r)},drain:async e=>{const t=x(e);try{for(let r=p();r.waits.length>0;r=p())if(!await z(Promise.allSettled(r.waits),t)){const o=p().labels;return console.error("[@lunora/platform-node] shard drain deadline passed with work still running: %s",o.join(", ")),{failed:I(),pending:o,timedOut:!0}}return{failed:I(),pending:[],timedOut:!1}}finally{t.cancel()}},directory:{get:e=>H(String(e)),getByName:e=>H(e),idForName:e=>e},idle:()=>p().waits.length===0,pending:()=>p().labels,rearmPersistedAlarms:()=>{f();const{directory:e}=n;if(e===void 0)return[];const t=[];for(const r of S)if(!s.has(r)&&J(A(e,`${F(r)}${v}`),r))try{b(r),t.push(r)}catch(o){console.error("[@lunora/platform-node] could not open shard %s to re-arm its persisted alarm",r,o)}return t},listShardKeys:()=>[...S],shardFor:b,suspendAlarms:c}};export{ae as createNodeShardRegistry};
|
|
1
|
+
import{mkdirSync as O,readdirSync as P}from"node:fs";import{join as A}from"node:path";import{LunoraError as U}from"@lunora/errors";import W from"better-sqlite3";import{startDrainDeadline as x,settlesBefore as z}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeShardKvStore as K}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeShardHost as T}from"./createNodeShardHost-VU8MPeba.mjs";import{createNodeSocketHost as V}from"./createNodeSocketHost-ByOmEGFe.mjs";const v=".sqlite3",F=n=>n.replaceAll(/[^\da-z._-]/gu,s=>[...Buffer.from(s,"utf8")].map(d=>`%${d.toString(16).padStart(2,"0").toUpperCase()}`).join("")),X=n=>decodeURIComponent(n),G=(n,s)=>{const d=s.slice(0,-v.length),l=A(n,s);let c;try{c=X(d)}catch{throw new U("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${l}" has a basename that is not valid percent-encoding, so the shard key it holds cannot be recovered. Rename or remove the file.`)}const f=`${F(c)}${v}`;if(f!==s)throw new U("SHARD_UNAVAILABLE",`@lunora/platform-node: shard database "${l}" was written under an older shard-key encoding. It decodes to shard key "${c}", which this build stores as "${f}" — so the key would be listed for fan-out while every read opened a new, empty database. Rename it: mv "${l}" "${A(n,f)}"`);return c},J=(n,s)=>{let d;try{return d=new W(n,{fileMustExist:!0,readonly:!0}),d.prepare("SELECT 1 FROM _lunora_alarm LIMIT 1").get()!==void 0}catch(l){return console.error("[@lunora/platform-node] could not check shard %s for a persisted alarm, so it is opened to re-arm any",s,l),!0}finally{d?.close()}},y=(n,s,d)=>n===0?"":`${String(n)} ${n===1?s:d}`,Q=(n,s)=>{const d=[y(s.requests,"request in flight","requests in flight"),y(s.alarms,"alarm running","alarms running"),y(s.background,"waitUntil task","waitUntil tasks"),s.closing?"a socket close handler running":""].filter(l=>l!=="");return`shard ${n}: ${d.join(", ")}`},ae=(n={})=>{const s=new Map;let d="open",l=!1;const c=()=>{l=!0;for(const e of s.values())e.suspendAlarms()},f=()=>{if(d!=="open")throw new Error(`@lunora/platform-node: the shard registry is ${d}, so it opens no shard and takes no request`)},m=new Map,B=async(e,t)=>{const r=Promise.resolve().then(t),o=r.then(()=>{},()=>{});let a=m.get(e);return a===void 0&&(a=new Set,m.set(e,a)),a.add(o),o.finally(()=>{a.delete(o),a.size===0&&m.get(e)===a&&m.delete(e)}).catch(()=>{}),r},S=new Set,u=new Set,E=[];if(n.directory!==void 0){O(n.directory,{recursive:!0});for(const e of P(n.directory))e.endsWith(v)&&S.add(G(n.directory,e))}const b=e=>{f();const t=s.get(e);if(t!==void 0)return t.shard;const r=n.directory===void 0?void 0:A(n.directory,`${F(e)}${v}`);let o;const{alarmsSettled:a,database:i,dispose:h,drain:g,host:w,pendingAlarms:_,pendingBackground:j,suspendAlarms:L,takeFailures:C}=T({onAlarm:()=>n.onAlarm?.(o),path:r,shardKey:e}),k=V(i);return o={inbound:k,kv:K(i),shard:w,shardKey:e,sockets:k.socket},s.set(e,{alarmsSettled:a,dispose:h,drain:k.drain,drainHost:g,pendingAlarms:_,pendingBackground:j,shard:o,suspendAlarms:L,takeFailures:C}),S.add(e),l&&L(),o},H=e=>({fetch:async t=>{const r=b(e),{onFetch:o}=n;return o===void 0?new Response(e):B(e,()=>o(t,r))}}),I=()=>[...E.splice(0),...[...s.values()].flatMap(e=>e.takeFailures())],p=()=>{const e=new Map,t=a=>{let i=e.get(a);return i===void 0&&(i={alarms:0,background:0,closing:!1,requests:0},e.set(a,i)),i},r=[];for(const[a,i]of m)r.push(...i),t(a).requests+=i.size;for(const[a,i]of s){const h=i.drain(),g=i.pendingBackground(),w=i.pendingAlarms();h!==void 0&&(t(a).closing=!0,r.push(h)),g>0&&(t(a).background=g),w>0&&(t(a).alarms=w),(g>0||w>0)&&r.push(i.drainHost())}return{labels:[...e].map(([a,i])=>Q(a,i)),waits:r}},N=(e,t)=>{const r=t.drain(),o=t.alarmsSettled();return[...m.get(e)??[],...o===void 0?[]:[o],...r===void 0?[]:[r]]},R=()=>{d!=="open"&&s.size===0&&(d="closed")},q=(e,t)=>{try{t.dispose()}catch(r){return r??new Error(`shard ${e} failed to close`)}s.delete(e)},$=(e,t)=>{const r=N(e,t);if(r.length>0){Promise.allSettled(r).then(()=>{u.has(e)&&s.get(e)===t&&$(e,t)}).catch(()=>{});return}u.delete(e);const o=q(e,t);o!==void 0&&(console.error("[@lunora/platform-node] shard %s failed to close after the work using it settled",e,o),E.push(`shard ${e} failed to close after the work using it settled`)),R()},D=(e,t,r)=>{const o=q(e,t);return o===void 0?u.delete(e):r&&!u.has(e)&&(u.add(e),$(e,t)),o},M=(e,t)=>{e.length>0&&console.error("[@lunora/platform-node] closed %d shard(s) with a request, alarm handler or socket close handler still running: %s",e.length,e.join(", "));for(const{error:r,key:o}of t)console.error("[@lunora/platform-node] shard %s failed to close",o,r);if(t.length>0)throw new AggregateError(t.map(({error:r})=>r),`@lunora/platform-node: ${String(t.length)} shard(s) failed to close: ${t.map(({key:r})=>r).join(", ")}`)};return{close:e=>{d==="open"&&(d="closing");const t=[],r=[];c();for(const[o,a]of s){const i=N(o,a);if(i.length===0||e?.force===!0){i.length>0&&t.push(o);const h=D(o,a,i.length>0);h!==void 0&&r.push({error:h,key:o})}else u.has(o)||(u.add(o),$(o,a))}R(),M(t,r)},drain:async e=>{const t=x(e);try{for(let r=p();r.waits.length>0;r=p())if(!await z(Promise.allSettled(r.waits),t)){const o=p().labels;return console.error("[@lunora/platform-node] shard drain deadline passed with work still running: %s",o.join(", ")),{failed:I(),pending:o,timedOut:!0}}return{failed:I(),pending:[],timedOut:!1}}finally{t.cancel()}},directory:{get:e=>H(String(e)),getByName:e=>H(e),idForName:e=>e},idle:()=>p().waits.length===0,pending:()=>p().labels,rearmPersistedAlarms:()=>{f();const{directory:e}=n;if(e===void 0)return[];const t=[];for(const r of S)if(!s.has(r)&&J(A(e,`${F(r)}${v}`),r))try{b(r),t.push(r)}catch(o){console.error("[@lunora/platform-node] could not open shard %s to re-arm its persisted alarm",r,o)}return t},listShardKeys:()=>[...S],shardFor:b,suspendAlarms:c}};export{v as SHARD_FILE_SUFFIX,ae as createNodeShardRegistry};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/platform-node",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.221",
|
|
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",
|
|
@@ -48,6 +48,7 @@
|
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"@lunora/d1": "^1.0.0-alpha.237",
|
|
50
50
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
51
|
+
"@lunora/mail": "^1.0.0-alpha.139",
|
|
51
52
|
"@lunora/platform": "^1.0.0-alpha.81",
|
|
52
53
|
"@lunora/queue": "^1.0.0-alpha.144",
|
|
53
54
|
"@lunora/runtime": "^1.0.0-alpha.292",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as d}from"@lunora/errors";import{NODE_CAPABILITIES as H}from"@lunora/platform";import{a as q,c as U,i as $,A as C}from"./node-dispatch-route-ByuCR26s.mjs";import{startDrainDeadline as V,settlesBefore as N,drainTimeoutMs as Q,drainTogether as x}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeGlobalStore as G}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as K}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeQueueHost as M}from"./createNodeQueueHost-szMV0PBN.mjs";import{createNodeR2Bucket as W}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as J}from"./createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as j}from"./createNodeShardHost-VU8MPeba.mjs";import{createNodeShardRegistry as Y}from"./createNodeShardRegistry-BHzxHBx1.mjs";import{createNodeSocketHost as z}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as X}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as Z}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const ee="__root__",re=e=>Object.entries(e).flatMap(([o,r])=>r.map(t=>{if(t.functionPath===void 0)throw new d("VALIDATION_ERROR",t.workflow===void 0?`@lunora/platform-node: cron job "${t.name}" has neither a function target nor a workflow target`:`@lunora/platform-node: cron job "${t.name}" starts workflow "${t.workflow}", which this host cannot do from a cron tick — schedule a function that calls ctx.workflows.get(name).create() instead`);return{args:t.args??{},expression:o,functionPath:t.functionPath,name:t.name}})),oe=(e,o)=>{const r=re(e);if(r.length>0&&!o)throw new d("VALIDATION_ERROR","@lunora/platform-node: `crons` declares jobs but nothing can deliver them — pass `onFetch` (to run them on the shard) or `onDispatch`");return r},te=(e,o)=>async(r,t,c)=>{if($(r,o,ee))throw new d("BAD_REQUEST",C);const i=await e({args:t,functionPath:r,id:c.id,identity:void 0,scheduledFor:c.scheduledFor,shardKey:o,traceparent:void 0});if(!i.ok)throw new d("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(i.status)}`)},Se=(e={})=>{const o=[],{database:r,dispose:t,drain:c,host:i,pendingAlarms:p,pendingBackground:g,suspendAlarms:R,takeFailures:S}=j(e);o.push(t);try{const l=K(r),s=Y(e);o.push(a=>{s.close(a)});const{directory:v}=s,k=q(v,e.onFetch!==void 0),y=U({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:k,schedulerSecret:e.dispatch?.schedulerSecret}),E=e.onFetch===void 0?void 0:te(k,e.shardKey??"__root__"),{declareCrons:b,dispose:T,pendingDispatches:h,scheduler:I,suspend:F}=J(r,{...e,onDispatch:e.onDispatch??E}),{socket:O}=z(r);o.push(T),e.crons!==void 0&&b(oe(e.crons,e.onDispatch!==void 0||e.onFetch!==void 0));const P=e.queues===void 0?void 0:M(r,{onBatch:e.onQueueBatch??(()=>{throw new d("VALIDATION_ERROR","@lunora/platform-node: createNodePlatform was given `queues` without `onQueueBatch`, so a delivered batch has nowhere to go — pass the worker's queue export from createWorker")}),queues:e.queues}),B=e.objectStorageDirectory===void 0?void 0:W({directory:e.objectStorageDirectory}),u=e.globalTablesPath===void 0?void 0:G({path:e.globalTablesPath});u!==void 0&&o.push(()=>{u.dispose()});const L=e.workflows===void 0?void 0:X({store:Z(r),workflows:e.workflows}),A=a=>{const n=[];for(const m of o.toReversed())try{m(a)}catch(w){n.push(w)}if(n.length>0)throw new AggregateError(n,`@lunora/platform-node: ${String(n.length)} resource(s) failed to close`)},_=()=>[...g()>0||p()>0?["waitUntil work on the platform host"]:[],...h().labels],f={drain:async a=>{const n=V(a);try{const[m,w]=await Promise.all([N(c(),n),N(Promise.allSettled(h().waits),n)]);if(m&&w)return{failed:S(),pending:[],timedOut:!1};const D=_();return console.error("[@lunora/platform-node] platform drain deadline passed with work still running: %s",D.join(", ")),{failed:S(),pending:D,timedOut:!0}}finally{n.cancel()}},idle:()=>g()===0&&p()===0&&h().waits.length===0,pending:_};return{capabilities:H,close:A,directory:v,dispatch:a=>y(a),idle:()=>f.idle()&&s.idle(),pending:()=>[...f.pending(),...s.pending()],drain:async a=>(Q(a),F(),R(),s.suspendAlarms(),x([f,s],a)),globalTables:u,kv:l,objectStorage:B,rearmPersistedAlarms:()=>s.rearmPersistedAlarms(),queues:P,scheduler:I,shard:i,sockets:O,workflows:L,[Symbol.dispose]:()=>{A()}}}catch(l){for(const s of o.toReversed())try{s()}catch{}throw l}};export{te as createJobDelivery,Se as createNodePlatform};
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{randomUUID as F}from"node:crypto";import{deserialize as H,serialize as W}from"node:v8";import{LunoraError as m}from"@lunora/errors";import{isQueueDefinition as X,queueDefaultName as $,queueBindingName as Q}from"@lunora/queue";const _={maxBatchSize:10,maxBatchTimeoutSeconds:5,maxRetries:3,retryDelaySeconds:0,visibilityTimeoutMs:3e4},V=86400,A=131072,S=262144,k=(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 m("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "bytes" needs an ArrayBuffer or a typed array')}case"text":{if(typeof e!="string")throw new m("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "text" needs a string');return Buffer.from(e,"utf8")}case"v8":return W(e);default:return Buffer.from(JSON.stringify(e??null),"utf8")}},O=(e,i,R)=>{const E=k(e,i);if(E.byteLength>A)throw new m("VALIDATION_ERROR",`@lunora/platform-node: a message for queue "${R}" encodes to ${String(E.byteLength)} bytes, over the Cloudflare Queues ceiling of ${String(A)} (128 KiB) per message — store the payload and enqueue a reference to it`);return E},D=(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 H(e);default:return JSON.parse(e.toString("utf8"))}},Y=e=>{try{return D(e.body,e.content_type)}catch{return}},y=e=>e===void 0||!Number.isFinite(e)?0:Math.min(Math.max(0,Math.ceil(e)),V)*1e3,K=(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 R=e.prepare("INSERT INTO _lunora_queue_messages (id, queue, body, content_type, visible_at, enqueued_at) VALUES (?, ?, ?, ?, ?, ?)"),E=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 *`),q=e.prepare("UPDATE _lunora_queue_messages SET visible_at = ? WHERE id = ?"),h=e.prepare("DELETE FROM _lunora_queue_messages WHERE id = ?"),v=e.prepare("UPDATE _lunora_queue_messages SET state = 'dead' WHERE id = ?"),B=e.prepare("SELECT enqueued_at FROM _lunora_queue_messages WHERE queue = ? AND state = 'pending' AND visible_at <= ? ORDER BY enqueued_at LIMIT 1"),I=e.prepare("SELECT COUNT(*) AS n FROM _lunora_queue_messages WHERE queue = ? AND state = 'pending' AND visible_at <= ?"),M=e.prepare("SELECT * FROM _lunora_queue_messages WHERE queue = ? AND state = 'dead' ORDER BY enqueued_at"),b=e.prepare("UPDATE _lunora_queue_messages SET state = 'pending', attempts = 0, visible_at = ? WHERE id = ? AND state = 'dead'"),p=Object.entries(i.queues).map(([t,n])=>{if(!X(n))throw new m("VALIDATION_ERROR",`@lunora/platform-node: "${t}" is not a defineQueue result`);return{definition:n,exportName:t,name:n.name??$(t)}}),x=new Set(p.map(t=>t.name));for(const t of p){const n=t.definition.deadLetterQueue;if(n!==void 0){if(n===t.name)throw new m("VALIDATION_ERROR",`@lunora/platform-node: queue "${t.name}" names itself as its own deadLetterQueue, which would redeliver forever`);if(!x.has(n))throw new m("VALIDATION_ERROR",`@lunora/platform-node: queue "${t.name}" names deadLetterQueue "${n}", which no declared queue provides — its dead letters would be unreachable`)}}const U=i.visibilityTimeoutMs??_.visibilityTimeoutMs,T=i.now??Date.now,g=(t,n,s,u,o)=>{R.run(F(),t,n,s,o+u,o)},w=(t,n,s,u,o)=>{if(s==="ack"){h.run(t.id);return}const c=n.definition.maxRetries??_.maxRetries;if(t.attempts>c){const l=n.definition.deadLetterQueue;l===void 0?v.run(t.id):(g(l,t.body,t.content_type,0,o),h.run(t.id));return}const f=y(u??n.definition.retryDelay??_.retryDelaySeconds);q.run(o+f,t.id)},N={},L={...i.env};for(const t of p){const n={send:async(s,u)=>{const o=u?.contentType??"json";g(t.name,O(s,o,t.name),o,y(u?.delaySeconds),T())},sendBatch:async(s,u)=>{const o=T(),c=y(u?.delaySeconds),f=[...s].map(a=>{const r=a.contentType??"json";return{contentType:r,delay:a.delaySeconds===void 0?c:y(a.delaySeconds),encoded:O(a.body,r,t.name)}}),l=f.reduce((a,r)=>a+r.encoded.byteLength,0);if(l>S)throw new m("VALIDATION_ERROR",`@lunora/platform-node: a sendBatch for queue "${t.name}" encodes to ${String(l)} bytes, over the Cloudflare Queues ceiling of ${String(S)} (256 KiB) per batch — split it across more calls`);e.transaction(()=>{for(const a of f)g(t.name,a.encoded,a.contentType,a.delay,o)})()}};N[t.exportName]=n,L[Q(t.exportName)]=n}const C=async(t,n)=>{const s=Math.min(Math.max(1,t.definition.maxBatchSize??_.maxBatchSize),100),u=I.get(t.name,n)?.n??0;if(u===0)return!1;if(u<s){const r=B.get(t.name,n)?.enqueued_at,d=Math.min(Math.max(0,t.definition.maxBatchTimeout??_.maxBatchTimeoutSeconds),60)*1e3;if(r!==void 0&&n-r<d)return!1}const o=e.transaction(()=>E.all(n+U,t.name,n,s)).immediate();if(o.length===0)return!1;const c=new Map,f=o.map(r=>({ack:()=>{c.set(r.id,{outcome:"ack"})},attempts:r.attempts,body:D(r.body,r.content_type),id:r.id,retry:d=>{c.set(r.id,{delaySeconds:d?.delaySeconds,outcome:"retry"})},timestamp:new Date(r.enqueued_at)})),l={ackAll:()=>{for(const r of o)c.set(r.id,{outcome:"ack"})},messages:f,queue:t.name,retryAll:r=>{for(const d of o)c.set(d.id,{delaySeconds:r?.delaySeconds,outcome:"retry"})}};let a="ack";try{await i.onBatch(l)}catch{a="retry"}return e.transaction(()=>{for(const r of o){const d=c.get(r.id);w(r,t,d?.outcome??a,d?.delaySeconds,n)}})(),!0};return{bindings:N,deadLetters:{list:t=>M.all(t).map(n=>({attempts:n.attempts,body:Y(n),id:n.id})),requeue:t=>b.run(T(),t).changes>0},env:L,poll:async(t=T())=>{let n=0;for(const s of p)s.definition.mode!=="pull"&&await C(s,t)&&(n+=1);return n}}};export{K as createNodeQueueHost};
|