@dudousxd/nestjs-durable-core 0.93.0 → 0.94.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
@@ -8977,6 +8977,72 @@ declare function markRemoteEvent<E extends object>(event: E): E;
8977
8977
  /** Whether `event` was produced by another instance and re-delivered here over the control plane. */
8978
8978
  declare function isRemoteEvent(event: object): boolean;
8979
8979
 
8980
+ /**
8981
+ * The trace id of `runId`: 32 lowercase hex, never all zeros, the same in every process. A control
8982
+ * plane records a tenant run's lifecycle events in this trace, and a tenant pod running the run's
8983
+ * steps under Telescope records the steps' own work in it too (the Telescope integration derives the
8984
+ * same id), so the two views join on `trace:<id>` without either side calling the other.
8985
+ */
8986
+ declare function runTraceId(runId: string): string;
8987
+ /**
8988
+ * How an observer on a control plane finds the tenant app of a run. A tenant's runs live in the
8989
+ * partition its token verified to (`run.namespace`); `run.*` events carry it, `step.*` events do
8990
+ * not, so the observer remembers it per run and, for a run it has seen no event of yet (a run
8991
+ * resumed after a restart, another pod's run), reads it once.
8992
+ */
8993
+ interface RunAppAttribution {
8994
+ /** The namespace (tenant partition) of `runId`, or `undefined` when the run is unknown. */
8995
+ namespaceOf(runId: string): Promise<string | undefined>;
8996
+ /**
8997
+ * The control plane's own namespaces: runs in these are its own, not a tenant's, and get no app.
8998
+ * `'default'` and an absent namespace are always the control plane's.
8999
+ */
9000
+ own?: readonly string[] | undefined;
9001
+ /** How many run → app answers to keep (oldest dropped first). Default 10,000. */
9002
+ cacheSize?: number | undefined;
9003
+ /**
9004
+ * How long one read may take before the event is forwarded unattributed (the run's next event
9005
+ * reads again). Default 5,000 ms.
9006
+ */
9007
+ lookupTimeoutMs?: number | undefined;
9008
+ }
9009
+ /** The tenant app of a run in `namespace`, or `undefined` for the control plane's own runs. */
9010
+ declare function tenantAppOf(namespace: string | undefined, own?: ReadonlySet<string> | readonly string[]): string | undefined;
9011
+ /** An engine event a control plane attributed to a tenant app. */
9012
+ type AttributedEngineEvent = EngineEvent & {
9013
+ app?: string | undefined;
9014
+ };
9015
+ /**
9016
+ * Remembers which tenant app each run belongs to and stamps it on that run's events, keeping their
9017
+ * order. An event whose run is not known yet waits for one read; that run's later events wait behind
9018
+ * it (a run's `step.completed` is never forwarded before its `step.started`), other runs' do not. A
9019
+ * read that fails or takes longer than `lookupTimeoutMs` forwards the event unattributed and is not
9020
+ * remembered, so the run's next event reads again.
9021
+ *
9022
+ * A tenant's event is forwarded with `app` set and, when the engine left it off (step events), its
9023
+ * partition as `namespace`. The control plane's own runs are forwarded unchanged.
9024
+ */
9025
+ declare class RunAppStamper {
9026
+ #private;
9027
+ constructor(options: RunAppAttribution);
9028
+ /** Call `forward` with `event` stamped with its app (when it has one), now or once it is known. */
9029
+ stamp(event: EngineEvent, forward: (event: AttributedEngineEvent) => void): void;
9030
+ }
9031
+ /** The slice of the durable module options {@link controlPlaneAttribution} reads. */
9032
+ interface RunAppTopologyOptions {
9033
+ topology?: string | undefined;
9034
+ namespace?: string | undefined;
9035
+ partition?: string | undefined;
9036
+ }
9037
+ /**
9038
+ * The {@link RunAppAttribution} of a control plane, or `undefined` for any other topology (a
9039
+ * standalone app or a tenant pod attributes nothing). `getRun` reads a run's namespace (the engine's
9040
+ * or the store's); the control plane's own `namespace`/`partition` are its own runs.
9041
+ */
9042
+ declare function controlPlaneAttribution(options: RunAppTopologyOptions | undefined, getRun: (runId: string) => Promise<{
9043
+ namespace?: string | undefined;
9044
+ } | null>): RunAppAttribution | undefined;
9045
+
8980
9046
  /**
8981
9047
  * The origin (see {@link import('./interfaces').WorkflowRun.origin}) stamped onto runs of the
8982
9048
  * workflows this package registers ITSELF — the built-in `__entity` runner behind durable entities
@@ -9666,4 +9732,4 @@ declare function prevRRuleFireMs(rule: ParsedRRule, atMs: number): number | null
9666
9732
  */
9667
9733
  declare function settleResultsWithPlainCalls(store: Pick<StateStore, 'getRun' | 'getCheckpoint'> & Partial<Pick<StateStore, 'getRuns' | 'getCheckpointsForSettle' | 'getCheckpoints' | 'settleCheckpointsIfPending'>>, results: StepResultSettlement[]): Promise<(StepCheckpoint | null)[]>;
9668
9734
 
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 };
9735
+ 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 };
package/dist/index.d.ts CHANGED
@@ -8977,6 +8977,72 @@ declare function markRemoteEvent<E extends object>(event: E): E;
8977
8977
  /** Whether `event` was produced by another instance and re-delivered here over the control plane. */
8978
8978
  declare function isRemoteEvent(event: object): boolean;
8979
8979
 
8980
+ /**
8981
+ * The trace id of `runId`: 32 lowercase hex, never all zeros, the same in every process. A control
8982
+ * plane records a tenant run's lifecycle events in this trace, and a tenant pod running the run's
8983
+ * steps under Telescope records the steps' own work in it too (the Telescope integration derives the
8984
+ * same id), so the two views join on `trace:<id>` without either side calling the other.
8985
+ */
8986
+ declare function runTraceId(runId: string): string;
8987
+ /**
8988
+ * How an observer on a control plane finds the tenant app of a run. A tenant's runs live in the
8989
+ * partition its token verified to (`run.namespace`); `run.*` events carry it, `step.*` events do
8990
+ * not, so the observer remembers it per run and, for a run it has seen no event of yet (a run
8991
+ * resumed after a restart, another pod's run), reads it once.
8992
+ */
8993
+ interface RunAppAttribution {
8994
+ /** The namespace (tenant partition) of `runId`, or `undefined` when the run is unknown. */
8995
+ namespaceOf(runId: string): Promise<string | undefined>;
8996
+ /**
8997
+ * The control plane's own namespaces: runs in these are its own, not a tenant's, and get no app.
8998
+ * `'default'` and an absent namespace are always the control plane's.
8999
+ */
9000
+ own?: readonly string[] | undefined;
9001
+ /** How many run → app answers to keep (oldest dropped first). Default 10,000. */
9002
+ cacheSize?: number | undefined;
9003
+ /**
9004
+ * How long one read may take before the event is forwarded unattributed (the run's next event
9005
+ * reads again). Default 5,000 ms.
9006
+ */
9007
+ lookupTimeoutMs?: number | undefined;
9008
+ }
9009
+ /** The tenant app of a run in `namespace`, or `undefined` for the control plane's own runs. */
9010
+ declare function tenantAppOf(namespace: string | undefined, own?: ReadonlySet<string> | readonly string[]): string | undefined;
9011
+ /** An engine event a control plane attributed to a tenant app. */
9012
+ type AttributedEngineEvent = EngineEvent & {
9013
+ app?: string | undefined;
9014
+ };
9015
+ /**
9016
+ * Remembers which tenant app each run belongs to and stamps it on that run's events, keeping their
9017
+ * order. An event whose run is not known yet waits for one read; that run's later events wait behind
9018
+ * it (a run's `step.completed` is never forwarded before its `step.started`), other runs' do not. A
9019
+ * read that fails or takes longer than `lookupTimeoutMs` forwards the event unattributed and is not
9020
+ * remembered, so the run's next event reads again.
9021
+ *
9022
+ * A tenant's event is forwarded with `app` set and, when the engine left it off (step events), its
9023
+ * partition as `namespace`. The control plane's own runs are forwarded unchanged.
9024
+ */
9025
+ declare class RunAppStamper {
9026
+ #private;
9027
+ constructor(options: RunAppAttribution);
9028
+ /** Call `forward` with `event` stamped with its app (when it has one), now or once it is known. */
9029
+ stamp(event: EngineEvent, forward: (event: AttributedEngineEvent) => void): void;
9030
+ }
9031
+ /** The slice of the durable module options {@link controlPlaneAttribution} reads. */
9032
+ interface RunAppTopologyOptions {
9033
+ topology?: string | undefined;
9034
+ namespace?: string | undefined;
9035
+ partition?: string | undefined;
9036
+ }
9037
+ /**
9038
+ * The {@link RunAppAttribution} of a control plane, or `undefined` for any other topology (a
9039
+ * standalone app or a tenant pod attributes nothing). `getRun` reads a run's namespace (the engine's
9040
+ * or the store's); the control plane's own `namespace`/`partition` are its own runs.
9041
+ */
9042
+ declare function controlPlaneAttribution(options: RunAppTopologyOptions | undefined, getRun: (runId: string) => Promise<{
9043
+ namespace?: string | undefined;
9044
+ } | null>): RunAppAttribution | undefined;
9045
+
8980
9046
  /**
8981
9047
  * The origin (see {@link import('./interfaces').WorkflowRun.origin}) stamped onto runs of the
8982
9048
  * workflows this package registers ITSELF — the built-in `__entity` runner behind durable entities
@@ -9666,4 +9732,4 @@ declare function prevRRuleFireMs(rule: ParsedRRule, atMs: number): number | null
9666
9732
  */
9667
9733
  declare function settleResultsWithPlainCalls(store: Pick<StateStore, 'getRun' | 'getCheckpoint'> & Partial<Pick<StateStore, 'getRuns' | 'getCheckpointsForSettle' | 'getCheckpoints' | 'settleCheckpointsIfPending'>>, results: StepResultSettlement[]): Promise<(StepCheckpoint | null)[]>;
9668
9734
 
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 };
9735
+ 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 };
package/dist/index.js CHANGED
@@ -16119,6 +16119,144 @@ function collectMetrics(engine) {
16119
16119
  }
16120
16120
  __name(collectMetrics, "collectMetrics");
16121
16121
 
16122
+ // src/run-app.ts
16123
+ import { createHash } from "node:crypto";
16124
+ function runTraceId(runId) {
16125
+ const hex = createHash("sha256").update(`durable:run:${runId}`).digest("hex").slice(0, 32);
16126
+ return /^0+$/.test(hex) ? `${hex.slice(0, 31)}1` : hex;
16127
+ }
16128
+ __name(runTraceId, "runTraceId");
16129
+ function tenantAppOf(namespace, own = []) {
16130
+ if (namespace === void 0 || namespace === "" || namespace === "default") return void 0;
16131
+ const mine = Array.isArray(own) ? own.includes(namespace) : own.has(namespace);
16132
+ return mine ? void 0 : namespace;
16133
+ }
16134
+ __name(tenantAppOf, "tenantAppOf");
16135
+ function positive(value, fallback) {
16136
+ return value !== void 0 && Number.isFinite(value) ? Math.max(1, value) : fallback;
16137
+ }
16138
+ __name(positive, "positive");
16139
+ var FAILED = Symbol("failed");
16140
+ var RunAppStamper = class {
16141
+ static {
16142
+ __name(this, "RunAppStamper");
16143
+ }
16144
+ #lookup;
16145
+ #own;
16146
+ #max;
16147
+ #timeoutMs;
16148
+ /** runId → app (`null`: the control plane's own run). */
16149
+ #apps = /* @__PURE__ */ new Map();
16150
+ /** runId → the last queued event of that run, while one is waiting on a read. */
16151
+ #tails = /* @__PURE__ */ new Map();
16152
+ constructor(options) {
16153
+ this.#lookup = (runId) => options.namespaceOf(runId);
16154
+ this.#own = new Set(options.own ?? []);
16155
+ this.#max = positive(options.cacheSize, 1e4);
16156
+ this.#timeoutMs = positive(options.lookupTimeoutMs, 5e3);
16157
+ }
16158
+ /** Call `forward` with `event` stamped with its app (when it has one), now or once it is known. */
16159
+ stamp(event, forward) {
16160
+ const runId = event.runId;
16161
+ const tail = this.#tails.get(runId);
16162
+ if (tail === void 0) {
16163
+ const known = this.#known(event);
16164
+ if (known !== void 0) {
16165
+ this.#forward(event, known, forward);
16166
+ return;
16167
+ }
16168
+ }
16169
+ const next = (tail ?? Promise.resolve()).then(async () => {
16170
+ try {
16171
+ let app = this.#known(event);
16172
+ if (app === void 0) {
16173
+ const namespace = await this.#read(runId);
16174
+ if (namespace === FAILED) {
16175
+ app = null;
16176
+ } else {
16177
+ app = tenantAppOf(namespace, this.#own) ?? null;
16178
+ this.#remember(runId, app);
16179
+ }
16180
+ }
16181
+ this.#forward(event, app, forward);
16182
+ } catch {
16183
+ }
16184
+ });
16185
+ this.#tails.set(runId, next);
16186
+ void next.then(() => {
16187
+ if (this.#tails.get(runId) === next) this.#tails.delete(runId);
16188
+ });
16189
+ }
16190
+ #forward(event, app, forward) {
16191
+ try {
16192
+ forward(this.#with(event, app));
16193
+ } finally {
16194
+ if (event.type === "run.completed" || event.type === "run.failed") {
16195
+ this.#apps.delete(event.runId);
16196
+ }
16197
+ }
16198
+ }
16199
+ /** The run's namespace, or {@link FAILED} when the read threw or did not answer in time. */
16200
+ async #read(runId) {
16201
+ let timer;
16202
+ const timeout = new Promise((resolve) => {
16203
+ timer = setTimeout(() => resolve(FAILED), this.#timeoutMs);
16204
+ timer.unref?.();
16205
+ });
16206
+ try {
16207
+ return await Promise.race([
16208
+ Promise.resolve().then(() => this.#lookup(runId)).catch(() => FAILED),
16209
+ timeout
16210
+ ]);
16211
+ } finally {
16212
+ clearTimeout(timer);
16213
+ }
16214
+ }
16215
+ /** The app of `event`'s run when it is known without a read (`null`: no app). */
16216
+ #known(event) {
16217
+ if (event.namespace !== void 0) {
16218
+ const app = tenantAppOf(event.namespace, this.#own) ?? null;
16219
+ this.#remember(event.runId, app);
16220
+ return app;
16221
+ }
16222
+ return this.#apps.get(event.runId);
16223
+ }
16224
+ /** A tenant's event carries its app, and its partition as `namespace` (step events have none). */
16225
+ #with(event, app) {
16226
+ if (app === null) return event;
16227
+ return event.namespace === void 0 ? {
16228
+ ...event,
16229
+ namespace: app,
16230
+ app
16231
+ } : {
16232
+ ...event,
16233
+ app
16234
+ };
16235
+ }
16236
+ #remember(runId, app) {
16237
+ if (this.#apps.has(runId)) this.#apps.delete(runId);
16238
+ else if (this.#apps.size >= this.#max) {
16239
+ const oldest = this.#apps.keys().next().value;
16240
+ if (oldest !== void 0) this.#apps.delete(oldest);
16241
+ }
16242
+ this.#apps.set(runId, app);
16243
+ }
16244
+ };
16245
+ function controlPlaneAttribution(options, getRun) {
16246
+ if (options?.topology !== "control-plane") return void 0;
16247
+ const own = [
16248
+ options.namespace,
16249
+ options.partition
16250
+ ].filter((ns) => typeof ns === "string" && ns !== "");
16251
+ return {
16252
+ namespaceOf: /* @__PURE__ */ __name(async (runId) => (await getRun(runId))?.namespace, "namespaceOf"),
16253
+ ...own.length > 0 ? {
16254
+ own
16255
+ } : {}
16256
+ };
16257
+ }
16258
+ __name(controlPlaneAttribution, "controlPlaneAttribution");
16259
+
16122
16260
  // src/search-attributes.ts
16123
16261
  function compare(actual, filter) {
16124
16262
  if (filter.op === "in") return filter.values.some((v) => actual === v);
@@ -17249,6 +17387,7 @@ export {
17249
17387
  RemoteStepTimeout,
17250
17388
  RemoteWorkflowExecutor,
17251
17389
  RemoteWorkflowTimeout,
17390
+ RunAppStamper,
17252
17391
  RunGateway,
17253
17392
  SINGLETON_ACTIVE_STATUSES,
17254
17393
  SINGLETON_ADMITTED_TAG,
@@ -17305,6 +17444,7 @@ export {
17305
17444
  codeOf,
17306
17445
  collectMetrics,
17307
17446
  concurrencyTag,
17447
+ controlPlaneAttribution,
17308
17448
  controlPlaneDescriptor,
17309
17449
  countRuns,
17310
17450
  coveredTokens,
@@ -17414,6 +17554,7 @@ export {
17414
17554
  runOutsideWorkflowCtx,
17415
17555
  runSchedules,
17416
17556
  runStepHandler,
17557
+ runTraceId,
17417
17558
  runValueFacetsFromRuns,
17418
17559
  runWaitPrefix,
17419
17560
  runWaitTargetOf,
@@ -17439,6 +17580,7 @@ export {
17439
17580
  summarizeFan,
17440
17581
  summarizeRunFromStore,
17441
17582
  summarizeTimeline,
17583
+ tenantAppOf,
17442
17584
  tenantGroup,
17443
17585
  tenantIdsFor,
17444
17586
  tenantVisible,