/*! * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /// import { EventEmitter } from 'events'; import { CosmosDbClient, ListenOptions } from '../client'; import { InterceptorProcessor } from '../interceptor'; import { RecursiveRequired } from '../types/internal'; import { ResolvedTaskDocument } from './document'; import { ProcessingState, SerializedActiveTask, TaskBase, TaskFinishMetadata, TaskStatus } from './types'; export default class ActiveTaskImpl extends EventEmitter implements ActiveTask { static create(client: CosmosDbClient, interceptor: InterceptorProcessor, document: ResolvedTaskDocument, options: RecursiveRequired): ActiveTaskImpl; get id(): string; get type(): string; get status(): TaskStatus; get enabled(): boolean; get createTime(): Date; get nextRunTime(): Date | undefined; get lastUpdatedTime(): Date; get lastRun(): { startTime: Date; finishTime: Date; succeeded: boolean; } | undefined; get currentRunStartTime(): Date | undefined; get deliveries(): number; get attempts(): number; get runs(): number; get payload(): T; set payload(payload: T); get interval(): string | number | undefined; get lastRunTime(): Date | undefined; get locked(): boolean; get processingState(): ProcessingState; /** * Underlying data controller. */ private _data; /** * Request interceptor. */ private _interceptor; /** * Resolved listener options. */ private _options; /** * The maximum amount of time in milliseconds to run the task. */ private get _maxExecutionTimeMs(); /** * Indicates whether the lock can/should be renewed. */ private get _canRenewLock(); /** * The time when processing began. */ private _processingStart; /** * Internal processing state. DO NOT USE DIRECTLY. */ private _internalProcessingState; /** * Setter for updating the processing state, which also notifies clients * of any changes. */ private set _processingState(value); private _pollTimer?; private _lockTimer?; private _lockExpirationTimer?; /** * The current lock token for the processor. */ private _lockToken; /** * The lock token we're trying to acquire next (if any). */ private _nextLockToken?; /** * Whether the task was enabled from the start. */ private _enabled; private constructor(); save(): Promise; delete(): Promise; complete(nextRunDelayMs?: number, savePayload?: boolean): Promise; fail(err?: any, nextRunDelayMs?: number, savePayload?: boolean): Promise; retry(err?: any, delayMs?: number, savePayload?: boolean): Promise; defer(delayMs: number, savePayload?: boolean): Promise; release(savePayload?: boolean): Promise; forceRelease(err?: any): void; /** * Acknowledge the task and finish processing using the given changes. * * @param result - The processing result if the acknowledge succeeds * @param changes - The patch to make to the task configuration * @param savePayload - Whether or not to save the payload (default: true) * @param logMeta - Optional metadata for logging purposes */ private _acknowledge; /** * Run the given operation to finish processing (and log the processing). * * @param result - The processing result if the finish succeeds * @param finisher - The operation to run when actually finishing the * task * @param logMeta - Optional metadata for logging purposes */ private _finish; /** * Notify consumers that the task is finished processing. * * @param result - The processing result * @param delayMs - Optional delay before reprocessing * @param error - Optional error from processing */ private _markFinished; private _finishPatches; /** * Schedule the next poll attempt. */ private _schedulePoll; /** * Schedule the next lock renewal. */ private _scheduleRenewLock; /** * Set up the timer that indicates that the lock is expired. */ private _scheduleLockExpiration; /** * Attempt to renew the lock on the task */ private _renewLock; /** * Poll the database for updates to this task. This is used to keep etag * versions in sync and handle task disabling. */ private _poll; /** * Signal that the lock was lost, or schedule a future check if necessary */ private _checkLock; /** * Check whether the task has been disabled */ private _checkDisabled; /** * Event handler for verifying task state whenever a server update happens */ private _onDataUpdated; /** * Clean up any timers, listeners, etc. that are active during task * processing. */ private _cleanup; /** * Verify that the task is not finished processing */ private _assertProcessing; /** * Verify that the task is not currently finishing */ private _assertNotFinishing; toJSON(): SerializedActiveTask; } /** * Representation of a task that is currently being processed by a {@link * Listener}. It provides the ability to see information and update values of * the task like when working with a {@link Task}, but also has additional * functionality specific to processing, such as completing, retrying, etc. * * @public */ export interface ActiveTask extends TaskBase, EventEmitter { /** * User-defined payload holding information about the task. * * @public */ payload: T; /** * Indicates whether the current processor has a valid lock on the task. If * this becomes false, the handler will no longer be allowed to update or * finish the task processing to avoid race conditions with other * processors. * * @public */ readonly locked: boolean; /** * The current state of processing for this task. * * @public */ readonly processingState: ProcessingState; /** * Update the task in the database to match the information in this * instance. This can only be called once at a time to avoid race conditions * between different updates of the payload. * * @public */ save(): Promise; /** * Delete this task from the database. The operation is idempotent and will * succeed even if the task has already been deleted. It also implicitly * completes the task. * * @public */ delete(): Promise; /** * Indicate that the task processing finished successfully. This will also * implicitly save the current state of the task by default. * * This function is called implicitly if the task handler returns without * calling any of the finishing functions. * * @param nextRunDelayMs - Optional amount of time to wait before executing * another run of the task. Setting this overrides * the time of the next run that is determined by * the task {@link TaskBase.interval | interval} * and can be used to trigger another run of a task * that would not otherwise have any runs. * @param savePayload - If true, saves the payload of the task while * finishing, preventing the processor from having * to make an extra call to the database to save * the final payload. Defaults to true. * * @public */ complete(nextRunDelayMs?: number, savePayload?: boolean): Promise; /** * Indicate that the task suffered an irrecoverable failure and should not * be attempted again. This does _not_ prevent future runs from executing in * the case of recurring tasks. This will also implicitly save the current * state of the task by default. * * @param err - The error associated with the failure. Useful * for error reporting/logging. * @param nextRunDelayMs - Optional amount of time to wait before executing * another run of the task. Setting this overrides * the time of the next run that is determined by * the task {@link TaskBase.interval | interval} * and can be used to trigger another run of a task * that would not otherwise have any runs. * @param savePayload - If true, saves the payload of the task while * finishing, preventing the processor from having * to make an extra call to the database to save * the final payload. Defaults to true. * * @public */ fail(err?: any, nextRunDelayMs?: number, savePayload?: boolean): Promise; /** * Indicate that the task encountered an error that may be retried. If the * configured retry limit has been reached, this is equivalent to calling * `fail()`. After the specified delay (or a backoff computed from * the configured retry options), the current run of the task will be * reprocessed. This will also implicitly save the current state of the * task by default. * * This function is called implicitly if the task handler throws an * exception (though it will not save the latest payload to avoid * creating inconsistent states by accident) * * @param err - The error associated with the failure. Useful for * error reporting/logging. * @param delayMs - Optional amount of time to wait in milliseconds * before attempting re-processing of the task. If not * specified, uses the retry options from the client to * compute a delay. * @param savePayload - If true, saves the payload of the task while * finishing, preventing the processor from having to * make an extra call to the database to save the final * payload. Defaults to true. * * @public */ retry(err?: any, delayMs?: number, savePayload?: boolean): Promise; /** * Indicate that the task is not done for processing and should be picked up * for processing at a later time. This is distinct from `retry()` in that * it does not indicate any failure and can be called an unlimited number of * times on a single run of a task without causing it to fail eventually. * Additionally, the delay before reprocessing must be specified. This will * also implicitly save the current state of the task by default. * * @param delayMs - The amount of time to wait in milliseconds before * attempting re-processing of the task. * @param savePayload - If true, saves the payload of the task while * finishing, preventing the processor from having to * make an extra call to the database to save the final * payload. Defaults to true. * * @public */ defer(delayMs: number, savePayload?: boolean): Promise; /** * Indicate that the task is not done processing but should not continue to * be processed by this processor. This is typically used to indicate that * task processing should be suspended after having been disabled. This will * also implicitly save the current state of the task by default. * * @param savePayload - If true, saves the payload of the task while * finishing, preventing the processor from having to * make an extra call to the database to save the final * payload. Defaults to true. * * @public */ release(savePayload?: boolean): Promise; /** * Stop processing of the task without informing the database that you have * stopped processing the task. This should be used as an absolute last * resort for releasing a task from processing as it doesn't allow any other * processors to pick up the task until the current lock expires. * * @param err - The error associated with the failure. Useful for error * reporting/logging. * * @public */ forceRelease(err?: any): void; /** * Convert the task to a serialization-friendly format * * @public */ toJSON(): SerializedActiveTask; on(event: 'stateChanged', listener: (state: ProcessingState) => void): this; on(event: 'finished', listener: (result: TaskFinishMetadata) => void): this; on(event: 'lockRenewed' | 'lockLost' | 'disabled' | 'inactive', listener: () => void): this; } //# sourceMappingURL=active.d.ts.map