@dudousxd/nestjs-durable 0.60.0 → 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
@@ -3215,6 +3215,7 @@ var TenantEventRepublisher = class {
3215
3215
  };
3216
3216
 
3217
3217
  // src/timer-poller.ts
3218
+ var durableCore = __toESM(require("@dudousxd/nestjs-durable-core"), 1);
3218
3219
  var import_nestjs_durable_core15 = require("@dudousxd/nestjs-durable-core");
3219
3220
  var import_common10 = require("@nestjs/common");
3220
3221
  function _ts_decorate10(decorators, target, key, desc) {
@@ -3243,6 +3244,8 @@ function _ts_param7(paramIndex, decorator) {
3243
3244
  };
3244
3245
  }
3245
3246
  __name(_ts_param7, "_ts_param");
3247
+ var SWEEP_FAILED = Symbol("sweep failed");
3248
+ var nextScheduleFireAt2 = durableCore.nextScheduleFireAt;
3246
3249
  var TimerPoller = class {
3247
3250
  static {
3248
3251
  __name(this, "TimerPoller");
@@ -3255,6 +3258,15 @@ var TimerPoller = class {
3255
3258
  /** The sweep in flight, so shutdown can wait for it instead of racing the store's close. */
3256
3259
  current;
3257
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;
3258
3270
  constructor(engine, options, leases = new SweepLeases()) {
3259
3271
  this.engine = engine;
3260
3272
  this.options = options;
@@ -3265,6 +3277,7 @@ var TimerPoller = class {
3265
3277
  if (!isDrivingOperator(this.options)) return;
3266
3278
  this.engine.consumeRuns?.();
3267
3279
  this.unsubscribeEnqueued = this.engine.onEnqueued((runId) => {
3280
+ this.noteActivity();
3268
3281
  if (typeof this.engine.runEnqueued === "function") {
3269
3282
  this.engine.runEnqueued(runId);
3270
3283
  return;
@@ -3273,14 +3286,102 @@ var TimerPoller = class {
3273
3286
  console.error(`[nestjs-durable] could not run enqueued run ${runId}:`, error);
3274
3287
  });
3275
3288
  });
3276
- void this.poll();
3277
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();
3278
3297
  if (intervalMs > 0) {
3279
3298
  this.timer = setInterval(() => void this.poll(), intervalMs);
3280
3299
  this.timer.unref?.();
3281
3300
  }
3282
3301
  }
3283
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
+ /**
3284
3385
  * Stop polling and wait for the sweep in flight (bounded by `shutdownTimeoutMs`, default 10s).
3285
3386
  * Nest runs every `onModuleDestroy` before any `onApplicationShutdown`, so returning here only once
3286
3387
  * the sweep has settled means no store call is still pending when the registrar drains and the
@@ -3289,8 +3390,11 @@ var TimerPoller = class {
3289
3390
  * from the later `engine.drain()`, so poll wait plus drain stay within one `shutdownTimeoutMs`.
3290
3391
  */
3291
3392
  async onModuleDestroy() {
3393
+ this.stopped = true;
3292
3394
  if (this.timer) clearInterval(this.timer);
3395
+ this.endWait?.();
3293
3396
  this.unsubscribeEnqueued?.();
3397
+ this.unsubscribeEvents?.();
3294
3398
  if (!isDrivingOperator(this.options)) return;
3295
3399
  this.engine.beginDrain?.();
3296
3400
  if (!this.current) return;
@@ -3316,7 +3420,7 @@ var TimerPoller = class {
3316
3420
  * the rest of the tick would silently widen one subsystem's outage into all of them.
3317
3421
  */
3318
3422
  poll() {
3319
- if (this.polling) return this.current ?? Promise.resolve();
3423
+ if (this.polling) return this.current ?? Promise.resolve(true);
3320
3424
  this.polling = true;
3321
3425
  const run = this.pollOnce().finally(() => {
3322
3426
  this.polling = false;
@@ -3325,31 +3429,44 @@ var TimerPoller = class {
3325
3429
  this.current = run;
3326
3430
  return run;
3327
3431
  }
3432
+ /** One poll of every sweep. Resolves whether it found work (or a sweep failed): see {@link loop}. */
3328
3433
  async pollOnce() {
3329
- {
3330
- await this.sweep("runPending", () => this.engine.runPending());
3331
- await this.sweep("recoverIncomplete", () => this.engine.recoverIncomplete());
3332
- await this.sweep("resumeDueTimers", () => this.engine.resumeDueTimers());
3333
- await this.sweep("sweepTimeouts", () => this.engine.sweepTimeouts());
3334
- await this.sweep("sweepStalled", () => this.leases.run("stalled-pager", async () => this.engine.sweepStalled?.()));
3335
- await this.sweep("sweepBufferedSignals", () => this.leases.run("buffered-signals", async () => this.engine.sweepBufferedSignals?.()));
3336
- await this.sweep("sweepExpiredSignalIds", () => this.leases.run("signal-ids", async () => this.engine.sweepExpiredSignalIds?.()));
3337
- await this.sweep("sweepLifecycleEvents", async () => this.engine.sweepLifecycleEvents?.());
3338
- const schedules = this.options.schedules;
3339
- if (schedules && schedules.length > 0) {
3340
- await this.sweep("schedules", () => (0, import_nestjs_durable_core15.runSchedules)(this.engine, schedules, Date.now()));
3341
- }
3342
- if (this.options.persistedSchedules) {
3343
- await this.sweep("persistedSchedules", () => this.engine.schedules.tick());
3344
- }
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()));
3345
3460
  }
3461
+ return worked;
3346
3462
  }
3347
3463
  /** Run one sweep, absorbing and reporting its failure — see {@link poll}. */
3348
3464
  async sweep(name, run) {
3349
3465
  try {
3350
- await run();
3466
+ return await run();
3351
3467
  } catch (error) {
3352
3468
  console.error(`[nestjs-durable] timer poll: ${name} failed; continuing:`, error);
3469
+ return SWEEP_FAILED;
3353
3470
  }
3354
3471
  }
3355
3472
  };