@temporalio/common 0.17.2 → 0.19.0-rc.1

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.
Files changed (97) hide show
  1. package/README.md +5 -11
  2. package/lib/converter/data-converter.d.ts +34 -62
  3. package/lib/converter/data-converter.js +0 -101
  4. package/lib/converter/data-converter.js.map +1 -1
  5. package/lib/{encoding.d.ts → converter/encoding.d.ts} +0 -0
  6. package/lib/{encoding.js → converter/encoding.js} +0 -0
  7. package/lib/converter/encoding.js.map +1 -0
  8. package/lib/converter/patch-protobuf-root.d.ts +8 -0
  9. package/lib/converter/patch-protobuf-root.js +43 -0
  10. package/lib/converter/patch-protobuf-root.js.map +1 -0
  11. package/lib/converter/payload-codec.d.ts +27 -0
  12. package/lib/converter/payload-codec.js +11 -0
  13. package/lib/converter/payload-codec.js.map +1 -0
  14. package/lib/converter/payload-converter.d.ts +63 -62
  15. package/lib/converter/payload-converter.js +113 -68
  16. package/lib/converter/payload-converter.js.map +1 -1
  17. package/lib/converter/payload-converters.d.ts +31 -0
  18. package/lib/converter/payload-converters.js +85 -0
  19. package/lib/converter/payload-converters.js.map +1 -0
  20. package/lib/converter/protobuf-payload-converters.d.ts +53 -0
  21. package/lib/converter/protobuf-payload-converters.js +159 -0
  22. package/lib/converter/protobuf-payload-converters.js.map +1 -0
  23. package/lib/converter/types.d.ts +2 -0
  24. package/lib/converter/types.js +3 -2
  25. package/lib/converter/types.js.map +1 -1
  26. package/lib/failure.d.ts +6 -6
  27. package/lib/failure.js +37 -35
  28. package/lib/failure.js.map +1 -1
  29. package/lib/index.d.ts +9 -11
  30. package/lib/index.js +12 -16
  31. package/lib/index.js.map +1 -1
  32. package/lib/protobufs.d.ts +13 -0
  33. package/lib/protobufs.js +31 -0
  34. package/lib/protobufs.js.map +1 -0
  35. package/package.json +11 -8
  36. package/src/converter/data-converter.ts +35 -176
  37. package/src/{encoding.ts → converter/encoding.ts} +0 -0
  38. package/src/converter/patch-protobuf-root.ts +49 -0
  39. package/src/converter/payload-codec.ts +30 -0
  40. package/src/converter/payload-converter.ts +122 -102
  41. package/src/converter/payload-converters.ts +89 -0
  42. package/src/converter/protobuf-payload-converters.ts +192 -0
  43. package/src/converter/types.ts +4 -1
  44. package/src/failure.ts +44 -43
  45. package/src/index.ts +9 -11
  46. package/src/protobufs.ts +15 -0
  47. package/tsconfig.json +2 -2
  48. package/tsconfig.tsbuildinfo +1 -1
  49. package/lib/activity-options.d.ts +0 -81
  50. package/lib/activity-options.js +0 -14
  51. package/lib/activity-options.js.map +0 -1
  52. package/lib/encoding.js.map +0 -1
  53. package/lib/errors.d.ts +0 -16
  54. package/lib/errors.js +0 -41
  55. package/lib/errors.js.map +0 -1
  56. package/lib/interceptors.d.ts +0 -18
  57. package/lib/interceptors.js +0 -24
  58. package/lib/interceptors.js.map +0 -1
  59. package/lib/interfaces.d.ts +0 -31
  60. package/lib/interfaces.js +0 -3
  61. package/lib/interfaces.js.map +0 -1
  62. package/lib/otel.d.ts +0 -26
  63. package/lib/otel.js +0 -82
  64. package/lib/otel.js.map +0 -1
  65. package/lib/retry-policy.d.ts +0 -43
  66. package/lib/retry-policy.js +0 -36
  67. package/lib/retry-policy.js.map +0 -1
  68. package/lib/time.d.ts +0 -16
  69. package/lib/time.js +0 -73
  70. package/lib/time.js.map +0 -1
  71. package/lib/tls-config.d.ts +0 -32
  72. package/lib/tls-config.js +0 -11
  73. package/lib/tls-config.js.map +0 -1
  74. package/lib/type-helpers.d.ts +0 -8
  75. package/lib/type-helpers.js +0 -9
  76. package/lib/type-helpers.js.map +0 -1
  77. package/lib/utils.d.ts +0 -4
  78. package/lib/utils.js +0 -11
  79. package/lib/utils.js.map +0 -1
  80. package/lib/workflow-handle.d.ts +0 -27
  81. package/lib/workflow-handle.js +0 -3
  82. package/lib/workflow-handle.js.map +0 -1
  83. package/lib/workflow-options.d.ts +0 -91
  84. package/lib/workflow-options.js +0 -26
  85. package/lib/workflow-options.js.map +0 -1
  86. package/src/activity-options.ts +0 -97
  87. package/src/errors.ts +0 -27
  88. package/src/interceptors.ts +0 -32
  89. package/src/interfaces.ts +0 -37
  90. package/src/otel.ts +0 -61
  91. package/src/retry-policy.ts +0 -73
  92. package/src/time.ts +0 -72
  93. package/src/tls-config.ts +0 -35
  94. package/src/type-helpers.ts +0 -11
  95. package/src/utils.ts +0 -6
  96. package/src/workflow-handle.ts +0 -30
  97. package/src/workflow-options.ts +0 -127
@@ -1,91 +0,0 @@
1
- import type { google } from '@temporalio/proto/lib/coresdk';
2
- import { Workflow } from './interfaces';
3
- import { RetryPolicy } from './retry-policy';
4
- export declare enum WorkflowIdReusePolicy {
5
- WORKFLOW_ID_REUSE_POLICY_UNSPECIFIED = 0,
6
- WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE = 1,
7
- WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY = 2,
8
- WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE = 3
9
- }
10
- export interface BaseWorkflowOptions {
11
- /**
12
- * Specifies server behavior if a completed workflow with the same id exists. Note that under no
13
- * conditions Temporal allows two workflows with the same namespace and workflow id run
14
- * simultaneously.
15
- * ALLOW_DUPLICATE_FAILED_ONLY is a default value. It means that workflow can start if
16
- * previous run failed or was canceled or terminated.
17
- * ALLOW_DUPLICATE allows new run independently of the previous run closure status.
18
- * REJECT_DUPLICATE doesn't allow new run independently of the previous run closure status.
19
- */
20
- workflowIdReusePolicy?: WorkflowIdReusePolicy;
21
- /**
22
- * Controls how a Workflow is retried.
23
- *
24
- * Workflows should typically use the system default, do not set this unless
25
- * you know what you're doing.
26
- */
27
- retry?: RetryPolicy;
28
- /**
29
- * Optional cron schedule for Workflow. If a cron schedule is specified, the Workflow will run
30
- * as a cron based on the schedule. The scheduling will be based on UTC time. The schedule for the next run only happens
31
- * after the current run is completed/failed/timeout. If a RetryPolicy is also supplied, and the Workflow failed
32
- * or timed out, the Workflow will be retried based on the retry policy. While the Workflow is retrying, it won't
33
- * schedule its next run. If the next schedule is due while the Workflow is running (or retrying), then it will skip that
34
- * schedule. Cron Workflow will not stop until it is terminated or cancelled (by returning temporal.CanceledError).
35
- * https://crontab.guru/ is useful for testing your cron expressions.
36
- */
37
- cronSchedule?: string;
38
- /**
39
- * Specifies additional non-indexed information in result of list workflow. The type of value
40
- * can be any object that are serializable by `DataConverter`.
41
- */
42
- memo?: Record<string, any>;
43
- /**
44
- * Specifies additional indexed information in result of list workflow. The type of value should
45
- * be a primitive (e.g. string, number, boolean), for dates use Date.toISOString();
46
- */
47
- searchAttributes?: Record<string, string | number | boolean>;
48
- }
49
- export declare type WithWorkflowArgs<W extends Workflow, T> = T & (Parameters<W> extends [any, ...any[]] ? {
50
- /**
51
- * Arguments to pass to the Workflow
52
- */
53
- args: Parameters<W>;
54
- } : {
55
- /**
56
- * Arguments to pass to the Workflow
57
- */
58
- args?: Parameters<W>;
59
- });
60
- export interface WorkflowDurationOptions {
61
- /**
62
- * The time after which workflow run is automatically terminated by Temporal service. Do not
63
- * rely on run timeout for business level timeouts. It is preferred to use in workflow timers
64
- * for this purpose.
65
- *
66
- * @format {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
67
- */
68
- workflowRunTimeout?: string | number;
69
- /**
70
- *
71
- * The time after which workflow execution (which includes run retries and continue as new) is
72
- * automatically terminated by Temporal service. Do not rely on execution timeout for business
73
- * level timeouts. It is preferred to use in workflow timers for this purpose.
74
- *
75
- * @format {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
76
- */
77
- workflowExecutionTimeout?: string | number;
78
- /**
79
- * Maximum execution time of a single workflow task. Default is 10 seconds.
80
- *
81
- * @format {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
82
- */
83
- workflowTaskTimeout?: string | number;
84
- }
85
- export declare type CommonWorkflowOptions = BaseWorkflowOptions & WorkflowDurationOptions;
86
- export declare type WithCompiledWorkflowDurationOptions<T extends WorkflowDurationOptions> = Omit<T, 'workflowExecutionTimeout' | 'workflowRunTimeout' | 'workflowTaskTimeout'> & {
87
- workflowExecutionTimeout?: google.protobuf.IDuration;
88
- workflowRunTimeout?: google.protobuf.IDuration;
89
- workflowTaskTimeout?: google.protobuf.IDuration;
90
- };
91
- export declare function compileWorkflowOptions<T extends WorkflowDurationOptions>(options: T): WithCompiledWorkflowDurationOptions<T>;
@@ -1,26 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.compileWorkflowOptions = exports.WorkflowIdReusePolicy = void 0;
4
- const time_1 = require("./time");
5
- const type_helpers_1 = require("./type-helpers");
6
- // Avoid importing the proto implementation to reduce workflow bundle size
7
- // Copied from coresdk.common.WorkflowIdReusePolicy
8
- var WorkflowIdReusePolicy;
9
- (function (WorkflowIdReusePolicy) {
10
- WorkflowIdReusePolicy[WorkflowIdReusePolicy["WORKFLOW_ID_REUSE_POLICY_UNSPECIFIED"] = 0] = "WORKFLOW_ID_REUSE_POLICY_UNSPECIFIED";
11
- WorkflowIdReusePolicy[WorkflowIdReusePolicy["WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE"] = 1] = "WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE";
12
- WorkflowIdReusePolicy[WorkflowIdReusePolicy["WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY"] = 2] = "WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY";
13
- WorkflowIdReusePolicy[WorkflowIdReusePolicy["WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE"] = 3] = "WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE";
14
- })(WorkflowIdReusePolicy = exports.WorkflowIdReusePolicy || (exports.WorkflowIdReusePolicy = {}));
15
- (0, type_helpers_1.checkExtends)();
16
- function compileWorkflowOptions(options) {
17
- const { workflowExecutionTimeout, workflowRunTimeout, workflowTaskTimeout, ...rest } = options;
18
- return {
19
- ...rest,
20
- workflowExecutionTimeout: workflowExecutionTimeout ? (0, time_1.msToTs)(workflowExecutionTimeout) : undefined,
21
- workflowRunTimeout: workflowRunTimeout ? (0, time_1.msToTs)(workflowRunTimeout) : undefined,
22
- workflowTaskTimeout: workflowTaskTimeout ? (0, time_1.msToTs)(workflowTaskTimeout) : undefined,
23
- };
24
- }
25
- exports.compileWorkflowOptions = compileWorkflowOptions;
26
- //# sourceMappingURL=workflow-options.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"workflow-options.js","sourceRoot":"","sources":["../src/workflow-options.ts"],"names":[],"mappings":";;;AAGA,iCAAgC;AAChC,iDAA8C;AAE9C,0EAA0E;AAC1E,mDAAmD;AACnD,IAAY,qBAKX;AALD,WAAY,qBAAqB;IAC/B,iIAAwC,CAAA;IACxC,yIAA4C,CAAA;IAC5C,iKAAwD,CAAA;IACxD,2IAA6C,CAAA;AAC/C,CAAC,EALW,qBAAqB,GAArB,6BAAqB,KAArB,6BAAqB,QAKhC;AAED,IAAA,2BAAY,GAA+D,CAAC;AAoG5E,SAAgB,sBAAsB,CACpC,OAAU;IAEV,MAAM,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;IAE/F,OAAO;QACL,GAAG,IAAI;QACP,wBAAwB,EAAE,wBAAwB,CAAC,CAAC,CAAC,IAAA,aAAM,EAAC,wBAAwB,CAAC,CAAC,CAAC,CAAC,SAAS;QACjG,kBAAkB,EAAE,kBAAkB,CAAC,CAAC,CAAC,IAAA,aAAM,EAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,SAAS;QAC/E,mBAAmB,EAAE,mBAAmB,CAAC,CAAC,CAAC,IAAA,aAAM,EAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,SAAS;KACnF,CAAC;AACJ,CAAC;AAXD,wDAWC"}
@@ -1,97 +0,0 @@
1
- import type { coresdk } from '@temporalio/proto/lib/coresdk';
2
- import { RetryPolicy } from './retry-policy';
3
- import { checkExtends } from './type-helpers';
4
-
5
- // Avoid importing the proto implementation to reduce workflow bundle size
6
- // Copied from coresdk.workflow_commands.ActivityCancellationType
7
- export enum ActivityCancellationType {
8
- TRY_CANCEL = 0,
9
- WAIT_CANCELLATION_COMPLETED = 1,
10
- ABANDON = 2,
11
- }
12
-
13
- checkExtends<coresdk.workflow_commands.ActivityCancellationType, ActivityCancellationType>();
14
-
15
- /**
16
- * Options for remote activity invocation - will be processed from a task queue.
17
- * @see https://www.javadoc.io/doc/io.temporal/temporal-sdk/latest/io/temporal/activity/ActivityOptions.Builder.html
18
- */
19
- export interface ActivityOptions {
20
- /**
21
- * Identifier to use for tracking the activity in Workflow history.
22
- * The `activityId` can be accessed by the activity function.
23
- * Does not need to be unique.
24
- *
25
- * @default an incremental sequence number
26
- */
27
- activityId?: string;
28
-
29
- /**
30
- * Namespace to schedule this activity in.
31
- * @default current worker namespace
32
- */
33
- namespace?: string;
34
-
35
- /**
36
- * Task queue name.
37
- *
38
- * @default current worker task queue
39
- */
40
- taskQueue?: string;
41
-
42
- /**
43
- * Heartbeat interval. Activity must heartbeat before this interval passes after a last heartbeat or activity start.
44
- * @format {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
45
- */
46
- heartbeatTimeout?: string | number;
47
-
48
- /**
49
- * RetryPolicy that define how activity is retried in case of failure. If this is not set, then the server-defined default activity retry policy will be used. To ensure zero retries, set maximum attempts to 1.
50
- */
51
- retry?: RetryPolicy;
52
-
53
- /**
54
- * Maximum time of a single Activity execution attempt.
55
- Note that the Temporal Server doesn't detect Worker process failures directly. It relies on this timeout to detect that an Activity that didn't complete on time. So this timeout should be as short as the longest possible execution of the Activity body. Potentially long running Activities must specify {@link heartbeatTimeout} and call {@link activity.Context.heartbeat} periodically for timely failure detection.
56
-
57
- * Either this option or {@link scheduleToCloseTimeout} is required.
58
- * @format {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
59
- */
60
- startToCloseTimeout?: string | number;
61
- /**
62
- * Time that the Activity Task can stay in the Task Queue before it is picked up by a Worker. Do not specify this timeout unless using host specific Task Queues for Activity Tasks are being used for routing.
63
- * `scheduleToStartTimeout` is always non-retryable. Retrying after this timeout doesn't make sense as it would just put the Activity Task back into the same Task Queue.
64
- * @default unlimited
65
- * @format {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
66
- */
67
- scheduleToStartTimeout?: string | number;
68
-
69
- /**
70
- * Total time that a workflow is willing to wait for Activity to complete.
71
- * `scheduleToCloseTimeout` limits the total time of an Activity's execution including retries (use {@link startToCloseTimeout} to limit the time of a single attempt).
72
- *
73
- * Either this option or {@link startToCloseTimeout} is required
74
- * @default unlimited
75
- * @format {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
76
- */
77
- scheduleToCloseTimeout?: string | number;
78
-
79
- /**
80
- * Determines what the SDK does when the Activity is cancelled.
81
- * - `TRY_CANCEL` - Initiate a cancellation request and immediately report cancellation to the workflow.
82
- * - `WAIT_CANCELLATION_COMPLETED` - Wait for activity cancellation completion. Note that activity must heartbeat to receive a
83
- * cancellation notification. This can block the cancellation for a long time if activity doesn't
84
- * heartbeat or chooses to ignore the cancellation request.
85
- * - `ABANDON` - Do not request cancellation of the activity and immediately report cancellation to the workflow.
86
- */
87
- cancellationType?: coresdk.workflow_commands.ActivityCancellationType;
88
- }
89
-
90
- export interface ActivityFunction<P extends any[], R> {
91
- (...args: P): Promise<R>;
92
- }
93
-
94
- /**
95
- * Mapping of Activity name to function
96
- */
97
- export type ActivityInterface = Record<string, ActivityFunction<any[], any>>;
package/src/errors.ts DELETED
@@ -1,27 +0,0 @@
1
- export class ValueError extends Error {
2
- public readonly name: string = 'ValueError';
3
- }
4
-
5
- export class DataConverterError extends Error {
6
- public readonly name: string = 'DataConverterError';
7
- }
8
-
9
- /**
10
- * Used in different parts of the project to signal that something unexpected has happened
11
- */
12
- export class IllegalStateError extends Error {
13
- public readonly name: string = 'IllegalStateError';
14
- }
15
-
16
- /**
17
- * Get error message from an Error or string or return undefined
18
- */
19
- export function errorMessage(err: unknown): string | undefined {
20
- if (typeof err === 'string') {
21
- return err;
22
- }
23
- if (err instanceof Error) {
24
- return err.message;
25
- }
26
- return undefined;
27
- }
@@ -1,32 +0,0 @@
1
- import type { coresdk } from '@temporalio/proto/lib/coresdk';
2
- import { AnyFunc, OmitLastParam } from './type-helpers';
3
-
4
- /**
5
- * Type of the next function for a given interceptor function
6
- *
7
- * Called from an interceptor to continue the interception chain
8
- */
9
- export type Next<IF, FN extends keyof IF> = Required<IF>[FN] extends AnyFunc ? OmitLastParam<Required<IF>[FN]> : never;
10
-
11
- /** Headers are just a mapping of header name to Payload */
12
- export type Headers = Record<string, coresdk.common.IPayload>;
13
-
14
- /**
15
- * Composes all interceptor methods into a single function
16
- *
17
- * @param interceptors a list of interceptors
18
- * @param method the name of the interceptor method to compose
19
- * @param next the original function to be executed at the end of the interception chain
20
- */
21
- export function composeInterceptors<I, M extends keyof I>(interceptors: I[], method: M, next: Next<I, M>): Next<I, M> {
22
- for (let i = interceptors.length - 1; i >= 0; --i) {
23
- const interceptor = interceptors[i];
24
- if (interceptor[method] !== undefined) {
25
- const prev = next;
26
- // We loose type safety here because Typescript can't deduce that interceptor[method] is a function that returns
27
- // the same type as Next<I, M>
28
- next = ((input: any) => (interceptor[method] as any)(input, prev)) as any;
29
- }
30
- }
31
- return next;
32
- }
package/src/interfaces.ts DELETED
@@ -1,37 +0,0 @@
1
- /** Type that can be returned from a Workflow `execute` function */
2
- export type WorkflowReturnType = Promise<any>;
3
- export type WorkflowSignalType = (...args: any[]) => Promise<void> | void;
4
- export type WorkflowQueryType = (...args: any[]) => any;
5
-
6
- /**
7
- * Broad Workflow function definition, specific Workflows will typically use a narrower type definition, e.g:
8
- * ```ts
9
- * export async function myWorkflow(arg1: number, arg2: string): Promise<string>;
10
- * ```
11
- */
12
- export type Workflow = (...args: any[]) => WorkflowReturnType;
13
-
14
- /**
15
- * An interface representing a Workflow signal definition, as returned from {@link defineSignal}
16
- *
17
- * @remarks `_Args` can be used for parameter type inference in handler functions and *WorkflowHandle methods.
18
- */
19
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
20
- export interface SignalDefinition<_Args extends any[] = []> {
21
- type: 'signal';
22
- name: string;
23
- }
24
-
25
- /**
26
- * An interface representing a Workflow query definition as returned from {@link defineQuery}
27
- *
28
- * @remarks `_Args` and `_Ret` can be used for parameter type inference in handler functions and *WorkflowHandle methods.
29
- */
30
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
31
- export interface QueryDefinition<_Ret, _Args extends any[] = []> {
32
- type: 'query';
33
- name: string;
34
- }
35
-
36
- /** Get the "unwrapped" return type (without Promise) of the execute handler from Workflow type `W` */
37
- export type WorkflowResultType<W extends Workflow> = ReturnType<W> extends Promise<infer R> ? R : never;
package/src/otel.ts DELETED
@@ -1,61 +0,0 @@
1
- import * as otel from '@opentelemetry/api';
2
- import { defaultDataConverter } from './converter/data-converter';
3
- import { Headers } from './interceptors';
4
-
5
- /** Default trace header for opentelemetry interceptors */
6
- export const TRACE_HEADER = '_tracer-data';
7
- /** As in workflow run id */
8
- export const RUN_ID_ATTR_KEY = 'run_id';
9
- /** For a workflow or activity task */
10
- export const TASK_TOKEN_ATTR_KEY = 'task_token';
11
- /** Number of jobs in a workflow activation */
12
- export const NUM_JOBS_ATTR_KEY = 'num_jobs';
13
-
14
- /**
15
- * If found, return an otel Context deserialized from the provided headers
16
- */
17
- export async function extractContextFromHeaders(headers: Headers): Promise<otel.Context | undefined> {
18
- const encodedSpanContext = headers[TRACE_HEADER];
19
- if (encodedSpanContext === undefined) {
20
- return undefined;
21
- }
22
- const textMap: Record<string, string> = await defaultDataConverter.fromPayload(encodedSpanContext);
23
- return otel.propagation.extract(otel.context.active(), textMap, otel.defaultTextMapGetter);
24
- }
25
-
26
- /**
27
- * If found, return an otel SpanContext deserialized from the provided headers
28
- */
29
- export async function extractSpanContextFromHeaders(headers: Headers): Promise<otel.SpanContext | undefined> {
30
- const context = await extractContextFromHeaders(headers);
31
- if (context === undefined) {
32
- return undefined;
33
- }
34
-
35
- return otel.trace.getSpanContext(context);
36
- }
37
-
38
- /**
39
- * Given headers, return new headers with the current otel context inserted
40
- */
41
- export async function headersWithContext(headers: Headers): Promise<Headers> {
42
- const carrier = {};
43
- otel.propagation.inject(otel.context.active(), carrier, otel.defaultTextMapSetter);
44
- return { ...headers, [TRACE_HEADER]: await defaultDataConverter.toPayload(carrier) };
45
- }
46
-
47
- /**
48
- * Link a span to an maybe-existing span context
49
- */
50
- export function linkSpans(fromSpan: otel.Span, toContext?: otel.SpanContext): void {
51
- if (toContext !== undefined) {
52
- // TODO: I have to go around typescript because otel api 😢
53
- // See https://github.com/open-telemetry/opentelemetry-js-api/issues/124
54
- const links = (fromSpan as any).links;
55
- if (links === undefined) {
56
- (fromSpan as any).links = [{ context: toContext }];
57
- } else {
58
- links.push({ context: toContext });
59
- }
60
- }
61
- }
@@ -1,73 +0,0 @@
1
- import type { temporal } from '@temporalio/proto';
2
- import { ValueError } from '.';
3
- import { msOptionalToNumber, msOptionalToTs, msToNumber, msToTs } from './time';
4
-
5
- /**
6
- * Options for retrying Workflows and Activities
7
- */
8
- export interface RetryPolicy {
9
- /**
10
- * Coefficient used to calculate the next retry interval.
11
- * The next retry interval is previous interval multiplied by this coefficient.
12
- * @minimum 1
13
- * @default 2
14
- */
15
- backoffCoefficient?: number;
16
- /**
17
- * Interval of the first retry.
18
- * If coefficient is 1 then it is used for all retries
19
- * @format {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
20
- * @default 1 second
21
- */
22
- initialInterval?: string | number;
23
- /**
24
- * Maximum number of attempts. When exceeded the retries stop even if not expired yet.
25
- * @minimum 1
26
- * @default Infinity
27
- */
28
- maximumAttempts?: number;
29
- /**
30
- * Maximum interval between retries.
31
- * Exponential backoff leads to interval increase.
32
- * This value is the cap of the increase.
33
- *
34
- * @default 100x of {@link initialInterval}
35
- * @format {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
36
- */
37
- maximumInterval?: string | number;
38
-
39
- /**
40
- * List of application failures types to not retry.
41
- */
42
- nonRetryableErrorTypes?: string[];
43
- }
44
-
45
- /**
46
- * Turns a TS RetryPolicy into a proto compatible RetryPolicy
47
- */
48
- export function compileRetryPolicy(retryPolicy: RetryPolicy): temporal.api.common.v1.IRetryPolicy {
49
- if (retryPolicy.backoffCoefficient != null && retryPolicy.backoffCoefficient <= 0) {
50
- throw new ValueError('RetryPolicy.backoffCoefficient must be greater than 0');
51
- }
52
- if (retryPolicy.maximumAttempts != null && retryPolicy.maximumAttempts <= 0) {
53
- throw new ValueError('RetryPolicy.maximumAttempts must be greater than 0');
54
- }
55
- const maximumInterval = msOptionalToNumber(retryPolicy.maximumInterval);
56
- const initialInterval = msToNumber(retryPolicy.initialInterval ?? 1000);
57
- if (maximumInterval === 0) {
58
- throw new ValueError('RetryPolicy.maximumInterval cannot be 0');
59
- }
60
- if (initialInterval === 0) {
61
- throw new ValueError('RetryPolicy.initialInterval cannot be 0');
62
- }
63
- if (maximumInterval != null && maximumInterval < initialInterval) {
64
- throw new ValueError('RetryPolicy.maximumInterval cannot be less than its initialInterval');
65
- }
66
- return {
67
- maximumAttempts: retryPolicy.maximumAttempts,
68
- initialInterval: msToTs(initialInterval),
69
- maximumInterval: msOptionalToTs(maximumInterval),
70
- backoffCoefficient: retryPolicy.backoffCoefficient,
71
- nonRetryableErrorTypes: retryPolicy.nonRetryableErrorTypes,
72
- };
73
- }
package/src/time.ts DELETED
@@ -1,72 +0,0 @@
1
- import Long from 'long';
2
- import ms from 'ms';
3
- import type * as iface from '@temporalio/proto/lib/coresdk';
4
- import { ValueError } from './errors';
5
-
6
- // NOTE: these are the same interface in JS
7
- // iface.google.protobuf.IDuration;
8
- // iface.google.protobuf.ITimestamp;
9
- // The conversion functions below should work for both
10
-
11
- export type Timestamp = iface.google.protobuf.ITimestamp;
12
-
13
- /**
14
- * Lossy conversion function from Timestamp to number due to possible overflow.
15
- * If ts is null or undefined returns undefined.
16
- */
17
- export function optionalTsToMs(ts: Timestamp | null | undefined): number | undefined {
18
- if (ts === undefined || ts === null) {
19
- return undefined;
20
- }
21
- return tsToMs(ts);
22
- }
23
-
24
- /**
25
- * Lossy conversion function from Timestamp to number due to possible overflow
26
- */
27
- export function tsToMs(ts: Timestamp | null | undefined): number {
28
- if (ts === undefined || ts === null) {
29
- throw new Error(`Expected timestamp, got ${ts}`);
30
- }
31
- const { seconds, nanos } = ts;
32
- return (seconds || Long.UZERO)
33
- .mul(1000)
34
- .add(Math.floor((nanos || 0) / 1000000))
35
- .toNumber();
36
- }
37
-
38
- export function msNumberToTs(millis: number): Timestamp {
39
- const seconds = Math.floor(millis / 1000);
40
- const nanos = (millis % 1000) * 1000000;
41
- if (Number.isNaN(seconds) || Number.isNaN(nanos)) {
42
- throw new ValueError(`Invalid millis ${millis}`);
43
- }
44
- return { seconds: Long.fromNumber(seconds), nanos };
45
- }
46
-
47
- export function msToTs(str: string | number): Timestamp {
48
- if (typeof str === 'number') {
49
- return msNumberToTs(str);
50
- }
51
- return msNumberToTs(ms(str));
52
- }
53
-
54
- export function msOptionalToTs(str: string | number | undefined): Timestamp | undefined {
55
- if (str === undefined) return undefined;
56
- if (typeof str === 'number') {
57
- return msNumberToTs(str);
58
- }
59
- return msNumberToTs(ms(str));
60
- }
61
-
62
- export function msOptionalToNumber(val: string | number | undefined): number | undefined {
63
- if (val === undefined) return undefined;
64
- return msToNumber(val);
65
- }
66
-
67
- export function msToNumber(val: string | number): number {
68
- if (typeof val === 'number') {
69
- return val;
70
- }
71
- return ms(val);
72
- }
package/src/tls-config.ts DELETED
@@ -1,35 +0,0 @@
1
- /** TLS configuration options. */
2
- export interface TLSConfig {
3
- /**
4
- * Overrides the target name used for SSL host name checking.
5
- * If this attribute is not specified, the name used for SSL host name checking will be the host from {@link ServerOptions.url}.
6
- * This _should_ be used for testing only.
7
- */
8
- serverNameOverride?: string;
9
- /**
10
- * Root CA certificate used by the server. If not set, and the server's
11
- * cert is issued by someone the operating system trusts, verification will still work (ex: Cloud offering).
12
- */
13
- serverRootCACertificate?: Buffer;
14
- /** Sets the client certificate and key for connecting with mTLS */
15
- clientCertPair?: {
16
- /** The certificate for this client */
17
- crt: Buffer;
18
- /** The private key for this client */
19
- key: Buffer;
20
- };
21
- }
22
-
23
- /**
24
- * TLS configuration.
25
- * Pass a falsy value to use a non-encrypted connection or `true` or `{}` to
26
- * connect with TLS without any customization.
27
- */
28
- export type TLSConfigOption = TLSConfig | boolean | null;
29
-
30
- /**
31
- * Normalize {@link TLSConfigOption} by turning false and null to undefined and true to and empty object
32
- */
33
- export function normalizeTlsConfig(tls?: TLSConfigOption): TLSConfig | undefined {
34
- return typeof tls === 'object' ? (tls === null ? undefined : tls) : tls ? {} : undefined;
35
- }
@@ -1,11 +0,0 @@
1
- /** Shorthand alias */
2
- export type AnyFunc = (...args: any[]) => any;
3
- /** A tuple without its last element */
4
- export type OmitLast<T> = T extends [...infer REST, any] ? REST : never;
5
- /** F with all arguments but the last */
6
- export type OmitLastParam<F extends AnyFunc> = (...args: OmitLast<Parameters<F>>) => ReturnType<F>;
7
-
8
- /** Verify that an type _Copy extends _Orig */
9
- export function checkExtends<_Orig, _Copy extends _Orig>(): void {
10
- // noop, just type check
11
- }
package/src/utils.ts DELETED
@@ -1,6 +0,0 @@
1
- /**
2
- * Helper to prevent undefined and null values overriding defaults when merging maps
3
- */
4
- export function filterNullAndUndefined<T extends Record<string, any>>(obj: T): T {
5
- return Object.fromEntries(Object.entries(obj).filter(([_k, v]) => v != null)) as any;
6
- }
@@ -1,30 +0,0 @@
1
- import { Workflow, WorkflowResultType, SignalDefinition } from './interfaces';
2
-
3
- /**
4
- * Base WorkflowHandle interface, extended in workflow and client libs.
5
- *
6
- * Transforms a workflow interface `T` into a client interface.
7
- */
8
- export interface BaseWorkflowHandle<T extends Workflow> {
9
- /**
10
- * Promise that resolves when Workflow execution completes
11
- */
12
- result(): Promise<WorkflowResultType<T>>;
13
-
14
- /**
15
- * Signal a running Workflow.
16
- *
17
- * @param def a signal definition as returned from {@link defineSignal}
18
- *
19
- * @example
20
- * ```ts
21
- * await handle.signal(incrementSignal, 3);
22
- * ```
23
- */
24
- signal<Args extends any[] = []>(def: SignalDefinition<Args> | string, ...args: Args): Promise<void>;
25
-
26
- /**
27
- * The workflowId of the current Workflow
28
- */
29
- readonly workflowId: string;
30
- }