@temporalio/workflow
Advanced tools
Comparing version 0.6.0 to 0.7.0
@@ -88,2 +88,8 @@ /** Magic symbol used to create the root scope - intentionally not exported */ | ||
/** | ||
* Method that runs a function in AsyncLocalStorage context. | ||
* | ||
* Could have been written as anonymous function, made into a method for improved stack traces. | ||
*/ | ||
protected runInContext<T>(fn: () => Promise<T>): Promise<T>; | ||
/** | ||
* Request to cancel the scope and linked children | ||
@@ -90,0 +96,0 @@ */ |
@@ -90,10 +90,16 @@ "use strict"; | ||
run(fn) { | ||
return storage.run(this, async () => { | ||
if (this.timeout) { | ||
sleep(this.timeout).then(() => this.cancel()); | ||
} | ||
return await fn(); | ||
}); | ||
return storage.run(this, this.runInContext.bind(this, fn)); | ||
} | ||
/** | ||
* Method that runs a function in AsyncLocalStorage context. | ||
* | ||
* Could have been written as anonymous function, made into a method for improved stack traces. | ||
*/ | ||
async runInContext(fn) { | ||
if (this.timeout) { | ||
sleep(this.timeout).then(() => this.cancel()); | ||
} | ||
return await fn(); | ||
} | ||
/** | ||
* Request to cancel the scope and linked children | ||
@@ -100,0 +106,0 @@ */ |
@@ -17,15 +17,17 @@ /** | ||
* | ||
* To schedule activities in the system, simply import an activity function from any registered activity file and call it like a normal function, the Temporal workflow runtime will replace the imported function with a stub which will schedules an activity. | ||
* To schedule Activities, use {@link ContextImpl.configureActivities | Context.configureActivities} to obtain an Activity function and call. | ||
* | ||
* Activities run with the worker's configured {@link WorkerOptions.activityDefaults | activityDefaults}, use {@link ContextImpl.configure | Context.configure} in order to customize the {@link ActivityOptions | activity options}. | ||
* | ||
* <!--SNIPSTART nodejs-schedule-activity-workflow--> | ||
* <!--SNIPEND--> | ||
* | ||
* ### Signals | ||
* ### Signals and Queries | ||
* | ||
* To add signal handlers to a workflow, add a signals property to the exported workflow object. | ||
* To add signal handlers to a Workflow, add a signals property to the exported `workflow` object. | ||
* Signal handlers can return either `void` or `Promise<void>`, you may schedule activities and timers from a signal handler. | ||
* | ||
* To add query handlers to a Workflow, add a queries property to the exported `workflow` object. | ||
* Query handlers must **not** mutate any variables or generate any commands (like Activities or Timers), they run synchronously and thus **must** return a `Promise`. | ||
* | ||
* #### Interface | ||
* | ||
* <!--SNIPSTART nodejs-workflow-signal-interface--> | ||
@@ -35,2 +37,3 @@ * <!--SNIPEND--> | ||
* #### Implementation | ||
* | ||
* <!--SNIPSTART nodejs-workflow-signal-implementation--> | ||
@@ -52,4 +55,3 @@ * <!--SNIPEND--> | ||
*/ | ||
import './global-overrides'; | ||
export { Workflow, ActivityCancellationType, ActivityFunction, ActivityOptions, LocalActivityOptions, RemoteActivityOptions, RetryOptions, rootCause, IllegalStateError, defaultDataConverter, DataConverter, WorkflowIdReusePolicy, ActivityFailure, ApplicationFailure, CancelledFailure, ChildWorkflowFailure, ServerFailure, TemporalFailure, TerminatedFailure, TimeoutFailure, } from '@temporalio/common'; | ||
export { Workflow, ActivityCancellationType, ActivityFunction, ActivityInterface, ActivityOptions, LocalActivityOptions, RemoteActivityOptions, RetryOptions, rootCause, IllegalStateError, defaultDataConverter, DataConverter, WorkflowIdReusePolicy, ActivityFailure, ApplicationFailure, CancelledFailure, ChildWorkflowFailure, ServerFailure, TemporalFailure, TerminatedFailure, TimeoutFailure, } from '@temporalio/common'; | ||
export { ApplyMode, ChildWorkflowOptions, ChildWorkflowCancellationType, ExternalDependencyFunction, ExternalDependency, ExternalDependencies, WorkflowInfo, } from './interfaces'; | ||
@@ -56,0 +58,0 @@ export * from './errors'; |
@@ -18,15 +18,17 @@ "use strict"; | ||
* | ||
* To schedule activities in the system, simply import an activity function from any registered activity file and call it like a normal function, the Temporal workflow runtime will replace the imported function with a stub which will schedules an activity. | ||
* To schedule Activities, use {@link ContextImpl.configureActivities | Context.configureActivities} to obtain an Activity function and call. | ||
* | ||
* Activities run with the worker's configured {@link WorkerOptions.activityDefaults | activityDefaults}, use {@link ContextImpl.configure | Context.configure} in order to customize the {@link ActivityOptions | activity options}. | ||
* | ||
* <!--SNIPSTART nodejs-schedule-activity-workflow--> | ||
* <!--SNIPEND--> | ||
* | ||
* ### Signals | ||
* ### Signals and Queries | ||
* | ||
* To add signal handlers to a workflow, add a signals property to the exported workflow object. | ||
* To add signal handlers to a Workflow, add a signals property to the exported `workflow` object. | ||
* Signal handlers can return either `void` or `Promise<void>`, you may schedule activities and timers from a signal handler. | ||
* | ||
* To add query handlers to a Workflow, add a queries property to the exported `workflow` object. | ||
* Query handlers must **not** mutate any variables or generate any commands (like Activities or Timers), they run synchronously and thus **must** return a `Promise`. | ||
* | ||
* #### Interface | ||
* | ||
* <!--SNIPSTART nodejs-workflow-signal-interface--> | ||
@@ -36,2 +38,3 @@ * <!--SNIPEND--> | ||
* #### Implementation | ||
* | ||
* <!--SNIPSTART nodejs-workflow-signal-implementation--> | ||
@@ -65,3 +68,2 @@ * <!--SNIPEND--> | ||
exports.Trigger = exports.CancellationScope = exports.AsyncLocalStorage = exports.deprecatePatch = exports.patched = exports.scheduleActivity = exports.validateActivityOptions = exports.uuid4 = exports.sleep = exports.ContextImpl = exports.Context = exports.ChildWorkflowCancellationType = exports.ApplyMode = exports.TimeoutFailure = exports.TerminatedFailure = exports.TemporalFailure = exports.ServerFailure = exports.ChildWorkflowFailure = exports.CancelledFailure = exports.ApplicationFailure = exports.ActivityFailure = exports.WorkflowIdReusePolicy = exports.defaultDataConverter = exports.IllegalStateError = exports.rootCause = exports.ActivityCancellationType = void 0; | ||
require("./global-overrides"); | ||
var common_1 = require("@temporalio/common"); | ||
@@ -68,0 +70,0 @@ Object.defineProperty(exports, "ActivityCancellationType", { enumerable: true, get: function () { return common_1.ActivityCancellationType; } }); |
@@ -1,6 +0,6 @@ | ||
import { ActivityOptions, Workflow, WorkflowSignalType, DataConverter } from '@temporalio/common'; | ||
import { Workflow, WorkflowSignalType, DataConverter } from '@temporalio/common'; | ||
import { coresdk } from '@temporalio/proto/lib/coresdk'; | ||
import { RNG } from './alea'; | ||
import { ExternalDependencies, WorkflowInfo } from './interfaces'; | ||
import { SignalInput, WorkflowInput, WorkflowInterceptors } from './interceptors'; | ||
import { QueryInput, SignalInput, WorkflowInput, WorkflowInterceptors } from './interceptors'; | ||
export declare type ResolveFunction<T = any> = (val: T) => any; | ||
@@ -24,2 +24,3 @@ export declare type RejectFunction<E = any> = (val: E) => any; | ||
resolveChildWorkflowExecution(activation: coresdk.workflow_activation.IResolveChildWorkflowExecution): Promise<void>; | ||
protected queryWorkflowNextHandler(input: QueryInput): Promise<unknown>; | ||
queryWorkflow(activation: coresdk.workflow_activation.IQueryWorkflow): void; | ||
@@ -110,6 +111,2 @@ signalWorkflowNextHandler(fn: WorkflowSignalType, input: SignalInput): Promise<void>; | ||
/** | ||
* Default ActivityOptions to set in `Context.configure` | ||
*/ | ||
activityDefaults?: ActivityOptions; | ||
/** | ||
* A deterministic RNG, used by the isolate's overridden Math.random | ||
@@ -116,0 +113,0 @@ */ |
@@ -55,3 +55,3 @@ "use strict"; | ||
catch (err) { | ||
const failure = common_1.ApplicationFailure.nonRetryable(err.message, 'ReferenceError'); | ||
const failure = common_1.ApplicationFailure.nonRetryable((0, common_1.errorMessage)(err), 'ReferenceError'); | ||
failure.stack = failure.stack?.split('\n')[0]; | ||
@@ -73,6 +73,6 @@ throw failure; | ||
} | ||
const execute = common_1.composeInterceptors(exports.state.interceptors.inbound, 'execute', this.startWorkflowNextHandler.bind(this, req.bind(undefined, info.filename))); | ||
const execute = (0, common_1.composeInterceptors)(exports.state.interceptors.inbound, 'execute', this.startWorkflowNextHandler.bind(this, req.bind(undefined, info.filename))); | ||
execute({ | ||
headers: new Map(Object.entries(activation.headers ?? {})), | ||
args: common_1.arrayFromPayloadsSync(exports.state.dataConverter, activation.arguments), | ||
args: (0, common_1.arrayFromPayloadsSync)(exports.state.dataConverter, activation.arguments), | ||
}) | ||
@@ -102,3 +102,3 @@ .then(completeWorkflow) | ||
const { failure } = activation.result.failed; | ||
const err = await common_1.optionalFailureToOptionalError(failure, exports.state.dataConverter); | ||
const err = await (0, common_1.optionalFailureToOptionalError)(failure, exports.state.dataConverter); | ||
reject(err); | ||
@@ -108,3 +108,3 @@ } | ||
const { failure } = activation.result.cancelled; | ||
const err = await common_1.optionalFailureToOptionalError(failure, exports.state.dataConverter); | ||
const err = await (0, common_1.optionalFailureToOptionalError)(failure, exports.state.dataConverter); | ||
reject(err); | ||
@@ -133,3 +133,3 @@ } | ||
} | ||
reject(await common_1.failureToError(activation.cancelled.failure, exports.state.dataConverter)); | ||
reject(await (0, common_1.failureToError)(activation.cancelled.failure, exports.state.dataConverter)); | ||
} | ||
@@ -155,3 +155,3 @@ else { | ||
} | ||
reject(await common_1.failureToError(failure, exports.state.dataConverter)); | ||
reject(await (0, common_1.failureToError)(failure, exports.state.dataConverter)); | ||
} | ||
@@ -163,5 +163,17 @@ else if (activation.result.cancelled) { | ||
} | ||
reject(await common_1.failureToError(failure, exports.state.dataConverter)); | ||
reject(await (0, common_1.failureToError)(failure, exports.state.dataConverter)); | ||
} | ||
} | ||
async queryWorkflowNextHandler(input) { | ||
const fn = exports.state.workflow?.queries?.[input.queryName]; | ||
if (fn === undefined) { | ||
// Fail the query | ||
throw new ReferenceError(`Workflow did not register a handler for ${input.queryName}`); | ||
} | ||
const ret = fn(...input.args); | ||
if (ret instanceof Promise) { | ||
throw new errors_1.DeterminismViolationError('Query handlers should not return a Promise'); | ||
} | ||
return ret; | ||
} | ||
queryWorkflow(activation) { | ||
@@ -172,17 +184,6 @@ const { queryType, queryId } = activation; | ||
} | ||
const execute = common_1.composeInterceptors(exports.state.interceptors.inbound, 'handleQuery', async (input) => { | ||
const fn = exports.state.workflow?.queries?.[input.queryName]; | ||
if (fn === undefined) { | ||
// Fail the query | ||
throw new ReferenceError(`Workflow did not register a handler for ${input.queryName}`); | ||
} | ||
const ret = fn(...input.args); | ||
if (ret instanceof Promise) { | ||
throw new errors_1.DeterminismViolationError('Query handlers should not return a Promise'); | ||
} | ||
return ret; | ||
}); | ||
const execute = (0, common_1.composeInterceptors)(exports.state.interceptors.inbound, 'handleQuery', this.queryWorkflowNextHandler.bind(this)); | ||
execute({ | ||
queryName: queryType, | ||
args: common_1.arrayFromPayloadsSync(exports.state.dataConverter, activation.arguments), | ||
args: (0, common_1.arrayFromPayloadsSync)(exports.state.dataConverter, activation.arguments), | ||
queryId, | ||
@@ -204,5 +205,5 @@ }).then((result) => completeQuery(queryId, result), (reason) => failQuery(queryId, reason)); | ||
} | ||
const execute = common_1.composeInterceptors(exports.state.interceptors.inbound, 'handleSignal', this.signalWorkflowNextHandler.bind(this, fn)); | ||
const execute = (0, common_1.composeInterceptors)(exports.state.interceptors.inbound, 'handleSignal', this.signalWorkflowNextHandler.bind(this, fn)); | ||
execute({ | ||
args: common_1.arrayFromPayloadsSync(exports.state.dataConverter, activation.input), | ||
args: (0, common_1.arrayFromPayloadsSync)(exports.state.dataConverter, activation.input), | ||
signalName, | ||
@@ -214,3 +215,3 @@ }).catch(handleWorkflowFailure); | ||
if (activation.failure) { | ||
reject(await common_1.failureToError(activation.failure, exports.state.dataConverter)); | ||
reject(await (0, common_1.failureToError)(activation.failure, exports.state.dataConverter)); | ||
} | ||
@@ -224,3 +225,3 @@ else { | ||
if (activation.failure) { | ||
reject(await common_1.failureToError(activation.failure, exports.state.dataConverter)); | ||
reject(await (0, common_1.failureToError)(activation.failure, exports.state.dataConverter)); | ||
} | ||
@@ -235,3 +236,3 @@ else { | ||
} | ||
exports.state.random = alea_1.alea(activation.randomnessSeed.toBytes()); | ||
exports.state.random = (0, alea_1.alea)(activation.randomnessSeed.toBytes()); | ||
} | ||
@@ -358,3 +359,3 @@ notifyHasPatch(activation) { | ||
async function handleWorkflowFailure(error) { | ||
if (exports.state.cancelled && errors_1.isCancellation(error)) { | ||
if (exports.state.cancelled && (0, errors_1.isCancellation)(error)) { | ||
exports.state.commands.push({ cancelWorkflowExecution: {} }); | ||
@@ -368,3 +369,3 @@ } | ||
failWorkflowExecution: { | ||
failure: await common_1.errorToFailure(common_1.ensureTemporalFailure(error), exports.state.dataConverter), | ||
failure: await (0, common_1.errorToFailure)((0, common_1.ensureTemporalFailure)(error), exports.state.dataConverter), | ||
}, | ||
@@ -382,3 +383,3 @@ }); | ||
exports.state.commands.push({ | ||
respondToQuery: { queryId, failed: await common_1.errorToFailure(common_1.ensureTemporalFailure(error), exports.state.dataConverter) }, | ||
respondToQuery: { queryId, failed: await (0, common_1.errorToFailure)((0, common_1.ensureTemporalFailure)(error), exports.state.dataConverter) }, | ||
}); | ||
@@ -385,0 +386,0 @@ } |
@@ -7,3 +7,2 @@ /** | ||
import ivm from 'isolated-vm'; | ||
import { ActivityOptions } from '@temporalio/common'; | ||
import { ApplyMode, ExternalDependencyFunction, WorkflowInfo } from './interfaces'; | ||
@@ -32,3 +31,3 @@ import { ExternalCall, state } from './internals'; | ||
export declare function mockBrowserDocumentForWebpack(): MockDocument; | ||
export declare function initRuntime(info: WorkflowInfo, activityDefaults: ActivityOptions, interceptorModules: string[], randomnessSeed: number[], isolateExtension: IsolateExtension): void; | ||
export declare function initRuntime(info: WorkflowInfo, interceptorModules: string[], randomnessSeed: number[], isolateExtension: IsolateExtension): void; | ||
declare type ActivationJobResult = { | ||
@@ -35,0 +34,0 @@ pendingExternalCalls: ExternalCall[]; |
@@ -46,3 +46,3 @@ "use strict"; | ||
seq, | ||
startToFireTimeout: common_1.msToTs(ms), | ||
startToFireTimeout: (0, common_1.msToTs)(ms), | ||
}, | ||
@@ -89,3 +89,3 @@ }); | ||
exports.mockBrowserDocumentForWebpack = mockBrowserDocumentForWebpack; | ||
function initRuntime(info, activityDefaults, interceptorModules, randomnessSeed, isolateExtension) { | ||
function initRuntime(info, interceptorModules, randomnessSeed, isolateExtension) { | ||
// Globals are overridden while building the isolate before loading user code. | ||
@@ -98,4 +98,3 @@ // For some reason the `WeakRef` mock is not restored properly when creating an isolate from snapshot in node 14 (at least on ubuntu), override again. | ||
internals_1.state.info = info; | ||
internals_1.state.activityDefaults = activityDefaults; | ||
internals_1.state.random = alea_1.alea(randomnessSeed); | ||
internals_1.state.random = (0, alea_1.alea)(randomnessSeed); | ||
promise_hooks_1.HookManager.instance.setIsolateExtension(isolateExtension); | ||
@@ -115,3 +114,3 @@ } | ||
if (!(job.variant === 'queryWorkflow' && activation.timestamp === null)) { | ||
internals_1.state.now = common_1.tsToMs(activation.timestamp); | ||
internals_1.state.now = (0, common_1.tsToMs)(activation.timestamp); | ||
} | ||
@@ -195,3 +194,3 @@ if (internals_1.state.info === undefined) { | ||
for (const { seq, result, error } of results) { | ||
const completion = internals_1.consumeCompletion('dependency', seq); | ||
const completion = (0, internals_1.consumeCompletion)('dependency', seq); | ||
if (error) { | ||
@@ -198,0 +197,0 @@ completion.reject(error); |
@@ -30,3 +30,3 @@ import { ActivityFunction, ActivityOptions, RemoteActivityOptions, Workflow } from '@temporalio/common'; | ||
*/ | ||
export declare function scheduleActivity<R>(activityType: string, args: any[], options?: ActivityOptions | undefined): Promise<R>; | ||
export declare function scheduleActivity<R>(activityType: string, args: any[], options: ActivityOptions): Promise<R>; | ||
export declare class ContextImpl { | ||
@@ -38,27 +38,39 @@ /** | ||
/** | ||
* Configure an activity function with given {@link ActivityOptions} | ||
* Activities use the worker options's {@link WorkerOptions.activityDefaults | activityDefaults} unless configured otherwise. | ||
* Configure Activity functions with given {@link ActivityOptions}. | ||
* | ||
* @typeparam P type of parameters of activity function, e.g `[string, string]` for `(a: string, b: string) => Promise<number>` | ||
* @typeparam R return type of activity function, e.g `number` for `(a: string, b: string) => Promise<number>` | ||
* This method may be called multiple times to setup Activities with different options. | ||
* | ||
* @param activity either an activity name if triggering an activity in another language, a tuple of [module, name] for untyped activities (e.g. ['@activities', 'greet']) or an imported activity function. | ||
* @param options partial {@link ActivityOptions} object, any attributes provided here override the provided activity's options | ||
* @return a [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) | ||
* for which each attribute is a callable Activity function | ||
* | ||
* @typeparam A An {@link ActivityInterface} - mapping of name to function | ||
* | ||
* @example | ||
* ```ts | ||
* import { Context } from '@temporalio/workflow'; | ||
* import { httpGet } from '@activities'; | ||
* import { Context, ActivityInterface } from '@temporalio/workflow'; | ||
* import * as activities from '../activities'; | ||
* | ||
* const httpGetWithCustomTimeout = Context.configure(httpGet, { | ||
* // Setup Activities from module exports | ||
* const { httpGet, otherActivity } = Context.configureActivities<typeof activities>({ | ||
* type: 'remote', | ||
* scheduleToCloseTimeout: '30 minutes', | ||
* startToCloseTimeout: '30 minutes', | ||
* }); | ||
* | ||
* // Example of creating an activity from string | ||
* // Passing type parameters is optional, configured function will be untyped unless provided | ||
* const httpGetFromJava = Context.configure<[string, number], number>('SomeJavaMethod'); // Use worker activityDefaults when 2nd parameter is omitted | ||
* // Setup Activities from an explicit interface (e.g. when defined by another SDK) | ||
* interface JavaActivities extends ActivityInterface { | ||
* httpGetFromJava(url: string): Promise<string> | ||
* someOtherJavaActivity(arg1: number, arg2: string): Promise<string>; | ||
* } | ||
* | ||
* const { | ||
* httpGetFromJava, | ||
* someOtherJavaActivity | ||
* } = Context.configureActivities<JavaActivities>({ | ||
* type: 'remote', | ||
* taskQueue: 'java-worker-taskQueue', | ||
* startToCloseTimeout: '5m', | ||
* }); | ||
* | ||
* export function main(): Promise<void> { | ||
* const response = await httpGetWithCustomTimeout('http://example.com'); | ||
* const response = await httpGet('http://example.com'); | ||
* // ... | ||
@@ -68,3 +80,3 @@ * } | ||
*/ | ||
configure<P extends any[], R>(activity: string | [string, string] | ActivityFunction<P, R>, options?: ActivityOptions | undefined): ActivityFunction<P, R>; | ||
configureActivities<A extends Record<string, ActivityFunction<any, any>>>(options: ActivityOptions): A; | ||
/** | ||
@@ -71,0 +83,0 @@ * Returns a client-side stub that can be used to signal and cancel an existing Workflow execution. |
@@ -11,3 +11,3 @@ "use strict"; | ||
// Avoid a circular dependency | ||
cancellation_scope_1.registerSleepImplementation(sleep); | ||
(0, cancellation_scope_1.registerSleepImplementation)(sleep); | ||
/** | ||
@@ -56,3 +56,3 @@ * Adds default values to `workflowId` and `workflowIdReusePolicy` to given workflow options. | ||
seq: input.seq, | ||
startToFireTimeout: common_1.msToTs(input.durationMs), | ||
startToFireTimeout: (0, common_1.msToTs)(input.durationMs), | ||
}, | ||
@@ -72,3 +72,3 @@ }); | ||
const seq = internals_1.state.nextSeqs.timer++; | ||
const execute = common_1.composeInterceptors(internals_1.state.interceptors.outbound, 'startTimer', timerNextHandler); | ||
const execute = (0, common_1.composeInterceptors)(internals_1.state.interceptors.outbound, 'startTimer', timerNextHandler); | ||
return execute({ | ||
@@ -128,4 +128,4 @@ durationMs: ms, | ||
maximumAttempts: options.retry.maximumAttempts, | ||
initialInterval: common_1.msOptionalToTs(options.retry.initialInterval), | ||
maximumInterval: common_1.msOptionalToTs(options.retry.maximumInterval), | ||
initialInterval: (0, common_1.msOptionalToTs)(options.retry.initialInterval), | ||
maximumInterval: (0, common_1.msOptionalToTs)(options.retry.maximumInterval), | ||
backoffCoefficient: options.retry.backoffCoefficient, | ||
@@ -136,6 +136,6 @@ nonRetryableErrorTypes: options.retry.nonRetryableErrorTypes, | ||
taskQueue: options.taskQueue || internals_1.state.info?.taskQueue, | ||
heartbeatTimeout: common_1.msOptionalToTs(options.heartbeatTimeout), | ||
scheduleToCloseTimeout: common_1.msOptionalToTs(options.scheduleToCloseTimeout), | ||
startToCloseTimeout: common_1.msOptionalToTs(options.startToCloseTimeout), | ||
scheduleToStartTimeout: common_1.msOptionalToTs(options.scheduleToStartTimeout), | ||
heartbeatTimeout: (0, common_1.msOptionalToTs)(options.heartbeatTimeout), | ||
scheduleToCloseTimeout: (0, common_1.msOptionalToTs)(options.scheduleToCloseTimeout), | ||
startToCloseTimeout: (0, common_1.msOptionalToTs)(options.startToCloseTimeout), | ||
scheduleToStartTimeout: (0, common_1.msOptionalToTs)(options.scheduleToStartTimeout), | ||
namespace: options.namespace, | ||
@@ -152,3 +152,3 @@ headerFields: Object.fromEntries(headers.entries()), | ||
*/ | ||
function scheduleActivity(activityType, args, options = internals_1.state.activityDefaults) { | ||
function scheduleActivity(activityType, args, options) { | ||
if (options === undefined) { | ||
@@ -158,3 +158,3 @@ throw new TypeError('Got empty activity options'); | ||
const seq = internals_1.state.nextSeqs.activity++; | ||
const execute = common_1.composeInterceptors(internals_1.state.interceptors.outbound, 'scheduleActivity', scheduleActivityNextHandler); | ||
const execute = (0, common_1.composeInterceptors)(internals_1.state.interceptors.outbound, 'scheduleActivity', scheduleActivityNextHandler); | ||
return execute({ | ||
@@ -220,5 +220,5 @@ activityType, | ||
taskQueue: options.taskQueue || internals_1.state.info?.taskQueue, | ||
workflowExecutionTimeout: common_1.msOptionalToTs(options.workflowExecutionTimeout), | ||
workflowRunTimeout: common_1.msOptionalToTs(options.workflowRunTimeout), | ||
workflowTaskTimeout: common_1.msOptionalToTs(options.workflowTaskTimeout), | ||
workflowExecutionTimeout: (0, common_1.msOptionalToTs)(options.workflowExecutionTimeout), | ||
workflowRunTimeout: (0, common_1.msOptionalToTs)(options.workflowRunTimeout), | ||
workflowTaskTimeout: (0, common_1.msOptionalToTs)(options.workflowTaskTimeout), | ||
namespace: exports.Context.info.namespace, | ||
@@ -232,6 +232,6 @@ header: Object.fromEntries(headers.entries()), | ||
? { | ||
indexedFields: common_1.mapToPayloadsSync(internals_1.state.dataConverter, options.searchAttributes), | ||
indexedFields: (0, common_1.mapToPayloadsSync)(internals_1.state.dataConverter, options.searchAttributes), | ||
} | ||
: undefined, | ||
memo: options.memo && common_1.mapToPayloadsSync(internals_1.state.dataConverter, options.memo), | ||
memo: options.memo && (0, common_1.mapToPayloadsSync)(internals_1.state.dataConverter, options.memo), | ||
}, | ||
@@ -292,13 +292,2 @@ }); | ||
} | ||
function activityInfo(activity) { | ||
if (typeof activity === 'string') { | ||
return { name: activity, type: activity }; | ||
} | ||
if (activity instanceof Array) { | ||
return { name: activity[1], type: JSON.stringify(activity) }; | ||
} | ||
else { | ||
return activity; | ||
} | ||
} | ||
class ContextImpl { | ||
@@ -312,27 +301,39 @@ /** | ||
/** | ||
* Configure an activity function with given {@link ActivityOptions} | ||
* Activities use the worker options's {@link WorkerOptions.activityDefaults | activityDefaults} unless configured otherwise. | ||
* Configure Activity functions with given {@link ActivityOptions}. | ||
* | ||
* @typeparam P type of parameters of activity function, e.g `[string, string]` for `(a: string, b: string) => Promise<number>` | ||
* @typeparam R return type of activity function, e.g `number` for `(a: string, b: string) => Promise<number>` | ||
* This method may be called multiple times to setup Activities with different options. | ||
* | ||
* @param activity either an activity name if triggering an activity in another language, a tuple of [module, name] for untyped activities (e.g. ['@activities', 'greet']) or an imported activity function. | ||
* @param options partial {@link ActivityOptions} object, any attributes provided here override the provided activity's options | ||
* @return a [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) | ||
* for which each attribute is a callable Activity function | ||
* | ||
* @typeparam A An {@link ActivityInterface} - mapping of name to function | ||
* | ||
* @example | ||
* ```ts | ||
* import { Context } from '@temporalio/workflow'; | ||
* import { httpGet } from '@activities'; | ||
* import { Context, ActivityInterface } from '@temporalio/workflow'; | ||
* import * as activities from '../activities'; | ||
* | ||
* const httpGetWithCustomTimeout = Context.configure(httpGet, { | ||
* // Setup Activities from module exports | ||
* const { httpGet, otherActivity } = Context.configureActivities<typeof activities>({ | ||
* type: 'remote', | ||
* scheduleToCloseTimeout: '30 minutes', | ||
* startToCloseTimeout: '30 minutes', | ||
* }); | ||
* | ||
* // Example of creating an activity from string | ||
* // Passing type parameters is optional, configured function will be untyped unless provided | ||
* const httpGetFromJava = Context.configure<[string, number], number>('SomeJavaMethod'); // Use worker activityDefaults when 2nd parameter is omitted | ||
* // Setup Activities from an explicit interface (e.g. when defined by another SDK) | ||
* interface JavaActivities extends ActivityInterface { | ||
* httpGetFromJava(url: string): Promise<string> | ||
* someOtherJavaActivity(arg1: number, arg2: string): Promise<string>; | ||
* } | ||
* | ||
* const { | ||
* httpGetFromJava, | ||
* someOtherJavaActivity | ||
* } = Context.configureActivities<JavaActivities>({ | ||
* type: 'remote', | ||
* taskQueue: 'java-worker-taskQueue', | ||
* startToCloseTimeout: '5m', | ||
* }); | ||
* | ||
* export function main(): Promise<void> { | ||
* const response = await httpGetWithCustomTimeout('http://example.com'); | ||
* const response = await httpGet('http://example.com'); | ||
* // ... | ||
@@ -342,3 +343,3 @@ * } | ||
*/ | ||
configure(activity, options = internals_1.state.activityDefaults) { | ||
configureActivities(options) { | ||
if (options === undefined) { | ||
@@ -349,12 +350,12 @@ throw new TypeError('options must be defined'); | ||
validateActivityOptions(options); | ||
const { name, type } = activityInfo(activity); | ||
// Wrap the function in an object so it gets the original function name | ||
const { [name]: fn } = { | ||
[name](...args) { | ||
return scheduleActivity(type, args, options); | ||
return new Proxy({}, { | ||
get(_, activityType) { | ||
if (typeof activityType !== 'string') { | ||
throw new TypeError(`Only strings are supported for Activity types, got: ${String(activityType)}`); | ||
} | ||
return (...args) => { | ||
return scheduleActivity(activityType, args, options); | ||
}; | ||
}, | ||
}; | ||
const configured = fn; | ||
Object.assign(configured, { type, options }); | ||
return configured; | ||
}); | ||
} | ||
@@ -394,3 +395,3 @@ /** | ||
return (...args) => { | ||
return common_1.composeInterceptors(internals_1.state.interceptors.outbound, 'signalWorkflow', signalWorkflowNextHandler)({ | ||
return (0, common_1.composeInterceptors)(internals_1.state.interceptors.outbound, 'signalWorkflow', signalWorkflowNextHandler)({ | ||
seq: internals_1.state.nextSeqs.signalWorkflow++, | ||
@@ -427,3 +428,3 @@ signalName, | ||
} | ||
const execute = common_1.composeInterceptors(internals_1.state.interceptors.outbound, 'startChildWorkflowExecution', startChildWorkflowExecutionNextHandler); | ||
const execute = (0, common_1.composeInterceptors)(internals_1.state.interceptors.outbound, 'startChildWorkflowExecution', startChildWorkflowExecutionNextHandler); | ||
[started, completed] = await execute({ | ||
@@ -457,3 +458,3 @@ seq: internals_1.state.nextSeqs.childWorkflow++, | ||
} | ||
return common_1.composeInterceptors(internals_1.state.interceptors.outbound, 'signalWorkflow', signalWorkflowNextHandler)({ | ||
return (0, common_1.composeInterceptors)(internals_1.state.interceptors.outbound, 'signalWorkflow', signalWorkflowNextHandler)({ | ||
seq: internals_1.state.nextSeqs.signalWorkflow++, | ||
@@ -532,3 +533,3 @@ signalName, | ||
return (...args) => { | ||
const fn = common_1.composeInterceptors(internals_1.state.interceptors.outbound, 'continueAsNew', async (input) => { | ||
const fn = (0, common_1.composeInterceptors)(internals_1.state.interceptors.outbound, 'continueAsNew', async (input) => { | ||
const { headers, args, options } = input; | ||
@@ -542,4 +543,4 @@ throw new interfaces_1.ContinueAsNew({ | ||
searchAttributes: options.searchAttributes, | ||
workflowRunTimeout: common_1.msOptionalToTs(options.workflowRunTimeout), | ||
workflowTaskTimeout: common_1.msOptionalToTs(options.workflowTaskTimeout), | ||
workflowRunTimeout: (0, common_1.msOptionalToTs)(options.workflowRunTimeout), | ||
workflowTaskTimeout: (0, common_1.msOptionalToTs)(options.workflowTaskTimeout), | ||
}); | ||
@@ -546,0 +547,0 @@ }); |
{ | ||
"name": "@temporalio/workflow", | ||
"version": "0.6.0", | ||
"version": "0.7.0", | ||
"description": "Temporal.io SDK Workflow sub-package", | ||
@@ -16,4 +16,4 @@ "main": "lib/index.js", | ||
"dependencies": { | ||
"@temporalio/common": "^0.1.0", | ||
"@temporalio/proto": "^0.3.0" | ||
"@temporalio/common": "^0.2.0", | ||
"@temporalio/proto": "^0.3.1" | ||
}, | ||
@@ -30,3 +30,3 @@ "bugs": { | ||
}, | ||
"gitHead": "cd10cb4b187a6a733770502fbca32b9dcd2d2244" | ||
"gitHead": "254e9f5793afc11cb5fb64a9829b1c55190092f0" | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
173586
45
3018
+ Added@temporalio/common@0.2.0(transitive)
- Removed@temporalio/common@0.1.0(transitive)
Updated@temporalio/common@^0.2.0
Updated@temporalio/proto@^0.3.1