Add Python Expression support (#4600)
* Scaffold Python project * Add Workflow Variable accessor * Add RunPython activity * Add option to register scripts via options
This commit is contained in:
parent
ab32474c29
commit
f8e0f20296
7
Elsa.sln
7
Elsa.sln
|
|
@ -283,6 +283,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "storage", "storage", "{B818
|
|||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Elsa.CSharp", "src\modules\Elsa.CSharp\Elsa.CSharp.csproj", "{24331E82-D7AF-45B1-ACF0-CA6C3B0B77DC}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Elsa.Python", "src\modules\Elsa.Python\Elsa.Python.csproj", "{790E94F2-5393-47DF-AC52-D9247F5B243A}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
|
|
@ -709,6 +711,10 @@ Global
|
|||
{24331E82-D7AF-45B1-ACF0-CA6C3B0B77DC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{24331E82-D7AF-45B1-ACF0-CA6C3B0B77DC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{24331E82-D7AF-45B1-ACF0-CA6C3B0B77DC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{790E94F2-5393-47DF-AC52-D9247F5B243A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{790E94F2-5393-47DF-AC52-D9247F5B243A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{790E94F2-5393-47DF-AC52-D9247F5B243A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{790E94F2-5393-47DF-AC52-D9247F5B243A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
|
@ -839,6 +845,7 @@ Global
|
|||
{B818988E-639C-4E6E-85C1-B231BCAD9DAB} = {5BA4A8FA-F7F4-45B3-AEC8-8886D35AAC79}
|
||||
{732BF088-6AD7-4C4D-9A48-8074253596D4} = {B818988E-639C-4E6E-85C1-B231BCAD9DAB}
|
||||
{24331E82-D7AF-45B1-ACF0-CA6C3B0B77DC} = {6EF07978-A6D2-40EB-891D-7D70C5F37E76}
|
||||
{790E94F2-5393-47DF-AC52-D9247F5B243A} = {6EF07978-A6D2-40EB-891D-7D70C5F37E76}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {D4B5CEAA-7D70-4FCB-A68E-B03FBE5E0E5E}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@
|
|||
<ProjectReference Include="..\..\modules\Elsa.CSharp\Elsa.CSharp.csproj" />
|
||||
<ProjectReference Include="..\..\modules\Elsa.EntityFrameworkCore.Sqlite\Elsa.EntityFrameworkCore.Sqlite.csproj" />
|
||||
<ProjectReference Include="..\..\modules\Elsa.EntityFrameworkCore.SqlServer\Elsa.EntityFrameworkCore.SqlServer.csproj" />
|
||||
<ProjectReference Include="..\..\modules\Elsa.Python\Elsa.Python.csproj" />
|
||||
<ProjectReference Include="..\..\modules\Elsa.Quartz.EntityFrameworkCore.Sqlite\Elsa.Quartz.EntityFrameworkCore.Sqlite.csproj" />
|
||||
<ProjectReference Include="..\..\modules\Elsa.FileStorage\Elsa.FileStorage.csproj" />
|
||||
<ProjectReference Include="..\Elsa\Elsa.csproj"/>
|
||||
|
|
|
|||
|
|
@ -151,7 +151,20 @@ services
|
|||
options.AppendScript("string Greet(string name) => $\"Hello {name}!\";");
|
||||
options.AppendScript("string SayHelloWorld() => Greet(\"World\");");
|
||||
})
|
||||
.UseJavaScript(options => options.AllowClrAccess = true)
|
||||
.UseJavaScript(options =>
|
||||
{
|
||||
options.AllowClrAccess = true;
|
||||
options.ConfigureEngine(engine =>
|
||||
{
|
||||
engine.Execute("function greet(name) { return `Hello ${name}!`; }");
|
||||
engine.Execute("function sayHelloWorld() { return greet('World'); }");
|
||||
});
|
||||
})
|
||||
.UsePython(options =>
|
||||
{
|
||||
options.AddScript("def greet(name): return f\"Hello {name}!\";");
|
||||
options.AddScript("def say_hello_world(): return greet(\"World\");");
|
||||
})
|
||||
.UseLiquid(liquid => liquid.FluidOptions = options => options.Encoder = HtmlEncoder.Default)
|
||||
.UseHttp(http =>
|
||||
{
|
||||
|
|
|
|||
|
|
@ -51,6 +51,7 @@ public class ExpressionJsonConverter : JsonConverter<IExpression>
|
|||
"Literal" => typeof(LiteralExpression),
|
||||
"CSharp" => typeof(CSharpExpression),
|
||||
"JavaScript" => typeof(JavaScriptExpression),
|
||||
"Python" => typeof(PythonExpression),
|
||||
"Liquid" => typeof(LiquidExpression),
|
||||
"Object" => typeof(ObjectExpression),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(expressionTypeName), expressionTypeName, null)
|
||||
|
|
@ -62,6 +63,7 @@ public class ExpressionJsonConverter : JsonConverter<IExpression>
|
|||
nameof(LiteralExpression) => "Literal",
|
||||
nameof(CSharpExpression) => "CSharp",
|
||||
nameof(JavaScriptExpression) => "JavaScript",
|
||||
nameof(PythonExpression) => "Python",
|
||||
nameof(LiquidExpression) => "Liquid",
|
||||
nameof(ObjectExpression) => "Object",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(expressionType), expressionType, null)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ using Elsa.Api.Client.Contracts;
|
|||
namespace Elsa.Api.Client.Expressions;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a c# expression.
|
||||
/// Represents a C# expression.
|
||||
/// </summary>
|
||||
public class CSharpExpression : IExpression
|
||||
{
|
||||
|
|
@ -19,19 +19,19 @@ public class CSharpExpression : IExpression
|
|||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CSharpExpression"/> class.
|
||||
/// </summary>
|
||||
/// <param name="value">The c# expression.</param>
|
||||
/// <param name="value">The C# expression.</param>
|
||||
public CSharpExpression(string value)
|
||||
{
|
||||
Value = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the c# expression.
|
||||
/// Gets or sets the C# expression.
|
||||
/// </summary>
|
||||
public string? Value { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the c# expression.
|
||||
/// Returns the C# expression.
|
||||
/// </summary>
|
||||
public override string ToString() => Value ?? "";
|
||||
}
|
||||
37
src/clients/Elsa.Api.Client/Expressions/PythonExpression.cs
Normal file
37
src/clients/Elsa.Api.Client/Expressions/PythonExpression.cs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
using System.Text.Json.Serialization;
|
||||
using Elsa.Api.Client.Contracts;
|
||||
|
||||
namespace Elsa.Api.Client.Expressions;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a Python expression.
|
||||
/// </summary>
|
||||
public class PythonExpression : IExpression
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PythonExpression"/> class.
|
||||
/// </summary>
|
||||
[JsonConstructor]
|
||||
public PythonExpression()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PythonExpression"/> class.
|
||||
/// </summary>
|
||||
/// <param name="value">The Python expression.</param>
|
||||
public PythonExpression(string value)
|
||||
{
|
||||
Value = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Python expression.
|
||||
/// </summary>
|
||||
public string? Value { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the Python expression.
|
||||
/// </summary>
|
||||
public override string ToString() => Value ?? "";
|
||||
}
|
||||
|
|
@ -27,12 +27,6 @@ public class RunCSharp : CodeActivity<object?>
|
|||
Script = new Input<string>(script);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A list of possible outcomes. Use "SetOutcome(string)" to set the outcome. Use "SetOutcomes(params string[])" to set multiple outcomes.
|
||||
/// </summary>
|
||||
[Input(Description = "A list of possible outcomes.", UIHint = InputUIHints.DynamicOutcomes)]
|
||||
public Input<ICollection<string>> PossibleOutcomes { get; set; } = default!;
|
||||
|
||||
/// <summary>
|
||||
/// The script to run.
|
||||
/// </summary>
|
||||
|
|
@ -42,6 +36,12 @@ public class RunCSharp : CodeActivity<object?>
|
|||
OptionsProvider = typeof(RunCSharpOptionsProvider)
|
||||
)]
|
||||
public Input<string> Script { get; set; } = new("");
|
||||
|
||||
/// <summary>
|
||||
/// A list of possible outcomes. Use "SetOutcome(string)" to set the outcome. Use "SetOutcomes(params string[])" to set multiple outcomes.
|
||||
/// </summary>
|
||||
[Input(Description = "A list of possible outcomes.", UIHint = InputUIHints.DynamicOutcomes)]
|
||||
public Input<ICollection<string>> PossibleOutcomes { get; set; } = default!;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async ValueTask ExecuteAsync(ActivityExecutionContext context)
|
||||
|
|
@ -52,7 +52,7 @@ public class RunCSharp : CodeActivity<object?>
|
|||
if (string.IsNullOrWhiteSpace(script))
|
||||
return;
|
||||
|
||||
// Get a JavaScript evaluator.
|
||||
// Get a C# evaluator.
|
||||
var evaluator = context.GetRequiredService<ICSharpEvaluator>();
|
||||
|
||||
// Run the script.
|
||||
|
|
|
|||
|
|
@ -24,6 +24,6 @@ public static class ModuleExtensions
|
|||
/// </summary>
|
||||
public static IModule UseCSharp(this IModule module, Action<CSharpOptions> configureOptions)
|
||||
{
|
||||
return module.UseCSharp(csharp => csharp.RoslynOptions += configureOptions);
|
||||
return module.UseCSharp(csharp => csharp.CSharpOptions += configureOptions);
|
||||
}
|
||||
}
|
||||
|
|
@ -27,14 +27,14 @@ public class CSharpFeature : FeatureBase
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the <see cref="RoslynOptions"/>.
|
||||
/// Configures the <see cref="CSharpOptions"/>.
|
||||
/// </summary>
|
||||
public Action<CSharpOptions> RoslynOptions { get; set; } = _ => { };
|
||||
public Action<CSharpOptions> CSharpOptions { get; set; } = _ => { };
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Apply()
|
||||
{
|
||||
Services.Configure(RoslynOptions);
|
||||
Services.Configure(CSharpOptions);
|
||||
|
||||
// C# services.
|
||||
Services
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using System.Text;
|
||||
using Elsa.CSharp.Notifications;
|
||||
using Elsa.Expressions.Models;
|
||||
using Elsa.Extensions;
|
||||
using Elsa.Mediator.Contracts;
|
||||
using Humanizer;
|
||||
|
|
@ -30,7 +31,7 @@ public class GenerateWorkflowVariableAccessors : INotificationHandler<Evaluating
|
|||
{
|
||||
var variableName = variable.Name.Pascalize();
|
||||
var variableType = variable.GetVariableType();
|
||||
var friendlyTypeName = GetFriendlyTypeName(variableType);
|
||||
var friendlyTypeName = variableType.GetFriendlyTypeName(Brackets.Angle);
|
||||
sb.AppendLine($"\tpublic {friendlyTypeName} {variableName}");
|
||||
sb.AppendLine("\t{");
|
||||
sb.AppendLine($"\t\tget => Get<{friendlyTypeName}>(\"{variableName}\");");
|
||||
|
|
@ -43,29 +44,4 @@ public class GenerateWorkflowVariableAccessors : INotificationHandler<Evaluating
|
|||
notification.AppendScript(sb.ToString());
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a friendly type name for the specified type that is suitable for constructing C# code.
|
||||
/// </summary>
|
||||
private static string GetFriendlyTypeName(Type type)
|
||||
{
|
||||
if (!type.IsGenericType)
|
||||
return type.FullName!;
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(type.Namespace);
|
||||
sb.Append('.');
|
||||
sb.Append(type.Name[..type.Name.IndexOf('`')]);
|
||||
sb.Append('<');
|
||||
var genericArgs = type.GetGenericArguments();
|
||||
for (var i = 0; i < genericArgs.Length; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
sb.Append(", ");
|
||||
sb.Append(GetFriendlyTypeName(genericArgs[i]));
|
||||
}
|
||||
|
||||
sb.Append('>');
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text;
|
||||
using Elsa.Expressions.Models;
|
||||
|
||||
// ReSharper disable once CheckNamespace
|
||||
namespace Elsa.Extensions;
|
||||
|
|
@ -18,7 +20,7 @@ public static class TypeExtensions
|
|||
public static string GetSimpleAssemblyQualifiedName(this Type type)
|
||||
{
|
||||
if (type is null) throw new ArgumentNullException(nameof(type));
|
||||
return SimpleAssemblyQualifiedTypeNameCache.GetOrAdd(type, BuildSimplifiedName);
|
||||
return SimpleAssemblyQualifiedTypeNameCache.GetOrAdd(type, GetSimplifiedName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -77,8 +79,33 @@ public static class TypeExtensions
|
|||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a friendly type name for the specified type.
|
||||
/// </summary>
|
||||
public static string GetFriendlyTypeName(this Type type, Brackets brackets)
|
||||
{
|
||||
if (!type.IsGenericType)
|
||||
return type.FullName!;
|
||||
|
||||
private static string BuildSimplifiedName(Type type)
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(type.Namespace);
|
||||
sb.Append('.');
|
||||
sb.Append(type.Name[..type.Name.IndexOf('`')]);
|
||||
sb.Append(brackets.Open);
|
||||
var genericArgs = type.GetGenericArguments();
|
||||
for (var i = 0; i < genericArgs.Length; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
sb.Append(", ");
|
||||
sb.Append(GetFriendlyTypeName(genericArgs[i], brackets));
|
||||
}
|
||||
|
||||
sb.Append(brackets.Close);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string GetSimplifiedName(Type type)
|
||||
{
|
||||
var assemblyName = type.Assembly.GetName().Name;
|
||||
|
||||
|
|
@ -90,7 +117,7 @@ public static class TypeExtensions
|
|||
var arity = genericTypeName[backtickIndex..];
|
||||
|
||||
var genericArguments = type.GetGenericArguments();
|
||||
var simplifiedGenericArguments = genericArguments.Select(BuildSimplifiedName);
|
||||
var simplifiedGenericArguments = genericArguments.Select(GetSimplifiedName);
|
||||
|
||||
return $"{typeNameWithoutArity}{arity}[[{string.Join("],[", simplifiedGenericArguments)}]], {assemblyName}";
|
||||
}
|
||||
|
|
|
|||
37
src/modules/Elsa.Expressions/Models/Brackets.cs
Normal file
37
src/modules/Elsa.Expressions/Models/Brackets.cs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
namespace Elsa.Expressions.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a bracket pair.
|
||||
/// </summary>
|
||||
public class Brackets
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the opening bracket.
|
||||
/// </summary>
|
||||
public char Open { get; }
|
||||
/// <summary>
|
||||
/// Gets the closing bracket.
|
||||
/// </summary>
|
||||
public char Close { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Brackets"/> class.
|
||||
/// </summary>
|
||||
/// <param name="open">The opening bracket.</param>
|
||||
/// <param name="close">The closing bracket.</param>
|
||||
public Brackets(char open, char close)
|
||||
{
|
||||
Open = open;
|
||||
Close = close;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An angle bracket pair.
|
||||
/// </summary>
|
||||
public static Brackets Angle => new('<', '>');
|
||||
|
||||
/// <summary>
|
||||
/// A square bracket pair.
|
||||
/// </summary>
|
||||
public static Brackets Square => new('[', ']');
|
||||
}
|
||||
|
|
@ -25,12 +25,6 @@ public class RunJavaScript : CodeActivity<object?>
|
|||
{
|
||||
Script = new Input<string>(script);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A list of possible outcomes. Use "setOutcome()" to set the outcome. Use "setOutcomes" to set multiple outcomes.
|
||||
/// </summary>
|
||||
[Input(Description = "A list of possible outcomes.", UIHint = InputUIHints.DynamicOutcomes)]
|
||||
public Input<ICollection<string>> PossibleOutcomes { get; set; } = default!;
|
||||
|
||||
/// <summary>
|
||||
/// The script to run.
|
||||
|
|
@ -41,6 +35,12 @@ public class RunJavaScript : CodeActivity<object?>
|
|||
OptionsProvider = typeof(RunJavaScriptOptionsProvider)
|
||||
)]
|
||||
public Input<string> Script { get; set; } = new("");
|
||||
|
||||
/// <summary>
|
||||
/// A list of possible outcomes. Use "setOutcome()" to set the outcome. Use "setOutcomes" to set multiple outcomes.
|
||||
/// </summary>
|
||||
[Input(Description = "A list of possible outcomes.", UIHint = InputUIHints.DynamicOutcomes)]
|
||||
public Input<ICollection<string>> PossibleOutcomes { get; set; } = default!;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async ValueTask ExecuteAsync(ActivityExecutionContext context)
|
||||
|
|
|
|||
70
src/modules/Elsa.Python/Activities/RunPython/RunPython.cs
Normal file
70
src/modules/Elsa.Python/Activities/RunPython/RunPython.cs
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
using Elsa.Extensions;
|
||||
using Elsa.Python.Contracts;
|
||||
using Elsa.Python.Models;
|
||||
using Elsa.Workflows.Core;
|
||||
using Elsa.Workflows.Core.Attributes;
|
||||
using Elsa.Workflows.Core.Models;
|
||||
|
||||
// ReSharper disable once CheckNamespace
|
||||
namespace Elsa.Python.Activities;
|
||||
|
||||
/// <summary>
|
||||
/// Executes Python code.
|
||||
/// </summary>
|
||||
[Activity("Elsa", "Scripting", "Executes Python code", DisplayName = "Run Python")]
|
||||
public class RunPython : CodeActivity<object?>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public RunPython([CallerFilePath] string? source = default, [CallerLineNumber] int? line = default) : base(source, line)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public RunPython(string script, [CallerFilePath] string? source = default, [CallerLineNumber] int? line = default) : this(source, line)
|
||||
{
|
||||
Script = new Input<string>(script);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The script to run.
|
||||
/// </summary>
|
||||
[Input(
|
||||
Description = "The script to run.",
|
||||
UIHint = InputUIHints.CodeEditor,
|
||||
OptionsProvider = typeof(RunPythonOptionsProvider)
|
||||
)]
|
||||
public Input<string> Script { get; set; } = new("");
|
||||
|
||||
/// <summary>
|
||||
/// A list of possible outcomes. Use "SetOutcome(string)" to set the outcome. Use "SetOutcomes(params string[])" to set multiple outcomes.
|
||||
/// </summary>
|
||||
[Input(Description = "A list of possible outcomes.", UIHint = InputUIHints.DynamicOutcomes)]
|
||||
public Input<ICollection<string>> PossibleOutcomes { get; set; } = default!;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async ValueTask ExecuteAsync(ActivityExecutionContext context)
|
||||
{
|
||||
var script = context.Get(Script);
|
||||
|
||||
// If no script was specified, there's nothing to do.
|
||||
if (string.IsNullOrWhiteSpace(script))
|
||||
return;
|
||||
|
||||
// Get a Python evaluator.
|
||||
var evaluator = context.GetRequiredService<IPythonEvaluator>();
|
||||
|
||||
// Run the script.
|
||||
var result = await evaluator.EvaluateAsync(script, typeof(object), context.ExpressionExecutionContext, context.CancellationToken);
|
||||
|
||||
// Set the result as output, if any.
|
||||
if (result is not null)
|
||||
context.Set(Result, result);
|
||||
|
||||
// Get the outcome or outcomes set by the script, if any. If not set, use "Done".
|
||||
var outcomes = context.ExpressionExecutionContext.TransientProperties.GetValueOrDefault(OutcomeProxy.OutcomePropertiesKey, () => new[] { "Done" })!;
|
||||
|
||||
// Complete the activity with the outcome.
|
||||
await context.CompleteActivityWithOutcomesAsync(outcomes);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
using System.Reflection;
|
||||
using Elsa.Workflows.Core.Contracts;
|
||||
using Elsa.Workflows.Management.ActivityInputOptions;
|
||||
|
||||
// ReSharper disable once CheckNamespace
|
||||
namespace Elsa.Python.Activities;
|
||||
|
||||
internal class RunPythonOptionsProvider : IActivityPropertyOptionsProvider
|
||||
{
|
||||
public ValueTask<IDictionary<string, object>> GetOptionsAsync(PropertyInfo property, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var options = new Dictionary<string, object>
|
||||
{
|
||||
["CodeEditorOptions"] = new CodeEditorOptions
|
||||
{
|
||||
Language = "python"
|
||||
}
|
||||
};
|
||||
|
||||
return new(options);
|
||||
}
|
||||
}
|
||||
25
src/modules/Elsa.Python/Contracts/IPythonEvaluator.cs
Normal file
25
src/modules/Elsa.Python/Contracts/IPythonEvaluator.cs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
using Elsa.Expressions.Models;
|
||||
using JetBrains.Annotations;
|
||||
|
||||
namespace Elsa.Python.Contracts;
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates C# expressions.
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
public interface IPythonEvaluator
|
||||
{
|
||||
/// <summary>
|
||||
/// Evaluates a Python expression.
|
||||
/// </summary>
|
||||
/// <param name="expression">The expression to evaluate.</param>
|
||||
/// <param name="returnType">The type of the return value.</param>
|
||||
/// <param name="context">The context in which the expression is evaluated.</param>
|
||||
/// <param name="cancellationToken">An optional cancellation token.</param>
|
||||
/// <returns>The result of the evaluation.</returns>
|
||||
Task<object?> EvaluateAsync(
|
||||
string expression,
|
||||
Type returnType,
|
||||
ExpressionExecutionContext context,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
23
src/modules/Elsa.Python/Elsa.Python.csproj
Normal file
23
src/modules/Elsa.Python/Elsa.Python.csproj
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<Import Project="..\..\..\common.props" />
|
||||
<Import Project="..\..\..\configureawait.props" />
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net6.0;net7.0</TargetFrameworks>
|
||||
<Description>
|
||||
Provides a Python expression provider.
|
||||
</Description>
|
||||
<PackageTags>elsa module expressions scripting python</PackageTags>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Elsa.Expressions\Elsa.Expressions.csproj" />
|
||||
<ProjectReference Include="..\Elsa.Workflows.Management\Elsa.Workflows.Management.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="IronPython" Version="3.4.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
23
src/modules/Elsa.Python/Expressions/PythonExpression.cs
Normal file
23
src/modules/Elsa.Python/Expressions/PythonExpression.cs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
using Elsa.Expressions.Contracts;
|
||||
|
||||
namespace Elsa.Python.Expressions;
|
||||
|
||||
/// <summary>
|
||||
/// A Python expression.
|
||||
/// </summary>
|
||||
public class PythonExpression : IExpression
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PythonExpression"/> class.
|
||||
/// </summary>
|
||||
/// <param name="value">The Python expression.</param>
|
||||
public PythonExpression(string value)
|
||||
{
|
||||
Value = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Python expression.
|
||||
/// </summary>
|
||||
public string Value { get; }
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
using Elsa.Expressions.Models;
|
||||
|
||||
namespace Elsa.Python.Expressions;
|
||||
|
||||
/// <summary>
|
||||
/// A reference to a Python expression.
|
||||
/// </summary>
|
||||
public class PythonExpressionBlockReference : MemoryBlockReference
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PythonExpressionBlockReference"/> class.
|
||||
/// </summary>
|
||||
/// <param name="expression">The expression to reference.</param>
|
||||
public PythonExpressionBlockReference(PythonExpression expression)
|
||||
{
|
||||
Expression = expression;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the referenced expression.
|
||||
/// </summary>
|
||||
public PythonExpression Expression { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Declares the referenced expression.
|
||||
/// </summary>
|
||||
/// <returns>A memory block holding the expression.</returns>
|
||||
public override MemoryBlock Declare() => new();
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
using Elsa.Expressions.Contracts;
|
||||
using Elsa.Expressions.Models;
|
||||
using Elsa.Python.Contracts;
|
||||
|
||||
namespace Elsa.Python.Expressions;
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates C# expressions.
|
||||
/// </summary>
|
||||
public class PythonExpressionHandler : IExpressionHandler
|
||||
{
|
||||
private readonly IPythonEvaluator _evaluator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PythonExpressionHandler"/> class.
|
||||
/// </summary>
|
||||
public PythonExpressionHandler(IPythonEvaluator evaluator)
|
||||
{
|
||||
_evaluator = evaluator;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<object?> EvaluateAsync(IExpression expression, Type returnType, ExpressionExecutionContext context)
|
||||
{
|
||||
var pythonExpression = (PythonExpression)expression;
|
||||
return await _evaluator.EvaluateAsync(pythonExpression.Value, returnType, context);
|
||||
}
|
||||
}
|
||||
29
src/modules/Elsa.Python/Extensions/ModuleExtensions.cs
Normal file
29
src/modules/Elsa.Python/Extensions/ModuleExtensions.cs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
using Elsa.Features.Services;
|
||||
using Elsa.Python.Features;
|
||||
using Elsa.Python.Options;
|
||||
|
||||
// ReSharper disable once CheckNamespace
|
||||
namespace Elsa.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// Adds extensions to <see cref="IModule"/> that installs the <see cref="PythonFeature"/> feature.
|
||||
/// </summary>
|
||||
public static class ModuleExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Setup the <see cref="PythonFeature"/> feature.
|
||||
/// </summary>
|
||||
public static IModule UsePython(this IModule module, Action<PythonFeature>? configure = default)
|
||||
{
|
||||
module.Configure(configure);
|
||||
return module;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Setup the <see cref="PythonFeature"/> feature.
|
||||
/// </summary>
|
||||
public static IModule UsePython(this IModule module, Action<PythonOptions> configureOptions)
|
||||
{
|
||||
return module.UsePython(python => python.PythonOptions += configureOptions);
|
||||
}
|
||||
}
|
||||
52
src/modules/Elsa.Python/Features/PythonFeature.cs
Normal file
52
src/modules/Elsa.Python/Features/PythonFeature.cs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
using Elsa.Common.Features;
|
||||
using Elsa.Expressions.Contracts;
|
||||
using Elsa.Expressions.Features;
|
||||
using Elsa.Extensions;
|
||||
using Elsa.Features.Abstractions;
|
||||
using Elsa.Features.Attributes;
|
||||
using Elsa.Features.Services;
|
||||
using Elsa.Python.Contracts;
|
||||
using Elsa.Python.Expressions;
|
||||
using Elsa.Python.Options;
|
||||
using Elsa.Python.Providers;
|
||||
using Elsa.Python.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Elsa.Python.Features;
|
||||
|
||||
/// <summary>
|
||||
/// Installs Python integration.
|
||||
/// </summary>
|
||||
[DependsOn(typeof(MediatorFeature))]
|
||||
[DependsOn(typeof(ExpressionsFeature))]
|
||||
public class PythonFeature : FeatureBase
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public PythonFeature(IModule module) : base(module)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the <see cref="Options.PythonOptions"/>.
|
||||
/// </summary>
|
||||
public Action<PythonOptions> PythonOptions { get; set; } = _ => { };
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Apply()
|
||||
{
|
||||
Services.Configure(PythonOptions);
|
||||
|
||||
// C# services.
|
||||
Services
|
||||
.AddSingleton<IExpressionSyntaxProvider, PythonExpressionSyntaxProvider>()
|
||||
.AddSingleton<IPythonEvaluator, IronPythonEvaluator>()
|
||||
.AddExpressionHandler<PythonExpressionHandler, PythonExpression>()
|
||||
;
|
||||
|
||||
// Handlers.
|
||||
Services.AddNotificationHandlersFrom<PythonFeature>();
|
||||
|
||||
// Activities.
|
||||
Module.AddActivitiesFrom<PythonFeature>();
|
||||
}
|
||||
}
|
||||
3
src/modules/Elsa.Python/FodyWeavers.xml
Normal file
3
src/modules/Elsa.Python/FodyWeavers.xml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
|
||||
<ConfigureAwait />
|
||||
</Weavers>
|
||||
22
src/modules/Elsa.Python/Handlers/AddInputAccessors.cs
Normal file
22
src/modules/Elsa.Python/Handlers/AddInputAccessors.cs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
using Elsa.Mediator.Contracts;
|
||||
using Elsa.Python.Models;
|
||||
using Elsa.Python.Notifications;
|
||||
using JetBrains.Annotations;
|
||||
|
||||
namespace Elsa.Python.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// Adds input accessors to the Python engine.
|
||||
/// </summary>
|
||||
[UsedImplicitly]
|
||||
public class AddInputAccessors : INotificationHandler<EvaluatingPython>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task HandleAsync(EvaluatingPython notification, CancellationToken cancellationToken)
|
||||
{
|
||||
var scope = notification.ScriptScope;
|
||||
var inputProxy = new InputProxy(notification.Context);
|
||||
scope.SetVariable("input", inputProxy);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
using Elsa.Mediator.Contracts;
|
||||
using Elsa.Python.Notifications;
|
||||
using Elsa.Python.Options;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Elsa.Python.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// This handler configures the Python engine based on the <see cref="PythonOptions"/>.
|
||||
/// </summary>
|
||||
[UsedImplicitly]
|
||||
public class ConfigurePythonFromOptions : INotificationHandler<EvaluatingPython>
|
||||
{
|
||||
private readonly PythonOptions _options;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ConfigurePythonFromOptions"/> class.
|
||||
/// </summary>
|
||||
public ConfigurePythonFromOptions(IOptions<PythonOptions> options)
|
||||
{
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task HandleAsync(EvaluatingPython notification, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var script in _options.Scripts)
|
||||
notification.AppendScript(script);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
using System.Text;
|
||||
using Elsa.Expressions.Models;
|
||||
using Elsa.Extensions;
|
||||
using Elsa.Mediator.Contracts;
|
||||
using Elsa.Python.Notifications;
|
||||
using JetBrains.Annotations;
|
||||
|
||||
namespace Elsa.Python.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the C# evaluator with methods to access workflow variables.
|
||||
/// </summary>
|
||||
[UsedImplicitly]
|
||||
public class GenerateWorkflowVariableAccessors : INotificationHandler<EvaluatingPython>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task HandleAsync(EvaluatingPython notification, CancellationToken cancellationToken)
|
||||
{
|
||||
var expressionExecutionContext = notification.Context;
|
||||
var variables = expressionExecutionContext.GetVariablesInScope().ToList();
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine("class WorkflowVariablesProxy:");
|
||||
sb.AppendLine(" def __init__(self, execution_context):");
|
||||
sb.AppendLine(" self.execution_context = execution_context");
|
||||
sb.AppendLine();
|
||||
|
||||
foreach (var variable in variables)
|
||||
{
|
||||
var variableName = variable.Name;
|
||||
var variableType = variable.GetVariableType();
|
||||
var friendlyTypeName = variableType.GetFriendlyTypeName(Brackets.Square);
|
||||
sb.AppendLine($" @property");
|
||||
sb.AppendLine($" def {variableName}(self):");
|
||||
sb.AppendLine($" return self.execution_context.GetVariable({friendlyTypeName}, '{variableName}')");
|
||||
sb.AppendLine($" @{variableName}.setter");
|
||||
sb.AppendLine($" def {variableName}(self, value):");
|
||||
sb.AppendLine($" self.execution_context.SetVariable('{variableName}', value)");
|
||||
}
|
||||
|
||||
sb.AppendLine();
|
||||
sb.AppendLine("variable = WorkflowVariablesProxy(execution_context);");
|
||||
|
||||
notification.AppendScript(sb.ToString());
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
36
src/modules/Elsa.Python/Models/ExecutionContextProxy.cs
Normal file
36
src/modules/Elsa.Python/Models/ExecutionContextProxy.cs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
using Elsa.Expressions.Helpers;
|
||||
using Elsa.Expressions.Models;
|
||||
using Elsa.Extensions;
|
||||
using JetBrains.Annotations;
|
||||
|
||||
namespace Elsa.Python.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Provides access to the current execution context.
|
||||
/// </summary>
|
||||
[UsedImplicitly]
|
||||
public partial class ExecutionContextProxy
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the current execution context.
|
||||
/// </summary>
|
||||
public ExpressionExecutionContext ExpressionExecutionContext { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ExecutionContextProxy"/> class.
|
||||
/// </summary>
|
||||
public ExecutionContextProxy(ExpressionExecutionContext expressionExecutionContext)
|
||||
{
|
||||
ExpressionExecutionContext = expressionExecutionContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the specified variable.
|
||||
/// </summary>
|
||||
public object? GetVariable(Type type, string name) => ExpressionExecutionContext.GetVariableInScope(name).ConvertTo(type);
|
||||
|
||||
/// <summary>
|
||||
/// Sets the value of the specified variable.
|
||||
/// </summary>
|
||||
public void SetVariable(string name, object? value) => ExpressionExecutionContext.SetVariable(name, value);
|
||||
}
|
||||
35
src/modules/Elsa.Python/Models/InputProxy.cs
Normal file
35
src/modules/Elsa.Python/Models/InputProxy.cs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
using Elsa.Expressions.Helpers;
|
||||
using Elsa.Expressions.Models;
|
||||
using Elsa.Extensions;
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace Elsa.Python.Models;
|
||||
|
||||
/// <summary>
|
||||
/// A wrapper for accessing activity input values from Python.
|
||||
/// </summary>
|
||||
public class InputProxy
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InputProxy"/> class.
|
||||
/// </summary>
|
||||
public InputProxy(ExpressionExecutionContext context)
|
||||
{
|
||||
Context = context;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the expression execution context.
|
||||
/// </summary>
|
||||
public ExpressionExecutionContext Context { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the specified input.
|
||||
/// </summary>
|
||||
public object? get(string name) => Context.GetInput(name);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the specified input.
|
||||
/// </summary>
|
||||
public object? get(Type type, string name) => Context.GetInput(name).ConvertTo(type);
|
||||
}
|
||||
34
src/modules/Elsa.Python/Models/OutcomeProxy.cs
Normal file
34
src/modules/Elsa.Python/Models/OutcomeProxy.cs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
using Elsa.Expressions.Models;
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace Elsa.Python.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Provides access to activity outcomes.
|
||||
/// </summary>
|
||||
public class OutcomeProxy
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the key of the outcomes property.
|
||||
/// </summary>
|
||||
public static readonly object OutcomePropertiesKey = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OutcomeProxy"/> class.
|
||||
/// </summary>
|
||||
public OutcomeProxy(ExpressionExecutionContext expressionExecutionContext)
|
||||
{
|
||||
ExpressionExecutionContext = expressionExecutionContext;
|
||||
}
|
||||
|
||||
private ExpressionExecutionContext ExpressionExecutionContext { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Sets the outcome of the current activity.
|
||||
/// </summary>
|
||||
/// <param name="outcomeNames">The names of the outcomes.</param>
|
||||
public void set(params string[] outcomeNames)
|
||||
{
|
||||
ExpressionExecutionContext.TransientProperties[OutcomePropertiesKey] = outcomeNames;
|
||||
}
|
||||
}
|
||||
47
src/modules/Elsa.Python/Models/OutputProxy.cs
Normal file
47
src/modules/Elsa.Python/Models/OutputProxy.cs
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
using Elsa.Expressions.Helpers;
|
||||
using Elsa.Expressions.Models;
|
||||
using Elsa.Extensions;
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace Elsa.Python.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Provides access to activity outputs.
|
||||
/// </summary>
|
||||
public class OutputProxy
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OutputProxy"/> class.
|
||||
/// </summary>
|
||||
public OutputProxy(ExpressionExecutionContext expressionExecutionContext)
|
||||
{
|
||||
Context = expressionExecutionContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the expression execution context.
|
||||
/// </summary>
|
||||
public ExpressionExecutionContext Context { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the specified output.
|
||||
/// </summary>
|
||||
/// <param name="activityIdOrName">The ID or name of the activity that produced the output.</param>
|
||||
/// <param name="outputName">The name of the output.</param>
|
||||
/// <returns>The value of the output.</returns>
|
||||
public object? get(string activityIdOrName, string? outputName = default) => Context.GetOutput(activityIdOrName, outputName);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the specified output.
|
||||
/// </summary>
|
||||
/// <param name="returnType">The type to convert the output value to.</param>
|
||||
/// <param name="activityIdOrName">The ID or name of the activity that produced the output.</param>
|
||||
/// <param name="outputName">The name of the output.</param>
|
||||
/// <returns>The value of the output.</returns>
|
||||
public object? get(Type returnType, string activityIdOrName, string? outputName = default) => get(activityIdOrName, outputName).ConvertTo(returnType);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the result of the last activity that executed.
|
||||
/// </summary>
|
||||
public object? last_result => Context.GetLastResult();
|
||||
}
|
||||
33
src/modules/Elsa.Python/Notifications/EvaluatingPython.cs
Normal file
33
src/modules/Elsa.Python/Notifications/EvaluatingPython.cs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
using System.Text;
|
||||
using Elsa.Expressions.Models;
|
||||
using Elsa.Mediator.Contracts;
|
||||
using Microsoft.Scripting.Hosting;
|
||||
|
||||
namespace Elsa.Python.Notifications;
|
||||
|
||||
/// <summary>
|
||||
/// This notification is published every time a Python expression is about to be evaluated, giving subscribers a chance to modify the Python engine.
|
||||
/// </summary>
|
||||
public record EvaluatingPython(ScriptEngine Engine, ScriptScope ScriptScope, ExpressionExecutionContext Context) : INotification
|
||||
{
|
||||
/// <summary>
|
||||
/// Appends a script to the Python engine.
|
||||
/// </summary>
|
||||
/// <param name="builder">A builder that builds the script to append.</param>
|
||||
public void AppendScript(Action<StringBuilder> builder)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
builder(sb);
|
||||
AppendScript(sb.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends a script to the Python engine.
|
||||
/// </summary>
|
||||
/// <param name="script">The script to append.</param>
|
||||
public void AppendScript(string script)
|
||||
{
|
||||
var engine = Engine;
|
||||
engine.Execute(script, ScriptScope);
|
||||
}
|
||||
}
|
||||
34
src/modules/Elsa.Python/Options/PythonOptions.cs
Normal file
34
src/modules/Elsa.Python/Options/PythonOptions.cs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
using System.Text;
|
||||
|
||||
namespace Elsa.Python.Options;
|
||||
|
||||
/// <summary>
|
||||
/// Options for the Python expression evaluator.
|
||||
/// </summary>
|
||||
public class PythonOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the Python script files to load.
|
||||
/// </summary>
|
||||
public ICollection<string> Scripts { get; } = new List<string>();
|
||||
|
||||
/// <summary>
|
||||
/// Appends a script to the Python engine.
|
||||
/// </summary>
|
||||
/// <param name="builder">A builder that builds the script to append.</param>
|
||||
public void AddScript(Action<StringBuilder> builder)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
builder(sb);
|
||||
AddScript(sb.ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends a script to the Python engine.
|
||||
/// </summary>
|
||||
/// <param name="script">The script to append.</param>
|
||||
public void AddScript(string script)
|
||||
{
|
||||
Scripts.Add(script);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
using Elsa.Expressions.Contracts;
|
||||
using Elsa.Expressions.Models;
|
||||
using Elsa.Python.Expressions;
|
||||
|
||||
namespace Elsa.Python.Providers;
|
||||
|
||||
internal class PythonExpressionSyntaxProvider : IExpressionSyntaxProvider
|
||||
{
|
||||
private const string SyntaxName = "Python";
|
||||
|
||||
public ValueTask<IEnumerable<ExpressionSyntaxDescriptor>> GetDescriptorsAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var javaScript = CreatePythonDescriptor();
|
||||
|
||||
return ValueTask.FromResult<IEnumerable<ExpressionSyntaxDescriptor>>(new[] { javaScript });
|
||||
}
|
||||
|
||||
private ExpressionSyntaxDescriptor CreatePythonDescriptor() => new()
|
||||
{
|
||||
Syntax = SyntaxName,
|
||||
Type = typeof(PythonExpression),
|
||||
CreateExpression = CreateCSharpExpression,
|
||||
CreateBlockReference = context => new PythonExpressionBlockReference(context.GetExpression<PythonExpression>()),
|
||||
CreateSerializableObject = context => new
|
||||
{
|
||||
Type = SyntaxName,
|
||||
context.GetExpression<PythonExpression>().Value
|
||||
}
|
||||
};
|
||||
|
||||
private IExpression CreateCSharpExpression(ExpressionConstructorContext context)
|
||||
{
|
||||
var script = context.Element.TryGetProperty("value", out var p) ? p.ToString() : "";
|
||||
return new PythonExpression(script);
|
||||
}
|
||||
}
|
||||
49
src/modules/Elsa.Python/Services/IronPythonEvaluator.cs
Normal file
49
src/modules/Elsa.Python/Services/IronPythonEvaluator.cs
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
using Elsa.Expressions.Helpers;
|
||||
using Elsa.Expressions.Models;
|
||||
using Elsa.Mediator.Contracts;
|
||||
using Elsa.Python.Contracts;
|
||||
using Elsa.Python.Models;
|
||||
using Elsa.Python.Notifications;
|
||||
|
||||
namespace Elsa.Python.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates Python expressions using IronPython.
|
||||
/// </summary>
|
||||
public class IronPythonEvaluator : IPythonEvaluator
|
||||
{
|
||||
private readonly INotificationSender _notificationSender;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="IronPythonEvaluator"/> class.
|
||||
/// </summary>
|
||||
public IronPythonEvaluator(INotificationSender notificationSender)
|
||||
{
|
||||
_notificationSender = notificationSender;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<object?> EvaluateAsync(string expression, Type returnType, ExpressionExecutionContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var engine = IronPython.Hosting.Python.CreateEngine();
|
||||
var scope = engine.CreateScope();
|
||||
var notification = new EvaluatingPython(engine, scope, context);
|
||||
|
||||
// Add imports.
|
||||
notification.AppendScript(sb =>
|
||||
{
|
||||
sb.AppendLine("import System");
|
||||
sb.AppendLine("import clr");
|
||||
});
|
||||
|
||||
// Add globals.
|
||||
scope.SetVariable("execution_context", new ExecutionContextProxy(context));
|
||||
scope.SetVariable("input", new InputProxy(context));
|
||||
scope.SetVariable("output", new OutputProxy(context));
|
||||
scope.SetVariable("outcome", new OutcomeProxy(context));
|
||||
|
||||
await _notificationSender.SendAsync(notification, cancellationToken);
|
||||
var result = (object?)engine.Execute(expression, scope);
|
||||
return result.ConvertTo(returnType);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue