Skip to content
Merged
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
76 changes: 64 additions & 12 deletions src/Generators/DurableTaskSourceGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,22 +63,32 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
transform: static (ctx, _) => GetDurableFunction(ctx))
.Where(static func => func != null)!;

// Get the project type configuration from MSBuild properties
IncrementalValueProvider<string?> projectTypeProvider = context.AnalyzerConfigOptionsProvider
.Select(static (provider, _) =>
{
provider.GlobalOptions.TryGetValue("build_property.DurableTaskGeneratorProjectType", out string? projectType);
return projectType;
});

// Collect all results and check if Durable Functions is referenced
IncrementalValueProvider<(Compilation, ImmutableArray<DurableTaskTypeInfo>, ImmutableArray<DurableEventTypeInfo>, ImmutableArray<DurableFunction>)> compilationAndTasks =
IncrementalValueProvider<(Compilation, ImmutableArray<DurableTaskTypeInfo>, ImmutableArray<DurableEventTypeInfo>, ImmutableArray<DurableFunction>, string?)> compilationAndTasks =
durableTaskAttributes.Collect()
.Combine(durableEventAttributes.Collect())
.Combine(durableFunctions.Collect())
.Combine(context.CompilationProvider)
.Combine(projectTypeProvider)
// Roslyn's IncrementalValueProvider.Combine creates nested tuple pairs: ((Left, Right), Right)
// After multiple .Combine() calls, we unpack the nested structure:
// x.Right = Compilation
// x.Left.Left.Left = DurableTaskAttributes (orchestrators, activities, entities)
// x.Left.Left.Right = DurableEventAttributes (events)
// x.Left.Right = DurableFunctions (Azure Functions metadata)
.Select((x, _) => (x.Right, x.Left.Left.Left, x.Left.Left.Right, x.Left.Right));
// x.Right = projectType (string?)
// x.Left.Right = Compilation
// x.Left.Left.Left.Left = DurableTaskAttributes (orchestrators, activities, entities)
// x.Left.Left.Left.Right = DurableEventAttributes (events)
// x.Left.Left.Right = DurableFunctions (Azure Functions metadata)
.Select((x, _) => (x.Left.Right, x.Left.Left.Left.Left, x.Left.Left.Left.Right, x.Left.Left.Right, x.Right));
Copy link
Member

Choose a reason for hiding this comment

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

Nit: This still makes me so sad 😅 You don't need to change it, just wanted to be sad about it :)

Copy link
Member

Choose a reason for hiding this comment

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

it is surely a beast.


// Generate the source
context.RegisterSourceOutput(compilationAndTasks, static (spc, source) => Execute(spc, source.Item1, source.Item2, source.Item3, source.Item4));
context.RegisterSourceOutput(compilationAndTasks, static (spc, source) => Execute(spc, source.Item1, source.Item2, source.Item3, source.Item4, source.Item5));
}

static DurableTaskTypeInfo? GetDurableTaskTypeInfo(GeneratorSyntaxContext context)
Expand Down Expand Up @@ -235,17 +245,16 @@ static void Execute(
Compilation compilation,
ImmutableArray<DurableTaskTypeInfo> allTasks,
ImmutableArray<DurableEventTypeInfo> allEvents,
ImmutableArray<DurableFunction> allFunctions)
ImmutableArray<DurableFunction> allFunctions,
string? projectType)
{
if (allTasks.IsDefaultOrEmpty && allEvents.IsDefaultOrEmpty && allFunctions.IsDefaultOrEmpty)
{
return;
}

// This generator also supports Durable Functions for .NET isolated, but we only generate Functions-specific
// code if we find the Durable Functions extension listed in the set of referenced assembly names.
bool isDurableFunctions = compilation.ReferencedAssemblyNames.Any(
assembly => assembly.Name.Equals("Microsoft.Azure.Functions.Worker.Extensions.DurableTask", StringComparison.OrdinalIgnoreCase));
// Determine if we should generate Durable Functions specific code
bool isDurableFunctions = DetermineIsDurableFunctions(compilation, allFunctions, projectType);

// Separate tasks into orchestrators, activities, and entities
List<DurableTaskTypeInfo> orchestrators = new();
Expand Down Expand Up @@ -381,6 +390,49 @@ public static class GeneratedDurableTaskExtensions
context.AddSource("GeneratedDurableTaskExtensions.cs", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8, SourceHashAlgorithm.Sha256));
}

/// <summary>
/// Determines whether the current project should be treated as an Azure Functions-based Durable Functions project.
/// </summary>
/// <param name="compilation">The Roslyn compilation for the project, used to inspect referenced assemblies.</param>
/// <param name="allFunctions">The collection of discovered Durable Functions triggers in the project.</param>
/// <param name="projectType">
/// An optional project type hint. When set to <c>"Functions"</c> or <c>"Standalone"</c>, this value takes precedence
/// over automatic detection. Any other value (including <c>"Auto"</c>) falls back to auto-detection.
/// </param>
/// <returns>
/// <c>true</c> if the project is determined to be a Durable Functions (Azure Functions) project; otherwise, <c>false</c>.
/// </returns>
static bool DetermineIsDurableFunctions(Compilation compilation, ImmutableArray<DurableFunction> allFunctions, string? projectType)
{
// Check if the user has explicitly configured the project type
if (!string.IsNullOrWhiteSpace(projectType))
{
// Explicit configuration takes precedence
if (projectType!.Equals("Functions", StringComparison.OrdinalIgnoreCase))
{
return true;
}
else if (projectType.Equals("Standalone", StringComparison.OrdinalIgnoreCase))
{
return false;
}
// If "Auto" or unrecognized value, fall through to auto-detection
}

// Auto-detect based on the presence of Azure Functions trigger attributes
// If we found any methods with OrchestrationTrigger, ActivityTrigger, or EntityTrigger attributes,
// then this is a Durable Functions project
if (!allFunctions.IsDefaultOrEmpty)
{
return true;
}

// Fallback: check if Durable Functions assembly is referenced
// This handles edge cases where the project references the assembly but hasn't defined triggers yet
return compilation.ReferencedAssemblyNames.Any(
assembly => assembly.Name.Equals("Microsoft.Azure.Functions.Worker.Extensions.DurableTask", StringComparison.OrdinalIgnoreCase));
}

static void AddOrchestratorFunctionDeclaration(StringBuilder sourceBuilder, DurableTaskTypeInfo orchestrator)
{
sourceBuilder.AppendLine($@"
Expand Down
60 changes: 60 additions & 0 deletions src/Generators/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,63 @@
Source generators for `Microsoft.DurableTask`

## Overview

The `Microsoft.DurableTask.Generators` package provides source generators that automatically generate type-safe extension methods for orchestrators and activities. The generator automatically detects whether you're using Azure Functions or the Durable Task Scheduler and generates appropriate code for your environment.

## Configuration

### Project Type Detection

The generator uses intelligent automatic detection to determine the project type:

1. **Primary Detection**: Checks for Azure Functions trigger attributes (`OrchestrationTrigger`, `ActivityTrigger`, `EntityTrigger`) in your code
- If any methods use these trigger attributes, it generates Azure Functions-specific code
- Otherwise, it generates standalone Durable Task Worker code

2. **Fallback Detection**: If no trigger attributes are found, checks if `Microsoft.Azure.Functions.Worker.Extensions.DurableTask` is referenced
- This handles projects that reference the Functions package but haven't defined triggers yet

This automatic detection solves the common issue where transitive dependencies on Functions packages would incorrectly trigger Functions mode even when not using Azure Functions.

### Explicit Project Type Configuration (Optional)

In rare scenarios where you need to override the automatic detection, you can explicitly configure the project type using the `DurableTaskGeneratorProjectType` MSBuild property in your `.csproj` file:

```xml
<PropertyGroup>
<DurableTaskGeneratorProjectType>Standalone</DurableTaskGeneratorProjectType>
</PropertyGroup>
```

#### Supported Values

- `Auto` (default): Automatically detects project type using the intelligent detection described above
- `Functions`: Forces generation of Azure Functions-specific code
- `Standalone`: Forces generation of standalone Durable Task Worker code (includes `AddAllGeneratedTasks` method)

#### Example: Force Standalone Mode

```xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<DurableTaskGeneratorProjectType>Standalone</DurableTaskGeneratorProjectType>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.DurableTask.Generators" OutputItemType="Analyzer" />
<!-- Your other package references -->
</ItemGroup>
</Project>
```

With standalone mode, the generator produces the `AddAllGeneratedTasks` extension method for worker registration:

```csharp
builder.Services.AddDurableTaskWorker(builder =>
{
builder.AddTasks(r => r.AddAllGeneratedTasks());
});
```

For more information, see https://github.com/microsoft/durabletask-dotnet
Loading
Loading