@guren/server 2.22.0 → 2.23.1

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.
Files changed (108) hide show
  1. package/dist/Job-BVvaY-7p.js +165 -0
  2. package/dist/auth/AuthManager.d.ts +29 -0
  3. package/dist/auth/AuthenticatableModel.d.ts +15 -0
  4. package/dist/auth/RequestAuthContext.d.ts +10 -1
  5. package/dist/auth/SessionGuard.d.ts +2 -0
  6. package/dist/auth/api-token.d.ts +6 -0
  7. package/dist/auth/context.d.ts +32 -0
  8. package/dist/auth/index.d.ts +7 -0
  9. package/dist/auth/index.js +2 -2
  10. package/dist/auth/model-capability.d.ts +8 -0
  11. package/dist/auth/oauth/index.d.ts +5 -0
  12. package/dist/auth/password/DefaultHasher.d.ts +17 -6
  13. package/dist/auth/password/configured-hasher.d.ts +23 -0
  14. package/dist/auth/providers/ModelUserProvider.d.ts +3 -0
  15. package/dist/auth/providers/unconfigured-user-provider.d.ts +12 -0
  16. package/dist/auth/types.d.ts +9 -0
  17. package/dist/{auth-CjE2oO50.js → auth-D_W1cJp3.js} +279 -84
  18. package/dist/authorization/Gate.d.ts +12 -0
  19. package/dist/authorization/index.js +1 -1
  20. package/dist/{authorization-CdEWZZw3.js → authorization-0mCGUFoI.js} +58 -12
  21. package/dist/broadcasting/BroadcastManager.d.ts +10 -0
  22. package/dist/broadcasting/index.js +1 -1
  23. package/dist/{broadcasting-B5RzB0A2.js → broadcasting-BdJnaq1O.js} +17 -3
  24. package/dist/console/Command.d.ts +3 -3
  25. package/dist/console/ConsoleKernel.d.ts +2 -2
  26. package/dist/console/index.d.ts +1 -1
  27. package/dist/console/types.d.ts +9 -1
  28. package/dist/container/Container.d.ts +18 -1
  29. package/dist/container/bindings.d.ts +5 -0
  30. package/dist/container/index.d.ts +4 -2
  31. package/dist/container/resolve-optional.d.ts +10 -0
  32. package/dist/context-af2n5abO.js +91 -0
  33. package/dist/{Job-CvDwk2Gj.js → default-application-Chbrul_m.js} +126 -82
  34. package/dist/encryption/Encrypter.d.ts +10 -0
  35. package/dist/encryption/index.js +1 -1
  36. package/dist/{encryption-uwP3Di4D.js → encryption-BRjZnshr.js} +23 -5
  37. package/dist/errors/ExceptionHandler.d.ts +10 -0
  38. package/dist/events/Event.d.ts +18 -0
  39. package/dist/events/EventManager.d.ts +56 -4
  40. package/dist/events/index.d.ts +2 -1
  41. package/dist/events/index.js +2 -2
  42. package/dist/events/queued.d.ts +8 -0
  43. package/dist/events/serialize.d.ts +8 -0
  44. package/dist/events/types.d.ts +19 -2
  45. package/dist/events-CaJKZ2qk.js +428 -0
  46. package/dist/health/checks/CacheCheck.d.ts +3 -5
  47. package/dist/health/checks/StorageCheck.d.ts +3 -5
  48. package/dist/health/index.js +1 -1
  49. package/dist/{health-DQSvUplL.js → health-CB0oS_UE.js} +2 -2
  50. package/dist/http/Application.d.ts +28 -0
  51. package/dist/http/default-application.d.ts +33 -0
  52. package/dist/http/middleware/detect-locale.d.ts +2 -1
  53. package/dist/http/request-container.d.ts +25 -0
  54. package/dist/i18n/I18nManager.d.ts +16 -3
  55. package/dist/i18n/index.d.ts +1 -1
  56. package/dist/i18n/index.js +2 -2
  57. package/dist/{i18n-BZ2VrSud.js → i18n-DRo1g0AN.js} +34 -10
  58. package/dist/index.d.ts +14 -9
  59. package/dist/index.js +196 -87
  60. package/dist/lambda/index.js +1 -1
  61. package/dist/logging/LogManager.d.ts +9 -0
  62. package/dist/logging/index.js +1 -1
  63. package/dist/{logging-Dmzdb6mL.js → logging-CXotojgW.js} +16 -3
  64. package/dist/mail/Mail.d.ts +14 -1
  65. package/dist/mail/MailManager.d.ts +10 -2
  66. package/dist/mail/index.js +1 -1
  67. package/dist/{mail-9CrvJyBZ.js → mail-zMjQimaJ.js} +42 -11
  68. package/dist/mvc/Controller.d.ts +2 -2
  69. package/dist/mvc/Router.d.ts +16 -5
  70. package/dist/mvc/inertia/InertiaEngine.d.ts +18 -3
  71. package/dist/mvc/inertia/shared.d.ts +7 -0
  72. package/dist/notifications/NotificationManager.d.ts +15 -0
  73. package/dist/notifications/index.js +1 -1
  74. package/dist/{notifications-D0VXkFLF.js → notifications-BLid0Y6M.js} +24 -5
  75. package/dist/providers/AuthServiceProvider.d.ts +5 -4
  76. package/dist/providers/AuthorizationServiceProvider.d.ts +2 -2
  77. package/dist/providers/BroadcastServiceProvider.d.ts +4 -1
  78. package/dist/providers/EncryptionServiceProvider.d.ts +7 -1
  79. package/dist/providers/EventServiceProvider.d.ts +1 -0
  80. package/dist/providers/LogServiceProvider.d.ts +6 -1
  81. package/dist/providers/MailServiceProvider.d.ts +7 -1
  82. package/dist/providers/NotificationServiceProvider.d.ts +4 -1
  83. package/dist/queue/Job.d.ts +39 -0
  84. package/dist/queue/QueueManager.d.ts +14 -5
  85. package/dist/queue/Worker.d.ts +2 -1
  86. package/dist/queue/index.d.ts +1 -1
  87. package/dist/queue/index.js +3 -3
  88. package/dist/queue/types.d.ts +7 -0
  89. package/dist/{queue-zPPYZdif.js → queue-IdJjqbyJ.js} +24 -10
  90. package/dist/redis/RedisSchedulerLock.d.ts +17 -0
  91. package/dist/redis/index.d.ts +2 -0
  92. package/dist/redis/index.js +21 -1
  93. package/dist/runtime/index.js +1 -1
  94. package/dist/scheduling/MemorySchedulerLock.d.ts +16 -0
  95. package/dist/scheduling/ScheduledTask.d.ts +19 -2
  96. package/dist/scheduling/Scheduler.d.ts +25 -0
  97. package/dist/scheduling/index.d.ts +2 -1
  98. package/dist/scheduling/index.js +2 -2
  99. package/dist/scheduling/types.d.ts +26 -2
  100. package/dist/{scheduling-C6tcOtUl.js → scheduling-DudNXGnh.js} +178 -20
  101. package/dist/storage/index.js +1 -1
  102. package/dist/{storage-D_yNe54O.js → storage-6HLaUf9j.js} +2 -13
  103. package/dist/support/deprecate.d.ts +16 -0
  104. package/dist/{vite-manifest-D295_7-_.js → vite-manifest-QooqG8FE.js} +1 -1
  105. package/dist/warn-once-p-IlMjra.js +13 -0
  106. package/package.json +2 -2
  107. package/dist/context-CXk_umpT.js +0 -21
  108. package/dist/events-DOmAHDeP.js +0 -230
@@ -1,3 +1,3 @@
1
- import { a as getRegisteredJobs, c as setQueueDriver, i as getQueueDriver, n as clearJobRegistry, o as registerJob, r as getJob, s as resolveJobName, t as Job } from "../Job-CvDwk2Gj.js";
2
- import { a as processJob, c as RedisDriver, i as Worker, l as SyncDriver, n as createQueueManager, o as SqsDriver, r as FailedJobReporter, s as createSqsAdapter, t as QueueManager, u as MemoryDriver } from "../queue-zPPYZdif.js";
3
- export { FailedJobReporter, Job, MemoryDriver, QueueManager, RedisDriver, SqsDriver, SyncDriver, Worker, clearJobRegistry, createQueueManager, createSqsAdapter, getJob, getQueueDriver, getRegisteredJobs, processJob, registerJob, resolveJobName, setQueueDriver };
1
+ import { a as getJob, d as resolveQueueDriver, f as setQueueDriver, l as registerJob, n as clearJobRegistry, o as getQueueDriver, r as clearQueueDriver, s as getRegisteredJobs, t as Job, u as resolveJobName } from "../Job-BVvaY-7p.js";
2
+ import { a as processJob, c as RedisDriver, i as Worker, l as SyncDriver, n as createQueueManager, o as SqsDriver, r as FailedJobReporter, s as createSqsAdapter, t as QueueManager, u as MemoryDriver } from "../queue-IdJjqbyJ.js";
3
+ export { FailedJobReporter, Job, MemoryDriver, QueueManager, RedisDriver, SqsDriver, SyncDriver, Worker, clearJobRegistry, clearQueueDriver, createQueueManager, createSqsAdapter, getJob, getQueueDriver, getRegisteredJobs, processJob, registerJob, resolveJobName, resolveQueueDriver, setQueueDriver };
@@ -1,3 +1,4 @@
1
+ import type { ContainerLike } from '../container/types.js';
1
2
  /** Serialized job data stored in the queue. */
2
3
  export interface QueuedJob<T = unknown> {
3
4
  id: string;
@@ -55,6 +56,12 @@ export interface JobOptions {
55
56
  }
56
57
  /** Worker options. */
57
58
  export interface WorkerOptions {
59
+ /**
60
+ * The container of the app whose jobs this worker runs; each job receives it
61
+ * through `setContainer()` before `handle()` (RFC 0023 §2). Without it a job
62
+ * resolves from the default application.
63
+ */
64
+ container?: ContainerLike;
58
65
  /**
59
66
  * Queues to process (in priority order).
60
67
  * @default ['default']
@@ -1,4 +1,4 @@
1
- import { c as setQueueDriver, r as getJob } from "./Job-CvDwk2Gj.js";
1
+ import { a as getJob, i as enqueueJob } from "./Job-BVvaY-7p.js";
2
2
  //#region src/queue/drivers/MemoryDriver.ts
3
3
  /** In-memory queue driver for development and testing. */
4
4
  var MemoryDriver = class {
@@ -569,7 +569,7 @@ var Worker = class {
569
569
  return;
570
570
  }
571
571
  try {
572
- const instance = new JobClass();
572
+ const instance = this.instantiate(JobClass);
573
573
  await this.executeWithTimeout(async () => instance.handle(job.payload), this.timeout);
574
574
  await this.driver.delete(job.id);
575
575
  this.events.jobProcessed?.(job);
@@ -588,7 +588,7 @@ var Worker = class {
588
588
  } else {
589
589
  await this.driver.fail(job, error);
590
590
  try {
591
- const instance = new JobClass();
591
+ const instance = this.instantiate(JobClass);
592
592
  if (instance.failed) await instance.failed(job.payload, error);
593
593
  } catch (failedError) {
594
594
  console.error(`Error in job.failed() handler:`, failedError);
@@ -606,6 +606,11 @@ var Worker = class {
606
606
  }));
607
607
  this.events.jobFailed?.(job, error, willRetry);
608
608
  }
609
+ instantiate(JobClass) {
610
+ const instance = new JobClass();
611
+ if (this.options.container) instance.setContainer(this.options.container);
612
+ return instance;
613
+ }
609
614
  async executeWithTimeout(fn, timeoutMs) {
610
615
  return new Promise((resolve, reject) => {
611
616
  const timer = setTimeout(() => {
@@ -625,8 +630,9 @@ var Worker = class {
625
630
  }
626
631
  };
627
632
  /** Process one job without a running worker, for tests and one-off execution. */
628
- async function processJob(driver, queue = "default") {
633
+ async function processJob(driver, queue = "default", options = {}) {
629
634
  const worker = new Worker(driver, {
635
+ ...options,
630
636
  queues: [queue],
631
637
  maxJobs: 1,
632
638
  stopWhenEmpty: true
@@ -668,8 +674,10 @@ var FailedJobReporter = class {
668
674
  //#endregion
669
675
  //#region src/queue/QueueManager.ts
670
676
  /**
671
- * Resolves queue drivers by name from the configured factories; `driver()` with
672
- * no name returns the default and publishes it as the global driver.
677
+ * Resolves queue drivers by name from the configured factories, memoized per
678
+ * name. Nothing here writes the `Job.dispatch()` pin: `getQueueDriver()` reads
679
+ * the manager the container holds, so a second app's manager is not shadowed by
680
+ * the first one's driver.
673
681
  */
674
682
  var QueueManager = class {
675
683
  defaultDriver;
@@ -687,9 +695,16 @@ var QueueManager = class {
687
695
  if (!factory) throw new Error(`Queue driver not found: ${driverName}`);
688
696
  const driver = factory();
689
697
  this.resolvedDrivers.set(driverName, driver);
690
- if (driverName === this.defaultDriver) setQueueDriver(driver);
691
698
  return driver;
692
699
  }
700
+ /**
701
+ * Explicit form of `JobClass.dispatch(payload, options)`: the same message,
702
+ * pushed through this manager's default driver rather than the ambient one
703
+ * (RFC 0023 §3).
704
+ */
705
+ async dispatch(JobClass, payload, options = {}) {
706
+ return enqueueJob(this.driver(), JobClass, payload, options);
707
+ }
693
708
  registerDriver(name, factory) {
694
709
  this.driverFactories.set(name, factory);
695
710
  this.resolvedDrivers.delete(name);
@@ -704,13 +719,12 @@ var QueueManager = class {
704
719
  return Array.from(this.driverFactories.keys());
705
720
  }
706
721
  /**
707
- * After this, `driver()` with no name, `getDefaultDriverName()`, and
708
- * `Job.dispatch()` all use the new driver.
722
+ * After this, `driver()` with no name, `getDefaultDriverName()`, and — for a
723
+ * manager bound as `queue` — `Job.dispatch()` all use the new driver.
709
724
  */
710
725
  setDefaultDriver(name) {
711
726
  if (!this.driverFactories.has(name)) throw new Error(`Queue driver not found: ${name}`);
712
727
  this.defaultDriver = name;
713
- setQueueDriver(this.driver(name));
714
728
  }
715
729
  };
716
730
  function createQueueManager(config) {
@@ -0,0 +1,17 @@
1
+ import type { Redis } from 'ioredis';
2
+ import type { SchedulerLock } from '../scheduling/types.js';
3
+ export interface RedisSchedulerLockOptions {
4
+ /** @default 'scheduler:' */
5
+ prefix?: string;
6
+ }
7
+ /**
8
+ * `SchedulerLock` shared by every server on one Redis: `SET NX EX` is the whole
9
+ * acquire, so two servers asking for the same tick get one `OK` between them.
10
+ */
11
+ export declare class RedisSchedulerLock implements SchedulerLock {
12
+ private readonly redis;
13
+ private readonly prefix;
14
+ constructor(redis: Redis, options?: RedisSchedulerLockOptions);
15
+ acquire(key: string, ttlSeconds: number): Promise<boolean>;
16
+ release(key: string): Promise<void>;
17
+ }
@@ -12,3 +12,5 @@ export { RedisEmailVerificationStore } from './RedisEmailVerificationStore.js';
12
12
  export type { RedisEmailVerificationStoreOptions } from './RedisEmailVerificationStore.js';
13
13
  export { RedisOAuthStateStore } from './RedisOAuthStateStore.js';
14
14
  export type { RedisOAuthStateStoreOptions } from './RedisOAuthStateStore.js';
15
+ export { RedisSchedulerLock } from './RedisSchedulerLock.js';
16
+ export type { RedisSchedulerLockOptions } from './RedisSchedulerLock.js';
@@ -459,4 +459,24 @@ var RedisOAuthStateStore = class {
459
459
  }
460
460
  };
461
461
  //#endregion
462
- export { Redis, RedisApiTokenStore, RedisEmailVerificationStore, RedisOAuthStateStore, RedisPasswordResetStore, RedisRateLimitStore, RedisSessionStore, RedisSlidingWindowRateLimitStore, createRedisClient };
462
+ //#region src/redis/RedisSchedulerLock.ts
463
+ /**
464
+ * `SchedulerLock` shared by every server on one Redis: `SET NX EX` is the whole
465
+ * acquire, so two servers asking for the same tick get one `OK` between them.
466
+ */
467
+ var RedisSchedulerLock = class {
468
+ redis;
469
+ prefix;
470
+ constructor(redis, options = {}) {
471
+ this.redis = redis;
472
+ this.prefix = options.prefix ?? "scheduler:";
473
+ }
474
+ async acquire(key, ttlSeconds) {
475
+ return await this.redis.set(this.prefix + key, "1", "EX", ttlSeconds, "NX") === "OK";
476
+ }
477
+ async release(key) {
478
+ await this.redis.del(this.prefix + key);
479
+ }
480
+ };
481
+ //#endregion
482
+ export { Redis, RedisApiTokenStore, RedisEmailVerificationStore, RedisOAuthStateStore, RedisPasswordResetStore, RedisRateLimitStore, RedisSchedulerLock, RedisSessionStore, RedisSlidingWindowRateLimitStore, createRedisClient };
@@ -1,5 +1,5 @@
1
1
  import { n as trimTrailingSlashes } from "../trim-slashes-BLY9hKAa.js";
2
- import { _ as parseImportMap, a as getManifestCss, c as isViteProduction, d as startViteDevServer, f as GUREN_ASCII_ART, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-D295_7-_.js";
2
+ import { _ as parseImportMap, a as getManifestCss, c as isViteProduction, d as startViteDevServer, f as GUREN_ASCII_ART, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-QooqG8FE.js";
3
3
  import { n as hash } from "../Hash-D2DFd8xX.js";
4
4
  import { createRequire } from "node:module";
5
5
  import { dirname, extname, join, resolve, sep } from "node:path";
@@ -0,0 +1,16 @@
1
+ import type { SchedulerLock } from './types.js';
2
+ /**
3
+ * Single-process `SchedulerLock`: one server, or tests. Two processes each
4
+ * holding their own instance never see each other's keys, so a multi-server
5
+ * deploy needs `RedisSchedulerLock` or another shared store.
6
+ */
7
+ export declare class MemorySchedulerLock implements SchedulerLock {
8
+ private readonly now;
9
+ private readonly held;
10
+ /** Keys the map may hold before an acquire sweeps it; a full pass per acquire is the alternative. */
11
+ private static readonly SWEEP_AT;
12
+ constructor(now?: () => number);
13
+ acquire(key: string, ttlSeconds: number): Promise<boolean>;
14
+ release(key: string): Promise<void>;
15
+ private sweep;
16
+ }
@@ -2,14 +2,31 @@ import type { TaskDefinition } from './types.js';
2
2
  export declare class ScheduledTask {
3
3
  private readonly definition;
4
4
  private lastRun;
5
- private isRunning;
5
+ /**
6
+ * The invocation holding the overlap guard; null when idle. The token is an
7
+ * object rather than `startedAt`: two runs handed the same fixed clock share
8
+ * a millisecond, and the later one would then release the earlier one's guard.
9
+ */
10
+ private running;
6
11
  constructor(definition: TaskDefinition);
7
12
  getName(): string;
8
13
  getExpression(): string;
9
14
  getTimezone(): string | undefined;
10
15
  isDue(date?: Date): boolean;
11
16
  shouldRun(): Promise<boolean>;
12
- run(): Promise<void>;
17
+ /** `now` is the instant the overlap guard is judged against; a fixed clock can be handed in. */
18
+ run(now?: Date): Promise<void>;
19
+ /** {@link run}, resolving false when the overlap guard or `when`/`skip` declined. */
20
+ tryRun(now?: Date): Promise<boolean>;
21
+ /**
22
+ * Whether `withoutOverlapping` would refuse a run starting at `now`. The
23
+ * scheduler asks before claiming the one-server lock, so a task its own
24
+ * guard declines costs no round trip to the lock store.
25
+ */
26
+ isOverlapBlockedAt(now?: Date): boolean;
27
+ /** The guard stops blocking once `overlapExpiresAt` milliseconds have elapsed, not after. */
28
+ private isRunningAt;
29
+ private releaseIfOwner;
13
30
  getLastRun(): Date | null;
14
31
  isCurrentlyRunning(): boolean;
15
32
  getDefinition(): TaskDefinition;
@@ -4,17 +4,42 @@ import { ScheduledTask } from './ScheduledTask.js';
4
4
  export declare class Scheduler {
5
5
  private tasks;
6
6
  private readonly options;
7
+ private readonly lock;
8
+ /** False when the lock is the implicit single-process default, which cannot span servers. */
9
+ private readonly lockWasGiven;
7
10
  private interval;
8
11
  private isRunning;
9
12
  private lastCheck;
10
13
  /** This scheduler's claim on its hot-reload slot while it is running. */
11
14
  private hotReloadClaim;
12
15
  constructor(options?: SchedulerOptions);
16
+ /** @throws When a task calls `runOnOneServer()` without a name to key the lock on. */
13
17
  schedule(definer: (schedule: Schedule) => void): void;
18
+ /** @throws When the task calls `runOnOneServer()` without a name to key the lock on. */
14
19
  addTask(task: ScheduledTask): void;
15
20
  getTasks(): ScheduledTask[];
16
21
  getDueTasks(date?: Date): ScheduledTask[];
22
+ /**
23
+ * Due tasks run concurrently: awaited one by one, a slow task pushed the rest
24
+ * past their minute, where the tick's once-per-minute check dropped them.
25
+ * Each task's own overlap guard still serialises that task with itself.
26
+ */
17
27
  runDueTasks(date?: Date): Promise<void>;
28
+ private runTask;
29
+ private releaseLock;
30
+ /** The name the task's claim is keyed on; null when it has none to key on. */
31
+ private lockName;
32
+ /**
33
+ * Same on every server for the same task and minute; the minute is UTC epoch,
34
+ * so timezones cannot split it. Null when the task claims no tick.
35
+ */
36
+ private lockKeyFor;
37
+ /** Registration-time facts, so they are judged when the task arrives rather than every tick. */
38
+ private checkOneServerTasks;
39
+ /** Judged through {@link lockName}, so the refusal and the key cannot disagree. */
40
+ private assertOneServerTasksAreNamed;
41
+ private warnIfOneServerTasksShareTheDefaultLock;
42
+ /** @throws When a task calls `runOnOneServer()` without a name to key the lock on. */
18
43
  start(): void;
19
44
  stop(): void;
20
45
  private tick;
@@ -1,4 +1,5 @@
1
- export type { TaskCallback, TaskDefinition, SchedulerOptions, ParsedCron, JobClass, } from './types.js';
1
+ export type { TaskCallback, TaskDefinition, SchedulerOptions, SchedulerLock, ParsedCron, JobClass, } from './types.js';
2
+ export { MemorySchedulerLock } from './MemorySchedulerLock.js';
2
3
  export { parseCron, matchesCron, getNextOccurrence, getNextOccurrences, isDue, isDueInTimezone, toTimezone, } from './CronParser.js';
3
4
  export { ScheduledTask } from './ScheduledTask.js';
4
5
  export { PendingSchedule, Schedule } from './Schedule.js';
@@ -1,2 +1,2 @@
1
- import { a as ScheduledTask, c as isDue, d as parseCron, f as toTimezone, i as Schedule, l as isDueInTimezone, n as createScheduler, o as getNextOccurrence, r as PendingSchedule, s as getNextOccurrences, t as Scheduler, u as matchesCron } from "../scheduling-C6tcOtUl.js";
2
- export { PendingSchedule, Schedule, ScheduledTask, Scheduler, createScheduler, getNextOccurrence, getNextOccurrences, isDue, isDueInTimezone, matchesCron, parseCron, toTimezone };
1
+ import { a as ScheduledTask, c as isDue, d as parseCron, f as toTimezone, i as Schedule, l as isDueInTimezone, n as createScheduler, o as getNextOccurrence, p as MemorySchedulerLock, r as PendingSchedule, s as getNextOccurrences, t as Scheduler, u as matchesCron } from "../scheduling-DudNXGnh.js";
2
+ export { MemorySchedulerLock, PendingSchedule, Schedule, ScheduledTask, Scheduler, createScheduler, getNextOccurrence, getNextOccurrences, isDue, isDueInTimezone, matchesCron, parseCron, toTimezone };
@@ -5,9 +5,12 @@ export interface TaskDefinition {
5
5
  timezone?: string;
6
6
  callback: TaskCallback;
7
7
  withoutOverlapping?: boolean;
8
- /** Milliseconds. */
8
+ /**
9
+ * Milliseconds after which a still-running invocation stops blocking the
10
+ * next one under `withoutOverlapping`, so a hung run does not block forever.
11
+ */
9
12
  overlapExpiresAt?: number;
10
- /** Requires a distributed lock. */
13
+ /** Runs only on the server that wins the tick's `SchedulerLock`; needs a name to key it on. */
11
14
  onOneServer?: boolean;
12
15
  when?: () => boolean | Promise<boolean>;
13
16
  skip?: () => boolean | Promise<boolean>;
@@ -16,12 +19,33 @@ export interface TaskDefinition {
16
19
  onSuccess?: () => void | Promise<void>;
17
20
  onFailure?: (error: Error) => void | Promise<void>;
18
21
  }
22
+ /**
23
+ * Cross-server mutex for `runOnOneServer()` tasks. `acquire` must be atomic
24
+ * (set-if-absent with expiry): two servers asking for the same key in the same
25
+ * tick must get one `true` between them.
26
+ */
27
+ export interface SchedulerLock {
28
+ acquire(key: string, ttlSeconds: number): Promise<boolean>;
29
+ release(key: string): Promise<void>;
30
+ }
19
31
  export interface SchedulerOptions {
20
32
  /** @default 'UTC' */
21
33
  timezone?: string;
22
34
  /** Milliseconds. @default 60000 */
23
35
  checkInterval?: number;
24
36
  logger?: (message: string) => void;
37
+ /**
38
+ * Backs `runOnOneServer()`. Defaults to a `MemorySchedulerLock`, which holds
39
+ * for one process only; a multi-server deploy needs a shared one
40
+ * (`RedisSchedulerLock`) or the task runs on every server.
41
+ */
42
+ lock?: SchedulerLock;
43
+ /**
44
+ * Prefixes every `runOnOneServer()` key. Two apps sharing one lock store must
45
+ * set distinct prefixes, or a task name they have in common claims one tick
46
+ * between them. @default 'schedule:'
47
+ */
48
+ lockPrefix?: string;
25
49
  }
26
50
  export interface ParsedCron {
27
51
  minute: number[];
@@ -1,4 +1,35 @@
1
+ import { t as warnOnce } from "./warn-once-p-IlMjra.js";
1
2
  import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-B5BXqaIH.js";
3
+ //#region src/scheduling/MemorySchedulerLock.ts
4
+ /**
5
+ * Single-process `SchedulerLock`: one server, or tests. Two processes each
6
+ * holding their own instance never see each other's keys, so a multi-server
7
+ * deploy needs `RedisSchedulerLock` or another shared store.
8
+ */
9
+ var MemorySchedulerLock = class MemorySchedulerLock {
10
+ now;
11
+ held = /* @__PURE__ */ new Map();
12
+ /** Keys the map may hold before an acquire sweeps it; a full pass per acquire is the alternative. */
13
+ static SWEEP_AT = 64;
14
+ constructor(now = Date.now) {
15
+ this.now = now;
16
+ }
17
+ async acquire(key, ttlSeconds) {
18
+ const now = this.now();
19
+ if (this.held.size >= MemorySchedulerLock.SWEEP_AT) this.sweep(now);
20
+ const expiresAt = this.held.get(key);
21
+ if (expiresAt !== void 0 && expiresAt > now) return false;
22
+ this.held.set(key, now + ttlSeconds * 1e3);
23
+ return true;
24
+ }
25
+ async release(key) {
26
+ this.held.delete(key);
27
+ }
28
+ sweep(now) {
29
+ for (const [key, expiresAt] of this.held) if (expiresAt <= now) this.held.delete(key);
30
+ }
31
+ };
32
+ //#endregion
2
33
  //#region src/scheduling/CronParser.ts
3
34
  function parseField(field, min, max) {
4
35
  const values = /* @__PURE__ */ new Set();
@@ -103,7 +134,12 @@ function isDueInTimezone(expression, timezone, date = /* @__PURE__ */ new Date()
103
134
  var ScheduledTask = class {
104
135
  definition;
105
136
  lastRun = null;
106
- isRunning = false;
137
+ /**
138
+ * The invocation holding the overlap guard; null when idle. The token is an
139
+ * object rather than `startedAt`: two runs handed the same fixed clock share
140
+ * a millisecond, and the later one would then release the earlier one's guard.
141
+ */
142
+ running = null;
107
143
  constructor(definition) {
108
144
  this.definition = definition;
109
145
  }
@@ -129,16 +165,29 @@ var ScheduledTask = class {
129
165
  }
130
166
  return true;
131
167
  }
132
- async run() {
133
- if (this.definition.withoutOverlapping) {
134
- if (this.isRunning) return;
135
- this.isRunning = true;
168
+ /** `now` is the instant the overlap guard is judged against; a fixed clock can be handed in. */
169
+ async run(now = /* @__PURE__ */ new Date()) {
170
+ await this.tryRun(now);
171
+ }
172
+ /** {@link run}, resolving false when the overlap guard or `when`/`skip` declined. */
173
+ async tryRun(now = /* @__PURE__ */ new Date()) {
174
+ if (this.isOverlapBlockedAt(now)) return false;
175
+ const token = {};
176
+ this.running = {
177
+ token,
178
+ startedAt: now.getTime()
179
+ };
180
+ let shouldRun;
181
+ try {
182
+ shouldRun = await this.shouldRun();
183
+ } catch (error) {
184
+ this.releaseIfOwner(token);
185
+ throw error;
136
186
  }
137
- if (!await this.shouldRun()) {
138
- if (this.definition.withoutOverlapping) this.isRunning = false;
139
- return;
187
+ if (!shouldRun) {
188
+ this.releaseIfOwner(token);
189
+ return false;
140
190
  }
141
- if (!this.definition.withoutOverlapping) this.isRunning = true;
142
191
  let error = null;
143
192
  try {
144
193
  if (this.definition.before) await this.definition.before();
@@ -149,16 +198,35 @@ var ScheduledTask = class {
149
198
  error = err instanceof Error ? err : new Error(String(err));
150
199
  if (this.definition.onFailure) await this.definition.onFailure(error);
151
200
  } finally {
152
- this.isRunning = false;
201
+ this.releaseIfOwner(token);
153
202
  if (this.definition.after) await this.definition.after();
154
203
  }
155
204
  if (error) throw error;
205
+ return true;
206
+ }
207
+ /**
208
+ * Whether `withoutOverlapping` would refuse a run starting at `now`. The
209
+ * scheduler asks before claiming the one-server lock, so a task its own
210
+ * guard declines costs no round trip to the lock store.
211
+ */
212
+ isOverlapBlockedAt(now = /* @__PURE__ */ new Date()) {
213
+ return this.definition.withoutOverlapping === true && this.isRunningAt(now.getTime());
214
+ }
215
+ /** The guard stops blocking once `overlapExpiresAt` milliseconds have elapsed, not after. */
216
+ isRunningAt(now) {
217
+ if (this.running === null) return false;
218
+ const expiresAt = this.definition.overlapExpiresAt;
219
+ if (expiresAt === void 0) return true;
220
+ return now - this.running.startedAt < expiresAt;
221
+ }
222
+ releaseIfOwner(token) {
223
+ if (this.running?.token === token) this.running = null;
156
224
  }
157
225
  getLastRun() {
158
226
  return this.lastRun;
159
227
  }
160
228
  isCurrentlyRunning() {
161
- return this.isRunning;
229
+ return this.running !== null;
162
230
  }
163
231
  getDefinition() {
164
232
  return { ...this.definition };
@@ -446,9 +514,20 @@ var Schedule = class {
446
514
  };
447
515
  //#endregion
448
516
  //#region src/scheduling/Scheduler.ts
517
+ /**
518
+ * How long a tick's `runOnOneServer()` claim stays held. It is never released
519
+ * after a completed run: a release would let a server whose clock reaches the
520
+ * same minute later re-run the tick. An hour outlives any realistic clock skew.
521
+ */
522
+ const ONE_SERVER_LOCK_TTL_SECONDS = 3600;
523
+ /** Prefixes every `runOnOneServer()` key; two apps sharing one store must not share it. */
524
+ const DEFAULT_ONE_SERVER_LOCK_PREFIX = "schedule:";
449
525
  var Scheduler = class {
450
526
  tasks = [];
451
527
  options;
528
+ lock;
529
+ /** False when the lock is the implicit single-process default, which cannot span servers. */
530
+ lockWasGiven;
452
531
  interval = null;
453
532
  isRunning = false;
454
533
  lastCheck = null;
@@ -458,16 +537,23 @@ var Scheduler = class {
458
537
  this.options = {
459
538
  timezone: options.timezone ?? "UTC",
460
539
  checkInterval: options.checkInterval ?? 6e4,
461
- logger: options.logger ?? (() => {})
540
+ logger: options.logger ?? (() => {}),
541
+ lockPrefix: options.lockPrefix ?? DEFAULT_ONE_SERVER_LOCK_PREFIX
462
542
  };
543
+ this.lockWasGiven = options.lock !== void 0;
544
+ this.lock = options.lock ?? new MemorySchedulerLock();
463
545
  }
546
+ /** @throws When a task calls `runOnOneServer()` without a name to key the lock on. */
464
547
  schedule(definer) {
465
548
  const schedule = new Schedule();
466
549
  definer(schedule);
467
550
  this.tasks.push(...schedule.buildTasks());
551
+ this.checkOneServerTasks();
468
552
  }
553
+ /** @throws When the task calls `runOnOneServer()` without a name to key the lock on. */
469
554
  addTask(task) {
470
555
  this.tasks.push(task);
556
+ this.checkOneServerTasks();
471
557
  }
472
558
  getTasks() {
473
559
  return [...this.tasks];
@@ -475,21 +561,90 @@ var Scheduler = class {
475
561
  getDueTasks(date = /* @__PURE__ */ new Date()) {
476
562
  return this.tasks.filter((task) => task.isDue(date));
477
563
  }
564
+ /**
565
+ * Due tasks run concurrently: awaited one by one, a slow task pushed the rest
566
+ * past their minute, where the tick's once-per-minute check dropped them.
567
+ * Each task's own overlap guard still serialises that task with itself.
568
+ */
478
569
  async runDueTasks(date = /* @__PURE__ */ new Date()) {
479
- const dueTasks = this.getDueTasks(date);
480
- for (const task of dueTasks) {
481
- this.options.logger(`Running task: ${task.getName()}`);
570
+ const results = await Promise.allSettled(this.getDueTasks(date).map((task) => this.runTask(task, date)));
571
+ for (const result of results) if (result.status === "rejected") this.options.logger(`Scheduler error: ${describe(result.reason)}`);
572
+ }
573
+ async runTask(task, date) {
574
+ if (task.isOverlapBlockedAt(date)) {
575
+ this.options.logger(`Task skipped: ${task.getName()}`);
576
+ return;
577
+ }
578
+ const lockKey = this.lockKeyFor(task, date);
579
+ if (lockKey !== null) {
580
+ let acquired;
482
581
  try {
483
- await task.run();
484
- this.options.logger(`Task completed: ${task.getName()}`);
582
+ acquired = await this.lock.acquire(lockKey, ONE_SERVER_LOCK_TTL_SECONDS);
485
583
  } catch (error) {
486
- const message = error instanceof Error ? error.message : String(error);
487
- this.options.logger(`Task failed: ${task.getName()} - ${message}`);
584
+ this.options.logger(`Lock failed: ${task.getName()} - ${describe(error)}`);
585
+ return;
488
586
  }
587
+ if (!acquired) {
588
+ this.options.logger(`Task skipped, another server holds it: ${task.getName()}`);
589
+ return;
590
+ }
591
+ }
592
+ this.options.logger(`Running task: ${task.getName()}`);
593
+ let ran;
594
+ try {
595
+ ran = await task.tryRun(date);
596
+ } catch (error) {
597
+ this.options.logger(`Task failed: ${task.getName()} - ${describe(error)}`);
598
+ return;
599
+ }
600
+ if (ran) {
601
+ this.options.logger(`Task completed: ${task.getName()}`);
602
+ return;
489
603
  }
604
+ this.options.logger(`Task skipped: ${task.getName()}`);
605
+ if (lockKey !== null) await this.releaseLock(lockKey, task);
490
606
  }
607
+ async releaseLock(lockKey, task) {
608
+ try {
609
+ await this.lock.release(lockKey);
610
+ } catch (error) {
611
+ this.options.logger(`Lock release failed: ${task.getName()} - ${describe(error)}`);
612
+ }
613
+ }
614
+ /** The name the task's claim is keyed on; null when it has none to key on. */
615
+ lockName(task) {
616
+ const { name } = task.getDefinition();
617
+ return name === void 0 || name === "" ? null : name;
618
+ }
619
+ /**
620
+ * Same on every server for the same task and minute; the minute is UTC epoch,
621
+ * so timezones cannot split it. Null when the task claims no tick.
622
+ */
623
+ lockKeyFor(task, date) {
624
+ const name = task.getDefinition().onOneServer ? this.lockName(task) : null;
625
+ if (name === null) return null;
626
+ return `${this.options.lockPrefix}${name}:${Math.floor(date.getTime() / 6e4)}`;
627
+ }
628
+ /** Registration-time facts, so they are judged when the task arrives rather than every tick. */
629
+ checkOneServerTasks() {
630
+ this.assertOneServerTasksAreNamed();
631
+ this.warnIfOneServerTasksShareTheDefaultLock();
632
+ }
633
+ /** Judged through {@link lockName}, so the refusal and the key cannot disagree. */
634
+ assertOneServerTasksAreNamed() {
635
+ const unnamed = this.tasks.filter((task) => task.getDefinition().onOneServer && this.lockName(task) === null);
636
+ if (unnamed.length === 0) return;
637
+ throw new Error(`${unnamed.length} scheduled task(s) call runOnOneServer() without a name. The lock is keyed on the name, so give each one a non-empty .name() before scheduling it.`);
638
+ }
639
+ warnIfOneServerTasksShareTheDefaultLock() {
640
+ if (this.lockWasGiven) return;
641
+ if (!this.tasks.some((task) => task.getDefinition().onOneServer)) return;
642
+ warnOnce("scheduler-default-one-server-lock", "[guren] Scheduled task(s) call runOnOneServer() and the scheduler was given no lock, so it is using an in-process MemorySchedulerLock. That holds for one process only: on a second server the task runs again. Pass createScheduler({ lock }) a shared SchedulerLock (RedisSchedulerLock) for a multi-server deploy.");
643
+ }
644
+ /** @throws When a task calls `runOnOneServer()` without a name to key the lock on. */
491
645
  start() {
492
646
  if (this.isRunning) return;
647
+ this.checkOneServerTasks();
493
648
  this.isRunning = true;
494
649
  this.options.logger("Scheduler started");
495
650
  this.hotReloadClaim = claimHotDisposable("scheduler", isHotReloadRuntime() ? (/* @__PURE__ */ new Error()).stack : void 0, this.options.timezone, () => this.stop());
@@ -550,5 +705,8 @@ var Scheduler = class {
550
705
  function createScheduler(options) {
551
706
  return new Scheduler(options);
552
707
  }
708
+ function describe(error) {
709
+ return error instanceof Error ? error.message : String(error);
710
+ }
553
711
  //#endregion
554
- export { ScheduledTask as a, isDue as c, parseCron as d, toTimezone as f, Schedule as i, isDueInTimezone as l, createScheduler as n, getNextOccurrence as o, PendingSchedule as r, getNextOccurrences as s, Scheduler as t, matchesCron as u };
712
+ export { ScheduledTask as a, isDue as c, parseCron as d, toTimezone as f, Schedule as i, isDueInTimezone as l, createScheduler as n, getNextOccurrence as o, MemorySchedulerLock as p, PendingSchedule as r, getNextOccurrences as s, Scheduler as t, matchesCron as u };
@@ -1,2 +1,2 @@
1
- import { a as LocalDriver, i as S3Driver, n as createStorageManager, r as MemoryDriver, t as StorageManager } from "../storage-D_yNe54O.js";
1
+ import { a as LocalDriver, i as S3Driver, n as createStorageManager, r as MemoryDriver, t as StorageManager } from "../storage-6HLaUf9j.js";
2
2
  export { LocalDriver, MemoryDriver, S3Driver, StorageManager, createStorageManager };
@@ -1,20 +1,9 @@
1
1
  import { t as trimSlashes } from "./trim-slashes-BLY9hKAa.js";
2
+ import { t as warnOnce } from "./warn-once-p-IlMjra.js";
2
3
  import { dirname, join, resolve, sep } from "node:path";
3
4
  import { copyFile, mkdir, open, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
4
5
  import { existsSync } from "node:fs";
5
6
  import { Readable } from "node:stream";
6
- //#region src/support/warn-once.ts
7
- const warned = /* @__PURE__ */ new Set();
8
- /**
9
- * Warn the first time a key is seen in this process: loud enough to be read
10
- * once, quiet enough not to drown a request log.
11
- */
12
- function warnOnce(key, message) {
13
- if (warned.has(key)) return;
14
- warned.add(key);
15
- console.warn(message);
16
- }
17
- //#endregion
18
7
  //#region src/storage/drivers/LocalDriver.ts
19
8
  var LocalDriver = class {
20
9
  root;
@@ -775,4 +764,4 @@ function createStorageManager(config) {
775
764
  return new StorageManager(config);
776
765
  }
777
766
  //#endregion
778
- export { LocalDriver as a, S3Driver as i, createStorageManager as n, warnOnce as o, MemoryDriver as r, StorageManager as t };
767
+ export { LocalDriver as a, S3Driver as i, createStorageManager as n, MemoryDriver as r, StorageManager as t };