Skip to content

Commit d11d914

Browse files
authored
docs: Review API docs (#744)
1 parent 46957e3 commit d11d914

File tree

23 files changed

+4515
-3222
lines changed

23 files changed

+4515
-3222
lines changed

packages/activity/src/index.ts

Lines changed: 69 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,42 @@
11
/**
2-
* This library provides tools for authoring activities.
2+
* This package's main export is {@link Context}. Get the current Activity's context with
3+
* {@link Context.current | `Context.current()`}:
34
*
4-
* Import this module from Activity code - must **not** be used in Workflows.
5+
* ```ts
6+
* import { Context } from '@temporalio/activity';
57
*
6-
* Any function can be used as an Activity as long as its parameters and return value are serializable using a [`DataConverter`](../interfaces/worker.DataConverter.md).
8+
* export async function myActivity() {
9+
* const context = Context.current();
10+
* }
11+
* ```
12+
*
13+
* Any function can be used as an Activity as long as its parameters and return value are serializable using a
14+
* {@link https://docs.temporal.io/concepts/what-is-a-data-converter/ | DataConverter}.
715
*
816
* ### Cancellation
9-
* Activities may be cancelled only if they [emit heartbeats](../classes/activity.Context.md#heartbeat).<br/>
10-
* There are 2 ways to handle Activity cancellation:
11-
* 1. await on [`Context.current().cancelled`](../classes/activity.Context.md#cancelled)
12-
* 1. Pass the context's [abort signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) at [`Context.current().cancellationSignal`](../classes/activity.Context.md#cancellationsignal) to a library that supports it
17+
*
18+
* Activities may be cancelled only if they {@link Context.heartbeat | emit heartbeats}.
19+
*
20+
* There are two ways to handle Activity cancellation:
21+
* 1. await on {@link Context.cancelled | `Context.current().cancelled`} or
22+
* {@link Context.sleep | `Context.current().sleep()`}, which each throw a
23+
* {@link CancelledFailure}.
24+
* 1. Pass the context's {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} at
25+
* {@link Context.cancellationSignal | `Context.current().cancellationSignal`} to a library that
26+
* supports it.
1327
*
1428
* ### Examples
1529
*
16-
* #### An Activity that fakes progress and can be cancelled
30+
* #### An Activity that sends progress heartbeats and can be cancelled
1731
*
1832
* <!--SNIPSTART typescript-activity-fake-progress-->
1933
* <!--SNIPEND-->
2034
*
2135
* #### An Activity that makes a cancellable HTTP request
2236
*
37+
* It passes the `AbortSignal` to {@link https://github.com/node-fetch/node-fetch#api | `fetch`}: `fetch(url, { signal:
38+
* Context.current().cancellationSignal })`.
39+
*
2340
* <!--SNIPSTART typescript-activity-cancellable-fetch-->
2441
* <!--SNIPEND-->
2542
*
@@ -38,11 +55,21 @@ export {
3855
export * from '@temporalio/internal-workflow-common/lib/errors';
3956

4057
/**
41-
* Throw this error from an Activity in order to make the Worker
42-
* forget about this Activity.
58+
* Throw this error from an Activity in order to make the Worker forget about this Activity.
59+
*
60+
* The Activity can then be completed asynchronously (from anywhere—usually outside the Worker) using
61+
* {@link AsyncCompletionClient}.
62+
*
63+
* @example
4364
*
44-
* The Activity can be completed asynchronously using
45-
* {@link AsyncCompletionClient}
65+
*```ts
66+
*import { CompleteAsyncError } from '@temporalio/activity';
67+
*
68+
*export async function myActivity(): Promise<never> {
69+
* // ...
70+
* throw new CompleteAsyncError();
71+
*}
72+
*```
4673
*/
4774
export class CompleteAsyncError extends Error {
4875
public readonly name: string = 'CompleteAsyncError';
@@ -56,7 +83,7 @@ export class CompleteAsyncError extends Error {
5683
export const asyncLocalStorage = new AsyncLocalStorage<Context>();
5784

5885
/**
59-
* Holds information about the current executing Activity
86+
* Holds information about the current Activity Execution. Retrieved inside an Activity with `Context.current().info`.
6087
*/
6188
export interface Info {
6289
taskToken: Uint8Array;
@@ -124,9 +151,14 @@ export interface Info {
124151
}
125152

126153
/**
127-
* Activity Context manager.
154+
* Activity Context, used to:
155+
*
156+
* - Get {@link Info} about the current Activity Execution
157+
* - Send {@link https://docs.temporal.io/concepts/what-is-an-activity-heartbeat | heartbeats}
158+
* - Get notified of Activity cancellation
159+
* - Sleep (cancellation-aware)
128160
*
129-
* Call `Context.current()` from Activity code in order to send heartbeats and get notified of Activity cancellation.
161+
* Call `Context.current()` from Activity code in order to get the current Activity's Context.
130162
*/
131163
export class Context {
132164
/**
@@ -136,13 +168,21 @@ export class Context {
136168
/**
137169
* Await this promise in an Activity to get notified of cancellation.
138170
*
139-
* This promise will never be resolved, it will only be rejected with a {@link CancelledFailure}.
171+
* This promise will never resolve—it will only be rejected with a {@link CancelledFailure}.
172+
*
173+
* @see [Cancellation](/api/namespaces/activity#cancellation)
140174
*/
141175
public readonly cancelled: Promise<never>;
142176
/**
143-
* An `AbortSignal` which can be used to cancel requests on Activity cancellation.
177+
* An {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} that can be used to react to
178+
* Activity cancellation.
144179
*
145-
* Typically used by the {@link https://www.npmjs.com/package/node-fetch#request-cancellation-with-abortsignal | fetch} and {@link https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options child_process} libraries but is supported by a few other libraries as well.
180+
* Used by {@link https://www.npmjs.com/package/node-fetch#request-cancellation-with-abortsignal | fetch} to abort an
181+
* in-progress request and
182+
* {@link https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options child_process}
183+
* to abort a child process, and is supported by some other libraries as well.
184+
*
185+
* @see [Cancellation](/api/namespaces/activity#cancellation)
146186
*/
147187
public readonly cancellationSignal: AbortSignal;
148188
/**
@@ -168,11 +208,17 @@ export class Context {
168208
}
169209

170210
/**
171-
* Send a heartbeat from an Activity.
211+
* Send a {@link https://docs.temporal.io/concepts/what-is-an-activity-heartbeat | heartbeat} from an Activity.
212+
*
213+
* If an Activity times out, then during the next retry, the last value of `details` is available at
214+
* {@link Info.heartbeatDetails}. This acts as a periodic checkpoint mechanism for the progress of an Activity.
172215
*
173-
* If an Activity times out, the last value of details is included in the {@link ActivityFailure} delivered to a Workflow in the `cause` attribute which will be set to {@link TimeoutFailure}. Then the Workflow can pass the details to the next Activity invocation. This acts as a periodic checkpoint mechanism for the progress of an Activity.
216+
* If an Activity times out on the final retry (relevant in cases in which {@link RetryPolicy.maximumAttempts} is
217+
* set), the Activity function call in the Workflow code will throw an {@link ActivityFailure} with the `cause`
218+
* attribute set to a {@link TimeoutFailure}, which has the last value of `details` available at
219+
* {@link TimeoutFailure.lastHeartbeatDetails}.
174220
*
175-
* The Activity must heartbeat in order to receive cancellation.
221+
* Activities must heartbeat in order to receive cancellation.
176222
*/
177223
public heartbeat(details?: unknown): void {
178224
this.heartbeatFn(details);
@@ -193,8 +239,8 @@ export class Context {
193239

194240
/**
195241
* Helper function for sleeping in an Activity.
196-
* @param ms sleep duration - {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
197-
* @returns a Promise that either resolves when deadline is reached or rejects when the Context is cancelled
242+
* @param ms Sleep duration: an {@link https://www.npmjs.com/package/ms | ms}-formatted string or number of milliseconds
243+
* @returns A Promise that either resolves when `ms` is reached or rejects when the Activity is cancelled
198244
*/
199245
public sleep(ms: number | string): Promise<void> {
200246
let handle: NodeJS.Timeout;

packages/client/src/async-completion-client.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,16 @@ import { isServerErrorResponse } from './errors';
1313
import { ConnectionLike, WorkflowService } from './types';
1414

1515
/**
16-
* Thrown by {@link AsyncCompletionClient} when trying to complete or heartbeat
17-
* an Activity which does not exist in the system.
16+
* Thrown by {@link AsyncCompletionClient} when trying to complete or heartbeat an Activity that does not exist in the
17+
* system.
1818
*/
1919
export class ActivityNotFoundError extends Error {
2020
public readonly name = 'ActivityNotFoundError';
2121
}
2222

2323
/**
2424
* Thrown by {@link AsyncCompletionClient} when trying to complete or heartbeat
25-
* an Activity for any reason apart from "not found".
25+
* an Activity for any reason apart from {@link ActivityNotFoundError}.
2626
*/
2727
export class ActivityCompletionError extends Error {
2828
public readonly name = 'ActivityCompletionError';

packages/client/src/connection.ts

Lines changed: 35 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import pkg from './pkg';
88
import { CallContext, Metadata, OperatorService, WorkflowService } from './types';
99

1010
/**
11-
* GRPC + Temporal server connection options
11+
* gRPC and Temporal Server connection options
1212
*/
1313
export interface ConnectionOptions {
1414
/**
@@ -147,25 +147,35 @@ export interface ConnectionCtorOptions {
147147
}
148148

149149
/**
150-
* Client connection to the Temporal Service
150+
* Client connection to the Temporal Server
151151
*
152-
* NOTE: Connections are expensive to construct and should be reused.
153-
* Make sure to `close()` any unused connections to avoid leaking resources.
152+
* ⚠️ Connections are expensive to construct and should be reused. Make sure to {@link close} any unused connections to
153+
* avoid leaking resources.
154154
*/
155155
export class Connection {
156+
/**
157+
* @internal
158+
*/
156159
public static readonly Client = grpc.makeGenericClientConstructor({}, 'WorkflowService', {});
157160

158161
public readonly options: ConnectionOptionsWithDefaults;
159162
protected readonly client: grpc.Client;
163+
160164
/**
161165
* Used to ensure `ensureConnected` is called once.
162166
*/
163167
protected connectPromise?: Promise<void>;
164168

165169
/**
166-
* Raw gRPC access to the Temporal service.
170+
* Raw gRPC access to Temporal Server's {@link
171+
* https://github.com/temporalio/api/blob/master/temporal/api/workflowservice/v1/service.proto | Workflow service}
167172
*/
168173
public readonly workflowService: WorkflowService;
174+
175+
/**
176+
* Raw gRPC access to Temporal Server's
177+
* {@link https://github.com/temporalio/api/blob/master/temporal/api/operatorservice/v1/service.proto | Operator service}
178+
*/
169179
public readonly operatorService: OperatorService;
170180
readonly callContextStorage: AsyncLocalStorage<CallContext>;
171181

@@ -213,9 +223,11 @@ export class Connection {
213223
/**
214224
* Ensure connection can be established.
215225
*
226+
* Does not need to be called if you use {@link connect}.
227+
*
216228
* This method's result is memoized to ensure it runs only once.
217229
*
218-
* Calls WorkflowService.getSystemInfo internally.
230+
* Calls {@link proto.temporal.api.workflowservice.v1.WorkflowService.getSystemInfo} internally.
219231
*/
220232
async ensureConnected(): Promise<void> {
221233
if (this.connectPromise == null) {
@@ -241,19 +253,19 @@ export class Connection {
241253
}
242254

243255
/**
244-
* Create a lazy Connection instance.
256+
* Create a lazy `Connection` instance.
245257
*
246-
* This method does not verify connectivity with the server, it is recommended to use
247-
* {@link connect} instead.
258+
* This method does not verify connectivity with the server. We recommend using {@link connect} instead.
248259
*/
249260
static lazy(options?: ConnectionOptions): Connection {
250261
return new this(this.createCtorOptions(options));
251262
}
252263

253264
/**
254-
* Establish a connection with the server and return a Connection instance.
265+
* Establish a connection with the server and return a `Connection` instance.
255266
*
256-
* This is the preferred method of creating connections as it verifies connectivity.
267+
* This is the preferred method of creating connections as it verifies connectivity by calling
268+
* {@link ensureConnected}.
257269
*/
258270
static async connect(options?: ConnectionOptions): Promise<Connection> {
259271
const conn = this.lazy(options);
@@ -303,29 +315,31 @@ export class Connection {
303315

304316
/**
305317
* Set the deadline for any service requests executed in `fn`'s scope.
318+
*
319+
* @returns value returned from `fn`
306320
*/
307-
async withDeadline<R>(deadline: number | Date, fn: () => Promise<R>): Promise<R> {
321+
async withDeadline<ReturnType>(deadline: number | Date, fn: () => Promise<ReturnType>): Promise<ReturnType> {
308322
const cc = this.callContextStorage.getStore();
309323
return await this.callContextStorage.run({ deadline, metadata: cc?.metadata }, fn);
310324
}
311325

312326
/**
313327
* Set metadata for any service requests executed in `fn`'s scope.
314328
*
315-
* The provided metadata is merged on top of any existing metadata in current scope
316-
* including metadata provided in {@link ConnectionOptions.metadata}
329+
* The provided metadata is merged on top of any existing metadata in current scope, including metadata provided in
330+
* {@link ConnectionOptions.metadata}.
317331
*
318-
* @returns returned value of `fn`
332+
* @returns value returned from `fn`
319333
*
320334
* @example
321335
*
322-
* ```ts
323-
* await conn.withMetadata({ apiKey: 'secret' }, () =>
324-
* conn.withMetadata({ otherKey: 'set' }, () => client.start(options)))
325-
* );
326-
* ```
336+
*```ts
337+
*const workflowHandle = await conn.withMetadata({ apiKey: 'secret' }, () =>
338+
* conn.withMetadata({ otherKey: 'set' }, () => client.start(options)))
339+
*);
340+
*```
327341
*/
328-
async withMetadata<R>(metadata: Metadata, fn: () => Promise<R>): Promise<R> {
342+
async withMetadata<ReturnType>(metadata: Metadata, fn: () => Promise<ReturnType>): Promise<ReturnType> {
329343
const cc = this.callContextStorage.getStore();
330344
metadata = { ...cc?.metadata, ...metadata };
331345
return await this.callContextStorage.run({ metadata, deadline: cc?.deadline }, fn);

packages/client/src/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/**
2-
* Client for communicating with the Temporal service.
2+
* Client for communicating with Temporal Server.
33
*
4-
* Interact with workflows using {@link WorkflowClient} or call GRPC methods directly using {@link Connection.workflowService}.
4+
* Most functionality is available through {@link WorkflowClient}, but you can also call gRPC methods directly using {@link Connection.workflowService} and {@link Connection.operatorService}.
55
*
66
* ### Usage
77
* <!--SNIPSTART typescript-hello-client-->

packages/client/src/workflow-client.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -906,9 +906,9 @@ export class WorkflowClient {
906906
* most recent Workflow Execution in the *Chain* that started with `firstExecutionRunId`.
907907
*
908908
* A *Chain* is a series of Workflow Executions that share the same Workflow ID and are connected by:
909-
* - Being part of the same [Cron](https://docs.temporal.io/typescript/clients#scheduling-cron-workflows)
910-
* - [Continue As New](https://docs.temporal.io/typescript/workflows#continueasnew)
911-
* - [Retries](https://typescript.temporal.io/api/interfaces/client.workflowoptions/#retry)
909+
* - Being part of the same {@link https://docs.temporal.io/typescript/clients#scheduling-cron-workflows | Cron}
910+
* - {@link https://docs.temporal.io/typescript/workflows#continueasnew | Continue As New}
911+
* - {@link https://typescript.temporal.io/api/interfaces/client.workflowoptions/#retry | Retries}
912912
*
913913
* This method does not validate `workflowId`. If there is no Workflow Execution with the given `workflowId`, handle
914914
* methods like `handle.describe()` will throw a {@link WorkflowNotFoundError} error.

packages/common/src/converter/data-converter.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ import { defaultPayloadConverter } from './payload-converters';
77
* binary in a {@link Payload} Protobuf message.
88
*
99
* The default `DataConverter` supports `undefined`, `Uint8Array`, and JSON serializables (so if
10-
* [`JSON.stringify(yourArgOrRetval)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description)
11-
* works, the default data converter will work). Protobufs are supported via [this
12-
* API](https://docs.temporal.io/typescript/data-converters#protobufs).
10+
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description | `JSON.stringify(yourArgOrRetval)`}
11+
* works, the default data converter will work). Protobufs are supported via
12+
* {@link https://docs.temporal.io/typescript/data-converters#protobufs | this API}.
1313
*
1414
* Use a custom `DataConverter` to control the contents of your {@link Payload}s. Common reasons for using a custom
1515
* `DataConverter` are:

packages/common/src/converter/payload-converter.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { Payload } from './types';
33
/**
44
* Used by the framework to serialize/deserialize data like parameters and return values.
55
*
6-
* This is called inside the [Workflow isolate](https://docs.temporal.io/typescript/determinism).
6+
* This is called inside the {@link https://docs.temporal.io/typescript/determinism | Workflow isolate}.
77
* To write async code or use Node APIs (or use packages that use Node APIs), use a {@link PayloadCodec}.
88
*/
99
export interface PayloadConverter {

packages/common/src/converter/payload-converters.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,9 @@ export class DefaultPayloadConverter extends CompositePayloadConverter {
137137
}
138138

139139
/**
140-
* The default {@link PayloadConverter} used by the SDK.
141-
* Supports `Uint8Array` and JSON serializables (so if [`JSON.stringify(yourArgOrRetval)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description) works, the default payload converter will work).
140+
* The default {@link PayloadConverter} used by the SDK. Supports `Uint8Array` and JSON serializables (so if
141+
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description | `JSON.stringify(yourArgOrRetval)`}
142+
* works, the default payload converter will work).
142143
*
143144
* To also support Protobufs, create a custom payload converter with {@link DefaultPayloadConverter}:
144145
*

0 commit comments

Comments
 (0)