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

Simplify Workflow Variables with JS #5946

Merged
merged 16 commits into from
Sep 6, 2024
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
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
<PackageVersion Include="NuGet.Protocol" Version="6.10.1" />
<PackageVersion Include="Nuke.Components" Version="8.0.0" />
<PackageVersion Include="Open.Linq.AsyncExtensions" Version="1.2.0" />
<PackageVersion Include="OpenTelemetry.Api" Version="1.9.0" />
<PackageVersion Include="Polly.Extensions.Http" Version="3.0.0" />
<PackageVersion Include="PolySharp" Version="1.14.1" />
<PackageVersion Include="Proto.Actor" Version="1.6.0" />
Expand Down
37 changes: 0 additions & 37 deletions src/apps/Elsa.Server.Web/Activities/SlowActivity.cs

This file was deleted.

56 changes: 0 additions & 56 deletions src/apps/Elsa.Server.Web/Middleware/SimulatedLatencyMiddleware.cs

This file was deleted.

1 change: 0 additions & 1 deletion src/apps/Elsa.Server.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using Elsa.Agents;
using Elsa.Alterations.Extensions;
using Elsa.Alterations.MassTransit.Extensions;
using Elsa.Caching.Options;
using Elsa.Common.DistributedLocks.Noop;
using Elsa.Dapper.Extensions;
using Elsa.Dapper.Services;
Expand Down
5 changes: 0 additions & 5 deletions src/apps/Elsa.Server.Web/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@
"LogLevel": {
"Default": "Warning",
"Elsa": "Warning",
"Elsa.Workflows.WorkflowExecutionContext": "Debug",
"Elsa.Workflows.Pipelines.ActivityExecution": "Debug",
"Elsa.Workflows.Middleware.Activities": "Debug",
"Elsa.Workflows.Runtime.Middleware.Activities": "Debug",
"Elsa.Workflows.Runtime.Services.DefaultBookmarkManager": "Debug",
"MassTransit": "Warning",
"Microsoft.Extensions.Http": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
Expand Down
13 changes: 7 additions & 6 deletions src/apps/ElsaStudioWebAssembly/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Elsa.Studio.Extensions;
using Elsa.Studio.Login.BlazorWasm.Extensions;
using Elsa.Studio.Login.HttpMessageHandlers;
using Elsa.Studio.Models;
using Elsa.Studio.Options;
using Elsa.Studio.Workflows.Designer.Extensions;
using Microsoft.AspNetCore.Components.Web;
Expand All @@ -24,12 +25,12 @@
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.RootComponents.RegisterCustomElsaStudioElements();

// Register shell services and modules.
var backendApiConfig = new BackendApiConfig
{
ConfigureBackendOptions = options => builder.Configuration.GetSection("Backend").Bind(options),
ConfigureHttpClientBuilder = options => options.AuthenticationHandler = typeof(AuthenticatingApiHttpMessageHandler)
};
// Register shell services and modules.
var backendApiConfig = new BackendApiConfig
{
ConfigureBackendOptions = options => builder.Configuration.GetSection("Backend").Bind(options),
ConfigureHttpClientBuilder = options => options.AuthenticationHandler = typeof(AuthenticatingApiHttpMessageHandler)
};

builder.Services.AddCore();
builder.Services.AddShell();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,15 @@ public static IServiceCollection AddFunctionDefinitionProvider<T>(this IServiceC
/// <returns>The service collection.</returns>
public static IServiceCollection AddTypeDefinitionProvider<T>(this IServiceCollection services, Func<IServiceProvider, T> factory) where T: class, ITypeDefinitionProvider =>
services.AddScoped<ITypeDefinitionProvider, T>();

/// <summary>
/// Adds a <see cref="IVariableDefinitionProvider"/> to the service collection.
/// </summary>
public static IServiceCollection AddVariableDefinitionProvider<T>(this IServiceCollection services) where T: class, IVariableDefinitionProvider => services.AddScoped<IVariableDefinitionProvider, T>();

/// <summary>
/// Adds a <see cref="IVariableDefinitionProvider"/> to the service collection.
/// </summary>
public static IServiceCollection AddVariableDefinitionProvider<T>(this IServiceCollection services, Func<IServiceProvider, T> factory) where T: class, IVariableDefinitionProvider =>
services.AddScoped<IVariableDefinitionProvider, T>(factory);
}
2 changes: 2 additions & 0 deletions src/modules/Elsa.JavaScript/Features/JavaScriptFeature.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ public override void Apply()
.AddFunctionDefinitionProvider<ActivityOutputFunctionsDefinitionProvider>()
.AddTypeDefinitionProvider<CommonTypeDefinitionProvider>()
.AddTypeDefinitionProvider<VariableTypeDefinitionProvider>()
.AddTypeDefinitionProvider<WorkflowVariablesTypeDefinitionProvider>()
.AddVariableDefinitionProvider<WorkflowVariablesVariableProvider>()
;

// Handlers.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System.Dynamic;
using Elsa.Extensions;
using Elsa.JavaScript.Helpers;
using Elsa.JavaScript.Models;
using Elsa.JavaScript.Notifications;
using Elsa.Mediator.Contracts;
using JetBrains.Annotations;
using Jint;
using Jint.Native;

namespace Elsa.JavaScript.Handlers;

/// A handler that configures the Jint engine with workflow variables.
[UsedImplicitly]
public class ConfigureEngineWithVariables : INotificationHandler<EvaluatingJavaScript>, INotificationHandler<EvaluatedJavaScript>
{
/// <inheritdoc />
public Task HandleAsync(EvaluatingJavaScript notification, CancellationToken cancellationToken)
{
CopyVariablesIntoEngine(notification);
return Task.CompletedTask;
}

public Task HandleAsync(EvaluatedJavaScript notification, CancellationToken cancellationToken)
{
CopyVariablesIntoWorkflowExecutionContext(notification);
return Task.CompletedTask;
}

private void CopyVariablesIntoWorkflowExecutionContext(EvaluatedJavaScript notification)
{
var context = notification.Context;
var engine = notification.Engine;
var variablesContainer = (IDictionary<string, object?>)engine.GetValue("variables").ToObject()!;

foreach (var (variableName, variableValue) in variablesContainer)
{
var processedValue = variableValue is JsObject jsObject ? jsObject.ToObject() : variableValue;
context.SetVariable(variableName, processedValue);
}
}

private void CopyVariablesIntoEngine(EvaluatingJavaScript notification)
{
var engine = notification.Engine;
var context = notification.Context;
var variableNames = context.GetVariableNamesInScope().ToList();
var variablesContainer = (IDictionary<string, object?>)new ExpandoObject();

foreach (var variableName in variableNames)
{
var variableValue = context.GetVariableInScope(variableName);
variableValue = ProcessVariableValue(engine, variableValue);
variablesContainer[variableName] = variableValue;
}

engine.SetValue("variables", variablesContainer);
}

private object? ProcessVariableValue(Engine engine, object? variableValue)
{
if (variableValue == null)
return null;

if(variableValue is not ExpandoObject expandoObject)
return variableValue;

return ObjectConverterHelper.ConvertToJsObject(engine, expandoObject);
}
}
59 changes: 59 additions & 0 deletions src/modules/Elsa.JavaScript/Helpers/ObjectConverterHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System.Collections;
using Elsa.Extensions;
using Jint;
using Jint.Native;
using Jint.Native.Object;
using Jint.Runtime.Descriptors;

namespace Elsa.JavaScript.Helpers;

internal static class ObjectConverterHelper
{
public static ObjectInstance ConvertToJsObject(Engine engine, IDictionary<string, object?> expando)
{
var jsObject = engine.Intrinsics.Object.Construct([]);

foreach (var kvp in expando)
{
var value = kvp.Value;
var jsValue = ConvertToJsValue(engine, value);
var propertyDescriptor = new PropertyDescriptor(jsValue, true, true, true);
jsObject.DefineOwnProperty(kvp.Key, propertyDescriptor);
}

return jsObject;
}

private static JsValue ConvertToJsValue(Engine engine, object? value)
{
if (value == null)
return JsValue.Null;

if (value is IDictionary<string, object?> dict)
return ConvertToJsObject(engine, dict);

var valueType = value.GetType();
if (valueType.IsCollectionType())
{
var list = (ICollection)value;
var jsArray = engine.Intrinsics.Array.Construct(list.Count);
var index = 0;

foreach (var item in list)
jsArray.Set(index++, ConvertToJsValue(engine, item), true);

return jsArray;
}

if (value is string str)
return JsValue.FromObject(engine, str);

if (value is int or double or float or decimal)
return JsValue.FromObject(engine, Convert.ToDouble(value));

if (value is bool b)
return JsValue.FromObject(engine, b);

return JsValue.FromObject(engine, value);
}
}
10 changes: 10 additions & 0 deletions src/modules/Elsa.JavaScript/Notifications/EvaluatedJavaScript.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using Elsa.Expressions.Models;
using Elsa.Mediator.Contracts;
using Jint;

namespace Elsa.JavaScript.Notifications;

/// <summary>
/// This notification is published every time a JavaScript expression has been evaluated.
/// </summary>
public record EvaluatedJavaScript(Engine Engine, ExpressionExecutionContext Context, object? Result) : INotification;
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ public class JintJavaScriptEvaluator(IConfiguration configuration, INotification
CancellationToken cancellationToken = default)
{
var engine = await GetConfiguredEngine(configureEngine, context, options, cancellationToken);
await mediator.SendAsync(new EvaluatingJavaScript(engine, context), cancellationToken);
var result = ExecuteExpressionAndGetResult(engine, expression);
await mediator.SendAsync(new EvaluatedJavaScript(engine, context, result), cancellationToken);

return result.ConvertTo(returnType);
}
Expand All @@ -64,8 +66,7 @@ private async Task<Engine> GetConfiguredEngine(Action<Engine>? configureEngine,
ConfigureArgumentGetters(engine, options);
ConfigureConfigurationAccess(engine);
_jintOptions.ConfigureEngineCallback(engine, context);
await mediator.SendAsync(new EvaluatingJavaScript(engine, context), cancellationToken);


return engine;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Elsa.JavaScript.TypeDefinitions.Builders;
using Elsa.JavaScript.TypeDefinitions.Contracts;
using Elsa.JavaScript.TypeDefinitions.Models;

namespace Elsa.JavaScript.TypeDefinitions.Abstractions;

public abstract class VariableDefinitionProvider : IVariableDefinitionProvider
{
protected virtual ValueTask<IEnumerable<VariableDefinition>> GetVariableDefinitionsAsync(TypeDefinitionContext context)
{
var variables = GetVariableDefinitions(context);
return new(variables);
}

protected virtual IEnumerable<VariableDefinition> GetVariableDefinitions(TypeDefinitionContext context)
{
yield break;
}

async ValueTask<IEnumerable<VariableDefinition>> IVariableDefinitionProvider.GetVariableDefinitionsAsync(TypeDefinitionContext context) => await GetVariableDefinitionsAsync(context);

protected VariableDefinition CreateVariableDefinition(Action<VariableDefinitionBuilder> setup)
{
var builder = new VariableDefinitionBuilder();
setup(builder);
return builder.BuildVariableDefinition();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Elsa.JavaScript.TypeDefinitions.Models;

namespace Elsa.JavaScript.TypeDefinitions.Builders;

public class VariableDefinitionBuilder
{
private readonly VariableDefinition _variableDefinition = new();

public VariableDefinitionBuilder Name(string name)
{
_variableDefinition.Name = name;
return this;
}

public VariableDefinitionBuilder Type(string type)
{
_variableDefinition.Type = type;
return this;
}

public VariableDefinition BuildVariableDefinition() => new(_variableDefinition.Name, _variableDefinition.Type);
}
Loading
Loading