Search code examples
c#asynchronousf#pulumi

F# async lambda interop with C# async model


I have such a piece of code (C#, Pulumi), which I want to translate to F#:

var registryInfo = repo.RegistryId.Apply(async (id) =>
        {
            var creds = await GetCredentials.InvokeAsync(new GetCredentialsArgs {RegistryId = id});
            var decodedData = Convert.FromBase64String(creds.AuthorizationToken);
            var decoded = ASCIIEncoding.ASCII.GetString(decodedData);

            var parts = decoded.Split(':');

            return new ImageRegistry
            {
                Server = creds.ProxyEndpoint,
                Username = parts[0],
                Password = parts[1],
            };
        });

What I have managed to do so far is:

let registryInfo = repo.RegistryId.Apply (fun id -> async {
let! creds = GetCredentialsArgs ( RegistryId = id) |> GetCredentials.InvokeAsync |> Async.AwaitTask
let decodedData = Convert.FromBase64String creds.AuthorizationToken
let decoded = ASCIIEncoding.ASCII.GetString decodedData
let parts = decoded.Split ':'
return ImageRegistry( Server = input creds.ProxyEndpoint, Username= input parts.[0], Password = input parts.[1])
} 
) 

The problem is that the code above in F# returns Output<Async<ImageRegistry>>, while C# code returns expected Output<ImageRegistry>. I am doing a transition from C# to F# (to extend my skills), but I cannot handle this case myself. How this should be properly done?


Solution

  • The library Pulumi.FSharp provides a useful helper Outputs.applyAsync for this:

    open Pulumi.FSharp
    
    let registryInfo =
        repo.RegistryId |>
        Outputs.applyAsync (fun id -> async {
            let! creds = GetCredentialsArgs ( RegistryId = id) |> GetCredentials.InvokeAsync |> Async.AwaitTask
            let decodedData = Convert.FromBase64String creds.AuthorizationToken
            let decoded = ASCIIEncoding.ASCII.GetString decodedData
            let parts = decoded.Split ':'
            return ImageRegistry( Server = input creds.ProxyEndpoint, Username= input parts.[0], Password = input parts.[1])
        })