@hatchet-dev/typescript-sdk 0.14.0 → 0.16.0-alpha.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 (43) hide show
  1. package/clients/admin/admin-client.d.ts +29 -0
  2. package/clients/admin/admin-client.js +34 -0
  3. package/clients/hatchet-client/client-config.d.ts +6 -0
  4. package/clients/hatchet-client/client-config.js +2 -0
  5. package/clients/hatchet-client/hatchet-client.d.ts +2 -0
  6. package/clients/hatchet-client/hatchet-client.js +25 -1
  7. package/clients/rest/api.d.ts +3 -0
  8. package/clients/rest/api.js +10 -0
  9. package/clients/rest/generated/Api.d.ts +11 -1
  10. package/clients/rest/generated/Api.js +10 -0
  11. package/clients/rest/generated/cloud/Api.d.ts +364 -0
  12. package/clients/rest/generated/cloud/Api.js +316 -0
  13. package/clients/rest/generated/cloud/data-contracts.d.ts +460 -0
  14. package/clients/rest/generated/cloud/data-contracts.js +68 -0
  15. package/clients/rest/generated/cloud/http-client.d.ts +41 -0
  16. package/clients/rest/generated/cloud/http-client.js +102 -0
  17. package/clients/rest/generated/data-contracts.d.ts +4 -0
  18. package/clients/rest/generated/data-contracts.js +1 -0
  19. package/clients/rest/index.d.ts +2 -2
  20. package/clients/rest/index.js +4 -5
  21. package/clients/worker/compute/compute-config.d.ts +96 -0
  22. package/clients/worker/compute/compute-config.js +52 -0
  23. package/clients/worker/compute/managed-compute.d.ts +15 -0
  24. package/clients/worker/compute/managed-compute.js +100 -0
  25. package/clients/worker/worker.d.ts +10 -2
  26. package/clients/worker/worker.js +31 -10
  27. package/examples/bulk-fanout-trigger.d.ts +1 -0
  28. package/examples/bulk-fanout-trigger.js +74 -0
  29. package/examples/bulk-fanout-worker.d.ts +1 -0
  30. package/examples/bulk-fanout-worker.js +93 -0
  31. package/examples/bulk-trigger.d.ts +1 -0
  32. package/examples/bulk-trigger.js +63 -0
  33. package/examples/managed-worker.d.ts +1 -0
  34. package/examples/managed-worker.js +65 -0
  35. package/package.json +7 -1
  36. package/protoc/dispatcher/dispatcher.d.ts +1 -0
  37. package/protoc/dispatcher/dispatcher.js +6 -0
  38. package/protoc/workflows/workflows.d.ts +18 -0
  39. package/protoc/workflows/workflows.js +121 -1
  40. package/step.d.ts +90 -0
  41. package/step.js +54 -1
  42. package/util/config-loader/config-loader.js +19 -1
  43. package/workflow.d.ts +285 -0
@@ -1,8 +1,8 @@
1
- import api from './api';
1
+ import api, { cloudApi, CloudApi } from './api';
2
2
  import { Api } from './generated/Api';
3
3
  import { Worker as _Worker, Workflow as _Workflow } from './generated/data-contracts';
4
4
  import * as APIContracts from './generated/data-contracts';
5
5
  type ApiWorker = _Worker;
6
6
  type ApiWorkflow = _Workflow;
7
- export { ApiWorker, ApiWorkflow, APIContracts, Api };
7
+ export { ApiWorker, ApiWorkflow, APIContracts, Api, CloudApi, cloudApi };
8
8
  export default api;
@@ -22,12 +22,11 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
25
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.Api = exports.APIContracts = void 0;
30
- const api_1 = __importDefault(require("./api"));
26
+ exports.cloudApi = exports.CloudApi = exports.Api = exports.APIContracts = void 0;
27
+ const api_1 = __importStar(require("./api"));
28
+ Object.defineProperty(exports, "cloudApi", { enumerable: true, get: function () { return api_1.cloudApi; } });
29
+ Object.defineProperty(exports, "CloudApi", { enumerable: true, get: function () { return api_1.CloudApi; } });
31
30
  const Api_1 = require("./generated/Api");
32
31
  Object.defineProperty(exports, "Api", { enumerable: true, get: function () { return Api_1.Api; } });
33
32
  const APIContracts = __importStar(require("./generated/data-contracts"));
@@ -0,0 +1,96 @@
1
+ import { ManagedWorkerRegion } from '../../rest/generated/cloud/data-contracts';
2
+ import { z } from 'zod';
3
+ export declare const SharedCPUComputeSchema: z.ZodObject<z.objectUtil.extendShape<{
4
+ pool: z.ZodOptional<z.ZodDefault<z.ZodString>>;
5
+ numReplicas: z.ZodDefault<z.ZodNumber>;
6
+ regions: z.ZodOptional<z.ZodArray<z.ZodNativeEnum<typeof ManagedWorkerRegion>, "many">>;
7
+ cpus: z.ZodNumber;
8
+ }, {
9
+ cpuKind: z.ZodLiteral<"shared">;
10
+ memoryMb: z.ZodEffects<z.ZodNumber, number, number>;
11
+ }>, "strip", z.ZodTypeAny, {
12
+ numReplicas: number;
13
+ cpus: number;
14
+ cpuKind: "shared";
15
+ memoryMb: number;
16
+ pool?: string | undefined;
17
+ regions?: ManagedWorkerRegion[] | undefined;
18
+ }, {
19
+ cpus: number;
20
+ cpuKind: "shared";
21
+ memoryMb: number;
22
+ pool?: string | undefined;
23
+ numReplicas?: number | undefined;
24
+ regions?: ManagedWorkerRegion[] | undefined;
25
+ }>;
26
+ export type SharedCPUCompute = z.infer<typeof SharedCPUComputeSchema>;
27
+ export declare const DedicatedCPUComputeSchema: z.ZodObject<z.objectUtil.extendShape<{
28
+ pool: z.ZodOptional<z.ZodDefault<z.ZodString>>;
29
+ numReplicas: z.ZodDefault<z.ZodNumber>;
30
+ regions: z.ZodOptional<z.ZodArray<z.ZodNativeEnum<typeof ManagedWorkerRegion>, "many">>;
31
+ cpus: z.ZodNumber;
32
+ }, {
33
+ cpuKind: z.ZodLiteral<"dedicated">;
34
+ memoryMb: z.ZodEffects<z.ZodNumber, number, number>;
35
+ }>, "strip", z.ZodTypeAny, {
36
+ numReplicas: number;
37
+ cpus: number;
38
+ cpuKind: "dedicated";
39
+ memoryMb: number;
40
+ pool?: string | undefined;
41
+ regions?: ManagedWorkerRegion[] | undefined;
42
+ }, {
43
+ cpus: number;
44
+ cpuKind: "dedicated";
45
+ memoryMb: number;
46
+ pool?: string | undefined;
47
+ numReplicas?: number | undefined;
48
+ regions?: ManagedWorkerRegion[] | undefined;
49
+ }>;
50
+ export type DedicatedCPUCompute = z.infer<typeof DedicatedCPUComputeSchema>;
51
+ export declare const ComputeSchema: z.ZodUnion<[z.ZodObject<z.objectUtil.extendShape<{
52
+ pool: z.ZodOptional<z.ZodDefault<z.ZodString>>;
53
+ numReplicas: z.ZodDefault<z.ZodNumber>;
54
+ regions: z.ZodOptional<z.ZodArray<z.ZodNativeEnum<typeof ManagedWorkerRegion>, "many">>;
55
+ cpus: z.ZodNumber;
56
+ }, {
57
+ cpuKind: z.ZodLiteral<"shared">;
58
+ memoryMb: z.ZodEffects<z.ZodNumber, number, number>;
59
+ }>, "strip", z.ZodTypeAny, {
60
+ numReplicas: number;
61
+ cpus: number;
62
+ cpuKind: "shared";
63
+ memoryMb: number;
64
+ pool?: string | undefined;
65
+ regions?: ManagedWorkerRegion[] | undefined;
66
+ }, {
67
+ cpus: number;
68
+ cpuKind: "shared";
69
+ memoryMb: number;
70
+ pool?: string | undefined;
71
+ numReplicas?: number | undefined;
72
+ regions?: ManagedWorkerRegion[] | undefined;
73
+ }>, z.ZodObject<z.objectUtil.extendShape<{
74
+ pool: z.ZodOptional<z.ZodDefault<z.ZodString>>;
75
+ numReplicas: z.ZodDefault<z.ZodNumber>;
76
+ regions: z.ZodOptional<z.ZodArray<z.ZodNativeEnum<typeof ManagedWorkerRegion>, "many">>;
77
+ cpus: z.ZodNumber;
78
+ }, {
79
+ cpuKind: z.ZodLiteral<"dedicated">;
80
+ memoryMb: z.ZodEffects<z.ZodNumber, number, number>;
81
+ }>, "strip", z.ZodTypeAny, {
82
+ numReplicas: number;
83
+ cpus: number;
84
+ cpuKind: "dedicated";
85
+ memoryMb: number;
86
+ pool?: string | undefined;
87
+ regions?: ManagedWorkerRegion[] | undefined;
88
+ }, {
89
+ cpus: number;
90
+ cpuKind: "dedicated";
91
+ memoryMb: number;
92
+ pool?: string | undefined;
93
+ numReplicas?: number | undefined;
94
+ regions?: ManagedWorkerRegion[] | undefined;
95
+ }>]>;
96
+ export declare const computeHash: (compute: z.infer<typeof ComputeSchema>) => string;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.computeHash = exports.ComputeSchema = exports.DedicatedCPUComputeSchema = exports.SharedCPUComputeSchema = void 0;
4
+ const data_contracts_1 = require("../../rest/generated/cloud/data-contracts");
5
+ const crypto_1 = require("crypto");
6
+ const zod_1 = require("zod");
7
+ const BaseComputeSchema = zod_1.z.object({
8
+ pool: zod_1.z.string().default('default').optional().describe('The name of the compute pool to use'),
9
+ numReplicas: zod_1.z
10
+ .number()
11
+ .int()
12
+ .min(0, { message: 'Must be at least 0' })
13
+ .max(1000, { message: 'Must be at most 1000' })
14
+ .default(1)
15
+ .describe('The number of replicas'),
16
+ regions: zod_1.z
17
+ .array(zod_1.z.nativeEnum(data_contracts_1.ManagedWorkerRegion))
18
+ .optional()
19
+ .describe('The regions to deploy the worker to'),
20
+ cpus: zod_1.z
21
+ .number()
22
+ .int()
23
+ .min(1, { message: 'Must be at least 1' })
24
+ .max(64, { message: 'Must be at most 64' })
25
+ .describe('The number of CPUs to use for the worker'),
26
+ });
27
+ exports.SharedCPUComputeSchema = BaseComputeSchema.extend({
28
+ cpuKind: zod_1.z.literal('shared'),
29
+ memoryMb: zod_1.z
30
+ .number()
31
+ .int()
32
+ .min(256, { message: 'Must be at least 256 MB' })
33
+ .max(65536, { message: 'Must be at most 65536 MB' })
34
+ .refine((val) => val % 256 === 0, { message: 'Must be divisible by 256 MB' })
35
+ .describe('The amount of memory in MB to use for the worker'),
36
+ });
37
+ exports.DedicatedCPUComputeSchema = BaseComputeSchema.extend({
38
+ cpuKind: zod_1.z.literal('dedicated'),
39
+ memoryMb: zod_1.z
40
+ .number()
41
+ .int()
42
+ .min(2048, { message: 'Must be at least 1024 MB' })
43
+ .max(65536, { message: 'Must be at most 65536 MB' })
44
+ .refine((val) => val % 256 === 0, { message: 'Must be divisible by 256 MB' })
45
+ .describe('The amount of memory in MB to use for the worker'),
46
+ });
47
+ exports.ComputeSchema = zod_1.z.union([exports.SharedCPUComputeSchema, exports.DedicatedCPUComputeSchema]);
48
+ const computeHash = (compute) => {
49
+ const str = JSON.stringify(compute);
50
+ return (0, crypto_1.createHash)('sha256').update(str).digest('hex');
51
+ };
52
+ exports.computeHash = computeHash;
@@ -0,0 +1,15 @@
1
+ import { HatchetClient } from '../../hatchet-client';
2
+ import { CreateManagedWorkerRuntimeConfigRequest } from '../../rest/generated/cloud/data-contracts';
3
+ import { Logger } from '../../../util/logger';
4
+ import { ActionRegistry } from '../worker';
5
+ export declare class ManagedCompute {
6
+ actions: ActionRegistry;
7
+ client: HatchetClient;
8
+ maxRuns: number;
9
+ configs: CreateManagedWorkerRuntimeConfigRequest[];
10
+ cloudRegisterId: string | undefined;
11
+ logger: Logger;
12
+ constructor(actions: ActionRegistry, client: HatchetClient, maxRuns?: number);
13
+ getComputeConfigs(actions: ActionRegistry): CreateManagedWorkerRuntimeConfigRequest[];
14
+ cloudRegister(): Promise<void>;
15
+ }
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ManagedCompute = void 0;
13
+ const logger_1 = require("../../../util/logger");
14
+ const compute_config_1 = require("./compute-config");
15
+ class ManagedCompute {
16
+ constructor(actions, client, maxRuns = 1) {
17
+ this.actions = actions;
18
+ this.client = client;
19
+ this.maxRuns = maxRuns;
20
+ this.configs = this.getComputeConfigs(this.actions);
21
+ this.cloudRegisterId = this.client.config.cloud_register_id;
22
+ this.logger = new logger_1.Logger(`Compute`, this.client.config.log_level);
23
+ if (this.configs.length === 0) {
24
+ this.logger.debug('No compute configs found, skipping cloud registration and running all actions locally.');
25
+ return;
26
+ }
27
+ if (!this.cloudRegisterId) {
28
+ this.logger.warn('Managed cloud compute plan:');
29
+ this.configs.forEach((compute) => {
30
+ var _a;
31
+ this.logger.warn(' ----------------------------');
32
+ this.logger.warn(` actions: ${(_a = compute.actions) === null || _a === void 0 ? void 0 : _a.join(', ')}`);
33
+ this.logger.warn(` num replicas: ${compute.numReplicas}`);
34
+ this.logger.warn(` cpu kind: ${compute.cpuKind}`);
35
+ this.logger.warn(` cpus: ${compute.cpus}`);
36
+ this.logger.warn(` memory mb: ${compute.memoryMb}`);
37
+ // this.logger.warn(` regions: ${compute.regions?.join(', ')}`);
38
+ });
39
+ this.logger.warn('NOTICE: local mode detected, skipping cloud registration and running all actions locally.');
40
+ }
41
+ }
42
+ getComputeConfigs(actions) {
43
+ /**
44
+ * Builds a map of compute hashes to compute configs and lists of actions that correspond to each compute hash.
45
+ */
46
+ const computeMap = {};
47
+ try {
48
+ Object.entries(actions).forEach(([action, { compute }]) => {
49
+ if (!compute) {
50
+ return;
51
+ }
52
+ const key = (0, compute_config_1.computeHash)(compute);
53
+ if (!computeMap[key]) {
54
+ computeMap[key] = {
55
+ actions: [],
56
+ numReplicas: compute.numReplicas,
57
+ cpuKind: compute.cpuKind,
58
+ cpus: compute.cpus,
59
+ memoryMb: compute.memoryMb,
60
+ regions: compute.regions,
61
+ slots: this.maxRuns,
62
+ };
63
+ }
64
+ computeMap[key].actions.push(action);
65
+ });
66
+ return Object.values(computeMap);
67
+ }
68
+ catch (e) {
69
+ this.logger.error(`Error getting compute configs: ${e}`);
70
+ return [];
71
+ }
72
+ }
73
+ cloudRegister() {
74
+ return __awaiter(this, void 0, void 0, function* () {
75
+ /**
76
+ * Registers the compute plan with the cloud if the environment variable is set.
77
+ * Exits the process upon completion.
78
+ */
79
+ if (this.cloudRegisterId) {
80
+ this.logger.info(`Registering cloud compute plan with ID: ${this.cloudRegisterId}`);
81
+ try {
82
+ if (this.configs.length === 0) {
83
+ this.logger.warn('No actions to register, skipping cloud registration.');
84
+ process.exit(0);
85
+ }
86
+ const req = {
87
+ runtimeConfigs: this.configs,
88
+ };
89
+ yield this.client.cloudApi.infraAsCodeCreate(this.cloudRegisterId, req);
90
+ process.exit(0);
91
+ }
92
+ catch (e) {
93
+ this.logger.error(`ERROR: ${e}`);
94
+ process.exit(1);
95
+ }
96
+ }
97
+ });
98
+ }
99
+ }
100
+ exports.ManagedCompute = ManagedCompute;
@@ -6,9 +6,16 @@ import { Workflow } from '../../workflow';
6
6
  import { Logger } from '../../util/logger';
7
7
  import { WebhookHandler } from './handler';
8
8
  import { WebhookWorkerCreateRequest } from '../rest/generated/data-contracts';
9
+ import { z } from 'zod';
9
10
  import { Context, StepRunFunction } from '../../step';
10
11
  import { WorkerLabels } from '../dispatcher/dispatcher-client';
11
- export type ActionRegistry = Record<Action['actionId'], Function>;
12
+ import { ComputeSchema } from './compute/compute-config';
13
+ type ActionFunction = StepRunFunction<any, any> | ((ctx: any) => string | Promise<string>);
14
+ type ActionRegistryRecord = {
15
+ func: ActionFunction;
16
+ compute?: z.infer<typeof ComputeSchema>;
17
+ };
18
+ export type ActionRegistry = Record<Action['actionId'], ActionRegistryRecord>;
12
19
  export interface WorkerOpts {
13
20
  name: string;
14
21
  handleKill?: boolean;
@@ -44,7 +51,7 @@ export declare class Worker {
44
51
  */
45
52
  register_workflow(initWorkflow: Workflow): Promise<void>;
46
53
  registerWorkflow(initWorkflow: Workflow): Promise<void>;
47
- registerAction<T, K>(actionId: string, action: StepRunFunction<T, K>): void;
54
+ registerAction<T, K>(actionId: string, action: StepRunFunction<T, K>, compute?: z.infer<typeof ComputeSchema>): void;
48
55
  handleStartStepRun(action: Action): Promise<void>;
49
56
  handleStartGroupKeyRun(action: Action): Promise<void>;
50
57
  getStepActionEvent(action: Action, eventType: StepActionEventType, payload?: any): StepActionEvent;
@@ -56,3 +63,4 @@ export declare class Worker {
56
63
  handleAction(action: Action): Promise<void>;
57
64
  upsertLabels(labels: WorkerLabels): Promise<WorkerLabels>;
58
65
  }
66
+ export {};
@@ -27,6 +27,7 @@ const workflows_1 = require("../../protoc/workflows");
27
27
  const logger_1 = require("../../util/logger");
28
28
  const handler_1 = require("./handler");
29
29
  const step_1 = require("../../step");
30
+ const managed_compute_1 = require("./compute/managed-compute");
30
31
  class Worker {
31
32
  constructor(client, options) {
32
33
  this.workflow_registry = [];
@@ -48,18 +49,33 @@ class Worker {
48
49
  registerActions(workflow) {
49
50
  var _a;
50
51
  const newActions = workflow.steps.reduce((acc, step) => {
51
- acc[`${workflow.id}:${step.name}`] = step.run;
52
+ // Only register actions that are in the runnable_actions list
53
+ if (!this.client.config.runnable_actions ||
54
+ this.client.config.runnable_actions.includes(`${workflow.id}:${step.name}`)) {
55
+ acc[`${workflow.id}:${step.name}`] = {
56
+ func: step.run,
57
+ compute: step.compute,
58
+ };
59
+ }
52
60
  return acc;
53
61
  }, {});
54
62
  const onFailureAction = workflow.onFailure
55
63
  ? {
56
- [`${workflow.id}-on-failure:${workflow.onFailure.name}`]: workflow.onFailure.run,
64
+ [`${workflow.id}-on-failure:${workflow.onFailure.name}`]: {
65
+ func: workflow.onFailure.run,
66
+ compute: workflow.onFailure.compute,
67
+ },
68
+ }
69
+ : {};
70
+ const concurrencyAction = ((_a = workflow.concurrency) === null || _a === void 0 ? void 0 : _a.name) && workflow.concurrency.key
71
+ ? {
72
+ [`${workflow.id}:${workflow.concurrency.name}`]: {
73
+ func: workflow.concurrency.key,
74
+ compute: undefined,
75
+ },
57
76
  }
58
77
  : {};
59
- this.action_registry = Object.assign(Object.assign(Object.assign({}, this.action_registry), newActions), onFailureAction);
60
- this.action_registry =
61
- ((_a = workflow.concurrency) === null || _a === void 0 ? void 0 : _a.name) && workflow.concurrency.key
62
- ? Object.assign(Object.assign({}, this.action_registry), { [`${workflow.id}:${workflow.concurrency.name}`]: workflow.concurrency.key }) : Object.assign({}, this.action_registry);
78
+ this.action_registry = Object.assign(Object.assign(Object.assign(Object.assign({}, this.action_registry), newActions), onFailureAction), concurrencyAction);
63
79
  }
64
80
  getHandler(workflows) {
65
81
  for (const workflow of workflows) {
@@ -162,8 +178,11 @@ class Worker {
162
178
  this.registerActions(workflow);
163
179
  });
164
180
  }
165
- registerAction(actionId, action) {
166
- this.action_registry[actionId] = action;
181
+ registerAction(actionId, action, compute) {
182
+ this.action_registry[actionId] = {
183
+ func: action,
184
+ compute,
185
+ };
167
186
  }
168
187
  handleStartStepRun(action) {
169
188
  return __awaiter(this, void 0, void 0, function* () {
@@ -177,7 +196,7 @@ class Worker {
177
196
  return;
178
197
  }
179
198
  const run = () => __awaiter(this, void 0, void 0, function* () {
180
- return step(context);
199
+ return step.func(context);
181
200
  });
182
201
  const success = (result) => __awaiter(this, void 0, void 0, function* () {
183
202
  this.logger.info(`Step run ${action.stepRunId} succeeded`);
@@ -262,7 +281,7 @@ class Worker {
262
281
  return;
263
282
  }
264
283
  const run = () => __awaiter(this, void 0, void 0, function* () {
265
- return step(context);
284
+ return step.func(context);
266
285
  });
267
286
  const success = (result) => {
268
287
  this.logger.info(`Step run ${action.stepRunId} succeeded`);
@@ -391,6 +410,8 @@ class Worker {
391
410
  var _a, e_1, _b, _c;
392
411
  // ensure all workflows are registered
393
412
  yield Promise.all(this.registeredWorkflowPromises);
413
+ const managedCompute = new managed_compute_1.ManagedCompute(this.action_registry, this.client, this.maxRuns);
414
+ yield managedCompute.cloudRegister();
394
415
  try {
395
416
  this.listener = yield this.client.dispatcher.getActionListener({
396
417
  workerName: this.name,
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
12
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
+ var m = o[Symbol.asyncIterator], i;
14
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
+ };
18
+ var __importDefault = (this && this.__importDefault) || function (mod) {
19
+ return (mod && mod.__esModule) ? mod : { "default": mod };
20
+ };
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ const sdk_1 = __importDefault(require("../sdk"));
23
+ const hatchet = sdk_1.default.init();
24
+ function main() {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ const workflowRuns = [];
27
+ workflowRuns[0] = {
28
+ workflowName: 'bulk-parent-workflow',
29
+ input: {},
30
+ options: {
31
+ additionalMetadata: {
32
+ key: 'value',
33
+ },
34
+ },
35
+ };
36
+ workflowRuns[1] = {
37
+ workflowName: 'bulk-parent-workflow',
38
+ input: { second: 'second' },
39
+ options: {
40
+ additionalMetadata: {
41
+ key: 'value',
42
+ },
43
+ },
44
+ };
45
+ try {
46
+ const workflowRunResponse = hatchet.admin.runWorkflows(workflowRuns);
47
+ const result = yield workflowRunResponse;
48
+ console.log('result', result);
49
+ result.forEach((workflowRun) => __awaiter(this, void 0, void 0, function* () {
50
+ var _a, e_1, _b, _c;
51
+ const stream = yield workflowRun.stream();
52
+ try {
53
+ for (var _d = true, stream_1 = __asyncValues(stream), stream_1_1; stream_1_1 = yield stream_1.next(), _a = stream_1_1.done, !_a; _d = true) {
54
+ _c = stream_1_1.value;
55
+ _d = false;
56
+ const event = _c;
57
+ console.log('event received', event);
58
+ }
59
+ }
60
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
61
+ finally {
62
+ try {
63
+ if (!_d && !_a && (_b = stream_1.return)) yield _b.call(stream_1);
64
+ }
65
+ finally { if (e_1) throw e_1.error; }
66
+ }
67
+ }));
68
+ }
69
+ catch (error) {
70
+ console.log('error', error);
71
+ }
72
+ });
73
+ }
74
+ main();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const sdk_1 = __importDefault(require("../sdk"));
16
+ const hatchet = sdk_1.default.init();
17
+ const parentWorkflow = {
18
+ id: 'bulk-parent-workflow',
19
+ description: 'simple example for spawning child workflows',
20
+ on: {
21
+ event: 'bulk:fanout:create',
22
+ },
23
+ steps: [
24
+ {
25
+ name: 'parent-spawn',
26
+ timeout: '70s',
27
+ run: (ctx) => __awaiter(void 0, void 0, void 0, function* () {
28
+ // Prepare the workflows to spawn
29
+ const workflowRequests = Array.from({ length: 300 }, (_, i) => ({
30
+ workflow: 'child-workflow',
31
+ input: { input: `child-input-${i}` },
32
+ options: { additionalMetadata: { childKey: 'childValue' } },
33
+ }));
34
+ const spawnedWorkflows = yield ctx.spawnWorkflows(workflowRequests);
35
+ const results = yield Promise.all(spawnedWorkflows.map((workflowRef) => workflowRef.result().then((result) => {
36
+ ctx.log('spawned workflow result:');
37
+ return result;
38
+ })));
39
+ console.log('spawned workflow results:', results);
40
+ console.log('number of spawned workflows:', results.length);
41
+ return { spawned: results.length };
42
+ }),
43
+ },
44
+ ],
45
+ };
46
+ const childWorkflow = {
47
+ id: 'child-workflow',
48
+ description: 'simple example for spawning child workflows',
49
+ on: {
50
+ event: 'child:create',
51
+ },
52
+ steps: [
53
+ {
54
+ name: 'child-work',
55
+ run: (ctx) => __awaiter(void 0, void 0, void 0, function* () {
56
+ const { input } = ctx.workflowInput();
57
+ // throw new Error('child error');
58
+ return { 'child-output': 'sm' };
59
+ }),
60
+ },
61
+ {
62
+ name: 'child-work2',
63
+ run: (ctx) => __awaiter(void 0, void 0, void 0, function* () {
64
+ const { input } = ctx.workflowInput();
65
+ // Perform CPU-bound work
66
+ // throw new Error('child error');
67
+ console.log('child workflow input:', input);
68
+ // Generate a large amount of garbage data
69
+ const garbageData = 'garbage'; // Print a snippet of the garbage data
70
+ return { 'child-output': garbageData };
71
+ }),
72
+ },
73
+ {
74
+ name: 'child-work3',
75
+ parents: ['child-work'],
76
+ run: (ctx) => __awaiter(void 0, void 0, void 0, function* () {
77
+ const { input } = ctx.workflowInput();
78
+ // throw new Error('child error');
79
+ const garbageData = 'child garbage';
80
+ return { 'child-output': garbageData };
81
+ }),
82
+ },
83
+ ],
84
+ };
85
+ function main() {
86
+ return __awaiter(this, void 0, void 0, function* () {
87
+ const worker = yield hatchet.worker('fanout-worker', { maxRuns: 1000 });
88
+ yield worker.registerWorkflow(parentWorkflow);
89
+ yield worker.registerWorkflow(childWorkflow);
90
+ worker.start();
91
+ });
92
+ }
93
+ main();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
12
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
+ var m = o[Symbol.asyncIterator], i;
14
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
+ };
18
+ var __importDefault = (this && this.__importDefault) || function (mod) {
19
+ return (mod && mod.__esModule) ? mod : { "default": mod };
20
+ };
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ const sdk_1 = __importDefault(require("../sdk"));
23
+ const hatchet = sdk_1.default.init();
24
+ function main() {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ const workflowRuns = [];
27
+ for (let i = 0; i < 100; i += 1) {
28
+ workflowRuns.push({
29
+ workflowName: 'simple-workflow',
30
+ input: {},
31
+ options: {
32
+ additionalMetadata: {
33
+ key: 'value',
34
+ dedupe: 'key',
35
+ },
36
+ },
37
+ });
38
+ }
39
+ const workflowRunResponse = hatchet.admin.runWorkflows(workflowRuns);
40
+ const result = yield workflowRunResponse;
41
+ console.log('result', result);
42
+ result.forEach((workflowRun) => __awaiter(this, void 0, void 0, function* () {
43
+ var _a, e_1, _b, _c;
44
+ const stream = yield workflowRun.stream();
45
+ try {
46
+ for (var _d = true, stream_1 = __asyncValues(stream), stream_1_1; stream_1_1 = yield stream_1.next(), _a = stream_1_1.done, !_a; _d = true) {
47
+ _c = stream_1_1.value;
48
+ _d = false;
49
+ const event = _c;
50
+ console.log('event received', event);
51
+ }
52
+ }
53
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
54
+ finally {
55
+ try {
56
+ if (!_d && !_a && (_b = stream_1.return)) yield _b.call(stream_1);
57
+ }
58
+ finally { if (e_1) throw e_1.error; }
59
+ }
60
+ }));
61
+ });
62
+ }
63
+ main();
@@ -0,0 +1 @@
1
+ export {};