@dudousxd/nestjs-durable 0.59.1 → 0.61.0

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/index.cjs CHANGED
@@ -38,6 +38,7 @@ __export(src_exports, {
38
38
  DURABLE_WORKER_RUNNERS: () => DURABLE_WORKER_RUNNERS,
39
39
  DURABLE_WORKER_RUNTIME: () => DURABLE_WORKER_RUNTIME,
40
40
  DeadLetter: () => DeadLetter,
41
+ DuplicateDurableCopyError: () => import_nestjs_durable_core20.DuplicateDurableCopyError,
41
42
  DurableModule: () => DurableModule,
42
43
  DurableStartClient: () => DurableStartClient,
43
44
  ENTITY_METADATA: () => ENTITY_METADATA,
@@ -3214,6 +3215,7 @@ var TenantEventRepublisher = class {
3214
3215
  };
3215
3216
 
3216
3217
  // src/timer-poller.ts
3218
+ var durableCore = __toESM(require("@dudousxd/nestjs-durable-core"), 1);
3217
3219
  var import_nestjs_durable_core15 = require("@dudousxd/nestjs-durable-core");
3218
3220
  var import_common10 = require("@nestjs/common");
3219
3221
  function _ts_decorate10(decorators, target, key, desc) {
@@ -3242,6 +3244,8 @@ function _ts_param7(paramIndex, decorator) {
3242
3244
  };
3243
3245
  }
3244
3246
  __name(_ts_param7, "_ts_param");
3247
+ var SWEEP_FAILED = Symbol("sweep failed");
3248
+ var nextScheduleFireAt2 = durableCore.nextScheduleFireAt;
3245
3249
  var TimerPoller = class {
3246
3250
  static {
3247
3251
  __name(this, "TimerPoller");
@@ -3254,6 +3258,15 @@ var TimerPoller = class {
3254
3258
  /** The sweep in flight, so shutdown can wait for it instead of racing the store's close. */
3255
3259
  current;
3256
3260
  unsubscribeEnqueued;
3261
+ unsubscribeEvents;
3262
+ /** Set by shutdown: the backoff loop stops scheduling polls. */
3263
+ stopped = false;
3264
+ /** Something happened (a run event, an enqueue nudge) since the last poll started. */
3265
+ activity = false;
3266
+ /** Ends the backoff loop's current wait early (set only while it waits). */
3267
+ endWait;
3268
+ /** When the owed-lifecycle listing last succeeded (see {@link owedSweepDue}). */
3269
+ owedSweptAt;
3257
3270
  constructor(engine, options, leases = new SweepLeases()) {
3258
3271
  this.engine = engine;
3259
3272
  this.options = options;
@@ -3264,6 +3277,7 @@ var TimerPoller = class {
3264
3277
  if (!isDrivingOperator(this.options)) return;
3265
3278
  this.engine.consumeRuns?.();
3266
3279
  this.unsubscribeEnqueued = this.engine.onEnqueued((runId) => {
3280
+ this.noteActivity();
3267
3281
  if (typeof this.engine.runEnqueued === "function") {
3268
3282
  this.engine.runEnqueued(runId);
3269
3283
  return;
@@ -3272,14 +3286,102 @@ var TimerPoller = class {
3272
3286
  console.error(`[nestjs-durable] could not run enqueued run ${runId}:`, error);
3273
3287
  });
3274
3288
  });
3275
- void this.poll();
3276
3289
  const intervalMs = this.options.timerPollMs ?? 1e3;
3290
+ const maxIdleMs = this.options.maxIdleIntervalMs ?? 5e3;
3291
+ if (intervalMs > 0 && maxIdleMs > intervalMs && this.canBackOff()) {
3292
+ this.unsubscribeEvents = this.engine.subscribe(() => this.noteActivity());
3293
+ void this.loop(intervalMs, maxIdleMs);
3294
+ return;
3295
+ }
3296
+ void this.poll();
3277
3297
  if (intervalMs > 0) {
3278
3298
  this.timer = setInterval(() => void this.poll(), intervalMs);
3279
3299
  this.timer.unref?.();
3280
3300
  }
3281
3301
  }
3282
3302
  /**
3303
+ * Whether polls may be spaced out while idle: the engine must reach new runs without the
3304
+ * pending-run poll and say when its next timer is due, and the in-process schedules must be able
3305
+ * to say when their next window is. Optional calls throughout: an older core keeps the fixed tick.
3306
+ */
3307
+ canBackOff() {
3308
+ if (this.engine.idleBackoffSupported !== true) return false;
3309
+ if (typeof this.engine.nextDueAt !== "function") return false;
3310
+ if ((this.options.schedules?.length ?? 0) > 0 && nextScheduleFireAt2 === void 0) return false;
3311
+ return true;
3312
+ }
3313
+ noteActivity() {
3314
+ this.activity = true;
3315
+ this.endWait?.();
3316
+ }
3317
+ /**
3318
+ * Poll, then wait: `intervalMs` after a poll that found work (or while anything happened), else
3319
+ * twice the last wait up to `maxIdleMs`, cut short so the next poll runs no later than the earliest
3320
+ * known due time. A run event or an enqueue nudge ends a wait at once.
3321
+ */
3322
+ async loop(intervalMs, maxIdleMs) {
3323
+ let wait = intervalMs;
3324
+ while (!this.stopped) {
3325
+ const arrived = this.activity;
3326
+ this.activity = false;
3327
+ const worked = await this.poll();
3328
+ if (this.stopped) return;
3329
+ const idle = !worked && !arrived && !this.activity;
3330
+ wait = idle ? Math.min(wait * 2, maxIdleMs) : intervalMs;
3331
+ let next = wait;
3332
+ if (next > intervalMs) next = await this.untilDue(next, intervalMs);
3333
+ if (this.stopped) return;
3334
+ if (this.activity) next = Math.min(next, intervalMs);
3335
+ await new Promise((resolve) => {
3336
+ const done = /* @__PURE__ */ __name(() => {
3337
+ clearTimeout(timer);
3338
+ this.endWait = void 0;
3339
+ resolve();
3340
+ }, "done");
3341
+ const timer = setTimeout(done, next);
3342
+ timer.unref?.();
3343
+ this.endWait = () => {
3344
+ if (this.stopped || next > intervalMs) done();
3345
+ };
3346
+ });
3347
+ }
3348
+ }
3349
+ /**
3350
+ * `wait`, shortened so the next poll runs no later than the earliest known due time: the engine's
3351
+ * next timer, blocked-run recovery poll or persisted schedule, and the next window of the
3352
+ * in-process `schedules`. Never below `intervalMs` (the regular tick catches what is due sooner). A
3353
+ * failed read keeps the regular tick.
3354
+ */
3355
+ async untilDue(wait, intervalMs) {
3356
+ try {
3357
+ const now = Date.now();
3358
+ const stored = await this.engine.nextDueAt(now + wait, {
3359
+ persistedSchedules: this.options.persistedSchedules === true
3360
+ });
3361
+ const schedules = this.options.schedules;
3362
+ const scheduled = schedules && schedules.length > 0 && nextScheduleFireAt2 ? nextScheduleFireAt2(this.engine, schedules, now) : void 0;
3363
+ let due = wait;
3364
+ for (const at of [
3365
+ stored,
3366
+ scheduled
3367
+ ]) {
3368
+ if (at !== void 0) due = Math.min(due, at - Date.now());
3369
+ }
3370
+ return Math.max(intervalMs, due);
3371
+ } catch {
3372
+ return intervalMs;
3373
+ }
3374
+ }
3375
+ /**
3376
+ * Whether this poll lists the owed lifecycle runs: until a sweep that listed them succeeded, then
3377
+ * once per `owedLifecycleSweepMs` (a clock that went back lists them again).
3378
+ */
3379
+ owedSweepDue(now) {
3380
+ const every = this.options.owedLifecycleSweepMs ?? 1e4;
3381
+ const last = this.owedSweptAt;
3382
+ return every <= 0 || last === void 0 || now < last || now - last >= every;
3383
+ }
3384
+ /**
3283
3385
  * Stop polling and wait for the sweep in flight (bounded by `shutdownTimeoutMs`, default 10s).
3284
3386
  * Nest runs every `onModuleDestroy` before any `onApplicationShutdown`, so returning here only once
3285
3387
  * the sweep has settled means no store call is still pending when the registrar drains and the
@@ -3288,8 +3390,11 @@ var TimerPoller = class {
3288
3390
  * from the later `engine.drain()`, so poll wait plus drain stay within one `shutdownTimeoutMs`.
3289
3391
  */
3290
3392
  async onModuleDestroy() {
3393
+ this.stopped = true;
3291
3394
  if (this.timer) clearInterval(this.timer);
3395
+ this.endWait?.();
3292
3396
  this.unsubscribeEnqueued?.();
3397
+ this.unsubscribeEvents?.();
3293
3398
  if (!isDrivingOperator(this.options)) return;
3294
3399
  this.engine.beginDrain?.();
3295
3400
  if (!this.current) return;
@@ -3315,7 +3420,7 @@ var TimerPoller = class {
3315
3420
  * the rest of the tick would silently widen one subsystem's outage into all of them.
3316
3421
  */
3317
3422
  poll() {
3318
- if (this.polling) return this.current ?? Promise.resolve();
3423
+ if (this.polling) return this.current ?? Promise.resolve(true);
3319
3424
  this.polling = true;
3320
3425
  const run = this.pollOnce().finally(() => {
3321
3426
  this.polling = false;
@@ -3324,31 +3429,44 @@ var TimerPoller = class {
3324
3429
  this.current = run;
3325
3430
  return run;
3326
3431
  }
3432
+ /** One poll of every sweep. Resolves whether it found work (or a sweep failed): see {@link loop}. */
3327
3433
  async pollOnce() {
3328
- {
3329
- await this.sweep("runPending", () => this.engine.runPending());
3330
- await this.sweep("recoverIncomplete", () => this.engine.recoverIncomplete());
3331
- await this.sweep("resumeDueTimers", () => this.engine.resumeDueTimers());
3332
- await this.sweep("sweepTimeouts", () => this.engine.sweepTimeouts());
3333
- await this.sweep("sweepStalled", () => this.leases.run("stalled-pager", async () => this.engine.sweepStalled?.()));
3334
- await this.sweep("sweepBufferedSignals", () => this.leases.run("buffered-signals", async () => this.engine.sweepBufferedSignals?.()));
3335
- await this.sweep("sweepExpiredSignalIds", () => this.leases.run("signal-ids", async () => this.engine.sweepExpiredSignalIds?.()));
3336
- await this.sweep("sweepLifecycleEvents", async () => this.engine.sweepLifecycleEvents?.());
3337
- const schedules = this.options.schedules;
3338
- if (schedules && schedules.length > 0) {
3339
- await this.sweep("schedules", () => (0, import_nestjs_durable_core15.runSchedules)(this.engine, schedules, Date.now()));
3340
- }
3341
- if (this.options.persistedSchedules) {
3342
- await this.sweep("persistedSchedules", () => this.engine.schedules.tick());
3343
- }
3434
+ let worked = false;
3435
+ const note = /* @__PURE__ */ __name((result) => {
3436
+ if (result === SWEEP_FAILED || Array.isArray(result) && result.length > 0) worked = true;
3437
+ }, "note");
3438
+ note(await this.sweep("runPending", () => this.engine.runPending()));
3439
+ note(await this.sweep("recoverIncomplete", () => this.engine.recoverIncomplete()));
3440
+ note(await this.sweep("resumeDueTimers", () => this.engine.resumeDueTimers()));
3441
+ note(await this.sweep("sweepTimeouts", () => this.engine.sweepTimeouts()));
3442
+ note(await this.sweep("sweepStalled", () => this.leases.run("stalled-pager", async () => this.engine.sweepStalled?.())));
3443
+ note(await this.sweep("sweepBufferedSignals", () => this.leases.run("buffered-signals", async () => this.engine.sweepBufferedSignals?.())));
3444
+ note(await this.sweep("sweepExpiredSignalIds", () => this.leases.run("signal-ids", async () => this.engine.sweepExpiredSignalIds?.())));
3445
+ const now = Date.now();
3446
+ const owed = this.owedSweepDue(now);
3447
+ note(await this.sweep("sweepLifecycleEvents", async () => {
3448
+ const published = await this.engine.sweepLifecycleEvents?.(void 0, void 0, {
3449
+ owed
3450
+ });
3451
+ if (owed) this.owedSweptAt = now;
3452
+ return published;
3453
+ }));
3454
+ const schedules = this.options.schedules;
3455
+ if (schedules && schedules.length > 0) {
3456
+ note(await this.sweep("schedules", () => (0, import_nestjs_durable_core15.runSchedules)(this.engine, schedules, Date.now())));
3457
+ }
3458
+ if (this.options.persistedSchedules) {
3459
+ note(await this.sweep("persistedSchedules", () => this.engine.schedules.tick()));
3344
3460
  }
3461
+ return worked;
3345
3462
  }
3346
3463
  /** Run one sweep, absorbing and reporting its failure — see {@link poll}. */
3347
3464
  async sweep(name, run) {
3348
3465
  try {
3349
- await run();
3466
+ return await run();
3350
3467
  } catch (error) {
3351
3468
  console.error(`[nestjs-durable] timer poll: ${name} failed; continuing:`, error);
3469
+ return SWEEP_FAILED;
3352
3470
  }
3353
3471
  }
3354
3472
  };
@@ -3991,6 +4109,7 @@ var DurableModule = class _DurableModule {
3991
4109
  __name(this, "DurableModule");
3992
4110
  }
3993
4111
  static forRoot(options) {
4112
+ (0, import_nestjs_durable_core19.sealDurableCopies)();
3994
4113
  _DurableModule.assertValid(options);
3995
4114
  return _DurableModule.build({
3996
4115
  provide: import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL,
@@ -3998,6 +4117,7 @@ var DurableModule = class _DurableModule {
3998
4117
  });
3999
4118
  }
4000
4119
  static forRootAsync(options) {
4120
+ (0, import_nestjs_durable_core19.sealDurableCopies)();
4001
4121
  return _DurableModule.build({
4002
4122
  provide: import_nestjs_durable_core19.DURABLE_OPTIONS_CANONICAL,
4003
4123
  useFactory: /* @__PURE__ */ __name(async (...args) => {
@@ -4217,6 +4337,7 @@ var import_nestjs_durable_core20 = require("@dudousxd/nestjs-durable-core");
4217
4337
  DURABLE_WORKER_RUNNERS,
4218
4338
  DURABLE_WORKER_RUNTIME,
4219
4339
  DeadLetter,
4340
+ DuplicateDurableCopyError,
4220
4341
  DurableModule,
4221
4342
  DurableStartClient,
4222
4343
  ENTITY_METADATA,