@hatchet-dev/typescript-sdk 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,8 +2,10 @@ import { Channel, ClientFactory } from 'nice-grpc';
2
2
  import { CreateWorkflowVersionOpts, RateLimitDuration, WorkflowServiceClient } from '../../protoc/workflows';
3
3
  import { ClientConfig } from '../hatchet-client/client-config';
4
4
  import { Logger } from '../../util/logger';
5
+ import WorkflowRunRef from '../../util/workflow-run-ref';
5
6
  import { Api } from '../rest';
6
- import { WorkflowRunStatus, WorkflowRunStatusList } from '../rest/generated/data-contracts';
7
+ import { WebhookWorkerCreateRequest, WorkflowRunStatus, WorkflowRunStatusList } from '../rest/generated/data-contracts';
8
+ import { ListenerClient } from '../listener/listener-client';
7
9
  type WorkflowMetricsQuery = {
8
10
  workflowId?: string;
9
11
  workflowName?: string;
@@ -32,7 +34,8 @@ export declare class AdminClient {
32
34
  api: Api;
33
35
  tenantId: string;
34
36
  logger: Logger;
35
- constructor(config: ClientConfig, channel: Channel, factory: ClientFactory, api: Api, tenantId: string);
37
+ listenerClient: ListenerClient;
38
+ constructor(config: ClientConfig, channel: Channel, factory: ClientFactory, api: Api, tenantId: string, listenerClient: ListenerClient);
36
39
  /**
37
40
  * @deprecated use putWorkflow instead
38
41
  */
@@ -48,6 +51,7 @@ export declare class AdminClient {
48
51
  */
49
52
  put_rate_limit(key: string, limit: number, duration: RateLimitDuration): Promise<void>;
50
53
  putRateLimit(key: string, limit: number, duration?: RateLimitDuration): Promise<void>;
54
+ registerWebhook(data: WebhookWorkerCreateRequest): Promise<import("axios").AxiosResponse<import("../rest/generated/data-contracts").WebhookWorkerCreated, any>>;
51
55
  /**
52
56
  * @deprecated use runWorkflow instead
53
57
  */
@@ -57,7 +61,7 @@ export declare class AdminClient {
57
61
  childIndex?: number | undefined;
58
62
  childKey?: string | undefined;
59
63
  additionalMetadata?: Record<string, string> | undefined;
60
- }): Promise<string>;
64
+ }): Promise<WorkflowRunRef<object>>;
61
65
  /**
62
66
  * Run a new instance of a workflow with the given input. This will create a new workflow run and return the ID of the
63
67
  * new run.
@@ -66,13 +70,13 @@ export declare class AdminClient {
66
70
  * @param options an object containing the options to run the workflow
67
71
  * @returns the ID of the new workflow run
68
72
  */
69
- runWorkflow<T = object>(workflowName: string, input: T, options?: {
73
+ runWorkflow<Q = object, P = object>(workflowName: string, input: Q, options?: {
70
74
  parentId?: string | undefined;
71
75
  parentStepRunId?: string | undefined;
72
76
  childIndex?: number | undefined;
73
77
  childKey?: string | undefined;
74
78
  additionalMetadata?: Record<string, string> | undefined;
75
- }): Promise<string>;
79
+ }): WorkflowRunRef<P>;
76
80
  /**
77
81
  * @deprecated use listWorkflows instead
78
82
  */
@@ -106,13 +110,13 @@ export declare class AdminClient {
106
110
  /**
107
111
  * @deprecated use getWorkflowRun instead
108
112
  */
109
- get_workflow_run(workflowRunId: string): Promise<import("../rest/generated/data-contracts").WorkflowRun>;
113
+ get_workflow_run(workflowRunId: string): Promise<WorkflowRunRef<unknown>>;
110
114
  /**
111
115
  * Get a workflow run.
112
116
  * @param workflowRunId the id of the workflow run to get
113
117
  * @returns the workflow run
114
118
  */
115
- getWorkflowRun(workflowRunId: string): Promise<import("../rest/generated/data-contracts").WorkflowRun>;
119
+ getWorkflowRun(workflowRunId: string): Promise<WorkflowRunRef<unknown>>;
116
120
  /**
117
121
  * @deprecated use listWorkflowRuns instead
118
122
  */
@@ -146,14 +150,17 @@ export declare class AdminClient {
146
150
  */
147
151
  schedule_workflow(name: string, options?: {
148
152
  schedules?: Date[];
153
+ input?: object;
149
154
  }): Promise<void>;
150
155
  /**
151
156
  * Schedule a workflow to run at a specific time or times.
152
157
  * @param name the name of the workflow to schedule
153
158
  * @param options an object containing the schedules to set
159
+ * @param input an object containing the input to the workflow
154
160
  */
155
161
  scheduleWorkflow(name: string, options?: {
156
162
  schedules?: Date[];
163
+ input?: object;
157
164
  }): void;
158
165
  /**
159
166
  * @deprecated use getWorkflowMetrics instead
@@ -17,6 +17,7 @@ const workflows_1 = require("../../protoc/workflows");
17
17
  const hatchet_error_1 = __importDefault(require("../../util/errors/hatchet-error"));
18
18
  const logger_1 = require("../../util/logger");
19
19
  const retrier_1 = require("../../util/retrier");
20
+ const workflow_run_ref_1 = __importDefault(require("../../util/workflow-run-ref"));
20
21
  /**
21
22
  * AdminClient is a client for interacting with the Hatchet Admin API. This allows you to configure, trigger,
22
23
  * and monitor workflows.
@@ -34,12 +35,13 @@ const retrier_1 = require("../../util/retrier");
34
35
  * ```
35
36
  */
36
37
  class AdminClient {
37
- constructor(config, channel, factory, api, tenantId) {
38
+ constructor(config, channel, factory, api, tenantId, listenerClient) {
38
39
  this.config = config;
39
40
  this.client = factory.create(workflows_1.WorkflowServiceDefinition, channel);
40
41
  this.api = api;
41
42
  this.tenantId = tenantId;
42
43
  this.logger = new logger_1.Logger(`Admin`, config.log_level);
44
+ this.listenerClient = listenerClient;
43
45
  }
44
46
  /**
45
47
  * @deprecated use putWorkflow instead
@@ -88,6 +90,11 @@ class AdminClient {
88
90
  }
89
91
  });
90
92
  }
93
+ registerWebhook(data) {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ return this.api.webhookCreate(this.tenantId, data);
96
+ });
97
+ }
91
98
  /**
92
99
  * @deprecated use runWorkflow instead
93
100
  */
@@ -105,22 +112,20 @@ class AdminClient {
105
112
  * @returns the ID of the new workflow run
106
113
  */
107
114
  runWorkflow(workflowName, input, options) {
108
- return __awaiter(this, void 0, void 0, function* () {
109
- let computedName = workflowName;
110
- try {
111
- if (this.config.namespace && !workflowName.startsWith(this.config.namespace)) {
112
- computedName = this.config.namespace + workflowName;
113
- }
114
- const inputStr = JSON.stringify(input);
115
- const resp = yield this.client.triggerWorkflow(Object.assign(Object.assign({ name: computedName, input: inputStr }, options), { additionalMetadata: (options === null || options === void 0 ? void 0 : options.additionalMetadata)
116
- ? JSON.stringify(options === null || options === void 0 ? void 0 : options.additionalMetadata)
117
- : undefined }));
118
- return resp.workflowRunId;
119
- }
120
- catch (e) {
121
- throw new hatchet_error_1.default(e.message);
115
+ let computedName = workflowName;
116
+ try {
117
+ if (this.config.namespace && !workflowName.startsWith(this.config.namespace)) {
118
+ computedName = this.config.namespace + workflowName;
122
119
  }
123
- });
120
+ const inputStr = JSON.stringify(input);
121
+ const resp = this.client.triggerWorkflow(Object.assign(Object.assign({ name: computedName, input: inputStr }, options), { additionalMetadata: (options === null || options === void 0 ? void 0 : options.additionalMetadata)
122
+ ? JSON.stringify(options === null || options === void 0 ? void 0 : options.additionalMetadata)
123
+ : undefined }));
124
+ return new workflow_run_ref_1.default(resp, this.listenerClient, options === null || options === void 0 ? void 0 : options.parentId);
125
+ }
126
+ catch (e) {
127
+ throw new hatchet_error_1.default(e.message);
128
+ }
124
129
  }
125
130
  /**
126
131
  * @deprecated use listWorkflows instead
@@ -196,8 +201,7 @@ class AdminClient {
196
201
  */
197
202
  getWorkflowRun(workflowRunId) {
198
203
  return __awaiter(this, void 0, void 0, function* () {
199
- const res = yield this.api.workflowRunGet(this.tenantId, workflowRunId);
200
- return res.data;
204
+ return new workflow_run_ref_1.default(workflowRunId, this.listenerClient);
201
205
  });
202
206
  }
203
207
  /**
@@ -231,12 +235,18 @@ class AdminClient {
231
235
  * Schedule a workflow to run at a specific time or times.
232
236
  * @param name the name of the workflow to schedule
233
237
  * @param options an object containing the schedules to set
238
+ * @param input an object containing the input to the workflow
234
239
  */
235
240
  scheduleWorkflow(name, options) {
236
241
  try {
242
+ let input;
243
+ if (options === null || options === void 0 ? void 0 : options.input) {
244
+ input = JSON.stringify(options.input);
245
+ }
237
246
  this.client.scheduleWorkflow({
238
247
  name,
239
248
  schedules: options === null || options === void 0 ? void 0 : options.schedules,
249
+ input,
240
250
  });
241
251
  }
242
252
  catch (e) {
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { Logger } from '../../../util/logger';
3
2
  import { DispatcherClient as PbDispatcherClient } from '../../../protoc/dispatcher';
4
3
  import { Worker } from 'worker_threads';
@@ -29,4 +29,5 @@ export declare class HatchetClient {
29
29
  static init(config?: Partial<ClientConfig>, options?: HatchetClientOptions, axiosConfig?: AxiosRequestConfig): HatchetClient;
30
30
  run(workflow: string | Workflow): Promise<Worker>;
31
31
  worker(workflow: string | Workflow, maxRuns?: number): Promise<Worker>;
32
+ webhooks(workflows: Workflow[]): import("../worker/handler").WebhookHandler;
32
33
  }
@@ -111,8 +111,8 @@ class HatchetClient {
111
111
  this.api = (0, rest_1.default)(this.config.api_url, this.config.token, axiosOpts);
112
112
  this.event = new event_client_1.EventClient(this.config, (0, exports.channelFactory)(this.config, this.credentials), clientFactory);
113
113
  this.dispatcher = new dispatcher_client_1.DispatcherClient(this.config, (0, exports.channelFactory)(this.config, this.credentials), clientFactory);
114
- this.admin = new admin_client_1.AdminClient(this.config, (0, exports.channelFactory)(this.config, this.credentials), clientFactory, this.api, this.tenantId);
115
114
  this.listener = new listener_client_1.ListenerClient(this.config, (0, exports.channelFactory)(this.config, this.credentials), clientFactory, this.api);
115
+ this.admin = new admin_client_1.AdminClient(this.config, (0, exports.channelFactory)(this.config, this.credentials), clientFactory, this.api, this.tenantId, this.listener);
116
116
  this.logger = new logger_1.default('HatchetClient', this.config.log_level);
117
117
  this.logger.info(`Initialized HatchetClient`);
118
118
  }
@@ -142,5 +142,11 @@ class HatchetClient {
142
142
  return worker;
143
143
  });
144
144
  }
145
+ webhooks(workflows) {
146
+ const worker = new worker_1.Worker(this, {
147
+ name: 'webhook-worker',
148
+ });
149
+ return worker.getHandler(workflows);
150
+ }
145
151
  }
146
152
  exports.HatchetClient = HatchetClient;
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { EventEmitter } from 'events';
3
2
  import { WorkflowRunEvent, SubscribeToWorkflowRunsRequest } from '../../protoc/dispatcher';
4
3
  import { ListenerClient } from './listener-client';
@@ -1,7 +1,6 @@
1
- /// <reference types="node" />
2
1
  import { Channel, ClientFactory } from 'nice-grpc';
3
2
  import { EventEmitter } from 'events';
4
- import { DispatcherClient as PbDispatcherClient } from '../../protoc/dispatcher';
3
+ import { DispatcherClient as PbDispatcherClient, DispatcherClient } from '../../protoc/dispatcher';
5
4
  import { ClientConfig } from '../hatchet-client/client-config';
6
5
  import { Logger } from '../../util/logger';
7
6
  import { Api } from '../rest';
@@ -23,21 +22,15 @@ export interface StepRunEvent {
23
22
  type: RunEventType;
24
23
  payload: string;
25
24
  }
26
- export declare class PollingAsyncListener {
27
- client: ListenerClient;
25
+ export declare class RunEventListener {
26
+ client: DispatcherClient;
28
27
  q: Array<StepRunEvent>;
29
28
  eventEmitter: EventEmitter<[never]>;
30
29
  pollInterval: any;
31
- constructor(workflowRunid: string, client: ListenerClient);
30
+ constructor(workflowRunid: string, client: DispatcherClient);
32
31
  emit(event: StepRunEvent): void;
33
32
  listen(workflowRunId: string): Promise<void>;
34
33
  retrySubscribe(workflowRunId: string): Promise<AsyncIterable<import("../../protoc/dispatcher").WorkflowEvent>>;
35
- getWorkflowRun(workflowRunId: string): Promise<{
36
- type: RunEventType;
37
- payload: string;
38
- } | undefined>;
39
- polling(workflowRunId: string): Promise<void>;
40
- close(): void;
41
34
  stream(): AsyncGenerator<StepRunEvent, void, unknown>;
42
35
  }
43
36
  export declare class ListenerClient {
@@ -45,9 +38,8 @@ export declare class ListenerClient {
45
38
  client: PbDispatcherClient;
46
39
  logger: Logger;
47
40
  api: Api;
48
- childListeners: Record<string, GrpcPooledListener>;
41
+ pooledListener: GrpcPooledListener | undefined;
49
42
  constructor(config: ClientConfig, channel: Channel, factory: ClientFactory, api: Api);
50
- getChildListener(workflowRunId: string, parentWorkflowRunId: string): import("./child-listener-client").Streamable;
51
- get(workflowRunId: string): PollingAsyncListener;
43
+ get(workflowRunId: string): import("./child-listener-client").Streamable;
52
44
  stream(workflowRunId: string): Promise<AsyncGenerator<StepRunEvent, void, unknown>>;
53
45
  }
@@ -32,7 +32,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
32
32
  return (mod && mod.__esModule) ? mod : { "default": mod };
33
33
  };
34
34
  Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.ListenerClient = exports.PollingAsyncListener = exports.RunEventType = void 0;
35
+ exports.ListenerClient = exports.RunEventListener = exports.RunEventType = void 0;
36
36
  // eslint-disable-next-line max-classes-per-file
37
37
  const nice_grpc_1 = require("nice-grpc");
38
38
  const events_1 = require("events");
@@ -94,13 +94,12 @@ const workflowStatusMap = {
94
94
  [data_contracts_1.WorkflowRunStatus.RUNNING]: undefined,
95
95
  [data_contracts_1.WorkflowRunStatus.QUEUED]: undefined,
96
96
  };
97
- class PollingAsyncListener {
97
+ class RunEventListener {
98
98
  constructor(workflowRunid, client) {
99
99
  this.q = [];
100
100
  this.eventEmitter = new events_1.EventEmitter();
101
101
  this.client = client;
102
102
  this.listen(workflowRunid);
103
- this.polling(workflowRunid);
104
103
  }
105
104
  emit(event) {
106
105
  this.q.push(event);
@@ -110,14 +109,9 @@ class PollingAsyncListener {
110
109
  return __awaiter(this, void 0, void 0, function* () {
111
110
  var _a, e_1, _b, _c;
112
111
  var _d;
113
- let listener = this.client.client.subscribeToWorkflowEvents({
112
+ let listener = this.client.subscribeToWorkflowEvents({
114
113
  workflowRunId,
115
114
  });
116
- const res = yield this.getWorkflowRun(workflowRunId);
117
- if (res) {
118
- this.emit(res);
119
- this.close();
120
- }
121
115
  try {
122
116
  try {
123
117
  for (var _e = true, listener_1 = __asyncValues(listener), listener_1_1; listener_1_1 = yield listener_1.next(), _a = listener_1_1.done, !_a; _e = true) {
@@ -126,19 +120,10 @@ class PollingAsyncListener {
126
120
  const workflowEvent = _c;
127
121
  const eventType = (_d = resourceTypeMap[workflowEvent.resourceType]) === null || _d === void 0 ? void 0 : _d[workflowEvent.eventType];
128
122
  if (eventType) {
129
- if (eventType === RunEventType.WORKFLOW_RUN_EVENT_TYPE_COMPLETED) {
130
- // OPTIMZATION - consider including the workflow run data in the event?
131
- const data = yield this.getWorkflowRun(workflowRunId);
132
- if (data) {
133
- this.emit(data);
134
- }
135
- }
136
- else {
137
- this.emit({
138
- type: eventType,
139
- payload: workflowEvent.eventPayload,
140
- });
141
- }
123
+ this.emit({
124
+ type: eventType,
125
+ payload: workflowEvent.eventPayload,
126
+ });
142
127
  }
143
128
  }
144
129
  }
@@ -158,7 +143,6 @@ class PollingAsyncListener {
158
143
  listener = yield this.retrySubscribe(workflowRunId);
159
144
  }
160
145
  }
161
- setTimeout(() => this.close(), DEFAULT_EVENT_LISTENER_POLL_INTERVAL * 5);
162
146
  });
163
147
  }
164
148
  retrySubscribe(workflowRunId) {
@@ -167,7 +151,7 @@ class PollingAsyncListener {
167
151
  while (retries < DEFAULT_EVENT_LISTENER_RETRY_COUNT) {
168
152
  try {
169
153
  yield (0, sleep_1.default)(DEFAULT_EVENT_LISTENER_RETRY_INTERVAL);
170
- const listener = this.client.client.subscribeToWorkflowEvents({
154
+ const listener = this.client.subscribeToWorkflowEvents({
171
155
  workflowRunId,
172
156
  });
173
157
  return listener;
@@ -179,54 +163,6 @@ class PollingAsyncListener {
179
163
  throw new hatchet_error_1.default(`Could not subscribe to the worker after ${DEFAULT_EVENT_LISTENER_RETRY_COUNT} retries`);
180
164
  });
181
165
  }
182
- getWorkflowRun(workflowRunId) {
183
- return __awaiter(this, void 0, void 0, function* () {
184
- var _a, _b, _c;
185
- try {
186
- const res = yield this.client.api.workflowRunGet(this.client.config.tenant_id, workflowRunId);
187
- const stepRuns = (_c = (_b = (_a = res.data.jobRuns) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.stepRuns) !== null && _c !== void 0 ? _c : [];
188
- const stepRunOutput = stepRuns.reduce((acc, stepRun) => {
189
- var _a;
190
- acc[((_a = stepRun.step) === null || _a === void 0 ? void 0 : _a.readableId) || ''] = JSON.parse(stepRun.output || '{}');
191
- return acc;
192
- }, {});
193
- if (Object.keys(workflowStatusMap).includes(res.data.status)) {
194
- const type = workflowStatusMap[res.data.status];
195
- if (!type)
196
- return undefined;
197
- return {
198
- type,
199
- payload: JSON.stringify(stepRunOutput),
200
- };
201
- }
202
- return undefined;
203
- }
204
- catch (e) {
205
- throw new hatchet_error_1.default(e.message);
206
- }
207
- });
208
- }
209
- polling(workflowRunId) {
210
- return __awaiter(this, void 0, void 0, function* () {
211
- this.pollInterval = setInterval(() => __awaiter(this, void 0, void 0, function* () {
212
- try {
213
- const result = yield this.getWorkflowRun(workflowRunId);
214
- if (result) {
215
- this.emit(result);
216
- this.close();
217
- }
218
- }
219
- catch (e) {
220
- // TODO error handling
221
- }
222
- }), DEFAULT_EVENT_LISTENER_POLL_INTERVAL);
223
- });
224
- }
225
- close() {
226
- if (this.pollInterval) {
227
- clearInterval(this.pollInterval);
228
- }
229
- }
230
166
  stream() {
231
167
  return __asyncGenerator(this, arguments, function* stream_1() {
232
168
  var _a, e_2, _b, _c;
@@ -253,33 +189,28 @@ class PollingAsyncListener {
253
189
  });
254
190
  }
255
191
  }
256
- exports.PollingAsyncListener = PollingAsyncListener;
192
+ exports.RunEventListener = RunEventListener;
257
193
  class ListenerClient {
258
194
  constructor(config, channel, factory, api) {
259
- this.childListeners = {};
260
195
  this.config = config;
261
196
  this.client = factory.create(dispatcher_1.DispatcherDefinition, channel);
262
197
  this.logger = new logger_1.Logger(`Listener`, config.log_level);
263
198
  this.api = api;
264
199
  }
265
- getChildListener(workflowRunId, parentWorkflowRunId) {
266
- if (!this.childListeners[parentWorkflowRunId]) {
267
- this.childListeners[parentWorkflowRunId] = new child_listener_client_1.GrpcPooledListener(this, () => {
268
- // cleanup listener when all children are done
269
- delete this.childListeners[parentWorkflowRunId];
200
+ get(workflowRunId) {
201
+ if (!this.pooledListener) {
202
+ this.pooledListener = new child_listener_client_1.GrpcPooledListener(this, () => {
203
+ this.pooledListener = undefined;
270
204
  });
271
205
  }
272
- return this.childListeners[parentWorkflowRunId].subscribe({
206
+ return this.pooledListener.subscribe({
273
207
  workflowRunId,
274
208
  });
275
209
  }
276
- get(workflowRunId) {
277
- const listener = new PollingAsyncListener(workflowRunId, this);
278
- return listener;
279
- }
280
210
  stream(workflowRunId) {
281
211
  return __awaiter(this, void 0, void 0, function* () {
282
- return this.get(workflowRunId).stream();
212
+ const listener = new RunEventListener(workflowRunId, this.client);
213
+ return listener.stream();
283
214
  });
284
215
  }
285
216
  }