-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathbatch.ts
More file actions
273 lines (258 loc) · 8.32 KB
/
batch.ts
File metadata and controls
273 lines (258 loc) · 8.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import type { DaemonRequest, DaemonResponse } from '../contracts.ts';
import { AppError, asAppError } from '../utils/errors.ts';
export const DEFAULT_BATCH_MAX_STEPS = 100;
export const BATCH_BLOCKED_COMMANDS: ReadonlySet<string> = new Set(['batch', 'replay']);
const BATCH_ALLOWED_STEP_KEYS = new Set(['command', 'positionals', 'flags', 'runtime']);
export const INHERITED_PARENT_FLAG_KEYS = [
'platform',
'target',
'device',
'udid',
'serial',
'verbose',
'out',
] as const;
export type DaemonBatchStep = {
command: string;
positionals?: string[];
flags?: Record<string, unknown>;
runtime?: unknown;
};
export type BatchFlags = Record<string, unknown> & {
batchOnError?: 'stop';
batchMaxSteps?: number;
batchSteps?: DaemonBatchStep[];
};
export type BatchRequest = Omit<DaemonRequest, 'flags'> & {
flags?: BatchFlags | Record<string, unknown>;
};
export type BatchInvoke = (req: BatchRequest) => Promise<DaemonResponse>;
export type NormalizedBatchStep = {
command: string;
positionals: string[];
flags: Record<string, unknown>;
runtime?: unknown;
};
export type BatchStepResult = {
step: number;
command: string;
ok: true;
data: Record<string, unknown>;
durationMs: number;
};
export async function runBatch(
req: BatchRequest,
sessionName: string,
invoke: BatchInvoke,
): Promise<DaemonResponse> {
const flags = readBatchFlags(req.flags);
const batchOnError = flags?.batchOnError ?? 'stop';
if (batchOnError !== 'stop') {
return batchErrorResponse('INVALID_ARGS', `Unsupported batch on-error mode: ${batchOnError}.`);
}
const batchMaxSteps = flags?.batchMaxSteps ?? DEFAULT_BATCH_MAX_STEPS;
if (!Number.isInteger(batchMaxSteps) || batchMaxSteps < 1 || batchMaxSteps > 1000) {
return batchErrorResponse(
'INVALID_ARGS',
`Invalid batch max-steps: ${String(flags?.batchMaxSteps)}`,
);
}
try {
const steps = validateAndNormalizeBatchSteps(flags?.batchSteps, batchMaxSteps);
const startedAt = Date.now();
const partialResults: BatchStepResult[] = [];
for (const [index, step] of steps.entries()) {
const stepResponse = await runBatchStep(req, sessionName, step, invoke, index + 1);
if (!stepResponse.ok) {
return {
ok: false,
error: {
code: stepResponse.error.code,
message: `Batch failed at step ${stepResponse.step} (${step.command}): ${stepResponse.error.message}`,
hint: stepResponse.error.hint,
diagnosticId: stepResponse.error.diagnosticId,
logPath: stepResponse.error.logPath,
details: {
...(stepResponse.error.details ?? {}),
step: stepResponse.step,
command: step.command,
positionals: step.positionals,
executed: index,
total: steps.length,
partialResults,
},
},
};
}
partialResults.push(stepResponse.result);
}
return {
ok: true,
data: {
total: steps.length,
executed: steps.length,
totalDurationMs: Date.now() - startedAt,
results: partialResults,
},
};
} catch (error) {
const appErr = asAppError(error);
return batchErrorResponse(appErr.code, appErr.message, appErr.details);
}
}
export function validateAndNormalizeBatchSteps(
steps: unknown,
maxSteps: number,
): NormalizedBatchStep[] {
if (!Array.isArray(steps) || steps.length === 0) {
throw new AppError('INVALID_ARGS', 'batch requires a non-empty batchSteps array.');
}
if (steps.length > maxSteps) {
throw new AppError(
'INVALID_ARGS',
`batch has ${steps.length} steps; max allowed is ${maxSteps}.`,
);
}
const normalized: NormalizedBatchStep[] = [];
for (let index = 0; index < steps.length; index += 1) {
const step = steps[index] as Partial<DaemonBatchStep>;
if (!step || typeof step !== 'object') {
throw new AppError('INVALID_ARGS', `Invalid batch step at index ${index}.`);
}
const unknownKeys = Object.keys(step).filter((key) => !BATCH_ALLOWED_STEP_KEYS.has(key));
if (unknownKeys.length > 0) {
const fields = unknownKeys.map((key) => `"${key}"`).join(', ');
throw new AppError(
'INVALID_ARGS',
`Batch step ${index + 1} has unknown field(s): ${fields}. Allowed fields: command, positionals, flags, runtime.`,
);
}
const command = typeof step.command === 'string' ? step.command.trim().toLowerCase() : '';
if (!command) {
throw new AppError('INVALID_ARGS', `Batch step ${index + 1} requires command.`);
}
if (BATCH_BLOCKED_COMMANDS.has(command)) {
throw new AppError('INVALID_ARGS', `Batch step ${index + 1} cannot run ${command}.`);
}
if (step.positionals !== undefined && !Array.isArray(step.positionals)) {
throw new AppError('INVALID_ARGS', `Batch step ${index + 1} positionals must be an array.`);
}
const positionals = (step.positionals ?? []) as unknown[];
if (positionals.some((value) => typeof value !== 'string')) {
throw new AppError(
'INVALID_ARGS',
`Batch step ${index + 1} positionals must contain only strings.`,
);
}
if (
step.flags !== undefined &&
(typeof step.flags !== 'object' || Array.isArray(step.flags) || !step.flags)
) {
throw new AppError('INVALID_ARGS', `Batch step ${index + 1} flags must be an object.`);
}
if (
step.runtime !== undefined &&
(typeof step.runtime !== 'object' || Array.isArray(step.runtime) || !step.runtime)
) {
throw new AppError('INVALID_ARGS', `Batch step ${index + 1} runtime must be an object.`);
}
normalized.push({
command,
positionals: positionals as string[],
flags: (step.flags ?? {}) as Record<string, unknown>,
runtime: step.runtime,
});
}
return normalized;
}
export function buildBatchStepFlags(
parentFlags: BatchFlags | Record<string, unknown> | undefined,
stepFlags: DaemonBatchStep['flags'] | Record<string, unknown> | undefined,
): BatchFlags {
const {
batchSteps: _batchSteps,
batchOnError: _batchOnError,
batchMaxSteps: _batchMaxSteps,
...merged
} = stepFlags ?? {};
return mergeParentFlags(readBatchFlags(parentFlags), merged as BatchFlags);
}
export function mergeParentFlags<TFlags extends Record<string, unknown>>(
parentFlags: BatchFlags | Record<string, unknown> | undefined,
childFlags: TFlags,
): TFlags {
const parentRecord = readBatchFlags(parentFlags) ?? {};
const childRecord = childFlags as Record<string, unknown>;
for (const key of INHERITED_PARENT_FLAG_KEYS) {
if (childRecord[key] === undefined && parentRecord[key] !== undefined) {
childRecord[key] = parentRecord[key];
}
}
return childFlags;
}
async function runBatchStep(
req: BatchRequest,
sessionName: string,
step: NormalizedBatchStep,
invoke: BatchInvoke,
stepNumber: number,
): Promise<
| { ok: true; step: number; result: BatchStepResult }
| {
ok: false;
step: number;
error: {
code: string;
message: string;
hint?: string;
diagnosticId?: string;
logPath?: string;
details?: Record<string, unknown>;
};
}
> {
const stepStartedAt = Date.now();
const stepFlags = buildBatchStepFlags(req.flags, step.flags);
if (stepFlags.session === undefined) {
stepFlags.session = sessionName;
}
const response = await invoke({
token: req.token,
session: sessionName,
command: step.command,
positionals: step.positionals,
flags: stepFlags,
runtime: (step.runtime === undefined ? req.runtime : step.runtime) as DaemonRequest['runtime'],
meta: req.meta,
});
const durationMs = Date.now() - stepStartedAt;
if (!response.ok) {
return { ok: false, step: stepNumber, error: response.error };
}
return {
ok: true,
step: stepNumber,
result: {
step: stepNumber,
command: step.command,
ok: true,
data: response.data ?? {},
durationMs,
},
};
}
function readBatchFlags(
flags: BatchFlags | Record<string, unknown> | undefined,
): BatchFlags | undefined {
return flags as BatchFlags | undefined;
}
function batchErrorResponse(
code: string,
message: string,
details?: Record<string, unknown>,
): Extract<DaemonResponse, { ok: false }> {
return {
ok: false,
error: { code, message, ...(details ? { details } : {}) },
};
}