Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for unions to PropertyValueSerializer #434

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changes/unreleased/Improvements-434.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
component: sdk
kind: Improvements
body: Add support for unions to PropertyValueSerializer
time: 2024-12-17T15:38:18.5114634+01:00
custom:
PR: "434"
92 changes: 92 additions & 0 deletions sdk/Pulumi.Tests/Provider/PropertyValueTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -736,4 +736,96 @@ public async Task DeserializingClassWithMultipleConstructorsWorks()
Assert.Equal(5, typeWithOptionalParameterCtor.First);
Assert.Equal(1, typeWithOptionalParameterCtor.Second);
}

class UnionArgs : ResourceArgs
{
[Input("union")]
public Union<string, int> Union { get; set; }

[Input("inputUnion")]
public InputUnion<string, int> InputUnion { get; set; } = null!;
}

[Fact]
public async Task SerializingUnionTypesWorksForT0()
{
using var inputTask = Task.Delay(1000).ContinueWith(r => "InputValue");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These don't need to Delay for a whole second. Just do a 10ms wait.


var serializer = CreateSerializer();
var args = new UnionArgs
{
Union = Union<string, int>.FromT0("value"),
InputUnion = Output.Create(inputTask)
};

var expected = Object(Pair("union", new PropertyValue("value")),
Pair("inputUnion", new PropertyValue("InputValue")));

Assert.Equal(expected, await serializer.Serialize(args));
}

[Fact]
public async Task SerializingUnionTypesWorksForT1()
{
using var inputTask = Task.Delay(1000).ContinueWith(r => 2);
var serializer = CreateSerializer();
var args = new UnionArgs
{
Union = Union<string, int>.FromT1(1),
InputUnion = Output.Create(inputTask)
};

var expected = Object(Pair("union", new PropertyValue(1)), Pair("inputUnion", new PropertyValue(2)));

Assert.Equal(expected, await serializer.Serialize(args));
}

[Fact]
public async Task DeserializingUnionTypesWorksForT0()
{
var input = Object(Pair("union", new PropertyValue("value")), Pair("inputUnion", new PropertyValue("inputValue")));
var serializer = CreateSerializer();
var expected = new UnionArgs
{
Union = Union<string, int>.FromT0("value"),
InputUnion = Output.Create(Union<string, int>.FromT0("inputValue"))
};

var result = await serializer.Deserialize<UnionArgs>(input);
Assert.Equal(expected.Union, result.Union);
var inputResult = await result.InputUnion.ToOutput().GetValueAsync(default);
Assert.Equal("inputValue", inputResult);
}

[Fact]
public async Task DeserializingUnionTypesWorksForT1()
{
var input = Object(Pair("union", new PropertyValue(1)), Pair("inputUnion", new PropertyValue(2)));
var serializer = CreateSerializer();
var expected = new UnionArgs
{
Union = Union<string, int>.FromT1(1),
InputUnion = Output.Create(Union<string, int>.FromT1(2))
};

var result = await serializer.Deserialize<UnionArgs>(input);
Assert.Equal(expected.Union, result.Union);
var inputResult = await result.InputUnion.ToOutput().GetValueAsync(default);
Assert.Equal(2, inputResult);
}

[Fact]
public async Task DeserializingUnionTypesWorksForUnknown()
{
var input = Object(Pair("union", new PropertyValue(1)), Pair("inputUnion", PropertyValue.Computed));
var serializer = CreateSerializer();

var deserialized = await serializer.Deserialize<UnionArgs>(input);

var output = deserialized.InputUnion.ToOutput();
var data = await output.DataTask;
Assert.False(data.IsSecret);
Assert.False(data.IsKnown);

}
}
47 changes: 47 additions & 0 deletions sdk/Pulumi/Provider/PropertyValueSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,11 @@ async Task<PropertyValue> SerializeOutput(IOutput output)
return await SerializeOutput(output);
}

if (value is IUnion union)
{
return await Serialize(union.Value);
}

if (value is InputArgs inputArgs)
{
var inputsMap = await inputArgs.ToDictionaryAsync().ConfigureAwait(false);
Expand Down Expand Up @@ -426,6 +431,34 @@ void ThrowTypeMismatchError(PropertyValueType expectedType)
}
}

if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Union<,>))
{
var firstElementType = targetType.GetGenericArguments()[0];
var secondElementType = targetType.GetGenericArguments()[1];
var resultType=typeof(Union<,>).MakeGenericType(firstElementType, secondElementType);
try
{
var val1 = DeserializeValue(value, firstElementType, path);
var fromT0Method = resultType.GetMethod(nameof(Union<int, int>.FromT0),
BindingFlags.Public | BindingFlags.Static);
return fromT0Method?.Invoke(null, new[] { val1 });
}
catch (Exception)
{
try
{
var val2 = DeserializeValue(value, secondElementType, path);
var fromT1Method = resultType.GetMethod(nameof(Union<int, int>.FromT1),
BindingFlags.Public | BindingFlags.Static);
return fromT1Method?.Invoke(null, new[] { val2 });
}
catch (Exception)
{
throw new InvalidOperationException($"Expected {firstElementType.FullName} or {secondElementType.FullName} but got {value.GetType().FullName} deserializing {path}");
}
}
}

if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(InputList<>))
{
// change InputList<T> to Output<ImmutableArray<T>> and deserialize
Expand Down Expand Up @@ -467,6 +500,20 @@ void ThrowTypeMismatchError(PropertyValueType expectedType)
return toOutputMethod.Invoke(null, new[] { input });
}

if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(InputUnion<,>))
{
var unionType = typeof(Union<,>).MakeGenericType(targetType.GenericTypeArguments[0],
targetType.GenericTypeArguments[1]);
var outputUnionType = typeof(Output<>).MakeGenericType(unionType);
var outputUnion = DeserializeValue(value, outputUnionType, path);

var fromOutputUnion = targetType.GetMethod(
"op_Implicit",
types: new[] { outputUnionType })!;

return fromOutputUnion.Invoke(null, new[] { outputUnion });
}

if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Input<>))
{
var elementType = targetType.GetGenericArguments()[0];
Expand Down
Loading