@dudousxd/nestjs-durable-core 0.95.0 → 0.97.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.d.cts CHANGED
@@ -3121,9 +3121,12 @@ interface Transport {
3121
3121
  * broker transports that carry the two-tier descriptor advertisement (BullMQ) implement it; a pure
3122
3122
  * in-process transport returns nothing, so the engine's routing guard stays disengaged (legacy
3123
3123
  * assume-compatible, design §7.7). The engine feeds these into {@link planDispatch} to decide whether
3124
- * a run can dispatch to `group` or must park `blocked`.
3124
+ * a run can dispatch to `group` or must park `blocked`. A transport may reuse a recent read of its
3125
+ * registry; `opts.fresh` asks it to read again (the engine does before it parks a run `blocked`).
3125
3126
  */
3126
- readWorkerDescriptors?(group: string): Promise<WorkerDescriptor[]>;
3127
+ readWorkerDescriptors?(group: string, opts?: {
3128
+ fresh?: boolean | undefined;
3129
+ }): Promise<WorkerDescriptor[]>;
3127
3130
  /**
3128
3131
  * Every live {@link WorkerDescriptor} in the deployment, across all groups — the read behind
3129
3132
  * {@link WorkflowEngine.announcedWorkflows}. Optional, same as {@link readWorkerDescriptors}: a
@@ -5184,6 +5187,13 @@ declare class ScheduleClient {
5184
5187
  * run ids started (or re-found, for an idempotent re-fire).
5185
5188
  */
5186
5189
  tick(nowMs?: number): Promise<string[]>;
5190
+ /**
5191
+ * When {@link tick} next has a schedule to fire, if one is due by `byMs`: the earliest `nextFireAt`
5192
+ * of the unpaused schedules (of this engine's namespace) due by then, else `undefined`. One indexed
5193
+ * read (the due-schedule scan `tick` makes, with a later bound and a limit of one). A store that
5194
+ * does not persist schedules has none.
5195
+ */
5196
+ nextFireAt(byMs: number): Promise<number | undefined>;
5187
5197
  /** Fire one due schedule and advance it. Returns the run id started, if any. */
5188
5198
  private fire;
5189
5199
  /** `overlap: 'skip'` and the previous run of this schedule is still in flight. */
@@ -5961,6 +5971,23 @@ declare class WorkflowEngine {
5961
5971
  * unsubscribe function. Only wire this on instances that should execute runs (workers).
5962
5972
  */
5963
5973
  onEnqueued(listener: (runId: string) => void): () => void;
5974
+ /**
5975
+ * Whether a poller may wait longer than its tick while there is nothing to do: a run another
5976
+ * instance starts must reach this one without the pending-run poll, so this engine needs a control
5977
+ * plane (the `enqueued` nudge, and the run events of other instances that tell a poller to look
5978
+ * again) or a run queue it consumes (see {@link consumeRuns}). See {@link nextDueAt}.
5979
+ */
5980
+ get idleBackoffSupported(): boolean;
5981
+ /**
5982
+ * The earliest known time (epoch ms) the poll has work, if it is at or before `byMs`: this
5983
+ * namespace's next due timer (`listDueTimers` up to `byMs`, limit one: it returns the most overdue
5984
+ * first), the next `blocked` run's recovery poll, and with `persistedSchedules` the next persisted
5985
+ * schedule to fire (see {@link ScheduleClient.nextFireAt}). `undefined` when nothing is due by
5986
+ * then. A poller reads it before waiting longer than its tick, so the wait never outlasts a timer.
5987
+ */
5988
+ nextDueAt(byMs: number, opts?: {
5989
+ persistedSchedules?: boolean;
5990
+ }): Promise<number | undefined>;
5964
5991
  /**
5965
5992
  * Pick up a run another instance announced as enqueued: run it here if it is still `pending`.
5966
5993
  * Bounded by {@link LOCAL_RUN_CONCURRENCY}, and a run another instance already took is skipped
@@ -6504,8 +6531,16 @@ declare class WorkflowEngine {
6504
6531
  * {@link LIFECYCLE_SWEEP_SCAN_MAX}. Pages advance by offset over a set the sweep itself shrinks,
6505
6532
  * so a run that moves into an earlier page is reached on the next tick, which starts over. A run
6506
6533
  * whose lifecycle lease another publisher holds is left for the next tick.
6534
+ *
6535
+ * `options.owed: false` does only the cheap part: the registry heartbeat (itself throttled) and the
6536
+ * run waits. The listing of marked runs filters on a tag (an unindexed `LIKE` on most stores, a
6537
+ * partial index on Postgres) and the heal reads recent runs per source workflow, so a poller runs
6538
+ * that part less often than its tick (see the NestJS timer poller) and passes `owed: false` in
6539
+ * between. It returns 0 then.
6507
6540
  */
6508
- sweepLifecycleEvents(nowMs?: number, limit?: number): Promise<number>;
6541
+ sweepLifecycleEvents(nowMs?: number, limit?: number, options?: {
6542
+ owed?: boolean;
6543
+ }): Promise<number>;
6509
6544
  /**
6510
6545
  * The (run, subscriber) pairs this engine already healed, until when it remembers them; see
6511
6546
  * {@link healLifecycleEvents}.
@@ -9150,6 +9185,14 @@ interface ScheduledWorkflow<W extends WorkflowRef = WorkflowRef> {
9150
9185
  interface RunSchedulesOptions {
9151
9186
  random?: () => number;
9152
9187
  }
9188
+ /**
9189
+ * The earliest time after `nowMs` at which {@link runSchedules} may have a window of `schedules` to
9190
+ * fire for `engine`: each unpaused schedule's next window boundary, and the fire time of any jittered
9191
+ * window an earlier call deferred. `nowMs` when a schedule cannot say (an unparsable cron, a missing
9192
+ * `cron-parser`), so a caller never waits past a window; `undefined` for none. Pass the same `engine`
9193
+ * object as to `runSchedules` (the deferred windows are remembered per engine object).
9194
+ */
9195
+ declare function nextScheduleFireAt(engine: object, schedules: readonly ScheduledWorkflow[], nowMs: number): number | undefined;
9153
9196
  /** Deterministic run id for a fixed-interval schedule's current time window. */
9154
9197
  declare function scheduledRunId(key: string, everyMs: number, nowMs: number): string;
9155
9198
  /**
@@ -9759,4 +9802,4 @@ declare function prevRRuleFireMs(rule: ParsedRRule, atMs: number): number | null
9759
9802
  */
9760
9803
  declare function settleResultsWithPlainCalls(store: Pick<StateStore, 'getRun' | 'getCheckpoint'> & Partial<Pick<StateStore, 'getRuns' | 'getCheckpointsForSettle' | 'getCheckpoints' | 'settleCheckpointsIfPending'>>, results: StepResultSettlement[]): Promise<(StepCheckpoint | null)[]>;
9761
9804
 
9762
- export { ACCUMULATOR_SEEN_MAX, ANY_WAIT_GROUP, type AccumulatorHost, type AccumulatorStartOptions, type Admission, type AdmissionBackend, type AdmissionItem, type AllOptions, type AllSettledOptions, type AllStepsOptions, type AllStepsSettledOptions, type AnnouncedWorkflow, type AnnouncementEvidence, type AttributeFilter, type AttributeOp, type AttributePredicateOperand, type AttributeValue, type AttributedEngineEvent, type BackoffStrategy, type BlockedDispatch, type BlockedResolution, type BufferedSignalRow, CHILD_EDGE_PREFIXES, CONTROL_FLOW_SIGNAL, CORE_ORIGIN, CURRENT_PROTOCOL_VERSION, type CapabilityRequirement, type CheckpointAggregatingStore, type CheckpointNameKind, type CheckpointQuery, type CheckpointStat, type ChildCallOptions, type ChildWait, CodecStateStore, type CodecStateStoreOptions, type ConcurrencyConfig, ConcurrencyLimitError, type ConcurrencyQuota, type ConsoleCapabilities, ContinueAsNew, type ControlMessage, type ControlPlane, DEFAULT_CONCURRENCY_STATUSES, DEFAULT_PARTITION, DEFAULT_STALLED_AFTER_MS, DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL, DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, type Disagreement, type DispatchDiagnostics, type DispatchPlan, DuplicateDurableCopyError, type DurableCopy, type DurableExecution, type DurableExecutionWrapper, type DurableTopology, type DurableWebhook, DurableWorkflow, type DynamicWorkflowCtx, ENGINE_MINTED_TAG_PREFIXES, ENTITY_WORKFLOW, EVENT_BUFFER_SCAN_LIMIT, EVENT_TOKEN_PREFIX, type EngineEvent, type EngineEventType, type EngineListener, type EngineTenancy, Entities, type EntityConfig, type EntityHandler, type EntityHost, type EntityWorkflowHost, EventAccumulators, type EventBatchConfig, type EventSubscription, FAN_SUMMARY_FAILURES, type FanJoin, type FanPage, type FanPageQuery, type FanSummary, type FanWait, FatalError, type FindStalledRunsOptions, GatherError, type GatherItemFailure, type GroupHealth, HANDOFF_SEQ_BASE, type Heartbeat, type HeartbeatSighting, type HeartbeatStatus, type HistoryEvent, InMemoryAdmissionBackend, InMemoryRunQueue, InMemoryStateStore, InMemoryTransport, type InferSearchAttributes, LEGACY_V1_CAPABILITIES, LEGACY_V1_PROTOCOL, LIFECYCLE_COALESCED_TAG_PREFIX, LIFECYCLE_HEAL_WINDOW_MS, LIFECYCLE_ORPHAN_MS, LIFECYCLE_OWED_TAG_PREFIX, LIFECYCLE_PENDING_TAG, LIFECYCLE_REGISTRY_HEARTBEAT_MS, LIFECYCLE_REGISTRY_STALE_MS, LIFECYCLE_REGISTRY_TAG, LIFECYCLE_REGISTRY_TTL_MS, LIFECYCLE_REGISTRY_WORKFLOW, LIFECYCLE_TRACE_TAG_PREFIX, LIFECYCLE_TRIGGERED_TAG_PREFIX, LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX, type LifecycleDelivery, type LifecycleDeliveryState, type LifecycleEventOf, type LifecycleKind, type LifecycleRegistryEntry, type LifecycleSource, type LifecycleSubscriptionLink, type ListStalledRunsOptions, type MetricsCollector, type MetricsSnapshot, type NamedTransport, type NegotiateOptions, type NegotiationOutcome, type NegotiationReason, type NegotiationResult, NestedWorkflowCallError, NonDeterminismError, type OnErrorInput, type OnErrorRoute, type OnEventEntry, type OwnedLeaseReclaim, PARENT_CLOSE_TAG_PREFIX, type ParentClosePolicy, type ParsedRRule, type PartitionSighting, type PayloadCodec, type QueueConfig, QueueController, REMOTE_EVENT, RUN_HISTORY_FIXTURE_VERSION, RUN_VALUE_FACET_LIMIT, RUN_VALUE_FACET_SCAN, RUN_WAIT_TOKEN_PREFIX, type RawWorkerDescriptor, RemoteStepError, RemoteStepTimeout, type RemoteTask, RemoteWorkflowExecutor, RemoteWorkflowTimeout, type RepublishLifecycleResult, type RepublishLifecycleTarget, type RetentionPolicy, type RoutableDispatch, type RoutableResolution, type RoutingResolution, type RunAppAttribution, RunAppStamper, type RunAppTopologyOptions, type RunAttributeRow, type RunConsumerOptions, type RunDetail, type RunDetailOptions, type RunDispatch, type RunDispatcher, type RunFacetQuery, type RunFacetRow, RunGateway, type RunListItem, type RunQuery, type RunQueueOptions, type RunReply, type RunReplyResult, type RunRequest, type RunRequestKind, type RunResult, type RunSchedulesOptions, type RunScope, type RunStatus, type RunTenant, type RunValueAxis, type RunValueFacetOptions, type RunValueFacetOrder, type RunValueFacetRow, type RunWaitLink, type RunWaiting, SINGLETON_ACTIVE_STATUSES, SINGLETON_ADMITTED_TAG, SINGLETON_LOCK_CHUNK, SINGLETON_RESERVED_TAGS, SINGLETON_TRACKED_TAG, STATE_STORE, STATE_STORE_CANONICAL, SUMMARY_CHILD_LIMIT, type ScalarAttributeFilter, ScheduleAlreadyExistsError, ScheduleClient, type ScheduleClientOptions, type ScheduleDescription, type ScheduleHost, type ScheduleListQuery, ScheduleNotFoundError, type ScheduleOptions, type ScheduleQuery, type ScheduleRecord, type ScheduleTickEngine, type ScheduledWorkflow, type SchemaIssue, type SchemaValidationCode, SchemaValidationError, type SearchAttributes, type SearchAttributesSchema, type Settled, type SignalOptions, SignalTimeoutError, type SignalWaiter, type SingletonConfig, SingletonQueueFullError, type StalePendingStep, type StalledRunInfo, StandardSchemaV1, type StartOptions, type StartRunMessage, type StateStore, type StepCheckpoint, type StepConfig, type StepDef, type StepDispatchOpts, type StepError, type StepEvent, type StepHandler, type StepInterceptor, type StepInvocation, type StepKind, type StepLogger, type StepOptions, type StepRef, type StepResult, type StepResultSettlement, type StepScope, type StepSettlement, type StepUndo, type StoreTransaction, type SubProcessHandle, TERMINAL_RUN_STATUSES, TRANSPORT, TRANSPORT_CANONICAL, type TenantEvent, type TenantFilter, type TenantRow, type TenantTokenSource, type TenantVerifier, type Transport, type UndoOf, type UpdateResult, type UpdateValidator, VERSION_UNDECLARED_TAG, type VerifiedTenant, WORKFLOW_NAME_KEY, type WaitAnyCondition, type WaitAnyOutcome, type WaitAnyResult, type WaitCondition, type WaitConditionSpec, type WaitForRunOptions, type WireDates, type WorkerAdjust, type WorkerConcurrencyStatus, type WorkerDescriptor, type WorkerHeartbeat, type WorkerLifecycle, type WorkerStatus, type WorkflowAnnouncement, WorkflowBlocked, type WorkflowClass, type WorkflowCommand, type WorkflowCtx, type WorkflowDecision, type WorkflowDirectory, WorkflowEngine, type WorkflowEngineDeps, type WorkflowExecutor, type WorkflowHandler, type WorkflowInputOf, type WorkflowLifecycleEvent, type WorkflowLifecycleLinks, WorkflowNotRegistered, type WorkflowOutputOf, type WorkflowRef, type WorkflowRegistration, type WorkflowRun, type WorkflowStartClient, type WorkflowStepEvent, WorkflowSuspended, type WorkflowTask, acceptingSubscription, accumulatorRunId, aggregateAnnouncements, aggregatesCheckpoints, announcementsOf, anyCheckpointName, applyAttributeQuery, assertConcurrency, assertRoutes, assertSingleDurableCopy, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, bufferedEventReaches, buildWorkflowDirectory, canRoute, capableWorkers, carriesLifecyclePending, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, coalescedSubscribersOf, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneAttribution, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, durableCopies, error, etagMatches, eventMatchOf, eventMatches, eventNameOf, eventPrefix, eventToken, extendEtag, facetOrigin, fanPageBounds, fanPageEtag, findStalledRuns, foldedCount, getRunsByIds, grantsClientTenant, handoffHandlerId, handoffName, hasDurableExecutionWrappers, heartbeatStatus, hmacTenantVerifier, indexWaitersByRun, info, inheritTenant, isAnyCheckpoint, isAnyMember, isEngineMintedTag, isEventToken, isFailedMember, isLegacyDescriptor, isLifecycleTag, isNonEmptyRunScope, isRemoteEvent, isWorkflowControlFlowSignal, legacySingletonHolders, lifecycleDeliveriesOf, lifecycleEventName, lifecycleEventOf, lifecycleKindOf, lifecycleRegistryNamespace, lifecycleRegistryRunId, lifecycleRegistrySubscriptions, lifecycleRunId, lifecycleSourceOf, lifecycleTraceparentOf, listSignalWaitersOfRuns, liveHandoff, log, markRemoteEvent, matchesAttributes, matchesTenantPredicates, mergeRunFacetRows, mergeRunValueFacetRows, missingCapabilities, negotiate, nextCronFireMs, nextRRuleFireMs, normalizeAttributeRows, normalizeDescriptor, observedAnnouncements, onErrorRunId, owedSubscribersOf, pageFan, pageFanFromStore, parentRunIdOf, parseDuration, parseLifecycleEvent, parseRRule, parseWebhookToken, partitionOfToken, planDispatch, poolNamespace, prevCronFireMs, prevRRuleFireMs, queryCheckpointsOf, readBufferedEvent, readRunsByIds, readSearchAttributes, requiredCapabilities, resolveConcurrency, resolveRouting, resolveRunWaiting, resolveTenantToken, resolveWireTenant, retentionKeeps, retiredHandoffName, routeFor, rowTenant, runCompletedEvent, runDetailEtag, runDurableExecution, runFailedEvent, runInStepLogger, runInStepScope, runInWorkflowCtx, runOutsideWorkflowCtx, runSchedules, runStepHandler, runTraceId, runValueFacetsFromRuns, runWaitPrefix, runWaitTargetOf, runWaitToken, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, scopeBufferedEvent, scopeTenantQuery, sealDurableCopies, settleResultsWithPlainCalls, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantAppOf, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
9805
+ export { ACCUMULATOR_SEEN_MAX, ANY_WAIT_GROUP, type AccumulatorHost, type AccumulatorStartOptions, type Admission, type AdmissionBackend, type AdmissionItem, type AllOptions, type AllSettledOptions, type AllStepsOptions, type AllStepsSettledOptions, type AnnouncedWorkflow, type AnnouncementEvidence, type AttributeFilter, type AttributeOp, type AttributePredicateOperand, type AttributeValue, type AttributedEngineEvent, type BackoffStrategy, type BlockedDispatch, type BlockedResolution, type BufferedSignalRow, CHILD_EDGE_PREFIXES, CONTROL_FLOW_SIGNAL, CORE_ORIGIN, CURRENT_PROTOCOL_VERSION, type CapabilityRequirement, type CheckpointAggregatingStore, type CheckpointNameKind, type CheckpointQuery, type CheckpointStat, type ChildCallOptions, type ChildWait, CodecStateStore, type CodecStateStoreOptions, type ConcurrencyConfig, ConcurrencyLimitError, type ConcurrencyQuota, type ConsoleCapabilities, ContinueAsNew, type ControlMessage, type ControlPlane, DEFAULT_CONCURRENCY_STATUSES, DEFAULT_PARTITION, DEFAULT_STALLED_AFTER_MS, DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL, DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, type Disagreement, type DispatchDiagnostics, type DispatchPlan, DuplicateDurableCopyError, type DurableCopy, type DurableExecution, type DurableExecutionWrapper, type DurableTopology, type DurableWebhook, DurableWorkflow, type DynamicWorkflowCtx, ENGINE_MINTED_TAG_PREFIXES, ENTITY_WORKFLOW, EVENT_BUFFER_SCAN_LIMIT, EVENT_TOKEN_PREFIX, type EngineEvent, type EngineEventType, type EngineListener, type EngineTenancy, Entities, type EntityConfig, type EntityHandler, type EntityHost, type EntityWorkflowHost, EventAccumulators, type EventBatchConfig, type EventSubscription, FAN_SUMMARY_FAILURES, type FanJoin, type FanPage, type FanPageQuery, type FanSummary, type FanWait, FatalError, type FindStalledRunsOptions, GatherError, type GatherItemFailure, type GroupHealth, HANDOFF_SEQ_BASE, type Heartbeat, type HeartbeatSighting, type HeartbeatStatus, type HistoryEvent, InMemoryAdmissionBackend, InMemoryRunQueue, InMemoryStateStore, InMemoryTransport, type InferSearchAttributes, LEGACY_V1_CAPABILITIES, LEGACY_V1_PROTOCOL, LIFECYCLE_COALESCED_TAG_PREFIX, LIFECYCLE_HEAL_WINDOW_MS, LIFECYCLE_ORPHAN_MS, LIFECYCLE_OWED_TAG_PREFIX, LIFECYCLE_PENDING_TAG, LIFECYCLE_REGISTRY_HEARTBEAT_MS, LIFECYCLE_REGISTRY_STALE_MS, LIFECYCLE_REGISTRY_TAG, LIFECYCLE_REGISTRY_TTL_MS, LIFECYCLE_REGISTRY_WORKFLOW, LIFECYCLE_TRACE_TAG_PREFIX, LIFECYCLE_TRIGGERED_TAG_PREFIX, LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX, type LifecycleDelivery, type LifecycleDeliveryState, type LifecycleEventOf, type LifecycleKind, type LifecycleRegistryEntry, type LifecycleSource, type LifecycleSubscriptionLink, type ListStalledRunsOptions, type MetricsCollector, type MetricsSnapshot, type NamedTransport, type NegotiateOptions, type NegotiationOutcome, type NegotiationReason, type NegotiationResult, NestedWorkflowCallError, NonDeterminismError, type OnErrorInput, type OnErrorRoute, type OnEventEntry, type OwnedLeaseReclaim, PARENT_CLOSE_TAG_PREFIX, type ParentClosePolicy, type ParsedRRule, type PartitionSighting, type PayloadCodec, type QueueConfig, QueueController, REMOTE_EVENT, RUN_HISTORY_FIXTURE_VERSION, RUN_VALUE_FACET_LIMIT, RUN_VALUE_FACET_SCAN, RUN_WAIT_TOKEN_PREFIX, type RawWorkerDescriptor, RemoteStepError, RemoteStepTimeout, type RemoteTask, RemoteWorkflowExecutor, RemoteWorkflowTimeout, type RepublishLifecycleResult, type RepublishLifecycleTarget, type RetentionPolicy, type RoutableDispatch, type RoutableResolution, type RoutingResolution, type RunAppAttribution, RunAppStamper, type RunAppTopologyOptions, type RunAttributeRow, type RunConsumerOptions, type RunDetail, type RunDetailOptions, type RunDispatch, type RunDispatcher, type RunFacetQuery, type RunFacetRow, RunGateway, type RunListItem, type RunQuery, type RunQueueOptions, type RunReply, type RunReplyResult, type RunRequest, type RunRequestKind, type RunResult, type RunSchedulesOptions, type RunScope, type RunStatus, type RunTenant, type RunValueAxis, type RunValueFacetOptions, type RunValueFacetOrder, type RunValueFacetRow, type RunWaitLink, type RunWaiting, SINGLETON_ACTIVE_STATUSES, SINGLETON_ADMITTED_TAG, SINGLETON_LOCK_CHUNK, SINGLETON_RESERVED_TAGS, SINGLETON_TRACKED_TAG, STATE_STORE, STATE_STORE_CANONICAL, SUMMARY_CHILD_LIMIT, type ScalarAttributeFilter, ScheduleAlreadyExistsError, ScheduleClient, type ScheduleClientOptions, type ScheduleDescription, type ScheduleHost, type ScheduleListQuery, ScheduleNotFoundError, type ScheduleOptions, type ScheduleQuery, type ScheduleRecord, type ScheduleTickEngine, type ScheduledWorkflow, type SchemaIssue, type SchemaValidationCode, SchemaValidationError, type SearchAttributes, type SearchAttributesSchema, type Settled, type SignalOptions, SignalTimeoutError, type SignalWaiter, type SingletonConfig, SingletonQueueFullError, type StalePendingStep, type StalledRunInfo, StandardSchemaV1, type StartOptions, type StartRunMessage, type StateStore, type StepCheckpoint, type StepConfig, type StepDef, type StepDispatchOpts, type StepError, type StepEvent, type StepHandler, type StepInterceptor, type StepInvocation, type StepKind, type StepLogger, type StepOptions, type StepRef, type StepResult, type StepResultSettlement, type StepScope, type StepSettlement, type StepUndo, type StoreTransaction, type SubProcessHandle, TERMINAL_RUN_STATUSES, TRANSPORT, TRANSPORT_CANONICAL, type TenantEvent, type TenantFilter, type TenantRow, type TenantTokenSource, type TenantVerifier, type Transport, type UndoOf, type UpdateResult, type UpdateValidator, VERSION_UNDECLARED_TAG, type VerifiedTenant, WORKFLOW_NAME_KEY, type WaitAnyCondition, type WaitAnyOutcome, type WaitAnyResult, type WaitCondition, type WaitConditionSpec, type WaitForRunOptions, type WireDates, type WorkerAdjust, type WorkerConcurrencyStatus, type WorkerDescriptor, type WorkerHeartbeat, type WorkerLifecycle, type WorkerStatus, type WorkflowAnnouncement, WorkflowBlocked, type WorkflowClass, type WorkflowCommand, type WorkflowCtx, type WorkflowDecision, type WorkflowDirectory, WorkflowEngine, type WorkflowEngineDeps, type WorkflowExecutor, type WorkflowHandler, type WorkflowInputOf, type WorkflowLifecycleEvent, type WorkflowLifecycleLinks, WorkflowNotRegistered, type WorkflowOutputOf, type WorkflowRef, type WorkflowRegistration, type WorkflowRun, type WorkflowStartClient, type WorkflowStepEvent, WorkflowSuspended, type WorkflowTask, acceptingSubscription, accumulatorRunId, aggregateAnnouncements, aggregatesCheckpoints, announcementsOf, anyCheckpointName, applyAttributeQuery, assertConcurrency, assertRoutes, assertSingleDurableCopy, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, bufferedEventReaches, buildWorkflowDirectory, canRoute, capableWorkers, carriesLifecyclePending, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, coalescedSubscribersOf, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneAttribution, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, durableCopies, error, etagMatches, eventMatchOf, eventMatches, eventNameOf, eventPrefix, eventToken, extendEtag, facetOrigin, fanPageBounds, fanPageEtag, findStalledRuns, foldedCount, getRunsByIds, grantsClientTenant, handoffHandlerId, handoffName, hasDurableExecutionWrappers, heartbeatStatus, hmacTenantVerifier, indexWaitersByRun, info, inheritTenant, isAnyCheckpoint, isAnyMember, isEngineMintedTag, isEventToken, isFailedMember, isLegacyDescriptor, isLifecycleTag, isNonEmptyRunScope, isRemoteEvent, isWorkflowControlFlowSignal, legacySingletonHolders, lifecycleDeliveriesOf, lifecycleEventName, lifecycleEventOf, lifecycleKindOf, lifecycleRegistryNamespace, lifecycleRegistryRunId, lifecycleRegistrySubscriptions, lifecycleRunId, lifecycleSourceOf, lifecycleTraceparentOf, listSignalWaitersOfRuns, liveHandoff, log, markRemoteEvent, matchesAttributes, matchesTenantPredicates, mergeRunFacetRows, mergeRunValueFacetRows, missingCapabilities, negotiate, nextCronFireMs, nextRRuleFireMs, nextScheduleFireAt, normalizeAttributeRows, normalizeDescriptor, observedAnnouncements, onErrorRunId, owedSubscribersOf, pageFan, pageFanFromStore, parentRunIdOf, parseDuration, parseLifecycleEvent, parseRRule, parseWebhookToken, partitionOfToken, planDispatch, poolNamespace, prevCronFireMs, prevRRuleFireMs, queryCheckpointsOf, readBufferedEvent, readRunsByIds, readSearchAttributes, requiredCapabilities, resolveConcurrency, resolveRouting, resolveRunWaiting, resolveTenantToken, resolveWireTenant, retentionKeeps, retiredHandoffName, routeFor, rowTenant, runCompletedEvent, runDetailEtag, runDurableExecution, runFailedEvent, runInStepLogger, runInStepScope, runInWorkflowCtx, runOutsideWorkflowCtx, runSchedules, runStepHandler, runTraceId, runValueFacetsFromRuns, runWaitPrefix, runWaitTargetOf, runWaitToken, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, scopeBufferedEvent, scopeTenantQuery, sealDurableCopies, settleResultsWithPlainCalls, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantAppOf, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
package/dist/index.d.ts CHANGED
@@ -3121,9 +3121,12 @@ interface Transport {
3121
3121
  * broker transports that carry the two-tier descriptor advertisement (BullMQ) implement it; a pure
3122
3122
  * in-process transport returns nothing, so the engine's routing guard stays disengaged (legacy
3123
3123
  * assume-compatible, design §7.7). The engine feeds these into {@link planDispatch} to decide whether
3124
- * a run can dispatch to `group` or must park `blocked`.
3124
+ * a run can dispatch to `group` or must park `blocked`. A transport may reuse a recent read of its
3125
+ * registry; `opts.fresh` asks it to read again (the engine does before it parks a run `blocked`).
3125
3126
  */
3126
- readWorkerDescriptors?(group: string): Promise<WorkerDescriptor[]>;
3127
+ readWorkerDescriptors?(group: string, opts?: {
3128
+ fresh?: boolean | undefined;
3129
+ }): Promise<WorkerDescriptor[]>;
3127
3130
  /**
3128
3131
  * Every live {@link WorkerDescriptor} in the deployment, across all groups — the read behind
3129
3132
  * {@link WorkflowEngine.announcedWorkflows}. Optional, same as {@link readWorkerDescriptors}: a
@@ -5184,6 +5187,13 @@ declare class ScheduleClient {
5184
5187
  * run ids started (or re-found, for an idempotent re-fire).
5185
5188
  */
5186
5189
  tick(nowMs?: number): Promise<string[]>;
5190
+ /**
5191
+ * When {@link tick} next has a schedule to fire, if one is due by `byMs`: the earliest `nextFireAt`
5192
+ * of the unpaused schedules (of this engine's namespace) due by then, else `undefined`. One indexed
5193
+ * read (the due-schedule scan `tick` makes, with a later bound and a limit of one). A store that
5194
+ * does not persist schedules has none.
5195
+ */
5196
+ nextFireAt(byMs: number): Promise<number | undefined>;
5187
5197
  /** Fire one due schedule and advance it. Returns the run id started, if any. */
5188
5198
  private fire;
5189
5199
  /** `overlap: 'skip'` and the previous run of this schedule is still in flight. */
@@ -5961,6 +5971,23 @@ declare class WorkflowEngine {
5961
5971
  * unsubscribe function. Only wire this on instances that should execute runs (workers).
5962
5972
  */
5963
5973
  onEnqueued(listener: (runId: string) => void): () => void;
5974
+ /**
5975
+ * Whether a poller may wait longer than its tick while there is nothing to do: a run another
5976
+ * instance starts must reach this one without the pending-run poll, so this engine needs a control
5977
+ * plane (the `enqueued` nudge, and the run events of other instances that tell a poller to look
5978
+ * again) or a run queue it consumes (see {@link consumeRuns}). See {@link nextDueAt}.
5979
+ */
5980
+ get idleBackoffSupported(): boolean;
5981
+ /**
5982
+ * The earliest known time (epoch ms) the poll has work, if it is at or before `byMs`: this
5983
+ * namespace's next due timer (`listDueTimers` up to `byMs`, limit one: it returns the most overdue
5984
+ * first), the next `blocked` run's recovery poll, and with `persistedSchedules` the next persisted
5985
+ * schedule to fire (see {@link ScheduleClient.nextFireAt}). `undefined` when nothing is due by
5986
+ * then. A poller reads it before waiting longer than its tick, so the wait never outlasts a timer.
5987
+ */
5988
+ nextDueAt(byMs: number, opts?: {
5989
+ persistedSchedules?: boolean;
5990
+ }): Promise<number | undefined>;
5964
5991
  /**
5965
5992
  * Pick up a run another instance announced as enqueued: run it here if it is still `pending`.
5966
5993
  * Bounded by {@link LOCAL_RUN_CONCURRENCY}, and a run another instance already took is skipped
@@ -6504,8 +6531,16 @@ declare class WorkflowEngine {
6504
6531
  * {@link LIFECYCLE_SWEEP_SCAN_MAX}. Pages advance by offset over a set the sweep itself shrinks,
6505
6532
  * so a run that moves into an earlier page is reached on the next tick, which starts over. A run
6506
6533
  * whose lifecycle lease another publisher holds is left for the next tick.
6534
+ *
6535
+ * `options.owed: false` does only the cheap part: the registry heartbeat (itself throttled) and the
6536
+ * run waits. The listing of marked runs filters on a tag (an unindexed `LIKE` on most stores, a
6537
+ * partial index on Postgres) and the heal reads recent runs per source workflow, so a poller runs
6538
+ * that part less often than its tick (see the NestJS timer poller) and passes `owed: false` in
6539
+ * between. It returns 0 then.
6507
6540
  */
6508
- sweepLifecycleEvents(nowMs?: number, limit?: number): Promise<number>;
6541
+ sweepLifecycleEvents(nowMs?: number, limit?: number, options?: {
6542
+ owed?: boolean;
6543
+ }): Promise<number>;
6509
6544
  /**
6510
6545
  * The (run, subscriber) pairs this engine already healed, until when it remembers them; see
6511
6546
  * {@link healLifecycleEvents}.
@@ -9150,6 +9185,14 @@ interface ScheduledWorkflow<W extends WorkflowRef = WorkflowRef> {
9150
9185
  interface RunSchedulesOptions {
9151
9186
  random?: () => number;
9152
9187
  }
9188
+ /**
9189
+ * The earliest time after `nowMs` at which {@link runSchedules} may have a window of `schedules` to
9190
+ * fire for `engine`: each unpaused schedule's next window boundary, and the fire time of any jittered
9191
+ * window an earlier call deferred. `nowMs` when a schedule cannot say (an unparsable cron, a missing
9192
+ * `cron-parser`), so a caller never waits past a window; `undefined` for none. Pass the same `engine`
9193
+ * object as to `runSchedules` (the deferred windows are remembered per engine object).
9194
+ */
9195
+ declare function nextScheduleFireAt(engine: object, schedules: readonly ScheduledWorkflow[], nowMs: number): number | undefined;
9153
9196
  /** Deterministic run id for a fixed-interval schedule's current time window. */
9154
9197
  declare function scheduledRunId(key: string, everyMs: number, nowMs: number): string;
9155
9198
  /**
@@ -9759,4 +9802,4 @@ declare function prevRRuleFireMs(rule: ParsedRRule, atMs: number): number | null
9759
9802
  */
9760
9803
  declare function settleResultsWithPlainCalls(store: Pick<StateStore, 'getRun' | 'getCheckpoint'> & Partial<Pick<StateStore, 'getRuns' | 'getCheckpointsForSettle' | 'getCheckpoints' | 'settleCheckpointsIfPending'>>, results: StepResultSettlement[]): Promise<(StepCheckpoint | null)[]>;
9761
9804
 
9762
- export { ACCUMULATOR_SEEN_MAX, ANY_WAIT_GROUP, type AccumulatorHost, type AccumulatorStartOptions, type Admission, type AdmissionBackend, type AdmissionItem, type AllOptions, type AllSettledOptions, type AllStepsOptions, type AllStepsSettledOptions, type AnnouncedWorkflow, type AnnouncementEvidence, type AttributeFilter, type AttributeOp, type AttributePredicateOperand, type AttributeValue, type AttributedEngineEvent, type BackoffStrategy, type BlockedDispatch, type BlockedResolution, type BufferedSignalRow, CHILD_EDGE_PREFIXES, CONTROL_FLOW_SIGNAL, CORE_ORIGIN, CURRENT_PROTOCOL_VERSION, type CapabilityRequirement, type CheckpointAggregatingStore, type CheckpointNameKind, type CheckpointQuery, type CheckpointStat, type ChildCallOptions, type ChildWait, CodecStateStore, type CodecStateStoreOptions, type ConcurrencyConfig, ConcurrencyLimitError, type ConcurrencyQuota, type ConsoleCapabilities, ContinueAsNew, type ControlMessage, type ControlPlane, DEFAULT_CONCURRENCY_STATUSES, DEFAULT_PARTITION, DEFAULT_STALLED_AFTER_MS, DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL, DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, type Disagreement, type DispatchDiagnostics, type DispatchPlan, DuplicateDurableCopyError, type DurableCopy, type DurableExecution, type DurableExecutionWrapper, type DurableTopology, type DurableWebhook, DurableWorkflow, type DynamicWorkflowCtx, ENGINE_MINTED_TAG_PREFIXES, ENTITY_WORKFLOW, EVENT_BUFFER_SCAN_LIMIT, EVENT_TOKEN_PREFIX, type EngineEvent, type EngineEventType, type EngineListener, type EngineTenancy, Entities, type EntityConfig, type EntityHandler, type EntityHost, type EntityWorkflowHost, EventAccumulators, type EventBatchConfig, type EventSubscription, FAN_SUMMARY_FAILURES, type FanJoin, type FanPage, type FanPageQuery, type FanSummary, type FanWait, FatalError, type FindStalledRunsOptions, GatherError, type GatherItemFailure, type GroupHealth, HANDOFF_SEQ_BASE, type Heartbeat, type HeartbeatSighting, type HeartbeatStatus, type HistoryEvent, InMemoryAdmissionBackend, InMemoryRunQueue, InMemoryStateStore, InMemoryTransport, type InferSearchAttributes, LEGACY_V1_CAPABILITIES, LEGACY_V1_PROTOCOL, LIFECYCLE_COALESCED_TAG_PREFIX, LIFECYCLE_HEAL_WINDOW_MS, LIFECYCLE_ORPHAN_MS, LIFECYCLE_OWED_TAG_PREFIX, LIFECYCLE_PENDING_TAG, LIFECYCLE_REGISTRY_HEARTBEAT_MS, LIFECYCLE_REGISTRY_STALE_MS, LIFECYCLE_REGISTRY_TAG, LIFECYCLE_REGISTRY_TTL_MS, LIFECYCLE_REGISTRY_WORKFLOW, LIFECYCLE_TRACE_TAG_PREFIX, LIFECYCLE_TRIGGERED_TAG_PREFIX, LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX, type LifecycleDelivery, type LifecycleDeliveryState, type LifecycleEventOf, type LifecycleKind, type LifecycleRegistryEntry, type LifecycleSource, type LifecycleSubscriptionLink, type ListStalledRunsOptions, type MetricsCollector, type MetricsSnapshot, type NamedTransport, type NegotiateOptions, type NegotiationOutcome, type NegotiationReason, type NegotiationResult, NestedWorkflowCallError, NonDeterminismError, type OnErrorInput, type OnErrorRoute, type OnEventEntry, type OwnedLeaseReclaim, PARENT_CLOSE_TAG_PREFIX, type ParentClosePolicy, type ParsedRRule, type PartitionSighting, type PayloadCodec, type QueueConfig, QueueController, REMOTE_EVENT, RUN_HISTORY_FIXTURE_VERSION, RUN_VALUE_FACET_LIMIT, RUN_VALUE_FACET_SCAN, RUN_WAIT_TOKEN_PREFIX, type RawWorkerDescriptor, RemoteStepError, RemoteStepTimeout, type RemoteTask, RemoteWorkflowExecutor, RemoteWorkflowTimeout, type RepublishLifecycleResult, type RepublishLifecycleTarget, type RetentionPolicy, type RoutableDispatch, type RoutableResolution, type RoutingResolution, type RunAppAttribution, RunAppStamper, type RunAppTopologyOptions, type RunAttributeRow, type RunConsumerOptions, type RunDetail, type RunDetailOptions, type RunDispatch, type RunDispatcher, type RunFacetQuery, type RunFacetRow, RunGateway, type RunListItem, type RunQuery, type RunQueueOptions, type RunReply, type RunReplyResult, type RunRequest, type RunRequestKind, type RunResult, type RunSchedulesOptions, type RunScope, type RunStatus, type RunTenant, type RunValueAxis, type RunValueFacetOptions, type RunValueFacetOrder, type RunValueFacetRow, type RunWaitLink, type RunWaiting, SINGLETON_ACTIVE_STATUSES, SINGLETON_ADMITTED_TAG, SINGLETON_LOCK_CHUNK, SINGLETON_RESERVED_TAGS, SINGLETON_TRACKED_TAG, STATE_STORE, STATE_STORE_CANONICAL, SUMMARY_CHILD_LIMIT, type ScalarAttributeFilter, ScheduleAlreadyExistsError, ScheduleClient, type ScheduleClientOptions, type ScheduleDescription, type ScheduleHost, type ScheduleListQuery, ScheduleNotFoundError, type ScheduleOptions, type ScheduleQuery, type ScheduleRecord, type ScheduleTickEngine, type ScheduledWorkflow, type SchemaIssue, type SchemaValidationCode, SchemaValidationError, type SearchAttributes, type SearchAttributesSchema, type Settled, type SignalOptions, SignalTimeoutError, type SignalWaiter, type SingletonConfig, SingletonQueueFullError, type StalePendingStep, type StalledRunInfo, StandardSchemaV1, type StartOptions, type StartRunMessage, type StateStore, type StepCheckpoint, type StepConfig, type StepDef, type StepDispatchOpts, type StepError, type StepEvent, type StepHandler, type StepInterceptor, type StepInvocation, type StepKind, type StepLogger, type StepOptions, type StepRef, type StepResult, type StepResultSettlement, type StepScope, type StepSettlement, type StepUndo, type StoreTransaction, type SubProcessHandle, TERMINAL_RUN_STATUSES, TRANSPORT, TRANSPORT_CANONICAL, type TenantEvent, type TenantFilter, type TenantRow, type TenantTokenSource, type TenantVerifier, type Transport, type UndoOf, type UpdateResult, type UpdateValidator, VERSION_UNDECLARED_TAG, type VerifiedTenant, WORKFLOW_NAME_KEY, type WaitAnyCondition, type WaitAnyOutcome, type WaitAnyResult, type WaitCondition, type WaitConditionSpec, type WaitForRunOptions, type WireDates, type WorkerAdjust, type WorkerConcurrencyStatus, type WorkerDescriptor, type WorkerHeartbeat, type WorkerLifecycle, type WorkerStatus, type WorkflowAnnouncement, WorkflowBlocked, type WorkflowClass, type WorkflowCommand, type WorkflowCtx, type WorkflowDecision, type WorkflowDirectory, WorkflowEngine, type WorkflowEngineDeps, type WorkflowExecutor, type WorkflowHandler, type WorkflowInputOf, type WorkflowLifecycleEvent, type WorkflowLifecycleLinks, WorkflowNotRegistered, type WorkflowOutputOf, type WorkflowRef, type WorkflowRegistration, type WorkflowRun, type WorkflowStartClient, type WorkflowStepEvent, WorkflowSuspended, type WorkflowTask, acceptingSubscription, accumulatorRunId, aggregateAnnouncements, aggregatesCheckpoints, announcementsOf, anyCheckpointName, applyAttributeQuery, assertConcurrency, assertRoutes, assertSingleDurableCopy, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, bufferedEventReaches, buildWorkflowDirectory, canRoute, capableWorkers, carriesLifecyclePending, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, coalescedSubscribersOf, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneAttribution, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, durableCopies, error, etagMatches, eventMatchOf, eventMatches, eventNameOf, eventPrefix, eventToken, extendEtag, facetOrigin, fanPageBounds, fanPageEtag, findStalledRuns, foldedCount, getRunsByIds, grantsClientTenant, handoffHandlerId, handoffName, hasDurableExecutionWrappers, heartbeatStatus, hmacTenantVerifier, indexWaitersByRun, info, inheritTenant, isAnyCheckpoint, isAnyMember, isEngineMintedTag, isEventToken, isFailedMember, isLegacyDescriptor, isLifecycleTag, isNonEmptyRunScope, isRemoteEvent, isWorkflowControlFlowSignal, legacySingletonHolders, lifecycleDeliveriesOf, lifecycleEventName, lifecycleEventOf, lifecycleKindOf, lifecycleRegistryNamespace, lifecycleRegistryRunId, lifecycleRegistrySubscriptions, lifecycleRunId, lifecycleSourceOf, lifecycleTraceparentOf, listSignalWaitersOfRuns, liveHandoff, log, markRemoteEvent, matchesAttributes, matchesTenantPredicates, mergeRunFacetRows, mergeRunValueFacetRows, missingCapabilities, negotiate, nextCronFireMs, nextRRuleFireMs, normalizeAttributeRows, normalizeDescriptor, observedAnnouncements, onErrorRunId, owedSubscribersOf, pageFan, pageFanFromStore, parentRunIdOf, parseDuration, parseLifecycleEvent, parseRRule, parseWebhookToken, partitionOfToken, planDispatch, poolNamespace, prevCronFireMs, prevRRuleFireMs, queryCheckpointsOf, readBufferedEvent, readRunsByIds, readSearchAttributes, requiredCapabilities, resolveConcurrency, resolveRouting, resolveRunWaiting, resolveTenantToken, resolveWireTenant, retentionKeeps, retiredHandoffName, routeFor, rowTenant, runCompletedEvent, runDetailEtag, runDurableExecution, runFailedEvent, runInStepLogger, runInStepScope, runInWorkflowCtx, runOutsideWorkflowCtx, runSchedules, runStepHandler, runTraceId, runValueFacetsFromRuns, runWaitPrefix, runWaitTargetOf, runWaitToken, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, scopeBufferedEvent, scopeTenantQuery, sealDurableCopies, settleResultsWithPlainCalls, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantAppOf, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
9805
+ export { ACCUMULATOR_SEEN_MAX, ANY_WAIT_GROUP, type AccumulatorHost, type AccumulatorStartOptions, type Admission, type AdmissionBackend, type AdmissionItem, type AllOptions, type AllSettledOptions, type AllStepsOptions, type AllStepsSettledOptions, type AnnouncedWorkflow, type AnnouncementEvidence, type AttributeFilter, type AttributeOp, type AttributePredicateOperand, type AttributeValue, type AttributedEngineEvent, type BackoffStrategy, type BlockedDispatch, type BlockedResolution, type BufferedSignalRow, CHILD_EDGE_PREFIXES, CONTROL_FLOW_SIGNAL, CORE_ORIGIN, CURRENT_PROTOCOL_VERSION, type CapabilityRequirement, type CheckpointAggregatingStore, type CheckpointNameKind, type CheckpointQuery, type CheckpointStat, type ChildCallOptions, type ChildWait, CodecStateStore, type CodecStateStoreOptions, type ConcurrencyConfig, ConcurrencyLimitError, type ConcurrencyQuota, type ConsoleCapabilities, ContinueAsNew, type ControlMessage, type ControlPlane, DEFAULT_CONCURRENCY_STATUSES, DEFAULT_PARTITION, DEFAULT_STALLED_AFTER_MS, DURABLE_OPTIONS, DURABLE_OPTIONS_CANONICAL, DURABLE_STEP_CONFIG, DURABLE_STEP_NAME, type Disagreement, type DispatchDiagnostics, type DispatchPlan, DuplicateDurableCopyError, type DurableCopy, type DurableExecution, type DurableExecutionWrapper, type DurableTopology, type DurableWebhook, DurableWorkflow, type DynamicWorkflowCtx, ENGINE_MINTED_TAG_PREFIXES, ENTITY_WORKFLOW, EVENT_BUFFER_SCAN_LIMIT, EVENT_TOKEN_PREFIX, type EngineEvent, type EngineEventType, type EngineListener, type EngineTenancy, Entities, type EntityConfig, type EntityHandler, type EntityHost, type EntityWorkflowHost, EventAccumulators, type EventBatchConfig, type EventSubscription, FAN_SUMMARY_FAILURES, type FanJoin, type FanPage, type FanPageQuery, type FanSummary, type FanWait, FatalError, type FindStalledRunsOptions, GatherError, type GatherItemFailure, type GroupHealth, HANDOFF_SEQ_BASE, type Heartbeat, type HeartbeatSighting, type HeartbeatStatus, type HistoryEvent, InMemoryAdmissionBackend, InMemoryRunQueue, InMemoryStateStore, InMemoryTransport, type InferSearchAttributes, LEGACY_V1_CAPABILITIES, LEGACY_V1_PROTOCOL, LIFECYCLE_COALESCED_TAG_PREFIX, LIFECYCLE_HEAL_WINDOW_MS, LIFECYCLE_ORPHAN_MS, LIFECYCLE_OWED_TAG_PREFIX, LIFECYCLE_PENDING_TAG, LIFECYCLE_REGISTRY_HEARTBEAT_MS, LIFECYCLE_REGISTRY_STALE_MS, LIFECYCLE_REGISTRY_TAG, LIFECYCLE_REGISTRY_TTL_MS, LIFECYCLE_REGISTRY_WORKFLOW, LIFECYCLE_TRACE_TAG_PREFIX, LIFECYCLE_TRIGGERED_TAG_PREFIX, LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX, type LifecycleDelivery, type LifecycleDeliveryState, type LifecycleEventOf, type LifecycleKind, type LifecycleRegistryEntry, type LifecycleSource, type LifecycleSubscriptionLink, type ListStalledRunsOptions, type MetricsCollector, type MetricsSnapshot, type NamedTransport, type NegotiateOptions, type NegotiationOutcome, type NegotiationReason, type NegotiationResult, NestedWorkflowCallError, NonDeterminismError, type OnErrorInput, type OnErrorRoute, type OnEventEntry, type OwnedLeaseReclaim, PARENT_CLOSE_TAG_PREFIX, type ParentClosePolicy, type ParsedRRule, type PartitionSighting, type PayloadCodec, type QueueConfig, QueueController, REMOTE_EVENT, RUN_HISTORY_FIXTURE_VERSION, RUN_VALUE_FACET_LIMIT, RUN_VALUE_FACET_SCAN, RUN_WAIT_TOKEN_PREFIX, type RawWorkerDescriptor, RemoteStepError, RemoteStepTimeout, type RemoteTask, RemoteWorkflowExecutor, RemoteWorkflowTimeout, type RepublishLifecycleResult, type RepublishLifecycleTarget, type RetentionPolicy, type RoutableDispatch, type RoutableResolution, type RoutingResolution, type RunAppAttribution, RunAppStamper, type RunAppTopologyOptions, type RunAttributeRow, type RunConsumerOptions, type RunDetail, type RunDetailOptions, type RunDispatch, type RunDispatcher, type RunFacetQuery, type RunFacetRow, RunGateway, type RunListItem, type RunQuery, type RunQueueOptions, type RunReply, type RunReplyResult, type RunRequest, type RunRequestKind, type RunResult, type RunSchedulesOptions, type RunScope, type RunStatus, type RunTenant, type RunValueAxis, type RunValueFacetOptions, type RunValueFacetOrder, type RunValueFacetRow, type RunWaitLink, type RunWaiting, SINGLETON_ACTIVE_STATUSES, SINGLETON_ADMITTED_TAG, SINGLETON_LOCK_CHUNK, SINGLETON_RESERVED_TAGS, SINGLETON_TRACKED_TAG, STATE_STORE, STATE_STORE_CANONICAL, SUMMARY_CHILD_LIMIT, type ScalarAttributeFilter, ScheduleAlreadyExistsError, ScheduleClient, type ScheduleClientOptions, type ScheduleDescription, type ScheduleHost, type ScheduleListQuery, ScheduleNotFoundError, type ScheduleOptions, type ScheduleQuery, type ScheduleRecord, type ScheduleTickEngine, type ScheduledWorkflow, type SchemaIssue, type SchemaValidationCode, SchemaValidationError, type SearchAttributes, type SearchAttributesSchema, type Settled, type SignalOptions, SignalTimeoutError, type SignalWaiter, type SingletonConfig, SingletonQueueFullError, type StalePendingStep, type StalledRunInfo, StandardSchemaV1, type StartOptions, type StartRunMessage, type StateStore, type StepCheckpoint, type StepConfig, type StepDef, type StepDispatchOpts, type StepError, type StepEvent, type StepHandler, type StepInterceptor, type StepInvocation, type StepKind, type StepLogger, type StepOptions, type StepRef, type StepResult, type StepResultSettlement, type StepScope, type StepSettlement, type StepUndo, type StoreTransaction, type SubProcessHandle, TERMINAL_RUN_STATUSES, TRANSPORT, TRANSPORT_CANONICAL, type TenantEvent, type TenantFilter, type TenantRow, type TenantTokenSource, type TenantVerifier, type Transport, type UndoOf, type UpdateResult, type UpdateValidator, VERSION_UNDECLARED_TAG, type VerifiedTenant, WORKFLOW_NAME_KEY, type WaitAnyCondition, type WaitAnyOutcome, type WaitAnyResult, type WaitCondition, type WaitConditionSpec, type WaitForRunOptions, type WireDates, type WorkerAdjust, type WorkerConcurrencyStatus, type WorkerDescriptor, type WorkerHeartbeat, type WorkerLifecycle, type WorkerStatus, type WorkflowAnnouncement, WorkflowBlocked, type WorkflowClass, type WorkflowCommand, type WorkflowCtx, type WorkflowDecision, type WorkflowDirectory, WorkflowEngine, type WorkflowEngineDeps, type WorkflowExecutor, type WorkflowHandler, type WorkflowInputOf, type WorkflowLifecycleEvent, type WorkflowLifecycleLinks, WorkflowNotRegistered, type WorkflowOutputOf, type WorkflowRef, type WorkflowRegistration, type WorkflowRun, type WorkflowStartClient, type WorkflowStepEvent, WorkflowSuspended, type WorkflowTask, acceptingSubscription, accumulatorRunId, aggregateAnnouncements, aggregatesCheckpoints, announcementsOf, anyCheckpointName, applyAttributeQuery, assertConcurrency, assertRoutes, assertSingleDurableCopy, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, bufferedEventReaches, buildWorkflowDirectory, canRoute, capableWorkers, carriesLifecyclePending, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, coalescedSubscribersOf, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneAttribution, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, durableCopies, error, etagMatches, eventMatchOf, eventMatches, eventNameOf, eventPrefix, eventToken, extendEtag, facetOrigin, fanPageBounds, fanPageEtag, findStalledRuns, foldedCount, getRunsByIds, grantsClientTenant, handoffHandlerId, handoffName, hasDurableExecutionWrappers, heartbeatStatus, hmacTenantVerifier, indexWaitersByRun, info, inheritTenant, isAnyCheckpoint, isAnyMember, isEngineMintedTag, isEventToken, isFailedMember, isLegacyDescriptor, isLifecycleTag, isNonEmptyRunScope, isRemoteEvent, isWorkflowControlFlowSignal, legacySingletonHolders, lifecycleDeliveriesOf, lifecycleEventName, lifecycleEventOf, lifecycleKindOf, lifecycleRegistryNamespace, lifecycleRegistryRunId, lifecycleRegistrySubscriptions, lifecycleRunId, lifecycleSourceOf, lifecycleTraceparentOf, listSignalWaitersOfRuns, liveHandoff, log, markRemoteEvent, matchesAttributes, matchesTenantPredicates, mergeRunFacetRows, mergeRunValueFacetRows, missingCapabilities, negotiate, nextCronFireMs, nextRRuleFireMs, nextScheduleFireAt, normalizeAttributeRows, normalizeDescriptor, observedAnnouncements, onErrorRunId, owedSubscribersOf, pageFan, pageFanFromStore, parentRunIdOf, parseDuration, parseLifecycleEvent, parseRRule, parseWebhookToken, partitionOfToken, planDispatch, poolNamespace, prevCronFireMs, prevRRuleFireMs, queryCheckpointsOf, readBufferedEvent, readRunsByIds, readSearchAttributes, requiredCapabilities, resolveConcurrency, resolveRouting, resolveRunWaiting, resolveTenantToken, resolveWireTenant, retentionKeeps, retiredHandoffName, routeFor, rowTenant, runCompletedEvent, runDetailEtag, runDurableExecution, runFailedEvent, runInStepLogger, runInStepScope, runInWorkflowCtx, runOutsideWorkflowCtx, runSchedules, runStepHandler, runTraceId, runValueFacetsFromRuns, runWaitPrefix, runWaitTargetOf, runWaitToken, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, scopeBufferedEvent, scopeTenantQuery, sealDurableCopies, settleResultsWithPlainCalls, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantAppOf, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
package/dist/index.js CHANGED
@@ -3568,6 +3568,25 @@ function jitterDue(engine, s, candidates, nowMs, random) {
3568
3568
  return due;
3569
3569
  }
3570
3570
  __name(jitterDue, "jitterDue");
3571
+ function nextScheduleFireAt(engine, schedules, nowMs) {
3572
+ let next;
3573
+ const consider = /* @__PURE__ */ __name((at) => {
3574
+ if (next === void 0 || at < next) next = at;
3575
+ }, "consider");
3576
+ for (const s of schedules) {
3577
+ for (const at of jitterFireAt.get(engine)?.get(s.key)?.values() ?? []) consider(at);
3578
+ if (s.paused) continue;
3579
+ try {
3580
+ if (s.cron != null) consider(nextCronFireMs(s.cron, nowMs, s.timezone));
3581
+ else if (s.everyMs != null && s.everyMs > 0) consider((Math.floor(nowMs / s.everyMs) + 1) * s.everyMs);
3582
+ else return nowMs;
3583
+ } catch {
3584
+ return nowMs;
3585
+ }
3586
+ }
3587
+ return next;
3588
+ }
3589
+ __name(nextScheduleFireAt, "nextScheduleFireAt");
3571
3590
  function scheduledRunId(key, everyMs, nowMs) {
3572
3591
  return `sched:${key}:${Math.floor(nowMs / everyMs)}`;
3573
3592
  }
@@ -4015,6 +4034,21 @@ var ScheduleClient = class {
4015
4034
  }
4016
4035
  return started;
4017
4036
  }
4037
+ /**
4038
+ * When {@link tick} next has a schedule to fire, if one is due by `byMs`: the earliest `nextFireAt`
4039
+ * of the unpaused schedules (of this engine's namespace) due by then, else `undefined`. One indexed
4040
+ * read (the due-schedule scan `tick` makes, with a later bound and a limit of one). A store that
4041
+ * does not persist schedules has none.
4042
+ */
4043
+ async nextFireAt(byMs) {
4044
+ if (!this.supported) return void 0;
4045
+ const [next] = await this.requireStore().listSchedules({
4046
+ dueBy: byMs,
4047
+ namespace: this.options.namespace,
4048
+ limit: 1
4049
+ });
4050
+ return next?.nextFireAt ?? void 0;
4051
+ }
4018
4052
  /** Fire one due schedule and advance it. Returns the run id started, if any. */
4019
4053
  async fire(record, nowMs) {
4020
4054
  const store = this.requireStore();
@@ -5047,11 +5081,11 @@ var TransportPool = class {
5047
5081
  * but none is published — both are the "guard disengaged / legacy assume-compatible" case, so the
5048
5082
  * engine's routing guard treats an empty result identically (design §7.7).
5049
5083
  */
5050
- async readWorkerDescriptors(group) {
5084
+ async readWorkerDescriptors(group, opts) {
5051
5085
  const descriptors = [];
5052
5086
  for (const { transport } of this.transports) {
5053
5087
  if (transport.readWorkerDescriptors) {
5054
- descriptors.push(...await transport.readWorkerDescriptors(group));
5088
+ descriptors.push(...await transport.readWorkerDescriptors(group, opts));
5055
5089
  }
5056
5090
  }
5057
5091
  return descriptors;
@@ -7219,6 +7253,38 @@ var WorkflowEngine = class _WorkflowEngine {
7219
7253
  return () => this.enqueuedListeners.delete(listener);
7220
7254
  }
7221
7255
  /**
7256
+ * Whether a poller may wait longer than its tick while there is nothing to do: a run another
7257
+ * instance starts must reach this one without the pending-run poll, so this engine needs a control
7258
+ * plane (the `enqueued` nudge, and the run events of other instances that tell a poller to look
7259
+ * again) or a run queue it consumes (see {@link consumeRuns}). See {@link nextDueAt}.
7260
+ */
7261
+ get idleBackoffSupported() {
7262
+ return this.controlPlane !== void 0 || this.queuesRunsOverTransport;
7263
+ }
7264
+ /**
7265
+ * The earliest known time (epoch ms) the poll has work, if it is at or before `byMs`: this
7266
+ * namespace's next due timer (`listDueTimers` up to `byMs`, limit one: it returns the most overdue
7267
+ * first), the next `blocked` run's recovery poll, and with `persistedSchedules` the next persisted
7268
+ * schedule to fire (see {@link ScheduleClient.nextFireAt}). `undefined` when nothing is due by
7269
+ * then. A poller reads it before waiting longer than its tick, so the wait never outlasts a timer.
7270
+ */
7271
+ async nextDueAt(byMs, opts = {}) {
7272
+ const [timers, blocked, schedule] = await Promise.all([
7273
+ this.store.listDueTimers(byMs, this.namespace, 1),
7274
+ this.dueBlockedRuns(byMs),
7275
+ opts.persistedSchedules ? this.schedules.nextFireAt(byMs) : void 0
7276
+ ]);
7277
+ let next;
7278
+ for (const at of [
7279
+ timers[0]?.wakeAt,
7280
+ ...blocked.map((run) => run.wakeAt),
7281
+ schedule ?? void 0
7282
+ ]) {
7283
+ if (at !== void 0 && (next === void 0 || at < next)) next = at;
7284
+ }
7285
+ return next;
7286
+ }
7287
+ /**
7222
7288
  * Pick up a run another instance announced as enqueued: run it here if it is still `pending`.
7223
7289
  * Bounded by {@link LOCAL_RUN_CONCURRENCY}, and a run another instance already took is skipped
7224
7290
  * after one read, instead of being leased and replayed here once more.
@@ -8746,14 +8812,21 @@ var WorkflowEngine = class _WorkflowEngine {
8746
8812
  * {@link LIFECYCLE_SWEEP_SCAN_MAX}. Pages advance by offset over a set the sweep itself shrinks,
8747
8813
  * so a run that moves into an earlier page is reached on the next tick, which starts over. A run
8748
8814
  * whose lifecycle lease another publisher holds is left for the next tick.
8815
+ *
8816
+ * `options.owed: false` does only the cheap part: the registry heartbeat (itself throttled) and the
8817
+ * run waits. The listing of marked runs filters on a tag (an unindexed `LIKE` on most stores, a
8818
+ * partial index on Postgres) and the heal reads recent runs per source workflow, so a poller runs
8819
+ * that part less often than its tick (see the NestJS timer poller) and passes `owed: false` in
8820
+ * between. It returns 0 then.
8749
8821
  */
8750
- async sweepLifecycleEvents(nowMs = this.clock(), limit = 100) {
8822
+ async sweepLifecycleEvents(nowMs = this.clock(), limit = 100, options = {}) {
8751
8823
  await this.heartbeatLifecycleRegistry().catch((error2) => {
8752
8824
  console.error("[nestjs-durable] lifecycle registry heartbeat failed; retrying next tick:", error2);
8753
8825
  });
8754
8826
  await this.sweepRunWaits(limit).catch((error2) => {
8755
8827
  console.error("[nestjs-durable] run-wait sweep failed; retrying next tick:", error2);
8756
8828
  });
8829
+ if (options.owed === false) return 0;
8757
8830
  await this.announcedSubscriptions();
8758
8831
  const pageSize = Math.max(1, limit);
8759
8832
  const scanMax = Math.max(pageSize, _WorkflowEngine.LIFECYCLE_SWEEP_SCAN_MAX);
@@ -13737,11 +13810,14 @@ ${run.workflowVersion}`;
13737
13810
  }
13738
13811
  /** The live descriptors for `token`, reused for {@link workerDescriptorCacheMs}; one read in flight. */
13739
13812
  liveWorkerDescriptors(token, fresh = false) {
13740
- if (this.workerDescriptorCacheMs <= 0) return this.pool.readWorkerDescriptors(token);
13813
+ const opts = fresh ? {
13814
+ fresh: true
13815
+ } : void 0;
13816
+ if (this.workerDescriptorCacheMs <= 0) return this.pool.readWorkerDescriptors(token, opts);
13741
13817
  const now = Date.now();
13742
13818
  const cached = this.descriptorCache.get(token);
13743
13819
  if (!fresh && cached && now - cached.at < this.workerDescriptorCacheMs) return cached.read;
13744
- const read = this.pool.readWorkerDescriptors(token);
13820
+ const read = this.pool.readWorkerDescriptors(token, opts);
13745
13821
  const entry = {
13746
13822
  at: now,
13747
13823
  read
@@ -17574,6 +17650,7 @@ export {
17574
17650
  negotiate,
17575
17651
  nextCronFireMs,
17576
17652
  nextRRuleFireMs,
17653
+ nextScheduleFireAt,
17577
17654
  normalizeAttributeRows,
17578
17655
  normalizeDescriptor,
17579
17656
  observedAnnouncements,