@outputai/cli 0.17.1-next.78fc808.0 → 0.18.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.
- package/dist/assets/docker/docker-compose-dev.yml +1 -1
- package/dist/commands/workflow/dataset/generate.d.ts +8 -6
- package/dist/commands/workflow/dataset/generate.js +46 -80
- package/dist/commands/workflow/dataset/generate.spec.js +154 -83
- package/dist/commands/workflow/debug.d.ts +8 -3
- package/dist/commands/workflow/debug.js +35 -25
- package/dist/commands/workflow/debug.spec.js +76 -22
- package/dist/commands/workflow/test.js +0 -3
- package/dist/commands/workflow/test.spec.js +19 -0
- package/dist/generated/framework_version.json +1 -1
- package/dist/services/datasets.d.ts +1 -3
- package/dist/services/datasets.js +1 -19
- package/dist/services/datasets.test.js +45 -3
- package/dist/services/temporal_client.d.ts +50 -0
- package/dist/services/temporal_client.js +84 -0
- package/dist/services/temporal_client.spec.d.ts +1 -0
- package/dist/services/temporal_client.spec.js +129 -0
- package/dist/services/workflow_debug.d.ts +68 -0
- package/dist/services/workflow_debug.js +273 -0
- package/dist/services/workflow_debug.spec.d.ts +1 -0
- package/dist/services/workflow_debug.spec.js +363 -0
- package/dist/services/workflow_run_data.d.ts +26 -0
- package/dist/services/workflow_run_data.js +67 -0
- package/dist/services/workflow_run_data.spec.d.ts +1 -0
- package/dist/services/workflow_run_data.spec.js +190 -0
- package/dist/types/trace.d.ts +1 -73
- package/dist/types/trace.js +1 -12
- package/dist/utils/payload_truncator.d.ts +23 -0
- package/dist/utils/payload_truncator.js +92 -0
- package/dist/utils/payload_truncator.spec.d.ts +1 -0
- package/dist/utils/payload_truncator.spec.js +51 -0
- package/dist/utils/temporal_flags.d.ts +14 -0
- package/dist/utils/temporal_flags.js +16 -0
- package/oclif.manifest.json +80 -36
- package/package.json +10 -2
- package/dist/utils/trace_extractor.d.ts +0 -27
- package/dist/utils/trace_extractor.js +0 -53
- package/dist/utils/trace_formatter.d.ts +0 -11
- package/dist/utils/trace_formatter.js +0 -401
|
@@ -1,31 +1,85 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
1
2
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
vi.mock('
|
|
8
|
-
|
|
3
|
+
import { WorkflowNotFoundError } from '@temporalio/client';
|
|
4
|
+
import WorkflowDebug from './debug.js';
|
|
5
|
+
import { collectWorkflowDebug } from '#services/workflow_debug.js';
|
|
6
|
+
import { createTemporalClient } from '#services/temporal_client.js';
|
|
7
|
+
vi.mock('#services/workflow_debug.js', () => ({ collectWorkflowDebug: vi.fn() }));
|
|
8
|
+
vi.mock('#services/temporal_client.js', async (importOriginal) => ({
|
|
9
|
+
...await importOriginal(),
|
|
10
|
+
createTemporalClient: vi.fn()
|
|
9
11
|
}));
|
|
10
12
|
describe('workflow debug command', () => {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
+
it('takes a required workflow id and an optional run id', () => {
|
|
14
|
+
expect(WorkflowDebug.args.workflowId.required).toBe(true);
|
|
15
|
+
expect(WorkflowDebug.flags['run-id'].required).toBeFalsy();
|
|
16
|
+
expect(WorkflowDebug.flags['run-id'].char).toBe('r');
|
|
17
|
+
});
|
|
18
|
+
it('shares the Temporal connection flags', () => {
|
|
19
|
+
expect(Object.keys(WorkflowDebug.flags)).toEqual(expect.arrayContaining(['profile', 'address', 'namespace']));
|
|
13
20
|
});
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
21
|
+
it('accepts --json as a hidden flag and does not hand output to the framework', () => {
|
|
22
|
+
expect(WorkflowDebug.enableJsonFlag).toBeFalsy();
|
|
23
|
+
expect(WorkflowDebug.flags.json.hidden).toBe(true);
|
|
24
|
+
});
|
|
25
|
+
describe('run()', () => {
|
|
26
|
+
const result = { complete: true, warnings: [], temporal: { address: 'a:1', namespace: 'default' }, workflows: [] };
|
|
27
|
+
const close = vi.fn();
|
|
28
|
+
const createCommand = (flags = {}) => {
|
|
29
|
+
const cmd = new WorkflowDebug(['wf-1'], {});
|
|
30
|
+
cmd.log = vi.fn();
|
|
31
|
+
cmd.parse = vi.fn().mockResolvedValue({ args: { workflowId: 'wf-1' }, flags: { 'run-id': undefined, ...flags } });
|
|
32
|
+
return cmd;
|
|
33
|
+
};
|
|
34
|
+
beforeEach(() => {
|
|
35
|
+
vi.clearAllMocks();
|
|
36
|
+
close.mockResolvedValue(undefined);
|
|
37
|
+
vi.mocked(createTemporalClient).mockResolvedValue({ client: {}, address: 'a:1', namespace: 'default', close });
|
|
38
|
+
vi.mocked(collectWorkflowDebug).mockResolvedValue(result);
|
|
39
|
+
});
|
|
40
|
+
it('prints the result as a single line of JSON and nothing else', async () => {
|
|
41
|
+
const cmd = createCommand();
|
|
42
|
+
await cmd.run();
|
|
43
|
+
expect(cmd.log).toHaveBeenCalledTimes(1);
|
|
44
|
+
expect(cmd.log).toHaveBeenCalledWith(JSON.stringify(result));
|
|
20
45
|
});
|
|
21
|
-
it('
|
|
22
|
-
const
|
|
23
|
-
|
|
46
|
+
it('connects with the Temporal flags and reads the requested run', async () => {
|
|
47
|
+
const flags = { 'run-id': 'run-9', profile: 'prod', address: 'x:1', namespace: 'ns' };
|
|
48
|
+
await createCommand(flags).run();
|
|
49
|
+
expect(createTemporalClient).toHaveBeenCalledWith(expect.objectContaining({ profile: 'prod', address: 'x:1', namespace: 'ns' }));
|
|
50
|
+
expect(collectWorkflowDebug).toHaveBeenCalledWith({}, { address: 'a:1', namespace: 'default', workflowId: 'wf-1', runId: 'run-9' });
|
|
51
|
+
});
|
|
52
|
+
it('closes the connection after a successful read', async () => {
|
|
53
|
+
await createCommand().run();
|
|
54
|
+
expect(close).toHaveBeenCalledTimes(1);
|
|
55
|
+
});
|
|
56
|
+
it('closes the connection when the read fails and prints nothing', async () => {
|
|
57
|
+
vi.mocked(collectWorkflowDebug).mockRejectedValue(new Error('boom'));
|
|
58
|
+
const cmd = createCommand();
|
|
59
|
+
await expect(cmd.run()).rejects.toThrow('boom');
|
|
60
|
+
expect(close).toHaveBeenCalledTimes(1);
|
|
61
|
+
expect(cmd.log).not.toHaveBeenCalled();
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
describe('catch()', () => {
|
|
65
|
+
const createCommand = () => {
|
|
66
|
+
const cmd = new WorkflowDebug(['wf-1'], {});
|
|
67
|
+
cmd.error = vi.fn((message) => {
|
|
68
|
+
throw new Error(message);
|
|
69
|
+
});
|
|
70
|
+
return cmd;
|
|
71
|
+
};
|
|
72
|
+
it('explains a workflow that is not found and exits 1', async () => {
|
|
73
|
+
const cmd = createCommand();
|
|
74
|
+
await expect(cmd.catch(new WorkflowNotFoundError('workflow not found for ID: wf-1', 'wf-1', undefined)))
|
|
75
|
+
.rejects.toThrow('Workflow not found for ID: wf-1. Check the workflow id, the run id and the namespace.');
|
|
76
|
+
expect(cmd.error).toHaveBeenCalledWith(expect.any(String), { exit: 1 });
|
|
24
77
|
});
|
|
25
|
-
it('
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
expect(
|
|
78
|
+
it('reports any other error as it is and exits 1', async () => {
|
|
79
|
+
const cmd = createCommand();
|
|
80
|
+
const message = 'Cannot connect to Temporal at a:1: refused';
|
|
81
|
+
await expect(cmd.catch(new Error(message))).rejects.toThrow(message);
|
|
82
|
+
expect(cmd.error).toHaveBeenCalledWith(message, { exit: 1 });
|
|
29
83
|
});
|
|
30
84
|
});
|
|
31
85
|
});
|
|
@@ -103,7 +103,6 @@ export default class WorkflowTest extends Command {
|
|
|
103
103
|
const results = [];
|
|
104
104
|
for (const dataset of datasets) {
|
|
105
105
|
this.log(` Running "${dataset.name}"...`);
|
|
106
|
-
const startMs = Date.now();
|
|
107
106
|
const response = await postWorkflowRun({
|
|
108
107
|
workflowName,
|
|
109
108
|
input: dataset.input,
|
|
@@ -111,7 +110,6 @@ export default class WorkflowTest extends Command {
|
|
|
111
110
|
}, {
|
|
112
111
|
config: { timeout: 600000 }
|
|
113
112
|
});
|
|
114
|
-
const executionTimeMs = Date.now() - startMs;
|
|
115
113
|
if (!response?.data) {
|
|
116
114
|
this.error(`Workflow execution failed for dataset "${dataset.name}"`, { exit: 1 });
|
|
117
115
|
}
|
|
@@ -119,7 +117,6 @@ export default class WorkflowTest extends Command {
|
|
|
119
117
|
...dataset,
|
|
120
118
|
last_output: {
|
|
121
119
|
output: response.data.output,
|
|
122
|
-
executionTimeMs,
|
|
123
120
|
date: new Date().toISOString()
|
|
124
121
|
}
|
|
125
122
|
};
|
|
@@ -99,6 +99,25 @@ describe('workflow test command', () => {
|
|
|
99
99
|
expect(result).toEqual(failingOutput);
|
|
100
100
|
expect(process.exitCode).toBe(1);
|
|
101
101
|
});
|
|
102
|
+
it('saves the fresh output with only the output and the date', async () => {
|
|
103
|
+
const WorkflowTest = (await import('./test.js')).default;
|
|
104
|
+
const { postWorkflowRun } = await import('#api/generated/api.js');
|
|
105
|
+
const { writeDataset } = await import('#services/datasets.js');
|
|
106
|
+
const cmd = new WorkflowTest(['simple'], {});
|
|
107
|
+
cmd.log = vi.fn();
|
|
108
|
+
cmd.jsonEnabled = vi.fn().mockReturnValue(false);
|
|
109
|
+
cmd.parse = vi.fn().mockResolvedValue({
|
|
110
|
+
args: { workflowName: 'simple' },
|
|
111
|
+
flags: { cached: false, save: true, dataset: undefined }
|
|
112
|
+
});
|
|
113
|
+
vi.mocked(postWorkflowRun)
|
|
114
|
+
.mockResolvedValueOnce({ data: { output: { result: 7 } }, status: 200, headers: new Headers() })
|
|
115
|
+
.mockResolvedValueOnce({ data: { output: passingOutput }, status: 200, headers: new Headers() });
|
|
116
|
+
await cmd.run();
|
|
117
|
+
const saved = vi.mocked(writeDataset).mock.calls[0][0];
|
|
118
|
+
expect(saved.last_output).toEqual({ output: { result: 7 }, date: expect.any(String) });
|
|
119
|
+
expect(saved.last_output).not.toHaveProperty('executionTimeMs');
|
|
120
|
+
});
|
|
102
121
|
it('routes registration, dataset runs, and the eval run to the resolved catalog', async () => {
|
|
103
122
|
const WorkflowTest = (await import('./test.js')).default;
|
|
104
123
|
const { postWorkflowRun } = await import('#api/generated/api.js');
|
|
@@ -15,7 +15,5 @@ export declare function readAllDatasets(workflowName: string, filterNames?: stri
|
|
|
15
15
|
}>;
|
|
16
16
|
export declare function writeDataset(dataset: Dataset, filePath: string): Promise<void>;
|
|
17
17
|
export declare function listDatasets(workflowName: string, basePath?: string): Promise<DatasetInfo[]>;
|
|
18
|
-
export declare function buildDataset(name: string, input: Record<string, unknown>, output: unknown
|
|
19
|
-
export declare function extractDatasetName(tracePathOrKey: string): string;
|
|
18
|
+
export declare function buildDataset(name: string, input: Record<string, unknown>, output: unknown): Dataset;
|
|
20
19
|
export declare function datasetFilePath(dir: string, name: string): string;
|
|
21
|
-
export declare function getExecutionTime(workflowId: string | undefined): Promise<number | undefined>;
|
|
@@ -3,7 +3,6 @@ import { existsSync } from 'node:fs';
|
|
|
3
3
|
import { resolve, join } from 'node:path';
|
|
4
4
|
import { load as parseYaml, dump as stringifyYaml } from 'js-yaml';
|
|
5
5
|
import { DatasetSchema } from '@outputai/core/evals';
|
|
6
|
-
import { getTrace } from '#services/trace_reader.js';
|
|
7
6
|
import { sanitizeSecrets } from '#utils/secret_sanitizer.js';
|
|
8
7
|
import { resolveWorkflowDir, WORKFLOWS_PATHS } from '#utils/workflow_dir.js';
|
|
9
8
|
import { getWorkflowsBasePath } from '#utils/paths.js';
|
|
@@ -109,20 +108,16 @@ export async function listDatasets(workflowName, basePath) {
|
|
|
109
108
|
}
|
|
110
109
|
return results;
|
|
111
110
|
}
|
|
112
|
-
export function buildDataset(name, input, output
|
|
111
|
+
export function buildDataset(name, input, output) {
|
|
113
112
|
return {
|
|
114
113
|
name,
|
|
115
114
|
input: sanitizeSecrets(input),
|
|
116
115
|
last_output: {
|
|
117
116
|
output: sanitizeSecrets(output),
|
|
118
|
-
executionTimeMs,
|
|
119
117
|
date: new Date().toISOString()
|
|
120
118
|
}
|
|
121
119
|
};
|
|
122
120
|
}
|
|
123
|
-
export function extractDatasetName(tracePathOrKey) {
|
|
124
|
-
return tracePathOrKey.replace(/^.*\//, '').replace(/\.json$/, '');
|
|
125
|
-
}
|
|
126
121
|
// Resolve the .yml path for a dataset case, sanitizing the name so it can never
|
|
127
122
|
// escape the datasets directory regardless of where the name came from
|
|
128
123
|
// (scenario arg, --name flag, or a workflow ID).
|
|
@@ -130,16 +125,3 @@ export function datasetFilePath(dir, name) {
|
|
|
130
125
|
const safeName = name.replace(/[^a-zA-Z0-9._-]/g, '_');
|
|
131
126
|
return join(dir, `${safeName}.yml`);
|
|
132
127
|
}
|
|
133
|
-
export function getExecutionTime(workflowId) {
|
|
134
|
-
if (!workflowId) {
|
|
135
|
-
return Promise.resolve(undefined);
|
|
136
|
-
}
|
|
137
|
-
return getTrace(workflowId)
|
|
138
|
-
.then(traceResult => {
|
|
139
|
-
const root = traceResult.data.root;
|
|
140
|
-
return (root.startTime && root.endTime) ?
|
|
141
|
-
root.endTime - root.startTime :
|
|
142
|
-
root.duration;
|
|
143
|
-
})
|
|
144
|
-
.catch(() => undefined);
|
|
145
|
-
}
|
|
@@ -3,7 +3,7 @@ import { mkdtemp, rm, writeFile, readFile, mkdir } from 'node:fs/promises';
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { tmpdir } from 'node:os';
|
|
5
5
|
import { load as parseYaml, dump as stringifyYaml } from 'js-yaml';
|
|
6
|
-
import { readDatasetFile, readAllDatasets, writeDataset, listDatasets, resolveDefaultDatasetsDir, datasetFilePath } from './datasets.js';
|
|
6
|
+
import { readDatasetFile, readAllDatasets, writeDataset, listDatasets, resolveDefaultDatasetsDir, datasetFilePath, buildDataset } from './datasets.js';
|
|
7
7
|
import * as catalog from '#api/workflow_catalog.js';
|
|
8
8
|
vi.mock('#api/workflow_catalog.js', () => ({
|
|
9
9
|
fetchWorkflowCatalog: vi.fn()
|
|
@@ -75,7 +75,7 @@ describe('readDatasetFile', () => {
|
|
|
75
75
|
});
|
|
76
76
|
const [dataset] = await readDatasetFile(filePath);
|
|
77
77
|
expect(dataset.last_output?.output).toEqual({ result: 42 });
|
|
78
|
-
expect(dataset.last_output
|
|
78
|
+
expect(dataset.last_output).toEqual({ output: { result: 42 }, date: '2026-01-01T00:00:00.000Z' });
|
|
79
79
|
});
|
|
80
80
|
});
|
|
81
81
|
// ---------------------------------------------------------------------------
|
|
@@ -170,7 +170,7 @@ describe('writeDataset', () => {
|
|
|
170
170
|
await writeYaml(filePath, {
|
|
171
171
|
my_case: { input: { q: 'hello' }, ground_truth: { expected: 42 } }
|
|
172
172
|
});
|
|
173
|
-
await writeDataset({ name: 'my_case', input: { q: 'hello' }, last_output: { output: { result: 42 },
|
|
173
|
+
await writeDataset({ name: 'my_case', input: { q: 'hello' }, last_output: { output: { result: 42 }, date: '2026-01-01T00:00:00.000Z' } }, filePath);
|
|
174
174
|
await writeDataset({
|
|
175
175
|
name: 'my_case', input: { q: 'hello' },
|
|
176
176
|
last_eval: { output: { datasetName: 'my_case', verdict: 'pass', evaluators: [] }, date: '2026-01-01T00:01:00.000Z' }
|
|
@@ -195,6 +195,48 @@ describe('writeDataset', () => {
|
|
|
195
195
|
expect(raw).toHaveProperty('my_case');
|
|
196
196
|
});
|
|
197
197
|
});
|
|
198
|
+
describe('writeDataset when the case already exists', () => {
|
|
199
|
+
it('replaces input and last_output and keeps ground_truth and the other fields', async () => {
|
|
200
|
+
const filePath = join(ctx.tmpDir, 'cases.yml');
|
|
201
|
+
await writeYaml(filePath, {
|
|
202
|
+
my_case: {
|
|
203
|
+
input: { q: 'old' },
|
|
204
|
+
ground_truth: { expected: 42 },
|
|
205
|
+
last_output: { output: { result: 1 }, executionTimeMs: 100, date: '2026-01-01T00:00:00.000Z' }
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
await writeDataset(buildDataset('my_case', { q: 'new' }, { result: 2 }), filePath);
|
|
209
|
+
const raw = parseYaml(await readFile(filePath, 'utf-8'));
|
|
210
|
+
expect(raw.my_case.input).toEqual({ q: 'new' });
|
|
211
|
+
expect(raw.my_case.ground_truth).toEqual({ expected: 42 });
|
|
212
|
+
expect(raw.my_case.last_output.output).toEqual({ result: 2 });
|
|
213
|
+
expect(raw.my_case.last_output).not.toHaveProperty('executionTimeMs');
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
// ---------------------------------------------------------------------------
|
|
217
|
+
// buildDataset
|
|
218
|
+
// ---------------------------------------------------------------------------
|
|
219
|
+
describe('buildDataset', () => {
|
|
220
|
+
it('builds a case with the input and a last_output of only the output and the date', () => {
|
|
221
|
+
const dataset = buildDataset('my_case', { q: 'hello' }, { result: 42 });
|
|
222
|
+
expect(dataset).toEqual({
|
|
223
|
+
name: 'my_case',
|
|
224
|
+
input: { q: 'hello' },
|
|
225
|
+
last_output: { output: { result: 42 }, date: expect.any(String) }
|
|
226
|
+
});
|
|
227
|
+
expect(dataset.last_output).not.toHaveProperty('executionTimeMs');
|
|
228
|
+
});
|
|
229
|
+
it('redacts secrets in the input and the output', () => {
|
|
230
|
+
const dataset = buildDataset('my_case', { apiKey: 'abc', q: 'hello' }, { auth_token: 'abc', answer: 'ok' });
|
|
231
|
+
expect(dataset.input.apiKey).not.toBe('abc');
|
|
232
|
+
expect(dataset.input.q).toBe('hello');
|
|
233
|
+
expect((dataset.last_output?.output).auth_token).not.toBe('abc');
|
|
234
|
+
expect((dataset.last_output?.output).answer).toBe('ok');
|
|
235
|
+
});
|
|
236
|
+
it('keeps a null output', () => {
|
|
237
|
+
expect(buildDataset('my_case', {}, null).last_output?.output).toBeNull();
|
|
238
|
+
});
|
|
239
|
+
});
|
|
198
240
|
// ---------------------------------------------------------------------------
|
|
199
241
|
// listDatasets
|
|
200
242
|
// ---------------------------------------------------------------------------
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Client } from '@temporalio/client';
|
|
2
|
+
import type { TemporalFlags } from '#utils/temporal_flags.js';
|
|
3
|
+
export interface TemporalConnectionConfig {
|
|
4
|
+
address: string;
|
|
5
|
+
namespace: string;
|
|
6
|
+
connectionOptions: {
|
|
7
|
+
address: string;
|
|
8
|
+
tls?: unknown;
|
|
9
|
+
apiKey?: string;
|
|
10
|
+
metadata?: Record<string, string>;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
export interface TemporalClientHandle {
|
|
14
|
+
client: Client;
|
|
15
|
+
address: string;
|
|
16
|
+
namespace: string;
|
|
17
|
+
close: () => Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Resolves where to connect. Precedence, highest first: flags, TEMPORAL_* env vars, the temporal.toml profile,
|
|
21
|
+
* then the dev stack's Temporal port on localhost (OUTPUT_TEMPORAL_HOST_PORT, 7233 by default) and the default namespace. The profile and env layers are read by `@temporalio/envconfig`; an explicit
|
|
22
|
+
* `--profile` that does not exist throws.
|
|
23
|
+
*
|
|
24
|
+
* @param flags - Shared Temporal flags
|
|
25
|
+
* @returns The effective address and namespace, and the options to open the connection with
|
|
26
|
+
*/
|
|
27
|
+
export declare function buildConnectionConfig(flags?: TemporalFlags): TemporalConnectionConfig;
|
|
28
|
+
/**
|
|
29
|
+
* Opens a Temporal client from the shared flags. Callers must call `close()` when done.
|
|
30
|
+
*
|
|
31
|
+
* @param flags - Shared Temporal flags
|
|
32
|
+
* @returns The client, the address and namespace it uses, and a close function
|
|
33
|
+
*/
|
|
34
|
+
export declare function createTemporalClient(flags?: TemporalFlags): Promise<TemporalClientHandle>;
|
|
35
|
+
/**
|
|
36
|
+
* Runs one Temporal call under a deadline, so an unresponsive server cannot hang the command.
|
|
37
|
+
*
|
|
38
|
+
* @param client - The Temporal client the call goes through
|
|
39
|
+
* @param call - The call to run; every request it makes shares the deadline
|
|
40
|
+
* @returns What the call returns
|
|
41
|
+
*/
|
|
42
|
+
export declare const callTemporal: <T>(client: Client, call: () => Promise<T>) => Promise<T>;
|
|
43
|
+
/**
|
|
44
|
+
* Builds the message a command prints for a failed Temporal read. A workflow or run that is not found says what to check.
|
|
45
|
+
* Anything else is reported as it is.
|
|
46
|
+
*
|
|
47
|
+
* @param error - The failure
|
|
48
|
+
* @returns The message for stderr
|
|
49
|
+
*/
|
|
50
|
+
export declare function formatTemporalError(error: unknown): string;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { Client, Connection, WorkflowNotFoundError } from '@temporalio/client';
|
|
2
|
+
import { loadClientConfigProfile, toClientOptions } from '@temporalio/envconfig';
|
|
3
|
+
import { config } from '#config.js';
|
|
4
|
+
const DEFAULT_NAMESPACE = 'default';
|
|
5
|
+
const CONNECT_TIMEOUT = '5s';
|
|
6
|
+
const CALL_TIMEOUT_MS = 30_000;
|
|
7
|
+
const GRPC_DEADLINE_EXCEEDED = 4;
|
|
8
|
+
/**
|
|
9
|
+
* Resolves where to connect. Precedence, highest first: flags, TEMPORAL_* env vars, the temporal.toml profile,
|
|
10
|
+
* then the dev stack's Temporal port on localhost (OUTPUT_TEMPORAL_HOST_PORT, 7233 by default) and the default namespace. The profile and env layers are read by `@temporalio/envconfig`; an explicit
|
|
11
|
+
* `--profile` that does not exist throws.
|
|
12
|
+
*
|
|
13
|
+
* @param flags - Shared Temporal flags
|
|
14
|
+
* @returns The effective address and namespace, and the options to open the connection with
|
|
15
|
+
*/
|
|
16
|
+
export function buildConnectionConfig(flags = {}) {
|
|
17
|
+
const profile = loadClientConfigProfile(flags.profile ? { profile: flags.profile } : {});
|
|
18
|
+
const { connectionOptions, namespace } = toClientOptions({
|
|
19
|
+
...profile,
|
|
20
|
+
...(flags.address ? { address: flags.address } : {}),
|
|
21
|
+
...(flags.namespace ? { namespace: flags.namespace } : {})
|
|
22
|
+
});
|
|
23
|
+
const address = connectionOptions.address ?? `localhost:${config.ports.temporal}`;
|
|
24
|
+
return {
|
|
25
|
+
address,
|
|
26
|
+
namespace: namespace ?? DEFAULT_NAMESPACE,
|
|
27
|
+
connectionOptions: {
|
|
28
|
+
address,
|
|
29
|
+
tls: connectionOptions.tls,
|
|
30
|
+
apiKey: connectionOptions.apiKey,
|
|
31
|
+
metadata: connectionOptions.metadata
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Opens a Temporal client from the shared flags. Callers must call `close()` when done.
|
|
37
|
+
*
|
|
38
|
+
* @param flags - Shared Temporal flags
|
|
39
|
+
* @returns The client, the address and namespace it uses, and a close function
|
|
40
|
+
*/
|
|
41
|
+
export async function createTemporalClient(flags = {}) {
|
|
42
|
+
const { address, namespace, connectionOptions } = buildConnectionConfig(flags);
|
|
43
|
+
const connection = await Connection.connect({ ...connectionOptions, connectTimeout: CONNECT_TIMEOUT })
|
|
44
|
+
.catch((error) => {
|
|
45
|
+
throw new Error(`Cannot connect to Temporal at ${address}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
46
|
+
});
|
|
47
|
+
return {
|
|
48
|
+
client: new Client({ connection, namespace }),
|
|
49
|
+
address,
|
|
50
|
+
namespace,
|
|
51
|
+
close: () => connection.close()
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Runs one Temporal call under a deadline, so an unresponsive server cannot hang the command.
|
|
56
|
+
*
|
|
57
|
+
* @param client - The Temporal client the call goes through
|
|
58
|
+
* @param call - The call to run; every request it makes shares the deadline
|
|
59
|
+
* @returns What the call returns
|
|
60
|
+
*/
|
|
61
|
+
export const callTemporal = async (client, call) => {
|
|
62
|
+
try {
|
|
63
|
+
return await client.connection.withDeadline(Date.now() + CALL_TIMEOUT_MS, call);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error?.code === GRPC_DEADLINE_EXCEEDED) {
|
|
67
|
+
throw new Error(`Temporal did not answer within ${CALL_TIMEOUT_MS / 1000}s`, { cause: error });
|
|
68
|
+
}
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Builds the message a command prints for a failed Temporal read. A workflow or run that is not found says what to check.
|
|
74
|
+
* Anything else is reported as it is.
|
|
75
|
+
*
|
|
76
|
+
* @param error - The failure
|
|
77
|
+
* @returns The message for stderr
|
|
78
|
+
*/
|
|
79
|
+
export function formatTemporalError(error) {
|
|
80
|
+
if (error instanceof WorkflowNotFoundError) {
|
|
81
|
+
return `${error.message.charAt(0).toUpperCase()}${error.message.slice(1)}. Check the workflow id, the run id and the namespace.`;
|
|
82
|
+
}
|
|
83
|
+
return error instanceof Error ? error.message : String(error);
|
|
84
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
import { Connection, WorkflowNotFoundError } from '@temporalio/client';
|
|
6
|
+
import { config } from '#config.js';
|
|
7
|
+
import { buildConnectionConfig, callTemporal, createTemporalClient, formatTemporalError } from './temporal_client.js';
|
|
8
|
+
vi.mock('@temporalio/client', async (importOriginal) => ({
|
|
9
|
+
WorkflowNotFoundError: (await importOriginal()).WorkflowNotFoundError,
|
|
10
|
+
Connection: { connect: vi.fn() },
|
|
11
|
+
Client: class {
|
|
12
|
+
options;
|
|
13
|
+
constructor(options) {
|
|
14
|
+
this.options = options;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}));
|
|
18
|
+
const profileFile = `
|
|
19
|
+
[profile.prod]
|
|
20
|
+
address = "prod.example:7233"
|
|
21
|
+
namespace = "prod-ns"
|
|
22
|
+
api_key = "secret"
|
|
23
|
+
|
|
24
|
+
[profile.staging]
|
|
25
|
+
address = "staging.example:7233"
|
|
26
|
+
namespace = "staging-ns"
|
|
27
|
+
`;
|
|
28
|
+
describe('temporal client', () => {
|
|
29
|
+
const savedEnv = { ...process.env };
|
|
30
|
+
const workspace = { directory: '' };
|
|
31
|
+
const useConfigFile = (contents) => {
|
|
32
|
+
const file = join(workspace.directory, 'temporal.toml');
|
|
33
|
+
writeFileSync(file, contents);
|
|
34
|
+
process.env.TEMPORAL_CONFIG_FILE = file;
|
|
35
|
+
};
|
|
36
|
+
beforeEach(() => {
|
|
37
|
+
vi.clearAllMocks();
|
|
38
|
+
Object.keys(process.env).filter(key => key.startsWith('TEMPORAL_')).forEach(key => delete process.env[key]);
|
|
39
|
+
workspace.directory = mkdtempSync(join(tmpdir(), 'temporal-client-'));
|
|
40
|
+
useConfigFile(profileFile);
|
|
41
|
+
});
|
|
42
|
+
afterEach(() => {
|
|
43
|
+
process.env = { ...savedEnv };
|
|
44
|
+
rmSync(workspace.directory, { recursive: true, force: true });
|
|
45
|
+
});
|
|
46
|
+
describe('buildConnectionConfig', () => {
|
|
47
|
+
it('falls back to localhost on the dev Temporal port and the default namespace', () => {
|
|
48
|
+
expect(buildConnectionConfig()).toMatchObject({ address: `localhost:${config.ports.temporal}`, namespace: 'default' });
|
|
49
|
+
});
|
|
50
|
+
it('reads the profile named by --profile, including its API key', () => {
|
|
51
|
+
const result = buildConnectionConfig({ profile: 'prod' });
|
|
52
|
+
expect(result).toMatchObject({ address: 'prod.example:7233', namespace: 'prod-ns' });
|
|
53
|
+
expect(result.connectionOptions).toMatchObject({ address: 'prod.example:7233', apiKey: 'secret' });
|
|
54
|
+
});
|
|
55
|
+
it('reads the profile named by TEMPORAL_PROFILE', () => {
|
|
56
|
+
process.env.TEMPORAL_PROFILE = 'staging';
|
|
57
|
+
expect(buildConnectionConfig()).toMatchObject({ address: 'staging.example:7233', namespace: 'staging-ns' });
|
|
58
|
+
});
|
|
59
|
+
it('lets the TEMPORAL_* environment override the profile', () => {
|
|
60
|
+
process.env.TEMPORAL_ADDRESS = 'env.example:7233';
|
|
61
|
+
process.env.TEMPORAL_NAMESPACE = 'env-ns';
|
|
62
|
+
expect(buildConnectionConfig({ profile: 'prod' })).toMatchObject({ address: 'env.example:7233', namespace: 'env-ns' });
|
|
63
|
+
});
|
|
64
|
+
it('lets the flags override the environment and the profile', () => {
|
|
65
|
+
process.env.TEMPORAL_ADDRESS = 'env.example:7233';
|
|
66
|
+
process.env.TEMPORAL_NAMESPACE = 'env-ns';
|
|
67
|
+
const result = buildConnectionConfig({ profile: 'prod', address: 'flag.example:7233', namespace: 'flag-ns' });
|
|
68
|
+
expect(result).toMatchObject({ address: 'flag.example:7233', namespace: 'flag-ns' });
|
|
69
|
+
});
|
|
70
|
+
it('throws for a profile that does not exist', () => {
|
|
71
|
+
expect(() => buildConnectionConfig({ profile: 'missing' })).toThrow();
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
describe('createTemporalClient', () => {
|
|
75
|
+
it('connects with a timeout and hands back the address, the namespace and a close function', async () => {
|
|
76
|
+
const close = vi.fn().mockResolvedValue(undefined);
|
|
77
|
+
vi.mocked(Connection.connect).mockResolvedValue({ close });
|
|
78
|
+
const handle = await createTemporalClient({ profile: 'prod' });
|
|
79
|
+
expect(Connection.connect).toHaveBeenCalledWith(expect.objectContaining({ address: 'prod.example:7233', apiKey: 'secret', connectTimeout: '5s' }));
|
|
80
|
+
expect(handle).toMatchObject({ address: 'prod.example:7233', namespace: 'prod-ns' });
|
|
81
|
+
expect(handle.client).toMatchObject({ options: { namespace: 'prod-ns' } });
|
|
82
|
+
await handle.close();
|
|
83
|
+
expect(close).toHaveBeenCalledTimes(1);
|
|
84
|
+
});
|
|
85
|
+
it('names the address when the connection fails and keeps the cause', async () => {
|
|
86
|
+
const cause = new Error('connection refused');
|
|
87
|
+
vi.mocked(Connection.connect).mockRejectedValue(cause);
|
|
88
|
+
const failure = await createTemporalClient({ address: 'nope.example:7233' }).catch((error) => error);
|
|
89
|
+
expect(failure).toMatchObject({ message: 'Cannot connect to Temporal at nope.example:7233: connection refused', cause });
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
describe('callTemporal', () => {
|
|
93
|
+
const buildClient = (withDeadline) => ({ connection: { withDeadline: vi.fn(withDeadline) } });
|
|
94
|
+
it('runs the call under a deadline in the future and returns its result', async () => {
|
|
95
|
+
const client = buildClient((_deadline, call) => call());
|
|
96
|
+
await expect(callTemporal(client, async () => 'done')).resolves.toBe('done');
|
|
97
|
+
const deadline = vi.mocked(client.connection.withDeadline).mock.calls[0][0];
|
|
98
|
+
expect(deadline).toBeGreaterThan(Date.now());
|
|
99
|
+
expect(deadline).toBeLessThanOrEqual(Date.now() + 30_000);
|
|
100
|
+
});
|
|
101
|
+
it('says Temporal did not answer when the deadline passes, and keeps the cause', async () => {
|
|
102
|
+
const cause = Object.assign(new Error('4 DEADLINE_EXCEEDED: Deadline exceeded'), { code: 4 });
|
|
103
|
+
const client = buildClient(async () => {
|
|
104
|
+
throw cause;
|
|
105
|
+
});
|
|
106
|
+
const failure = await callTemporal(client, async () => 'done').catch((error) => error);
|
|
107
|
+
expect(failure).toMatchObject({ message: 'Temporal did not answer within 30s', cause });
|
|
108
|
+
});
|
|
109
|
+
it('rethrows any other failure untouched', async () => {
|
|
110
|
+
const failure = Object.assign(new Error('permission denied'), { code: 7 });
|
|
111
|
+
const client = buildClient(async () => {
|
|
112
|
+
throw failure;
|
|
113
|
+
});
|
|
114
|
+
await expect(callTemporal(client, async () => 'done')).rejects.toBe(failure);
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
describe('formatTemporalError', () => {
|
|
118
|
+
it('says what to check for a workflow or run that is not found', () => {
|
|
119
|
+
const missing = new WorkflowNotFoundError('workflow not found for ID: wf-1', 'wf-1', undefined);
|
|
120
|
+
expect(formatTemporalError(missing)).toBe('Workflow not found for ID: wf-1. Check the workflow id, the run id and the namespace.');
|
|
121
|
+
});
|
|
122
|
+
it('reports any other error by its message', () => {
|
|
123
|
+
expect(formatTemporalError(new Error('Temporal did not answer within 30s'))).toBe('Temporal did not answer within 30s');
|
|
124
|
+
});
|
|
125
|
+
it('reports a value that is not an error as text', () => {
|
|
126
|
+
expect(formatTemporalError('boom')).toBe('boom');
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
});
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { type Client } from '@temporalio/client';
|
|
2
|
+
type Json = Record<string, any>;
|
|
3
|
+
export interface DebugOptions {
|
|
4
|
+
/** Pages (of 1,000 events) that may be read across the whole tree */
|
|
5
|
+
pageBudget?: number;
|
|
6
|
+
/** Events that may be kept across the whole tree; the last page read is cut to fit */
|
|
7
|
+
eventBudget?: number;
|
|
8
|
+
/** Histories fetched at once; speed only, the output order does not change */
|
|
9
|
+
concurrency?: number;
|
|
10
|
+
}
|
|
11
|
+
/** One workflow in the output: its metadata first, its own history events last */
|
|
12
|
+
export interface WorkflowEntry {
|
|
13
|
+
workflowId: string;
|
|
14
|
+
runId: string;
|
|
15
|
+
workflowType: string;
|
|
16
|
+
status: string | null;
|
|
17
|
+
parent?: {
|
|
18
|
+
workflowId: string;
|
|
19
|
+
runId: string;
|
|
20
|
+
};
|
|
21
|
+
pendingActivities: Json[];
|
|
22
|
+
pendingChildren: Json[];
|
|
23
|
+
events: Json[];
|
|
24
|
+
}
|
|
25
|
+
export interface WorkflowDebugResult {
|
|
26
|
+
/** True when nothing is missing; exactly `warnings.length === 0` */
|
|
27
|
+
complete: boolean;
|
|
28
|
+
/** Plain sentences about what could not be read, for people and LLMs */
|
|
29
|
+
warnings: string[];
|
|
30
|
+
temporal: {
|
|
31
|
+
address: string;
|
|
32
|
+
namespace: string;
|
|
33
|
+
};
|
|
34
|
+
/** The requested workflow first, then every child and every continued run, ordered by the time each was started */
|
|
35
|
+
workflows: WorkflowEntry[];
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Walks Temporal's JSON for an event (or any message) and replaces every payload with its decoded, truncated value.
|
|
39
|
+
* Everything else keeps Temporal's own shape; only stack traces are cut to their first lines.
|
|
40
|
+
*
|
|
41
|
+
* @param node - Value from Temporal's JSON
|
|
42
|
+
* @returns A copy with decoded payloads
|
|
43
|
+
*/
|
|
44
|
+
export declare const decodeNode: (node: unknown) => unknown;
|
|
45
|
+
/**
|
|
46
|
+
* Reads one workflow run from Temporal, with every child it started and every run that continues from it.
|
|
47
|
+
* The result has one entry per run.
|
|
48
|
+
* Events keep Temporal's default JSON form with payloads decoded and truncated, and nothing added.
|
|
49
|
+
* The status and pending lists are described after every history was read, so they are never older than the events.
|
|
50
|
+
* Paging is breadth-first under one page budget and one event budget for the whole tree. A failure on the requested run's first page throws;
|
|
51
|
+
* any other read failure becomes a warning and the entry keeps what was read.
|
|
52
|
+
*
|
|
53
|
+
* @param client - Temporal client
|
|
54
|
+
* @param params - What to read and where it lives
|
|
55
|
+
* @param params.address - Address the client uses, echoed in the result
|
|
56
|
+
* @param params.namespace - Namespace the client uses, echoed in the result
|
|
57
|
+
* @param params.workflowId - Workflow to read
|
|
58
|
+
* @param params.runId - Run to start from; the latest run when omitted
|
|
59
|
+
* @param options - Page budget, event budget and concurrency
|
|
60
|
+
* @returns The workflow entries, plus `complete` and the warnings for anything that was left out
|
|
61
|
+
*/
|
|
62
|
+
export declare function collectWorkflowDebug(client: Client, params: {
|
|
63
|
+
address: string;
|
|
64
|
+
namespace: string;
|
|
65
|
+
workflowId: string;
|
|
66
|
+
runId?: string;
|
|
67
|
+
}, options?: DebugOptions): Promise<WorkflowDebugResult>;
|
|
68
|
+
export {};
|