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
use crate::output::HASHMAP;
use anyhow::{Context, Error, Result};
use log::{error, info};
use pulumi_wasm_wit::client_bindings::component::pulumi_wasm::stack_interface::{
    finish, FunctionInvocationRequest, FunctionInvocationResult,
};

pub fn run<F>(f: F) -> Result<(), Error>
where
    F: Fn() -> Result<(), Error>,
{
    let outer = || {
        pulumi_wasm_common::setup_logger();
        f()?;
        run_loop()?;
        Ok(())
    };

    let result = outer();

    match result {
        Ok(()) => Ok(()),
        Err(e) => {
            error!("Error running pulumi wasm: [{e}]");
            Err(e)
        }
    }
}

fn run_loop() -> Result<(), Error> {
    run_all_function()
}

fn run_all_function() -> Result<(), Error> {
    let mut functions = finish(&[]);

    loop {
        if functions.is_empty() {
            return Ok(());
        }
        let mapped = map_functions(&functions)?;
        functions = finish(&mapped);
    }
}

fn map_functions(functions: &[FunctionInvocationRequest]) -> Result<Vec<FunctionInvocationResult>> {
    let functions_map = HASHMAP.lock().unwrap();

    functions
        .iter()
        .map(
            |FunctionInvocationRequest {
                 id,
                 function_id,
                 value,
             }| {
                info!("Invoking function [{function_id}] with value [{value:?}]");
                let f = functions_map
                    .get(function_id)
                    .context(format!("Function with id {function_id} not found"))?;
                Ok(FunctionInvocationResult {
                    id,
                    value: f(value)?,
                })
            },
        )
        .collect()
}