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
35 changes: 35 additions & 0 deletions src/Testing/Wolverine.Core.FSharpContracts/Contracts.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Wolverine;
using Wolverine.Attributes;
using Wolverine.Runtime;

Expand Down Expand Up @@ -96,3 +97,37 @@ public void Handle(Gate command)
{
}
}

// -----------------------------------------------------------------------------
// Phase B (issue GH-2969): a minimal in-memory stateful saga. Start creates the
// saga state; Handle continues it. Exercises the Wolverine.Persistence.Sagas
// frame set (saga-id resolution, create-new, load/assert-exists, store-or-delete)
// against the default in-memory saga store — no external persistence.
// -----------------------------------------------------------------------------

/// <summary>Starts a <see cref="CountingSaga" />.</summary>
public record StartCount(string Id);

/// <summary>Continues a <see cref="CountingSaga" />.</summary>
public record IncrementCount(string Id);

/// <summary>A minimal stateful saga over the in-memory store.</summary>
public class CountingSaga : Saga
{
public string? Id { get; set; }
public int Count { get; set; }

public static CountingSaga Start(StartCount command)
{
return new CountingSaga { Id = command.Id };
}

public void Handle(IncrementCount command)
{
Count++;
if (Count >= 3)
{
MarkCompleted();
}
}
}
59 changes: 59 additions & 0 deletions src/Testing/Wolverine.Core.FSharpFixture/Generated.fs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ open Microsoft.Extensions.Logging
open System
open System.Threading
open System.Threading.Tasks
open Wolverine.Persistence.Sagas
open Wolverine.Runtime
open Wolverine.Runtime.Handlers

Expand Down Expand Up @@ -87,3 +88,61 @@ type GateHandler1696712162() =

System.Threading.Tasks.Task.CompletedTask

type IncrementCountHandler540640831(inMemorySagaPersistor: Wolverine.Persistence.Sagas.InMemorySagaPersistor) =
inherit Wolverine.Runtime.Handlers.MessageHandler()
let _inMemorySagaPersistor = inMemorySagaPersistor

override _.HandleAsync(context: Wolverine.Runtime.MessageContext, cancellation: System.Threading.CancellationToken) : System.Threading.Tasks.Task =
// The actual message body
let incrementCount = context.Envelope.Message :?> Wolverine.Core.FSharpContracts.IncrementCount

// Application-specific Open Telemetry auditing
if not (isNull System.Diagnostics.Activity.Current) then
System.Diagnostics.Activity.Current.SetTag("Id", incrementCount.Id) |> ignore
let sagaId = if isNull incrementCount.Id then context.Envelope.SagaId else incrementCount.Id
if System.String.IsNullOrEmpty(sagaId) then
raise (Wolverine.Persistence.Sagas.IndeterminateSagaStateIdException(context.Envelope))
let countingSaga = _inMemorySagaPersistor.Load<Wolverine.Core.FSharpContracts.CountingSaga>(sagaId)
if isNull countingSaga then
raise (Wolverine.Persistence.Sagas.UnknownSagaException(typeof<Wolverine.Core.FSharpContracts.CountingSaga>, sagaId))
else
context.SetSagaId(sagaId)
if not (isNull System.Diagnostics.Activity.Current) then
System.Diagnostics.Activity.Current.SetTag("wolverine.saga.id", sagaId.ToString()) |> ignore
System.Diagnostics.Activity.Current.SetTag("wolverine.saga.type", "Wolverine.Core.FSharpContracts.CountingSaga") |> ignore

// The actual message execution
countingSaga.Handle(incrementCount)

// Delete the saga if completed, otherwise update it
if countingSaga.IsCompleted() then
_inMemorySagaPersistor.Delete<Wolverine.Core.FSharpContracts.CountingSaga>(sagaId)
else
_inMemorySagaPersistor.Store<Wolverine.Core.FSharpContracts.CountingSaga>(countingSaga)
// No unit of work
System.Threading.Tasks.Task.CompletedTask

type StartCountHandler1561563330(inMemorySagaPersistor: Wolverine.Persistence.Sagas.InMemorySagaPersistor) =
inherit Wolverine.Runtime.Handlers.MessageHandler()
let _inMemorySagaPersistor = inMemorySagaPersistor

override _.HandleAsync(context: Wolverine.Runtime.MessageContext, cancellation: System.Threading.CancellationToken) : System.Threading.Tasks.Task =
// The actual message body
let startCount = context.Envelope.Message :?> Wolverine.Core.FSharpContracts.StartCount

// Application-specific Open Telemetry auditing
if not (isNull System.Diagnostics.Activity.Current) then
System.Diagnostics.Activity.Current.SetTag("Id", startCount.Id) |> ignore

// The actual message execution
let outgoing1 = Wolverine.Core.FSharpContracts.CountingSaga.Start(startCount)

context.SetSagaId(startCount.Id)
if not (isNull System.Diagnostics.Activity.Current) then
System.Diagnostics.Activity.Current.SetTag("wolverine.saga.id", startCount.Id.ToString()) |> ignore
System.Diagnostics.Activity.Current.SetTag("wolverine.saga.type", "Wolverine.Core.FSharpContracts.CountingSaga") |> ignore
if not (outgoing1.IsCompleted()) then
_inMemorySagaPersistor.Store<Wolverine.Core.FSharpContracts.CountingSaga>(outgoing1)
// No unit of work
System.Threading.Tasks.Task.CompletedTask

Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public static string GenerateCode()
opts.Discovery.IncludeType<NameHandler>();
opts.Discovery.IncludeType<CheckThingHandler>();
opts.Discovery.IncludeType<GateHandler>();
opts.Discovery.IncludeType<CountingSaga>();

// Inserts ApplyExecutionDiagnosticTagsFrame at the head of every chain.
opts.Tracking.HandlerExecutionDiagnosticsEnabled = true;
Expand Down
7 changes: 7 additions & 0 deletions src/Wolverine/Persistence/Sagas/AssertSagaStateExistsFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,11 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
$"throw new {typeof(UnknownSagaException)}(typeof({_sagaState.VariableType.FullNameInCode()}), {_sagaId.Usage});");
Next?.GenerateCode(method, writer);
}

public override void GenerateFSharpCode(GeneratedMethod method, ISourceWriter writer)
{
writer.Write(
$"raise ({typeof(UnknownSagaException).FSharpName()}(typeof<{_sagaState.VariableType.FSharpName()}>, {_sagaId.Usage}))");
Next?.GenerateFSharpCode(method, writer);
}
}
11 changes: 11 additions & 0 deletions src/Wolverine/Persistence/Sagas/ConditionalSagaInsertFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,17 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
Next?.GenerateCode(method, writer);
}

public override void GenerateFSharpCode(GeneratedMethod method, ISourceWriter writer)
{
writer.Write($"BLOCK:if not ({_saga.Usage}.{nameof(Saga.IsCompleted)}()) then");
_insert.GenerateFSharpCode(method, writer);
writer.FinishBlock();

_commit.GenerateFSharpCode(method, writer);

Next?.GenerateFSharpCode(method, writer);
}

public override IEnumerable<Variable> FindVariables(IMethodVariables chain)
{
yield return _saga;
Expand Down
6 changes: 6 additions & 0 deletions src/Wolverine/Persistence/Sagas/CreateNewSagaFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,10 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
writer.Write($"var {Saga.Usage} = new {Saga.VariableType.FullNameInCode()}();");
Next?.GenerateCode(method, writer);
}

public override void GenerateFSharpCode(GeneratedMethod method, ISourceWriter writer)
{
writer.Write($"{Saga.FSharpAssignmentUsage} = {Saga.VariableType.FSharpName()}()");
Next?.GenerateFSharpCode(method, writer);
}
}
28 changes: 28 additions & 0 deletions src/Wolverine/Persistence/Sagas/PullSagaIdFromEnvelopeFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,34 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
Next?.GenerateCode(method, writer);
}

public override void GenerateFSharpCode(GeneratedMethod method, ISourceWriter writer)
{
var id = SagaChain.SagaIdVariableName;
var ex = typeof(IndeterminateSagaStateIdException).FSharpName();
var envSagaId = $"{_envelope!.Usage}.{nameof(Envelope.SagaId)}";

if (SagaId.VariableType == typeof(string))
{
writer.Write($"let {id} = {envSagaId}");
writer.Write($"BLOCK:if System.String.IsNullOrEmpty({id}) then");
writer.Write($"raise ({ex}({_envelope.Usage}))");
writer.FinishBlock();
}
else
{
// F# auto-tuples the out-parameter TryParse; bind the id from the match, raising on failure.
var clrType = SagaId.VariableType.FullName; // System.Guid / System.Int64 — valid static call target
writer.Write($"BLOCK:let {id} =");
writer.Write($"BLOCK:match {clrType}.TryParse({envSagaId}) with");
writer.Write("| true, parsed -> parsed");
writer.Write($"| _ -> raise ({ex}({_envelope.Usage}))");
writer.FinishBlock();
writer.FinishBlock();
}

Next?.GenerateFSharpCode(method, writer);
}

public override IEnumerable<Variable> FindVariables(IMethodVariables chain)
{
_envelope = chain.FindVariable(typeof(Envelope));
Expand Down
45 changes: 45 additions & 0 deletions src/Wolverine/Persistence/Sagas/PullSagaIdFromMessageFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,51 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
Next?.GenerateCode(method, writer);
}

public override void GenerateFSharpCode(GeneratedMethod method, ISourceWriter writer)
{
var id = SagaChain.SagaIdVariableName;
var ex = typeof(IndeterminateSagaStateIdException).FSharpName();
var messageMember = $"{_message!.Usage}.{_sagaIdMember.Name}";
var envelopeSagaId = $"{_envelope!.Usage}.{nameof(Envelope.SagaId)}";

if (_isStrongTypedId)
{
// Read straight from the message and reject the default value.
writer.Write($"let {id} = {messageMember}");
writer.Write($"BLOCK:if {id}.Equals(Unchecked.defaultof<{_sagaIdType!.FSharpName()}>) then");
writer.Write($"raise ({ex}({_envelope.Usage}))");
writer.FinishBlock();
}
else if (_sagaIdType == typeof(string))
{
// F# has no `??`; fall back to the envelope's saga id when the message member is null.
writer.Write($"let {id} = if isNull {messageMember} then {envelopeSagaId} else {messageMember}");
writer.Write($"BLOCK:if System.String.IsNullOrEmpty({id}) then");
writer.Write($"raise ({ex}({_envelope.Usage}))");
writer.FinishBlock();
}
else
{
// Guid / numeric: read from the message, else parse the envelope's saga id. F# auto-tuples
// the out-parameter TryParse into a (bool * value) match. Unchecked.defaultof<T> is both the
// numeric/Guid zero and the "indeterminate" sentinel.
var clrType = _sagaIdType!.FullName; // e.g. System.Guid / System.Int64 — valid for a static call
var fsharpType = _sagaIdType.FSharpName();
writer.Write($"let mutable {id} = {messageMember}");
writer.Write($"BLOCK:if {id} = Unchecked.defaultof<{fsharpType}> then");
writer.Write($"BLOCK:match {clrType}.TryParse({envelopeSagaId}) with");
writer.Write($"| true, parsed -> {id} <- parsed");
writer.Write($"| _ -> {id} <- {messageMember}");
writer.FinishBlock();
writer.FinishBlock();
writer.Write($"BLOCK:if {id} = Unchecked.defaultof<{fsharpType}> then");
writer.Write($"raise ({ex}({_envelope.Usage}))");
writer.FinishBlock();
}

Next?.GenerateFSharpCode(method, writer);
}

private void generateStrongTypedIdCode(ISourceWriter writer)
{
var typeNameInCode = _sagaIdType!.FullNameInCode();
Expand Down
7 changes: 7 additions & 0 deletions src/Wolverine/Persistence/Sagas/ResolveSagaFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,11 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
_loadFrame.GenerateCode(method, writer);
Next?.GenerateCode(method, writer);
}

public override void GenerateFSharpCode(GeneratedMethod method, ISourceWriter writer)
{
_findSagaIdFrame.GenerateFSharpCode(method, writer);
_loadFrame.GenerateFSharpCode(method, writer);
Next?.GenerateFSharpCode(method, writer);
}
}
13 changes: 13 additions & 0 deletions src/Wolverine/Persistence/Sagas/SagaStoreOrDeleteFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,17 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)

Next?.GenerateCode(method, writer);
}

public override void GenerateFSharpCode(GeneratedMethod method, ISourceWriter writer)
{
writer.WriteComment("Delete the saga if completed, otherwise update it");
writer.Write($"BLOCK:if {_saga.Usage}.{nameof(Saga.IsCompleted)}() then");
_delete.GenerateFSharpCode(method, writer);
writer.FinishBlock();
writer.Write("BLOCK:else");
_update.GenerateFSharpCode(method, writer);
writer.FinishBlock();

Next?.GenerateFSharpCode(method, writer);
}
}
19 changes: 19 additions & 0 deletions src/Wolverine/Persistence/Sagas/SetSagaIdFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
using JasperFx.Core.Reflection;
using Wolverine.Configuration;
using Wolverine.Runtime;

namespace Wolverine.Persistence.Sagas;
Expand Down Expand Up @@ -41,4 +42,22 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
}
Next?.GenerateCode(method, writer);
}

public override void GenerateFSharpCode(GeneratedMethod method, ISourceWriter writer)
{
var sagaId = FSharpEmitHelpers.FSharpUsage(_sagaId);
writer.Write($"{_context!.Usage}.{nameof(MessageContext.SetSagaId)}({sagaId})");

// F# has no null-conditional `?.`, and SetTag returns the Activity; guard once and pipe to ignore.
var current = $"{typeof(Activity).FSharpName()}.{nameof(Activity.Current)}";
writer.Write($"BLOCK:if not (isNull {current}) then");
writer.Write($"{current}.{nameof(Activity.SetTag)}(\"{WolverineTracing.SagaId}\", {sagaId}.ToString()) |> ignore");
if (_sagaType != null)
{
writer.Write($"{current}.{nameof(Activity.SetTag)}(\"{WolverineTracing.SagaType}\", \"{_sagaType.FullName}\") |> ignore");
}

writer.FinishBlock();
Next?.GenerateFSharpCode(method, writer);
}
}
17 changes: 17 additions & 0 deletions src/Wolverine/Persistence/Sagas/SetSagaIdFromSagaFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,21 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
}
Next?.GenerateCode(method, writer);
}

public override void GenerateFSharpCode(GeneratedMethod method, ISourceWriter writer)
{
var member = $"{_message.Usage}.{_sagaIdMember.Name}";
writer.Write($"{_context!.Usage}.{nameof(MessageContext.SetSagaId)}({member})");

var current = $"{typeof(Activity).FSharpName()}.{nameof(Activity.Current)}";
writer.Write($"BLOCK:if not (isNull {current}) then");
writer.Write($"{current}.{nameof(Activity.SetTag)}(\"{WolverineTracing.SagaId}\", {member}.ToString()) |> ignore");
if (_sagaType != null)
{
writer.Write($"{current}.{nameof(Activity.SetTag)}(\"{WolverineTracing.SagaType}\", \"{_sagaType.FullName}\") |> ignore");
}

writer.FinishBlock();
Next?.GenerateFSharpCode(method, writer);
}
}