@dudousxd/nestjs-durable-core 0.92.0 → 0.93.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
@@ -4091,6 +4091,36 @@ declare const CONTROL_FLOW_SIGNAL: unique symbol;
4091
4091
  */
4092
4092
  declare function isWorkflowControlFlowSignal(error: unknown): boolean;
4093
4093
 
4094
+ /**
4095
+ * One loaded copy of this package: its version and the real path of its package root. Two copies are
4096
+ * the same when their roots are, so the `src` and `dist` builds of one checkout, the ESM and CJS
4097
+ * builds of one install, or one module evaluated twice (test runners reload modules) count once.
4098
+ */
4099
+ interface DurableCopy {
4100
+ version: string;
4101
+ root: string;
4102
+ }
4103
+ /** What every loaded copy writes to, shared through `globalThis` so copies can see each other. */
4104
+ interface DurableCopyRegistry {
4105
+ copies: Map<string, DurableCopy>;
4106
+ /** Set once a module booted: a copy that loads after that cannot be caught at boot any more. */
4107
+ booted: boolean;
4108
+ }
4109
+ /** Thrown at boot when two different installs of `@dudousxd/nestjs-durable-core` are loaded in one process. */
4110
+ declare class DuplicateDurableCopyError extends Error {
4111
+ readonly copies: DurableCopy[];
4112
+ constructor(copies: DurableCopy[]);
4113
+ }
4114
+ /** Every distinct copy registered so far. */
4115
+ declare function durableCopies(registry?: DurableCopyRegistry): DurableCopy[];
4116
+ /** Throws {@link DuplicateDurableCopyError} when more than one distinct copy is registered. */
4117
+ declare function assertSingleDurableCopy(registry?: DurableCopyRegistry): void;
4118
+ /**
4119
+ * Called on the boot path (`DurableModule.forRoot` / `forRootAsync`): check now, and make any
4120
+ * distinct copy that loads later fail on load. Safe to call any number of times.
4121
+ */
4122
+ declare function sealDurableCopies(registry?: DurableCopyRegistry): void;
4123
+
4094
4124
  /**
4095
4125
  * A start-time concurrency quota for ONE start: at most `limit` runs sharing `key` may be in flight
4096
4126
  * (in `countStatuses`) at once; a start that would exceed it is rejected with
@@ -6587,6 +6617,12 @@ declare class WorkflowEngine {
6587
6617
  * tenant reads as null (see {@link WorkflowEngineDeps.tenancy}).
6588
6618
  */
6589
6619
  getRun(runId: string): Promise<WorkflowRun | null>;
6620
+ /**
6621
+ * The runs matching `query`, narrowed to the ones the caller may see (with tenancy on, another
6622
+ * tenant's runs are left out, like {@link getRun}). Pair it with `workflow` / `statuses` to bound
6623
+ * the scan on a large store. `overlap: 'skip'` schedules use it to find their in-flight runs.
6624
+ */
6625
+ listRuns(query: RunQuery): Promise<WorkflowRun[]>;
6590
6626
  /** A run's full checkpoint timeline, ordered by seq (what the testing kit's `captureHistory`
6591
6627
  * reads, next to {@link getRun}). Empty for a run the caller may not see. */
6592
6628
  listCheckpoints(runId: string): Promise<StepCheckpoint[]>;
@@ -8977,9 +9013,11 @@ interface ScheduledWorkflow<W extends WorkflowRef = WorkflowRef> {
8977
9013
  /** Temporarily stop firing this schedule (kept registered). Defaults to false. */
8978
9014
  paused?: boolean;
8979
9015
  /**
8980
- * What to do when the previous window's run hasn't finished yet (fixed-interval schedules only):
8981
- * `'allow'` (default) starts the new window anyway; `'skip'` skips it while the prior run is still
8982
- * `running`/`suspended`, so a slow run can't pile up overlapping executions.
9016
+ * What to do when an earlier window's run hasn't finished yet (interval and cron schedules alike):
9017
+ * `'allow'` (default) starts the new window anyway; `'skip'` skips every window while any earlier
9018
+ * run of this schedule is still in flight (pending, running, suspended, blocked or cancelling), so a
9019
+ * slow run can't pile up overlapping executions. With `backfill`, missed windows start one at a
9020
+ * time.
8983
9021
  */
8984
9022
  overlap?: 'allow' | 'skip';
8985
9023
  /**
@@ -9053,7 +9091,13 @@ declare function scheduleRunIdAt(s: ScheduledWorkflow, nowMs: number): string;
9053
9091
  * has seen a window's run exist, later calls in that window skip it without a store read. A
9054
9092
  * jittered window is deferred to a later call, never slept on.
9055
9093
  */
9056
- declare function runSchedules(engine: Pick<WorkflowEngine, 'start' | 'getRun'> & Partial<Pick<WorkflowEngine, 'isDraining'>>, schedules: readonly ScheduledWorkflow[], nowMs: number, opts?: RunSchedulesOptions): Promise<string[]>;
9094
+ declare function runSchedules(engine: ScheduleTickEngine, schedules: readonly ScheduledWorkflow[], nowMs: number, opts?: RunSchedulesOptions): Promise<string[]>;
9095
+ /**
9096
+ * What {@link runSchedules} needs from the engine. `listRuns` is what lets `overlap: 'skip'` find an
9097
+ * in-flight run this process never saw (started before a restart, or by another instance); a driver
9098
+ * without it only sees the runs it observed itself plus the previous window.
9099
+ */
9100
+ type ScheduleTickEngine = Pick<WorkflowEngine, 'start' | 'getRun'> & Partial<Pick<WorkflowEngine, 'isDraining' | 'listRuns'>>;
9057
9101
 
9058
9102
  /**
9059
9103
  * A {@link StepLogger} that appends to `events`, stamping each line with `now()`. Shared by the
@@ -9622,4 +9666,4 @@ declare function prevRRuleFireMs(rule: ParsedRRule, atMs: number): number | null
9622
9666
  */
9623
9667
  declare function settleResultsWithPlainCalls(store: Pick<StateStore, 'getRun' | 'getCheckpoint'> & Partial<Pick<StateStore, 'getRuns' | 'getCheckpointsForSettle' | 'getCheckpoints' | 'settleCheckpointsIfPending'>>, results: StepResultSettlement[]): Promise<(StepCheckpoint | null)[]>;
9624
9668
 
9625
- 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 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, 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 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 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, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, bufferedEventReaches, buildWorkflowDirectory, canRoute, capableWorkers, carriesLifecyclePending, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, coalescedSubscribersOf, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, 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, runValueFacetsFromRuns, runWaitPrefix, runWaitTargetOf, runWaitToken, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, scopeBufferedEvent, scopeTenantQuery, settleResultsWithPlainCalls, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
9669
+ 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 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 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, 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, 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, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
package/dist/index.d.ts CHANGED
@@ -4091,6 +4091,36 @@ declare const CONTROL_FLOW_SIGNAL: unique symbol;
4091
4091
  */
4092
4092
  declare function isWorkflowControlFlowSignal(error: unknown): boolean;
4093
4093
 
4094
+ /**
4095
+ * One loaded copy of this package: its version and the real path of its package root. Two copies are
4096
+ * the same when their roots are, so the `src` and `dist` builds of one checkout, the ESM and CJS
4097
+ * builds of one install, or one module evaluated twice (test runners reload modules) count once.
4098
+ */
4099
+ interface DurableCopy {
4100
+ version: string;
4101
+ root: string;
4102
+ }
4103
+ /** What every loaded copy writes to, shared through `globalThis` so copies can see each other. */
4104
+ interface DurableCopyRegistry {
4105
+ copies: Map<string, DurableCopy>;
4106
+ /** Set once a module booted: a copy that loads after that cannot be caught at boot any more. */
4107
+ booted: boolean;
4108
+ }
4109
+ /** Thrown at boot when two different installs of `@dudousxd/nestjs-durable-core` are loaded in one process. */
4110
+ declare class DuplicateDurableCopyError extends Error {
4111
+ readonly copies: DurableCopy[];
4112
+ constructor(copies: DurableCopy[]);
4113
+ }
4114
+ /** Every distinct copy registered so far. */
4115
+ declare function durableCopies(registry?: DurableCopyRegistry): DurableCopy[];
4116
+ /** Throws {@link DuplicateDurableCopyError} when more than one distinct copy is registered. */
4117
+ declare function assertSingleDurableCopy(registry?: DurableCopyRegistry): void;
4118
+ /**
4119
+ * Called on the boot path (`DurableModule.forRoot` / `forRootAsync`): check now, and make any
4120
+ * distinct copy that loads later fail on load. Safe to call any number of times.
4121
+ */
4122
+ declare function sealDurableCopies(registry?: DurableCopyRegistry): void;
4123
+
4094
4124
  /**
4095
4125
  * A start-time concurrency quota for ONE start: at most `limit` runs sharing `key` may be in flight
4096
4126
  * (in `countStatuses`) at once; a start that would exceed it is rejected with
@@ -6587,6 +6617,12 @@ declare class WorkflowEngine {
6587
6617
  * tenant reads as null (see {@link WorkflowEngineDeps.tenancy}).
6588
6618
  */
6589
6619
  getRun(runId: string): Promise<WorkflowRun | null>;
6620
+ /**
6621
+ * The runs matching `query`, narrowed to the ones the caller may see (with tenancy on, another
6622
+ * tenant's runs are left out, like {@link getRun}). Pair it with `workflow` / `statuses` to bound
6623
+ * the scan on a large store. `overlap: 'skip'` schedules use it to find their in-flight runs.
6624
+ */
6625
+ listRuns(query: RunQuery): Promise<WorkflowRun[]>;
6590
6626
  /** A run's full checkpoint timeline, ordered by seq (what the testing kit's `captureHistory`
6591
6627
  * reads, next to {@link getRun}). Empty for a run the caller may not see. */
6592
6628
  listCheckpoints(runId: string): Promise<StepCheckpoint[]>;
@@ -8977,9 +9013,11 @@ interface ScheduledWorkflow<W extends WorkflowRef = WorkflowRef> {
8977
9013
  /** Temporarily stop firing this schedule (kept registered). Defaults to false. */
8978
9014
  paused?: boolean;
8979
9015
  /**
8980
- * What to do when the previous window's run hasn't finished yet (fixed-interval schedules only):
8981
- * `'allow'` (default) starts the new window anyway; `'skip'` skips it while the prior run is still
8982
- * `running`/`suspended`, so a slow run can't pile up overlapping executions.
9016
+ * What to do when an earlier window's run hasn't finished yet (interval and cron schedules alike):
9017
+ * `'allow'` (default) starts the new window anyway; `'skip'` skips every window while any earlier
9018
+ * run of this schedule is still in flight (pending, running, suspended, blocked or cancelling), so a
9019
+ * slow run can't pile up overlapping executions. With `backfill`, missed windows start one at a
9020
+ * time.
8983
9021
  */
8984
9022
  overlap?: 'allow' | 'skip';
8985
9023
  /**
@@ -9053,7 +9091,13 @@ declare function scheduleRunIdAt(s: ScheduledWorkflow, nowMs: number): string;
9053
9091
  * has seen a window's run exist, later calls in that window skip it without a store read. A
9054
9092
  * jittered window is deferred to a later call, never slept on.
9055
9093
  */
9056
- declare function runSchedules(engine: Pick<WorkflowEngine, 'start' | 'getRun'> & Partial<Pick<WorkflowEngine, 'isDraining'>>, schedules: readonly ScheduledWorkflow[], nowMs: number, opts?: RunSchedulesOptions): Promise<string[]>;
9094
+ declare function runSchedules(engine: ScheduleTickEngine, schedules: readonly ScheduledWorkflow[], nowMs: number, opts?: RunSchedulesOptions): Promise<string[]>;
9095
+ /**
9096
+ * What {@link runSchedules} needs from the engine. `listRuns` is what lets `overlap: 'skip'` find an
9097
+ * in-flight run this process never saw (started before a restart, or by another instance); a driver
9098
+ * without it only sees the runs it observed itself plus the previous window.
9099
+ */
9100
+ type ScheduleTickEngine = Pick<WorkflowEngine, 'start' | 'getRun'> & Partial<Pick<WorkflowEngine, 'isDraining' | 'listRuns'>>;
9057
9101
 
9058
9102
  /**
9059
9103
  * A {@link StepLogger} that appends to `events`, stamping each line with `now()`. Shared by the
@@ -9622,4 +9666,4 @@ declare function prevRRuleFireMs(rule: ParsedRRule, atMs: number): number | null
9622
9666
  */
9623
9667
  declare function settleResultsWithPlainCalls(store: Pick<StateStore, 'getRun' | 'getCheckpoint'> & Partial<Pick<StateStore, 'getRuns' | 'getCheckpointsForSettle' | 'getCheckpoints' | 'settleCheckpointsIfPending'>>, results: StepResultSettlement[]): Promise<(StepCheckpoint | null)[]>;
9624
9668
 
9625
- 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 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, 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 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 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, attributeColumnFor, attributeOperand, attributePredicateOperands, axisIsRunColumn, bindWorkflowClass, breakpointToken, bufferedEventReaches, buildWorkflowDirectory, canRoute, capableWorkers, carriesLifecyclePending, checkpointNameKind, checkpointStatsOf, childIdsOf, classifyWaiterToken, clearDurableExecutionWrappers, clearTerminalSingletonAdmission, coalescedSubscribersOf, codeAndDetails, codeOf, collectMetrics, concurrencyTag, controlPlaneDescriptor, countRuns, coveredTokens, createStepLogger, currentStep, currentStepScope, currentWorkflowCtx, debug, describeWorker, descriptorHash, detailsOf, 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, runValueFacetsFromRuns, runWaitPrefix, runWaitTargetOf, runWaitToken, sanitizeQueueToken, scheduleRunIdAt, scheduledRunId, scopeBufferedEvent, scopeTenantQuery, settleResultsWithPlainCalls, signTenantToken, singletonAdmissionDenialPatch, singletonAdmissionTags, singletonClaimantIds, sqlComparator, stepConfigOf, stepId, stepNameOf, sub, subEvent, subProcess, summarizeFan, summarizeRunFromStore, summarizeTimeline, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
9669
+ 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 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 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, 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, 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, tenantGroup, tenantIdsFor, tenantVisible, toEventSubscription, traceIdOfTraceparent, triggerFailedSubscribersOf, triggeredRunsOf, triggeredSubscribersOf, useDurableExecution, verifyWireTenant, warn, withSingletonTracked, withoutSingletonMarkers, workflowName };
package/dist/index.js CHANGED
@@ -100,16 +100,16 @@ var QueueController = class {
100
100
  * A bare item (no waiterId) is compared on its hints directly.
101
101
  */
102
102
  isNext(waiterId, item) {
103
- const self = (waiterId != null ? this.waiters.get(waiterId) : void 0) ?? {
103
+ const self2 = (waiterId != null ? this.waiters.get(waiterId) : void 0) ?? {
104
104
  priority: item?.priority ?? 0,
105
105
  key: item?.key,
106
106
  seq: Number.POSITIVE_INFINITY
107
107
  };
108
- let best = self;
108
+ let best = self2;
109
109
  for (const w of this.waiters.values()) {
110
110
  if (this.better(w, best)) best = w;
111
111
  }
112
- return best === self;
112
+ return best === self2;
113
113
  }
114
114
  /** Strict "a should be admitted before b" comparison under the active policy. */
115
115
  better(a, b) {
@@ -563,6 +563,113 @@ function parseDuration(duration) {
563
563
  }
564
564
  __name(parseDuration, "parseDuration");
565
565
 
566
+ // src/copy-guard.ts
567
+ import { readFileSync, realpathSync } from "node:fs";
568
+ import { dirname, join } from "node:path";
569
+ import { fileURLToPath } from "node:url";
570
+
571
+ // src/origin.ts
572
+ var CORE_ORIGIN = "@dudousxd/nestjs-durable-core";
573
+
574
+ // src/copy-guard.ts
575
+ var DURABLE_COPIES_KEY = Symbol.for("@dudousxd/nestjs-durable.copies");
576
+ var DUPLICATE_COPY_DOCS = "https://davidecarvalho.github.io/aviary/docs/durable/troubleshooting#two-copies-of-dudousxdnestjs-durable-core";
577
+ var DUPLICATE_COPY_FIX = `Make every package resolve one copy: declare the same peer dependency versions in the app as in the workspace packages that depend on ${CORE_ORIGIN} (or pin them with pnpm overrides), reinstall, and check that \`pnpm why ${CORE_ORIGIN}\` shows a single variant.`;
578
+ var DuplicateDurableCopyError = class extends Error {
579
+ static {
580
+ __name(this, "DuplicateDurableCopyError");
581
+ }
582
+ copies;
583
+ constructor(copies) {
584
+ super(duplicateCopyMessage(copies));
585
+ this.name = "DuplicateDurableCopyError";
586
+ this.copies = copies;
587
+ }
588
+ };
589
+ function duplicateCopyMessage(copies) {
590
+ const list2 = copies.map((c) => ` - ${c.version} at ${c.root}`).join("\n");
591
+ return [
592
+ `${CORE_ORIGIN} is loaded ${copies.length} times, from different installs:`,
593
+ list2,
594
+ "Each copy has its own WorkflowEngine class, so code from one copy cannot resolve the engine the other copy registered (Nest cannot inject `WorkflowEngine`, `instanceof` checks fail, and workflows registered on one engine are unknown to the other).",
595
+ DUPLICATE_COPY_FIX,
596
+ `See ${DUPLICATE_COPY_DOCS}`
597
+ ].join("\n");
598
+ }
599
+ __name(duplicateCopyMessage, "duplicateCopyMessage");
600
+ function durableCopyRegistry() {
601
+ const slot = globalThis;
602
+ const existing = slot[DURABLE_COPIES_KEY];
603
+ if (existing?.copies instanceof Map) return existing;
604
+ const fresh = {
605
+ copies: /* @__PURE__ */ new Map(),
606
+ booted: false
607
+ };
608
+ slot[DURABLE_COPIES_KEY] = fresh;
609
+ return fresh;
610
+ }
611
+ __name(durableCopyRegistry, "durableCopyRegistry");
612
+ function durableCopies(registry = durableCopyRegistry()) {
613
+ return [
614
+ ...registry.copies.values()
615
+ ];
616
+ }
617
+ __name(durableCopies, "durableCopies");
618
+ function registerDurableCopy(copy, registry = durableCopyRegistry()) {
619
+ if (registry.copies.has(copy.root)) return;
620
+ registry.copies.set(copy.root, copy);
621
+ if (registry.booted) assertSingleDurableCopy(registry);
622
+ }
623
+ __name(registerDurableCopy, "registerDurableCopy");
624
+ function assertSingleDurableCopy(registry = durableCopyRegistry()) {
625
+ const copies = durableCopies(registry);
626
+ if (copies.length > 1) throw new DuplicateDurableCopyError(copies);
627
+ }
628
+ __name(assertSingleDurableCopy, "assertSingleDurableCopy");
629
+ function sealDurableCopies(registry = durableCopyRegistry()) {
630
+ assertSingleDurableCopy(registry);
631
+ registry.booted = true;
632
+ }
633
+ __name(sealDurableCopies, "sealDurableCopies");
634
+ function thisCopy() {
635
+ let start;
636
+ try {
637
+ start = dirname(fileURLToPath(import.meta.url));
638
+ } catch {
639
+ return null;
640
+ }
641
+ let dir = start;
642
+ for (; ; ) {
643
+ try {
644
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
645
+ if (pkg.name === CORE_ORIGIN) {
646
+ return {
647
+ version: typeof pkg.version === "string" ? pkg.version : "unknown",
648
+ root: realPath(dir)
649
+ };
650
+ }
651
+ } catch {
652
+ }
653
+ const parent = dirname(dir);
654
+ if (parent === dir) return {
655
+ version: "unknown",
656
+ root: realPath(start)
657
+ };
658
+ dir = parent;
659
+ }
660
+ }
661
+ __name(thisCopy, "thisCopy");
662
+ function realPath(path) {
663
+ try {
664
+ return realpathSync(path);
665
+ } catch {
666
+ return path;
667
+ }
668
+ }
669
+ __name(realPath, "realPath");
670
+ var self = thisCopy();
671
+ if (self !== null) registerDurableCopy(self);
672
+
566
673
  // src/backoff.ts
567
674
  function backoffDelay(attempt, options) {
568
675
  const base = options?.backoffMs ?? 0;
@@ -1868,9 +1975,6 @@ async function assertConcurrency(store, workflow, quota) {
1868
1975
  }
1869
1976
  __name(assertConcurrency, "assertConcurrency");
1870
1977
 
1871
- // src/origin.ts
1872
- var CORE_ORIGIN = "@dudousxd/nestjs-durable-core";
1873
-
1874
1978
  // src/entities.ts
1875
1979
  var NUDGE = {
1876
1980
  nudge: true
@@ -3547,13 +3651,7 @@ async function runSchedules(engine, schedules, nowMs, opts) {
3547
3651
  ] : due;
3548
3652
  const candidates = windows.filter((id) => !settled.get(s.key)?.has(id));
3549
3653
  if (candidates.length === 0) continue;
3550
- if (s.overlap === "skip" && s.everyMs) {
3551
- const prevBucket = Math.floor(nowMs / s.everyMs) - 1;
3552
- if (prevBucket >= 0) {
3553
- const prev = await engine.getRun(`sched:${s.key}:${prevBucket}`);
3554
- if (prev && (prev.status === "running" || prev.status === "suspended")) continue;
3555
- }
3556
- }
3654
+ if (s.overlap === "skip" && await overlapping(engine, s, nowMs)) continue;
3557
3655
  if (!(s.jitter && s.jitter > 0)) jitterFireAt.get(engine)?.delete(s.key);
3558
3656
  const firing = s.jitter && s.jitter > 0 ? jitterDue(engine, s, candidates, nowMs, random) : candidates;
3559
3657
  if (firing.length === 0) continue;
@@ -3561,16 +3659,97 @@ async function runSchedules(engine, schedules, nowMs, opts) {
3561
3659
  if (engine.isDraining?.()) break;
3562
3660
  const existing = await engine.getRun(runId);
3563
3661
  remember(settled, s.key, runId);
3564
- if (existing) continue;
3662
+ if (existing) {
3663
+ if (s.overlap === "skip" && !isTerminal(existing.status)) {
3664
+ noteInFlight(engine, s.key, runId);
3665
+ break;
3666
+ }
3667
+ continue;
3668
+ }
3565
3669
  await engine.start(workflowName(s.workflow), s.input, runId, {
3566
3670
  namespace: s.namespace
3567
3671
  });
3568
3672
  ids.push(runId);
3673
+ if (s.overlap === "skip") {
3674
+ noteInFlight(engine, s.key, runId);
3675
+ break;
3676
+ }
3569
3677
  }
3570
3678
  }
3571
3679
  return ids;
3572
3680
  }
3573
3681
  __name(runSchedules, "runSchedules");
3682
+ var IN_FLIGHT = [
3683
+ "pending",
3684
+ "running",
3685
+ "suspended",
3686
+ "blocked",
3687
+ "cancelling"
3688
+ ];
3689
+ function isTerminal(status) {
3690
+ return TERMINAL_RUN_STATUSES.includes(status);
3691
+ }
3692
+ __name(isTerminal, "isTerminal");
3693
+ var inFlightRuns = /* @__PURE__ */ new WeakMap();
3694
+ function inFlightFor(engine, key) {
3695
+ let byKey = inFlightRuns.get(engine);
3696
+ if (byKey === void 0) {
3697
+ byKey = /* @__PURE__ */ new Map();
3698
+ inFlightRuns.set(engine, byKey);
3699
+ }
3700
+ let ids = byKey.get(key);
3701
+ if (ids === void 0) {
3702
+ ids = /* @__PURE__ */ new Set();
3703
+ byKey.set(key, ids);
3704
+ }
3705
+ return ids;
3706
+ }
3707
+ __name(inFlightFor, "inFlightFor");
3708
+ function noteInFlight(engine, key, runId) {
3709
+ const ids = inFlightFor(engine, key);
3710
+ ids.add(runId);
3711
+ if (ids.size > 64) ids.delete(ids.values().next().value);
3712
+ }
3713
+ __name(noteInFlight, "noteInFlight");
3714
+ async function overlapping(engine, s, nowMs) {
3715
+ const known = inFlightFor(engine, s.key);
3716
+ for (const runId of [
3717
+ ...known
3718
+ ].reverse()) {
3719
+ const run2 = await engine.getRun(runId);
3720
+ if (run2 && !isTerminal(run2.status)) return true;
3721
+ known.delete(runId);
3722
+ }
3723
+ if (engine.listRuns) {
3724
+ const prefix = `sched:${s.key}:`;
3725
+ const runs = await engine.listRuns({
3726
+ workflow: workflowName(s.workflow),
3727
+ statuses: IN_FLIGHT
3728
+ });
3729
+ const blocking = runs.filter((r) => r.id.startsWith(prefix) && !isTerminal(r.status));
3730
+ for (const r of blocking) noteInFlight(engine, s.key, r.id);
3731
+ return blocking.length > 0;
3732
+ }
3733
+ const prev = previousWindowRunId(s, nowMs);
3734
+ if (prev === void 0) return false;
3735
+ const run = await engine.getRun(prev);
3736
+ if (!run || isTerminal(run.status)) return false;
3737
+ noteInFlight(engine, s.key, prev);
3738
+ return true;
3739
+ }
3740
+ __name(overlapping, "overlapping");
3741
+ function previousWindowRunId(s, nowMs) {
3742
+ if (s.cron != null) {
3743
+ const current = prevCronFireMs(s.cron, nowMs, s.timezone);
3744
+ return `sched:${s.key}:${prevCronFireMs(s.cron, current - 1, s.timezone)}`;
3745
+ }
3746
+ if (s.everyMs != null) {
3747
+ const bucket = Math.floor(nowMs / s.everyMs) - 1;
3748
+ return bucket >= 0 ? `sched:${s.key}:${bucket}` : void 0;
3749
+ }
3750
+ return void 0;
3751
+ }
3752
+ __name(previousWindowRunId, "previousWindowRunId");
3574
3753
  var settledRunIds = /* @__PURE__ */ new WeakMap();
3575
3754
  function settledIdsFor(engine) {
3576
3755
  let memo = settledRunIds.get(engine);
@@ -9154,6 +9333,14 @@ var WorkflowEngine = class _WorkflowEngine {
9154
9333
  getRun(runId) {
9155
9334
  return this.visibleRun(runId);
9156
9335
  }
9336
+ /**
9337
+ * The runs matching `query`, narrowed to the ones the caller may see (with tenancy on, another
9338
+ * tenant's runs are left out, like {@link getRun}). Pair it with `workflow` / `statuses` to bound
9339
+ * the scan on a large store. `overlap: 'skip'` schedules use it to find their in-flight runs.
9340
+ */
9341
+ listRuns(query) {
9342
+ return this.store.listRuns(this.scopeRunQuery(query));
9343
+ }
9157
9344
  /** A run's full checkpoint timeline, ordered by seq (what the testing kit's `captureHistory`
9158
9345
  * reads, next to {@link getRun}). Empty for a run the caller may not see. */
9159
9346
  async listCheckpoints(runId) {
@@ -17018,6 +17205,7 @@ export {
17018
17205
  DURABLE_OPTIONS_CANONICAL,
17019
17206
  DURABLE_STEP_CONFIG,
17020
17207
  DURABLE_STEP_NAME,
17208
+ DuplicateDurableCopyError,
17021
17209
  DurableWorkflow,
17022
17210
  ENGINE_MINTED_TAG_PREFIXES,
17023
17211
  ENTITY_WORKFLOW,
@@ -17094,6 +17282,7 @@ export {
17094
17282
  applyAttributeQuery,
17095
17283
  assertConcurrency,
17096
17284
  assertRoutes,
17285
+ assertSingleDurableCopy,
17097
17286
  attributeColumnFor,
17098
17287
  attributeOperand,
17099
17288
  attributePredicateOperands,
@@ -17127,6 +17316,7 @@ export {
17127
17316
  describeWorker,
17128
17317
  descriptorHash,
17129
17318
  detailsOf,
17319
+ durableCopies,
17130
17320
  error,
17131
17321
  etagMatches,
17132
17322
  eventMatchOf,
@@ -17233,6 +17423,7 @@ export {
17233
17423
  scheduledRunId,
17234
17424
  scopeBufferedEvent,
17235
17425
  scopeTenantQuery,
17426
+ sealDurableCopies,
17236
17427
  settleResultsWithPlainCalls,
17237
17428
  signTenantToken,
17238
17429
  singletonAdmissionDenialPatch,