hen 0.15.0

Run protocol-aware API request collections from the command line or through MCP.
Documentation
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use simple_logger;
use std::{
    collections::{HashMap, HashSet},
    path::PathBuf,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc, Mutex,
    },
};

use hen::{
    automation, benchmark,
    error::{HenError, HenErrorKind, HenResult},
    parser, request,
};

use crate::{
    cli::{CommandOutcome, RunArgs},
    cli_interrupt::execute_plan_with_interrupt,
    cli_load::{load_collection, resolve_execution_plan},
    cli_output::{
        print_body_preview, print_failure_line, print_machine_error, print_run_report,
        print_status_line, print_summary, print_timing_line,
    },
};

struct PromptSession {
    previous_mode: parser::context::PromptMode,
}

impl PromptSession {
    fn configure(args: &RunArgs) -> Self {
        let previous_mode = parser::context::prompt_mode();
        let prompt_inputs: HashMap<String, String> = args.inputs.iter().cloned().collect();
        let prompt_mode = if args.non_interactive {
            parser::context::PromptMode::NonInteractive
        } else {
            parser::context::PromptMode::Interactive
        };
        parser::context::set_prompt_mode(prompt_mode);
        parser::context::set_prompt_inputs(prompt_inputs);

        Self { previous_mode }
    }
}

impl Drop for PromptSession {
    fn drop(&mut self) {
        parser::context::set_prompt_inputs(HashMap::new());
        parser::context::set_prompt_mode(self.previous_mode);
    }
}

pub(crate) async fn run(args: RunArgs) -> HenResult<CommandOutcome> {
    if args.output.is_text() {
        run_text(args).await?;
        return Ok(CommandOutcome::success());
    }

    Ok(run_machine_output(args).await)
}

async fn run_text(args: RunArgs) -> HenResult<()> {
    let _prompt_session = PromptSession::configure(&args);

    if args.verbose {
        simple_logger::init_with_level(log::Level::Debug).map_err(|err| {
            HenError::new(HenErrorKind::Cli, "Failed to initialize logger")
                .with_detail(err.to_string())
        })?;
    }

    log::debug!("Starting hen with args {:?}", args);

    let cwd = std::env::current_dir().map_err(|err| {
        HenError::new(HenErrorKind::Io, "Failed to determine current directory")
            .with_detail(err.to_string())
    })?;

    let collection = load_collection(&args, cwd.clone()).map_err(|err| match err.kind() {
        HenErrorKind::Parse | HenErrorKind::Io => err,
        _ => err.with_detail("While loading collection"),
    })?;

    log::debug!("PARSED COLLECTION\n{:#?}", collection);

    let planner = request::RequestPlanner::new(&collection.requests).map_err(|err| {
        HenError::new(
            HenErrorKind::Planner,
            "Failed to build request dependency graph",
        )
        .with_detail(err.to_string())
    })?;

    let (plan, display_targets, primary_target) =
        resolve_execution_plan(&collection, &planner, &args)?;

    automation::validate_plan_prompt_inputs(&collection.requests, &plan)?;

    if args.export {
        for idx in &display_targets {
            if let Some(request) = collection.requests.get(*idx) {
                println!("{}", request.as_curl());
            }
        }
        return Ok(());
    }

    if let Some(count) = args.benchmark {
        if let Some(target) = primary_target {
            benchmark::benchmark(&collection.requests, &planner, target, count)
                .await
                .map_err(|err| {
                    HenError::new(HenErrorKind::Benchmark, "Benchmark execution failed")
                        .with_detail(err.to_string())
                })?;
        } else {
            return Err(HenError::new(
                HenErrorKind::Benchmark,
                "Benchmark requires selecting a specific request",
            )
            .with_exit_code(2));
        }

        return Ok(());
    }

    let parallel_enabled = args.parallel || args.max_concurrency > 0;
    let max_concurrency = if args.max_concurrency == 0 {
        None
    } else {
        Some(args.max_concurrency)
    };

    let execution_options = request::ExecutionOptions {
        parallel: parallel_enabled,
        max_concurrency,
        continue_on_error: args.continue_on_error,
    };

    log::debug!(
        "Execution options: parallel={}, max_concurrency={:?}, continue_on_error={}",
        execution_options.parallel,
        execution_options.max_concurrency,
        execution_options.continue_on_error
    );

    let display_set: HashSet<usize> = display_targets.iter().copied().collect();
    let display_set_shared = Arc::new(display_set.clone());
    let verbose = args.verbose;

    #[derive(Default)]
    struct StreamPrinterState {
        needs_separator: bool,
    }

    let printer_state = Arc::new(Mutex::new(StreamPrinterState::default()));
    let events_emitted = Arc::new(AtomicBool::new(false));

    let observer: request::ExecutionObserver = Arc::new({
        let display_set = Arc::clone(&display_set_shared);
        let printer_state = Arc::clone(&printer_state);
        let events_emitted = Arc::clone(&events_emitted);
        move |event: request::ExecutionEvent| match event {
            request::ExecutionEvent::RequestCompleted { record } => {
                let mut state = printer_state.lock().unwrap();
                events_emitted.store(true, Ordering::Relaxed);
                if state.needs_separator {
                    println!();
                } else {
                    state.needs_separator = true;
                }
                print_status_line(&record);
                if verbose {
                    print_timing_line(record.execution.artifact.timing_phases.as_slice());
                }
                if display_set.contains(&record.index) {
                    print_body_preview(&record, verbose);
                }
            }
            request::ExecutionEvent::RequestFailed { failure } => {
                let mut state = printer_state.lock().unwrap();
                events_emitted.store(true, Ordering::Relaxed);
                if state.needs_separator {
                    println!();
                } else {
                    state.needs_separator = true;
                }
                print_failure_line(&failure);
                if verbose {
                    if let Some(artifact) = failure.artifact() {
                        print_timing_line(artifact.timing_phases.as_slice());
                    }
                }
            }
            request::ExecutionEvent::AssertionPassed { request, assertion } => {
                let _guard = printer_state.lock().unwrap();
                events_emitted.store(true, Ordering::Relaxed);
                println!("✅ [{}] [{}]", request, assertion);
            }
        }
    });

    let execution_result = execute_plan_with_interrupt(
        &collection.requests,
        &plan,
        execution_options,
        Some(observer),
    )
    .await;

    let execution_result = execution_result?;
    let records = execution_result.records;
    let failures = execution_result.failures;
    let execution_failed = execution_result.execution_failed;
    let interrupted = execution_result.interrupted;

    if events_emitted.load(Ordering::Relaxed) {
        println!();
    } else {
        if !records.is_empty() {
            for (idx, record) in records.iter().enumerate() {
                if idx > 0 {
                    println!();
                }
                print_status_line(record);
                if verbose {
                    print_timing_line(record.execution.artifact.timing_phases.as_slice());
                }
                if display_set.contains(&record.index) {
                    print_body_preview(record, verbose);
                }
            }
        }

        if !failures.is_empty() {
            if !records.is_empty() {
                println!();
            }
            for failure in &failures {
                print_failure_line(failure);
                if verbose {
                    if let Some(artifact) = failure.artifact() {
                        print_timing_line(artifact.timing_phases.as_slice());
                    }
                }
            }
        }

        if !records.is_empty() || !failures.is_empty() {
            println!();
        }
    }

    print_summary(&records, &failures, interrupted, plan.len());

    if let Some(signal) = interrupted {
        return Err(
            HenError::new(
                HenErrorKind::Execution,
                format!("Execution interrupted by {}", signal.as_str()),
            )
            .with_exit_code(signal.exit_code()),
        );
    }

    if !failures.is_empty() {
        let failure_details = failures
            .iter()
            .map(|failure| failure.to_string())
            .collect::<Vec<_>>()
            .join("\n");

        return Err(
            HenError::new(HenErrorKind::Execution, "One or more requests failed")
                .with_detail(failure_details),
        );
    }

    if execution_failed {
        return Err(HenError::new(
            HenErrorKind::Execution,
            "Execution terminated before completing all requests",
        ));
    }

    Ok(())
}

async fn run_machine_output(args: RunArgs) -> CommandOutcome {
    let output = args.output;
    let suite_name = args.path.as_deref().unwrap_or("hen run").to_string();

    match build_machine_run_outcome(&args).await {
        Ok(outcome) => {
            print_run_report(output, &outcome);

            let exit_code = if let Some(signal) = outcome.interrupted {
                signal.exit_code()
            } else if outcome.failures.is_empty() && !outcome.execution_failed {
                0
            } else {
                1
            };

            CommandOutcome::with_exit_code(exit_code)
        }
        Err(err) => {
            print_machine_error(output, &suite_name, "run", &err);
            CommandOutcome::with_exit_code(err.exit_code())
        }
    }
}

async fn build_machine_run_outcome(args: &RunArgs) -> HenResult<automation::RunOutcome> {
    if args.export {
        return Err(HenError::new(
            HenErrorKind::Input,
            format!(
                "--output {} cannot be combined with --export",
                args.output.as_str()
            ),
        )
        .with_exit_code(2));
    }

    if args.benchmark.is_some() {
        return Err(HenError::new(
            HenErrorKind::Input,
            format!(
                "--output {} cannot be combined with --benchmark",
                args.output.as_str()
            ),
        )
        .with_exit_code(2));
    }

    let path = match args.path.as_ref() {
        Some(path) => PathBuf::from(path),
        None => std::env::current_dir().map_err(|err| {
            HenError::new(HenErrorKind::Io, "Failed to determine current directory")
                .with_detail(err.to_string())
        })?,
    };

    let parallel_enabled = args.parallel || args.max_concurrency > 0;
    let max_concurrency = if args.max_concurrency == 0 {
        None
    } else {
        Some(args.max_concurrency)
    };

    let execution_options = request::ExecutionOptions {
        parallel: parallel_enabled,
        max_concurrency,
        continue_on_error: args.continue_on_error,
    };

    let prepared = automation::prepare_run_path(automation::RunRequest {
        path,
        selector: args.selector.clone(),
        inputs: args.inputs.iter().cloned().collect(),
        execution_options: execution_options.clone(),
    })
    .await?;

    let execution = execute_plan_with_interrupt(
        &prepared.requests,
        &prepared.plan,
        execution_options,
        None,
    )
    .await?;

    Ok(automation::finish_run(
        prepared,
        execution.records,
        execution.failures,
        execution.execution_failed,
        execution.interrupted,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_guard() -> std::sync::MutexGuard<'static, ()> {
        static TEST_GUARD: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
        TEST_GUARD
            .get_or_init(|| std::sync::Mutex::new(()))
            .lock()
            .unwrap()
    }

    #[test]
    fn prompt_session_is_interactive_for_text_runs_by_default() {
        let _guard = test_guard();
        let previous_mode = parser::context::prompt_mode();
        parser::context::set_prompt_mode(parser::context::PromptMode::NonInteractive);

        let session = PromptSession::configure(&RunArgs::default());

        assert_eq!(
            parser::context::prompt_mode(),
            parser::context::PromptMode::Interactive
        );

        drop(session);
        parser::context::set_prompt_mode(previous_mode);
    }

    #[test]
    fn prompt_session_remains_non_interactive_when_requested() {
        let _guard = test_guard();
        let previous_mode = parser::context::prompt_mode();
        parser::context::set_prompt_mode(parser::context::PromptMode::Interactive);

        let session = PromptSession::configure(&RunArgs {
            non_interactive: true,
            ..RunArgs::default()
        });

        assert_eq!(
            parser::context::prompt_mode(),
            parser::context::PromptMode::NonInteractive
        );

        drop(session);
        parser::context::set_prompt_mode(previous_mode);
    }
}