From 4bf69015b9d3eaa95a45630c91d378c45c5a2aaa Mon Sep 17 00:00:00 2001 From: meisa Date: Sat, 8 Aug 2026 21:39:30 +0200 Subject: [PATCH 1/6] Consolidate application authoring and release readiness --- .gitignore | 1 + CHANGELOG.md | 28 + Directory.Packages.props | 2 + FluxFlow.sln | 47 + README.md | 131 +- .../ApplicationLinkCompilationBenchmarks.cs | 44 + .../ApplicationMessagingBenchmarks.cs | 53 + .../ApplicationTopologyBenchmarks.cs | 33 + .../BenchmarkApplication.cs | 133 ++ .../FluxFlow.Engine.Benchmarks.csproj | 20 + .../FluxFlow.Engine.Benchmarks/Program.cs | 5 + docs/01-getting-started.md | 35 +- docs/02-definitions-and-links.md | 77 +- docs/03-node-authoring.md | 57 +- docs/04-package-authoring.md | 100 +- docs/05-hosting-and-observability.md | 41 + docs/09-json-conversion.md | 9 + docs/10-expression-mapping.md | 17 + docs/14-public-api-overview.md | 85 +- docs/15-engine-compatibility.md | 32 + docs/22-canonical-vnext-migration.md | 43 + docs/23-engine-2-to-3-migration.md | 12 +- docs/24-reliable-in-process-delivery.md | 16 + docs/25-durable-inputs.md | 31 + docs/27-durable-output-capture.md | 14 +- docs/29-durable-output-delivery.md | 15 + docs/38-release-validation.md | 55 +- docs/39-typed-code-first-authoring.md | 268 +++ docs/40-unified-component-contracts.md | 132 ++ ...41-end-to-end-code-first-simplification.md | 133 ++ docs/42-application-health-readiness.md | 120 ++ ...rformance-concurrency-lifetime-baseline.md | 167 ++ docs/README.md | 16 +- eng/package-consumer-acceptance.ps1 | 78 +- .../FluxFlow.PackageConsumerAcceptance.csproj | 3 + eng/package-consumer-acceptance/Program.cs | 293 +++- .../RestartDurabilityScenario.cs | 483 +++++ eng/packages.json | 8 + eng/public-api/baseline.txt | 51 +- .../README.md | 340 ++++ .../README.md | 462 +++++ .../README.md | 632 +++++++ .../README.md | 499 ++++++ .../README.md | 1548 +++++++++++++++++ .../README.md | 922 ++++++++++ .../README.md | 498 ++++++ memory/00-index.md | 31 +- memory/01-current-state.md | 166 +- ...-consumer-restart-durability-acceptance.md | 125 ++ memory/297-typed-component-port-binding.md | 134 ++ .../298-declarative-component-port-naming.md | 80 + ...-typed-code-first-application-authoring.md | 135 ++ ...-unified-code-first-component-contracts.md | 148 ++ ...01-end-to-end-code-first-simplification.md | 79 + memory/302-application-health-readiness.md | 110 ++ ...rformance-concurrency-lifetime-baseline.md | 198 +++ samples/FluxFlow.CompositionSample/Program.cs | 191 +- .../Program.cs | 17 +- .../SampleWorkflow.cs | 64 +- .../FluxFlow.MqttCompositionSample/Program.cs | 101 +- .../FluxFlow.SampleApp.csproj | 1 - samples/FluxFlow.SampleApp/OrderNodes.cs | 37 +- samples/FluxFlow.SampleApp/Program.cs | 7 +- .../SampleComponentRegistration.cs | 137 +- .../SampleExpressionEngine.cs | 35 - .../SampleWorkspaceDefinition.cs | 105 +- .../AssertionsAuthoringExtensions.cs | 27 +- .../AssertionsComponentDefinition.cs | 1 + .../AssertionsServiceCollectionExtensions.cs | 66 +- .../README.md | 10 + .../ComponentDesignMetadataFinalizer.cs | 43 +- .../ComponentRegistrationBuilder.cs | 101 +- .../ComponentRegistrationExtensions.cs | 48 +- .../DesignedComponentBindingBuilder.cs | 151 ++ .../DesignedComponentContract.cs | 85 + src/FluxFlow.Components.Designer/README.md | 97 +- .../ExpectationsAuthoringExtensions.cs | 26 +- .../ExpectationsComponentDefinition.cs | 2 +- ...ExpectationsServiceCollectionExtensions.cs | 32 +- .../README.md | 10 + .../FileSystemAuthoringExtensions.cs | 85 +- .../FileSystemComponentDefinition.cs | 2 +- .../FileSystemServiceCollectionExtensions.cs | 119 +- .../README.md | 10 + .../HttpAuthoringExtensions.cs | 27 +- .../HttpComponentDefinition.cs | 1 + .../HttpServiceCollectionExtensions.cs | 32 +- .../README.md | 10 + .../MappingAuthoringExtensions.cs | 27 +- .../MappingComponentDefinition.cs | 1 + .../MappingServiceCollectionExtensions.cs | 66 +- .../README.md | 10 + .../MetricsAuthoringExtensions.cs | 26 +- .../MetricsComponentDefinition.cs | 2 +- .../MetricsServiceCollectionExtensions.cs | 32 +- .../README.md | 10 + .../ObservabilityAuthoringExtensions.cs | 55 +- .../ObservabilityComponentDefinition.cs | 2 +- ...bservabilityServiceCollectionExtensions.cs | 98 +- .../README.md | 10 + .../PayloadsAuthoringExtensions.cs | 27 +- .../PayloadsComponentDefinition.cs | 1 + .../PayloadsServiceCollectionExtensions.cs | 32 +- .../README.md | 10 + .../ProjectionsAuthoringExtensions.cs | 26 +- .../ProjectionsComponentDefinition.cs | 2 +- .../ProjectionsServiceCollectionExtensions.cs | 32 +- .../README.md | 10 + .../README.md | 10 + .../ResilienceAuthoringExtensions.cs | 35 +- .../ResilienceComponentDefinition.cs | 1 + .../ResilienceServiceCollectionExtensions.cs | 46 +- .../README.md | 10 + .../RoutingAuthoringExtensions.cs | 64 +- .../RoutingComponentDefinition.cs | 2 +- .../RoutingServiceCollectionExtensions.cs | 107 +- .../README.md | 10 + .../SerializationAuthoringExtensions.cs | 59 +- .../SerializationComponentDefinition.cs | 2 +- ...erializationServiceCollectionExtensions.cs | 131 +- .../README.md | 10 + .../SessionsAuthoringExtensions.cs | 64 +- .../SessionsComponentDefinition.cs | 2 +- .../SessionsServiceCollectionExtensions.cs | 85 +- .../README.md | 10 + .../SourcesAuthoringExtensions.cs | 44 +- .../SourcesComponentDefinition.cs | 2 +- .../SourcesServiceCollectionExtensions.cs | 53 +- .../README.md | 10 + .../StateAuthoringExtensions.cs | 24 +- .../StateComponentDefinition.cs | 2 +- .../StateServiceCollectionExtensions.cs | 32 +- .../README.md | 10 + .../StorageAuthoringExtensions.cs | 58 +- .../StorageComponentDefinition.cs | 2 +- .../StorageCompositionStoreResolver.cs | 12 +- .../StorageServiceCollectionExtensions.cs | 157 +- .../README.md | 10 + .../TimersAuthoringExtensions.cs | 95 +- .../TimersComponentDefinition.cs | 2 +- .../TimersServiceCollectionExtensions.cs | 155 +- .../README.md | 10 + .../ValidationAuthoringExtensions.cs | 27 +- .../ValidationComponentDefinition.cs | 2 +- .../ValidationServiceCollectionExtensions.cs | 32 +- .../ApplicationLinkCompiler.cs | 113 +- .../ApplicationLinkDefinition.cs | 122 ++ .../CompiledApplicationLink.cs | 10 +- .../ApplicationModel/ApplicationDefinition.cs | 74 + .../Authoring/ApplicationDefinitionBuilder.cs | 101 +- .../Authoring/ApplicationResourceContract.cs | 93 + .../ApplicationResourceContractCollection.cs | 29 + .../Authoring/AuthoringHandles.cs | 95 +- .../Authoring/ComponentContract.cs | 96 + .../Authoring/ComponentContractCollection.cs | 29 + .../ResourceDefinitionContainerBuilder.cs | 117 +- .../Authoring/WorkflowDefinitionBuilder.cs | 277 ++- .../FluxFlowServiceCollectionExtensions.cs | 21 + .../Factories/ComponentCatalog.cs | 15 + .../Factories/ComponentDescriptor.cs | 76 +- .../Factories/ComponentNodeActivation.cs | 23 + src/FluxFlow.Composition/README.md | 113 +- .../FluxFlowRegistrationBuilder.cs | 27 + .../FluxFlowRegistrationExtensions.cs | 49 +- .../RuntimeComponentBindingBuilder.cs | 197 +++ .../RuntimeComponentRegistrationBuilder.cs | 335 +++- .../IApplicationResourceRegistrar.cs | 2 + .../Runtime/ComponentEventSource.cs | 18 + .../Runtime/ComponentEvents.cs | 6 - .../Runtime/ComponentInstance.cs | 66 +- .../Runtime/ComponentPorts.cs | 5 + .../DurableApplicationInputs.cs | 10 + .../DurableOutputRegistration.cs | 10 + .../FluxFlow.Engine.HealthChecks.csproj | 34 + .../FluxFlowApplicationHealthCheck.cs | 122 ++ .../FluxFlowHealthChecksBuilderExtensions.cs | 32 + src/FluxFlow.Engine.HealthChecks/README.md | 44 + src/FluxFlow.Engine/ApplicationPorts.cs | 54 + src/FluxFlow.Engine/FluxFlowApplication.cs | 8 +- .../Hosting/ApplicationRuntimeAssembler.cs | 3 +- .../ApplicationRuntimeComponentActivator.cs | 4 +- .../Hosting/ApplicationRuntimeDrainPlan.cs | 116 ++ .../Hosting/ApplicationRuntimePlanFactory.cs | 20 +- .../Hosting/ApplicationRuntimePortSurface.cs | 5 +- .../Hosting/ApplicationRuntimePreparation.cs | 4 + ...plicationRuntimeResourceSnapshotFactory.cs | 13 +- .../ApplicationRuntimeRevisionCandidate.cs | 21 +- .../Revisions/ApplicationRevisionPlanner.cs | 97 +- .../CompositionServiceProviderSnapshot.cs | 22 +- ...mpositionServiceProviderSnapshotBuilder.cs | 6 +- .../Ports/ApplicationInputPort.cs | 3 + .../Ports/ApplicationInputRevisionLifetime.cs | 3 + .../Ports/ApplicationOutputPort.cs | 50 +- .../Ports/ApplicationPortEventPublisher.cs | 56 +- .../Ports/ApplicationPortRevision.cs | 30 +- .../Ports/ApplicationPortRuntime.cs | 86 + .../Ports/ApplicationSignalInputPort.cs | 1 + src/FluxFlow.Engine/README.md | 81 +- src/FluxFlow.Fluent.Hosting/README.md | 7 +- src/FluxFlow.Fluent/Flow.cs | 4 +- src/FluxFlow.Fluent/FlowBuilder.cs | 24 +- src/FluxFlow.Fluent/FlowGraph.cs | 170 +- src/FluxFlow.Fluent/FlowGraphBuilder.cs | 225 ++- src/FluxFlow.Fluent/FluxFlow.Fluent.csproj | 2 + src/FluxFlow.Fluent/README.md | 42 +- .../MqttApplicationAuthoringExtensions.cs | 180 +- .../Authoring/MqttComponentAuthoring.cs | 23 +- .../Authoring/MqttResourceAuthoring.cs | 16 +- .../MqttComponentDefinition.cs | 2 +- .../MqttCompositionNodeFactories.cs | 69 +- .../MqttServiceCollectionExtensions.cs | 61 +- .../README.md | 51 +- ...ertionsServiceCollectionExtensionsTests.cs | 4 +- .../ComponentDesignMetadataCatalogTests.cs | 94 +- .../DesignedComponentBindingBuilderTests.cs | 320 ++++ ...xFlowDesignedComponentRegistrationTests.cs | 217 ++- ...tationsServiceCollectionExtensionsTests.cs | 6 +- ...eSystemServiceCollectionExtensionsTests.cs | 18 +- ...MappingServiceCollectionExtensionsTests.cs | 6 +- ...MetricsServiceCollectionExtensionsTests.cs | 2 +- ...MqttApplicationDefinitionAuthoringTests.cs | 43 +- .../MqttServiceCollectionExtensionsTests.cs | 51 + ...abilityServiceCollectionExtensionsTests.cs | 2 +- ...ayloadsServiceCollectionExtensionsTests.cs | 2 +- ...ectionsServiceCollectionExtensionsTests.cs | 2 +- ...RoutingServiceCollectionExtensionsTests.cs | 10 +- ...izationServiceCollectionExtensionsTests.cs | 2 +- ...essionsServiceCollectionExtensionsTests.cs | 19 +- ...SourcesServiceCollectionExtensionsTests.cs | 4 +- .../StateServiceCollectionExtensionsTests.cs | 6 +- ...StorageServiceCollectionExtensionsTests.cs | 25 +- .../TimersServiceCollectionExtensionsTests.cs | 4 +- ...idationServiceCollectionExtensionsTests.cs | 4 +- .../ApplicationDefinitionAuthoringTests.cs | 79 +- ...ApplicationDefinitionFluentCaptureTests.cs | 78 +- .../ApplicationDefinitionJsonTests.cs | 92 + .../ApplicationLinkCompilerTests.cs | 6 +- .../ComponentDescriptorTests.cs | 6 +- .../ComponentEventTests.cs | 90 +- .../FluxFlowRegistrationBuilderTests.cs | 167 +- .../RuntimeComponentBindingBuilderTests.cs | 555 ++++++ .../TestCompositionNodes.cs | 45 +- ...TypedCodeFirstApplicationAuthoringTests.cs | 563 ++++++ ...edCodeFirstApplicationLinkCompilerTests.cs | 201 +++ .../TypedCodeFirstResourceAuthoringTests.cs | 259 +++ .../DesignerHostCatalogTests.cs | 4 +- .../DurableApplicationInputsTests.cs | 65 + .../DurableInputTestApplication.cs | 91 +- .../DurableOutputRegistrationTests.cs | 56 + .../FluxFlow.Engine.HealthChecks.Tests.csproj | 25 + .../FluxFlowApplicationHealthCheckTests.cs | 661 +++++++ .../FluxFlowHealthCheckRegistrationTests.cs | 207 +++ .../ApplicationPortHandleTests.cs | 381 ++++ ...ApplicationResourceContractRuntimeTests.cs | 589 +++++++ .../ApplicationRevisionPlannerTests.cs | 138 ++ .../ApplicationRuntimeAssemblerTests.cs | 925 ++++++++-- .../ApplicationRuntimeConcurrencyTests.cs | 708 ++++++++ .../ApplicationRuntimeSignalsTests.cs | 136 +- ...CompositionServiceProviderSnapshotTests.cs | 63 + .../FluxFlow.Fluent.Tests/FlowBuilderTests.cs | 58 +- .../FlowObservationTests.cs | 42 + tests/FluxFlow.Fluent.Tests/TestFlowNodes.cs | 33 + ...irstApplicationAuthoringConventionTests.cs | 444 +++++ ...onentCompositionMetadataConventionTests.cs | 94 +- ...ComponentFamilyAuthoringConventionTests.cs | 153 ++ .../ComponentFamilyRegistrationMatrixTests.cs | 58 +- .../DocumentationBoundaryTests.cs | 45 +- .../HealthReadinessConventionTests.cs | 252 +++ .../PackageConsumerAcceptanceScriptTests.cs | 471 ++++- .../PerformanceHardeningConventionTests.cs | 168 ++ .../TypedComponentAuthoringConventionTests.cs | 307 ++++ 271 files changed, 22461 insertions(+), 3156 deletions(-) create mode 100644 benchmarks/FluxFlow.Engine.Benchmarks/ApplicationLinkCompilationBenchmarks.cs create mode 100644 benchmarks/FluxFlow.Engine.Benchmarks/ApplicationMessagingBenchmarks.cs create mode 100644 benchmarks/FluxFlow.Engine.Benchmarks/ApplicationTopologyBenchmarks.cs create mode 100644 benchmarks/FluxFlow.Engine.Benchmarks/BenchmarkApplication.cs create mode 100644 benchmarks/FluxFlow.Engine.Benchmarks/FluxFlow.Engine.Benchmarks.csproj create mode 100644 benchmarks/FluxFlow.Engine.Benchmarks/Program.cs create mode 100644 docs/39-typed-code-first-authoring.md create mode 100644 docs/40-unified-component-contracts.md create mode 100644 docs/41-end-to-end-code-first-simplification.md create mode 100644 docs/42-application-health-readiness.md create mode 100644 docs/43-performance-concurrency-lifetime-baseline.md create mode 100644 eng/package-consumer-acceptance/RestartDurabilityScenario.cs create mode 100644 goals/2026-08-07-package-consumer-restart-durability-acceptance/README.md create mode 100644 goals/2026-08-08-application-health-readiness/README.md create mode 100644 goals/2026-08-08-end-to-end-code-first-simplification/README.md create mode 100644 goals/2026-08-08-release-candidate-consolidation/README.md create mode 100644 goals/2026-08-08-typed-code-first-application-authoring/README.md create mode 100644 goals/2026-08-08-typed-component-port-binding/README.md create mode 100644 goals/2026-08-08-unified-code-first-component-contracts/README.md create mode 100644 memory/296-package-consumer-restart-durability-acceptance.md create mode 100644 memory/297-typed-component-port-binding.md create mode 100644 memory/298-declarative-component-port-naming.md create mode 100644 memory/299-typed-code-first-application-authoring.md create mode 100644 memory/300-unified-code-first-component-contracts.md create mode 100644 memory/301-end-to-end-code-first-simplification.md create mode 100644 memory/302-application-health-readiness.md create mode 100644 memory/303-performance-concurrency-lifetime-baseline.md delete mode 100644 samples/FluxFlow.SampleApp/SampleExpressionEngine.cs create mode 100644 src/FluxFlow.Components.Designer/DesignedComponentBindingBuilder.cs create mode 100644 src/FluxFlow.Components.Designer/DesignedComponentContract.cs create mode 100644 src/FluxFlow.Composition/ApplicationLinks/ApplicationLinkDefinition.cs create mode 100644 src/FluxFlow.Composition/Authoring/ApplicationResourceContract.cs create mode 100644 src/FluxFlow.Composition/Authoring/ApplicationResourceContractCollection.cs create mode 100644 src/FluxFlow.Composition/Authoring/ComponentContract.cs create mode 100644 src/FluxFlow.Composition/Authoring/ComponentContractCollection.cs create mode 100644 src/FluxFlow.Composition/Factories/ComponentNodeActivation.cs create mode 100644 src/FluxFlow.Composition/Registration/RuntimeComponentBindingBuilder.cs create mode 100644 src/FluxFlow.Composition/Runtime/ComponentEventSource.cs delete mode 100644 src/FluxFlow.Composition/Runtime/ComponentEvents.cs create mode 100644 src/FluxFlow.Engine.HealthChecks/FluxFlow.Engine.HealthChecks.csproj create mode 100644 src/FluxFlow.Engine.HealthChecks/FluxFlowApplicationHealthCheck.cs create mode 100644 src/FluxFlow.Engine.HealthChecks/FluxFlowHealthChecksBuilderExtensions.cs create mode 100644 src/FluxFlow.Engine.HealthChecks/README.md create mode 100644 src/FluxFlow.Engine/Hosting/ApplicationRuntimeDrainPlan.cs create mode 100644 tests/FluxFlow.Components.Designer.Tests/DesignedComponentBindingBuilderTests.cs create mode 100644 tests/FluxFlow.Composition.Tests/RuntimeComponentBindingBuilderTests.cs create mode 100644 tests/FluxFlow.Composition.Tests/TypedCodeFirstApplicationAuthoringTests.cs create mode 100644 tests/FluxFlow.Composition.Tests/TypedCodeFirstApplicationLinkCompilerTests.cs create mode 100644 tests/FluxFlow.Composition.Tests/TypedCodeFirstResourceAuthoringTests.cs create mode 100644 tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlow.Engine.HealthChecks.Tests.csproj create mode 100644 tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlowApplicationHealthCheckTests.cs create mode 100644 tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlowHealthCheckRegistrationTests.cs create mode 100644 tests/FluxFlow.Engine.Tests/ApplicationPortHandleTests.cs create mode 100644 tests/FluxFlow.Engine.Tests/ApplicationResourceContractRuntimeTests.cs create mode 100644 tests/FluxFlow.Engine.Tests/ApplicationRuntimeConcurrencyTests.cs create mode 100644 tests/FluxFlow.Release.Tests/CodeFirstApplicationAuthoringConventionTests.cs create mode 100644 tests/FluxFlow.Release.Tests/HealthReadinessConventionTests.cs create mode 100644 tests/FluxFlow.Release.Tests/PerformanceHardeningConventionTests.cs create mode 100644 tests/FluxFlow.Release.Tests/TypedComponentAuthoringConventionTests.cs diff --git a/.gitignore b/.gitignore index a750b0d5..905460b7 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ artifacts/ *.suo TestResults/ coverage/ +BenchmarkDotNet.Artifacts/ .testagent/ *.nupkg *.snupkg diff --git a/CHANGELOG.md b/CHANGELOG.md index 75e0cc38..7a250c80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,34 @@ Current framework simplification release train. Historical entries below describe earlier package lines. +## Unreleased + +- Adds a permanent non-packable benchmark suite for real typed/addressed + request/reply, pipeline scale, and link-compilation scale. +- Removes unconditional-link condition-context allocations and small diagnostic + `params`/LINQ allocations, reducing the measured eight-hop ShortRun allocation + from 53.25 KB to 43.29 KB without a public API or semantic change. +- Strengthens deterministic concurrent messaging, revision, shutdown, and + lifetime coverage; performance timings remain manual evidence rather than CI + thresholds. +- Clarifies across every component-family package that complete code-first + contracts require only `AddFluxFlow(definition)`, while JSON/catalog hosts use + explicit family registration. +- Extends package-only acceptance with unchanged portable-definition apply, + rejected invalid-candidate rollback, exact active revision retention, and a + fresh request through the retained JSON route. + +## FluxFlow.Engine.HealthChecks 1.0.0 + +- Adds one idempotent standard .NET readiness registration over the existing + FluxFlow application state and active revision. +- Reports failed hot reload as degraded while rollback preserves the active + revision; missing, unstarted, failed initial, stopping, and stopped + applications fail closed as unhealthy. +- Emits only bounded lifecycle/revision/status/diagnostic-code metadata and adds + no worker, polling, timer, storage query, endpoint, reflection, or Engine + dependency. + ## FluxFlow.Engine.DurableOutput.TSql 2.0.0 - Implements exact-token, unexpired-lease renewal with one direct parameterized diff --git a/Directory.Packages.props b/Directory.Packages.props index cbb04887..add12bde 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,6 +5,7 @@ + @@ -15,6 +16,7 @@ + diff --git a/FluxFlow.sln b/FluxFlow.sln index 44a86a35..2e8709df 100644 --- a/FluxFlow.sln +++ b/FluxFlow.sln @@ -277,6 +277,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FluxFlow.Engine.DurableOutp EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FluxFlow.Engine.DurableOutput.TSql.Tests", "tests\FluxFlow.Engine.DurableOutput.TSql.Tests\FluxFlow.Engine.DurableOutput.TSql.Tests.csproj", "{7E415CFB-33D1-4FBA-9D60-AB884D8F72B2}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FluxFlow.Engine.HealthChecks", "src\FluxFlow.Engine.HealthChecks\FluxFlow.Engine.HealthChecks.csproj", "{1A9633CE-05CB-4A96-A44C-63C9E8B0A841}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FluxFlow.Engine.HealthChecks.Tests", "tests\FluxFlow.Engine.HealthChecks.Tests\FluxFlow.Engine.HealthChecks.Tests.csproj", "{B51F2E78-3A24-4F12-9D78-6D38E9D01A22}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "benchmarks", "benchmarks", "{66320409-64EC-F7C5-3DEF-65E7510DAAD1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FluxFlow.Engine.Benchmarks", "benchmarks\FluxFlow.Engine.Benchmarks\FluxFlow.Engine.Benchmarks.csproj", "{47340D45-F196-4B44-94FE-6DF9DD848232}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -1883,6 +1891,42 @@ Global {7E415CFB-33D1-4FBA-9D60-AB884D8F72B2}.Release|x64.Build.0 = Release|Any CPU {7E415CFB-33D1-4FBA-9D60-AB884D8F72B2}.Release|x86.ActiveCfg = Release|Any CPU {7E415CFB-33D1-4FBA-9D60-AB884D8F72B2}.Release|x86.Build.0 = Release|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Debug|x64.ActiveCfg = Debug|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Debug|x64.Build.0 = Debug|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Debug|x86.ActiveCfg = Debug|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Debug|x86.Build.0 = Debug|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Release|Any CPU.Build.0 = Release|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Release|x64.ActiveCfg = Release|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Release|x64.Build.0 = Release|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Release|x86.ActiveCfg = Release|Any CPU + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841}.Release|x86.Build.0 = Release|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Debug|x64.ActiveCfg = Debug|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Debug|x64.Build.0 = Debug|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Debug|x86.ActiveCfg = Debug|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Debug|x86.Build.0 = Debug|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Release|Any CPU.Build.0 = Release|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Release|x64.ActiveCfg = Release|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Release|x64.Build.0 = Release|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Release|x86.ActiveCfg = Release|Any CPU + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22}.Release|x86.Build.0 = Release|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Debug|Any CPU.Build.0 = Debug|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Debug|x64.ActiveCfg = Debug|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Debug|x64.Build.0 = Debug|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Debug|x86.ActiveCfg = Debug|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Debug|x86.Build.0 = Debug|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Release|Any CPU.ActiveCfg = Release|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Release|Any CPU.Build.0 = Release|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Release|x64.ActiveCfg = Release|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Release|x64.Build.0 = Release|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Release|x86.ActiveCfg = Release|Any CPU + {47340D45-F196-4B44-94FE-6DF9DD848232}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -2017,5 +2061,8 @@ Global {0A16F586-1571-4BB0-813F-A87C65924B14} = {0AB3BF05-4346-4AA6-1389-037BE0695223} {A7F4BE09-7C20-4B20-98CC-3BB61C854229} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {5292D24D-2D7A-4AB1-A065-EB5E5D2C994E} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + {1A9633CE-05CB-4A96-A44C-63C9E8B0A841} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {B51F2E78-3A24-4F12-9D78-6D38E9D01A22} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + {47340D45-F196-4B44-94FE-6DF9DD848232} = {66320409-64EC-F7C5-3DEF-65E7510DAAD1} EndGlobalSection EndGlobal diff --git a/README.md b/README.md index f4f72d5c..7dd9ba9d 100644 --- a/README.md +++ b/README.md @@ -5,12 +5,15 @@ FluxFlow is a standalone-node-first workflow toolkit for .NET. The default architecture is: 1. Build reusable nodes over `FluxFlow.Nodes`. -2. Register component factories explicitly with `FluxFlow.Composition`. -3. Load the canonical application document with exactly `Resources` and - `Workflows`. +2. Declare complete typed component contracts with `FluxFlow.Composition`, or + register those contracts explicitly for a JSON/dynamic host. +3. Either load the canonical JSON application document with exactly `Resources` + and `Workflows`, or build a typed application directly in compiled C#. 4. Activate it through `FluxFlow.Engine` with one `AddFluxFlow(...)` registration when hosted lifecycle or addressable runtime ports are needed. -5. Keep resources such as clients, stores, secrets, and protocol adapters owned by the host or adapter package. +5. Let code-first resource declarations carry their package registrar while + keeping concrete clients, stores, secrets, and protocol adapters explicitly + owned by the revision or host. `FluxFlow.Engine` remains optional for component packages. Canonical hosts use `FluxFlowApplication` for revisions, compiled links, stable direct ports, and @@ -25,6 +28,7 @@ system signals without moving external resource ownership into the engine. | `FluxFlow.Resilience` | Transport-neutral retry policy, schedules, state transitions, jitter, and direct-call execution. | | `FluxFlow.Composition` | Canonical application definitions, addresses, links, component registrations, events, and processing profiles. | | `FluxFlow.Engine` | Optional canonical application host with transactional revisions, stable direct ports, and system signals. | +| `FluxFlow.Engine.HealthChecks` | Optional standard .NET readiness check over the existing Engine lifecycle and active revision. | | `FluxFlow.Engine.DurableInput` | Optional provider-neutral durable inbox with Engine-accepted or explicit workflow-completion acknowledgement, dead-letter operations, payload-free status, and explicit bounded terminal retention. | | `FluxFlow.Engine.DurableInput.SqlFile` | Production SQLite single-file store with exact lease renewal, generation-protected dead-letter replay, read-only status, and transactional retention. | | `FluxFlow.Engine.DurableInput.TSql` | Production opt-in networked T-SQL inbox with shared atomic leasing, exact renewal, dead-letter inspection/replay, read-only status, and transactional retention. | @@ -55,23 +59,80 @@ Nodes are plain Dataflow processors. Construct them, link their ports, send ## Composition Example -`FluxFlow.Composition` adds strict canonical definitions, explicit factory -registration, validation, and link compilation around -standalone nodes: +`FluxFlow.Composition` adds strict definitions, complete typed component +contracts, validation, and link compilation around standalone nodes. A +contract declares runtime behavior and typed authoring once: ```csharp -services.AddFluxFlowComponents().AddRuntimeComponent( - "sample.uppercase", - component => - { - component.UseFactory(CreateUppercaseAsync); - component.AddInput("Input"); - component.AddOutput("Output"); - }); +public static ComponentContract Uppercase { get; } = + ComponentContract.Create( + "sample.uppercase", + component => + { + component + .UseFactory(static _ => new UppercaseNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); + }, + static handle => new UppercaseHandle(handle)); +``` + +Developers can instead author and host the graph directly in typed C#. This is +an independent compiled-code path, not a JSON generator: + +```csharp +var definitionBuilder = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var main) + .AddWorkflow("audit", out var audit); + +main + .AddComponent("source", OrderComponents.Source, out var source) + .AddComponent("review", OrderComponents.Review, out var review) + .AddComponent("priority", OrderComponents.Sink, out var priority); + +audit.AddComponent("events", OrderComponents.EventCollector, out var events); + +source.Output.ConnectTo(review.Input); +review.Output.ConnectTo(priority.Input, when: static order => order.Priority); +review.Events.ConnectTo(events.Input); + +var definition = definitionBuilder.Build(); +services.AddFluxFlow(definition); +``` + +The built definition carries the exact component descriptors and application +resource contracts it uses, so normal code-first hosting needs no second +component or resource-family registration. Component-specific +builders own settings, and named handles expose `Input`, `Output`, `Events`, and +other domain ports. Direct `ConnectTo` supports same-owner cross-workflow links +and returns the output handle for fan-out. Workflow `Connect` stays local; +application `Connect` is the explicit cross-workflow form. Typed predicates are +synchronous, revision-owned C# delegates and do not require an expression +engine. See [Typed Code-First Application Authoring](docs/39-typed-code-first-authoring.md) +and [Unified Component Contracts](docs/40-unified-component-contracts.md). + +Those same handles continue across the runtime boundary: + +```csharp +var result = application.Ports.ReceiveAsync(priority.Output); +await application.Ports.SendAsync(review.Input, FlowMessage.Create(order)); +var received = await result; +``` +Typed overloads are also available for observation, request/reply, durable +input enqueue, durable output capture, and explicit keyed resource binding. +They delegate to the same canonical-address implementation and keep +`FlowMessage` metadata explicit. + +Portable JSON remains independent and contains no executable delegates. A JSON +host registers the required contracts explicitly: + +```csharp var definition = ApplicationDefinitionJson.Deserialize(json); -var catalog = provider.GetRequiredService(); -var links = new ApplicationLinkCompiler(catalog).Compile(definition); +services + .AddFluxFlow(definition) + .AddComponent(SampleComponents.Uppercase); ``` There is no reflection, assembly scanning, alias rewrite, or engine dependency @@ -92,12 +153,33 @@ var application = provider.GetRequiredService(); await application.StartAsync(); ``` +Hosts that use standard .NET health checks can opt into one readiness signal +without changing Engine or starting another worker: + +```csharp +using FluxFlow.Engine.HealthChecks; + +services.AddHealthChecks() + .AddFluxFlowApplication(); +``` + +The check is named `fluxflow.application` and tagged `fluxflow` plus `ready`. +It is healthy when an active revision is available, degraded when a rejected +update leaves the previous revision serving, and unhealthy when FluxFlow is +missing, inactive, or stopped. See +[Application Health Readiness](docs/42-application-health-readiness.md). + Adapter packages still own concrete resources and register them in DI, usually -as named keyed services. +as named keyed services. A compiled-C# resource contract carries only its +portable type/options, typed handle, and explicit registrar. JSON cannot and +does not serialize that executable behavior, so configuration hosts continue +to register the relevant package family explicitly. Expected failures remain ordinary value-or-error `FlowMessage` values on `Output`; component contracts do not expose a universal Errors port. -Every canonical component also exposes traced `Workflow.Component.Events`; +Every built-in component explicitly declares its traced +`Workflow.Component.Events` port. Custom components choose the event-port name +with `HasEvents(...)`, and components that omit it have no implicit event port; unrecoverable faults remain on `Completion`. Canonical JSON does not expose Dataflow capacities or parallelism settings. An optional `processing.profile` resource provides semantic `Mode`, `Order`, and `Buffer` settings when defaults @@ -150,6 +232,17 @@ Build and test with the same configuration. The Release verification suite runs sample applications from those prebuilt outputs so a missing artifact fails visibly instead of triggering an implicit restore or build. +For allocation and throughput investigation, use the permanent non-packable +benchmark suite. Start with a dry run; timing remains manual evidence and is +not a flaky CI threshold: + +```sh +dotnet run --project benchmarks/FluxFlow.Engine.Benchmarks/FluxFlow.Engine.Benchmarks.csproj --configuration Release -- --filter "*" --job Dry --noOverwrite +``` + +See [Performance, Concurrency, And Lifetime Baseline](docs/43-performance-concurrency-lifetime-baseline.md) +for the measured cases, current machine-local baseline, and full-run commands. + ## License FluxFlow is licensed under the MIT License. diff --git a/benchmarks/FluxFlow.Engine.Benchmarks/ApplicationLinkCompilationBenchmarks.cs b/benchmarks/FluxFlow.Engine.Benchmarks/ApplicationLinkCompilationBenchmarks.cs new file mode 100644 index 00000000..dd4daa21 --- /dev/null +++ b/benchmarks/FluxFlow.Engine.Benchmarks/ApplicationLinkCompilationBenchmarks.cs @@ -0,0 +1,44 @@ +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Columns; +using FluxFlow.Composition; +using FluxFlow.Composition.Authoring; +using FluxFlow.Composition.Links; +using FluxFlow.Composition.Model; + +namespace FluxFlow.Engine.Benchmarks; + +[MemoryDiagnoser] +[RankColumn] +public class ApplicationLinkCompilationBenchmarks +{ + private ApplicationDefinition _definition = null!; + private ApplicationLinkCompiler _compiler = null!; + + [Params(1, 32, 128)] + public int LinkCount { get; set; } + + [GlobalSetup] + public void Setup() + { + var builder = new ApplicationDefinitionBuilder(); + var workflow = builder.AddWorkflow("main"); + EchoHandle? previous = null; + + for (var index = 0; index <= LinkCount; index++) + { + var current = workflow.AddComponent( + $"echo-{index}", + BenchmarkComponents.Echo); + previous?.Output.ConnectTo(current.Input); + previous = current; + } + + _definition = builder.Build(); + _compiler = new ApplicationLinkCompiler( + new ComponentCatalog([BenchmarkComponents.Echo.Descriptor])); + } + + [Benchmark] + public ApplicationLinkCompilationResult Compile() + => _compiler.Compile(_definition); +} diff --git a/benchmarks/FluxFlow.Engine.Benchmarks/ApplicationMessagingBenchmarks.cs b/benchmarks/FluxFlow.Engine.Benchmarks/ApplicationMessagingBenchmarks.cs new file mode 100644 index 00000000..53e54bac --- /dev/null +++ b/benchmarks/FluxFlow.Engine.Benchmarks/ApplicationMessagingBenchmarks.cs @@ -0,0 +1,53 @@ +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Columns; +using FluxFlow.Engine.Ports; +using FluxFlow.Nodes; + +namespace FluxFlow.Engine.Benchmarks; + +[MemoryDiagnoser] +[RankColumn] +public class ApplicationMessagingBenchmarks +{ + private static readonly FlowMessage Message = FlowMessage.Create("benchmark-message"); + + private BenchmarkApplication _unconditional = null!; + private BenchmarkApplication _conditional = null!; + + [GlobalSetup] + public async Task SetupAsync() + { + _unconditional = await BenchmarkApplication.StartAsync(hopCount: 2); + _conditional = await BenchmarkApplication.StartAsync( + hopCount: 2, + static value => value.Length > 0); + } + + [GlobalCleanup] + public async Task CleanupAsync() + { + await _conditional.DisposeAsync(); + await _unconditional.DisposeAsync(); + } + + [Benchmark(Baseline = true)] + public Task> AddressedUnconditionalRequest() + => _unconditional.Application.Ports.SendAndReceiveAsync( + _unconditional.Input.Input.Address, + _unconditional.Output.Output.Address, + Message); + + [Benchmark] + public Task> TypedUnconditionalRequest() + => _unconditional.Application.Ports.SendAndReceiveAsync( + _unconditional.Input.Input, + _unconditional.Output.Output, + Message); + + [Benchmark] + public Task> TypedConditionalRequest() + => _conditional.Application.Ports.SendAndReceiveAsync( + _conditional.Input.Input, + _conditional.Output.Output, + Message); +} diff --git a/benchmarks/FluxFlow.Engine.Benchmarks/ApplicationTopologyBenchmarks.cs b/benchmarks/FluxFlow.Engine.Benchmarks/ApplicationTopologyBenchmarks.cs new file mode 100644 index 00000000..4d15b504 --- /dev/null +++ b/benchmarks/FluxFlow.Engine.Benchmarks/ApplicationTopologyBenchmarks.cs @@ -0,0 +1,33 @@ +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Columns; +using FluxFlow.Engine.Ports; +using FluxFlow.Nodes; + +namespace FluxFlow.Engine.Benchmarks; + +[MemoryDiagnoser] +[RankColumn] +public class ApplicationTopologyBenchmarks +{ + private static readonly FlowMessage Message = FlowMessage.Create("benchmark-message"); + + private BenchmarkApplication _application = null!; + + [Params(1, 8)] + public int HopCount { get; set; } + + [GlobalSetup] + public async Task SetupAsync() + => _application = await BenchmarkApplication.StartAsync(HopCount); + + [GlobalCleanup] + public async Task CleanupAsync() + => await _application.DisposeAsync(); + + [Benchmark] + public Task> TypedRequestThroughPipeline() + => _application.Application.Ports.SendAndReceiveAsync( + _application.Input.Input, + _application.Output.Output, + Message); +} diff --git a/benchmarks/FluxFlow.Engine.Benchmarks/BenchmarkApplication.cs b/benchmarks/FluxFlow.Engine.Benchmarks/BenchmarkApplication.cs new file mode 100644 index 00000000..ae9d45ea --- /dev/null +++ b/benchmarks/FluxFlow.Engine.Benchmarks/BenchmarkApplication.cs @@ -0,0 +1,133 @@ +using FluxFlow.Composition; +using FluxFlow.Composition.Authoring; +using FluxFlow.Engine; +using FluxFlow.Nodes; +using Microsoft.Extensions.DependencyInjection; + +namespace FluxFlow.Engine.Benchmarks; + +internal static class BenchmarkComponents +{ + internal static ComponentContract Echo { get; } = + ComponentContract.Create( + "benchmark.echo", + static runtime => runtime + .UseFactory(static _ => new EchoNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events), + static component => new EchoHandle(component)); +} + +internal sealed class EchoHandle(ComponentHandle definition) : AuthoredComponentHandle(definition) +{ + internal InputPortHandle Input { get; } = definition.Input("Input"); + + internal OutputPortHandle Output { get; } = definition.Output("Output"); +} + +internal sealed class EchoNode : FlowNode +{ + internal EchoNode() + : base(new FlowNodeOptions { InputCapacity = 1_024 }) + { + } + + protected override async Task ProcessAsync(FlowMessage message) + => await EmitAsync(message, Stopping).ConfigureAwait(false); +} + +internal sealed class BenchmarkApplication : IAsyncDisposable +{ + private readonly ServiceProvider _provider; + + private BenchmarkApplication( + ServiceProvider provider, + FluxFlowApplication application, + EchoHandle input, + EchoHandle output) + { + _provider = provider; + Application = application; + Input = input; + Output = output; + } + + internal FluxFlowApplication Application { get; } + + internal EchoHandle Input { get; } + + internal EchoHandle Output { get; } + + internal static async Task StartAsync( + int hopCount, + Func? condition = null) + { + if (hopCount <= 0) + throw new ArgumentOutOfRangeException(nameof(hopCount)); + + var builder = new ApplicationDefinitionBuilder(); + var workflow = builder.AddWorkflow("main"); + EchoHandle? first = null; + EchoHandle? previous = null; + + for (var index = 0; index < hopCount; index++) + { + var current = workflow.AddComponent( + $"echo-{index}", + BenchmarkComponents.Echo); + first ??= current; + + if (previous is not null) + { + if (condition is null) + previous.Output.ConnectTo(current.Input); + else + previous.Output.ConnectTo(current.Input, condition); + } + + previous = current; + } + + var services = new ServiceCollection(); + services.AddFluxFlow( + builder.Build(), + options => + { + options.StartWithHost = false; + options.InputCapacity = 1_024; + options.OutputCapacity = 1_024; + }); + + var provider = services.BuildServiceProvider(); + try + { + var application = provider.GetRequiredService(); + var started = await application.StartAsync().ConfigureAwait(false); + if (!started.IsApplied) + { + throw new InvalidOperationException( + $"Benchmark application startup failed: {started.Status}."); + } + + return new BenchmarkApplication(provider, application, first!, previous!); + } + catch + { + await provider.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + public async ValueTask DisposeAsync() + { + try + { + await Application.StopAsync().ConfigureAwait(false); + } + finally + { + await _provider.DisposeAsync().ConfigureAwait(false); + } + } +} diff --git a/benchmarks/FluxFlow.Engine.Benchmarks/FluxFlow.Engine.Benchmarks.csproj b/benchmarks/FluxFlow.Engine.Benchmarks/FluxFlow.Engine.Benchmarks.csproj new file mode 100644 index 00000000..73ef6a6a --- /dev/null +++ b/benchmarks/FluxFlow.Engine.Benchmarks/FluxFlow.Engine.Benchmarks.csproj @@ -0,0 +1,20 @@ + + + + Exe + net10.0 + false + + + + + + + + + + + + + + diff --git a/benchmarks/FluxFlow.Engine.Benchmarks/Program.cs b/benchmarks/FluxFlow.Engine.Benchmarks/Program.cs new file mode 100644 index 00000000..87c286f8 --- /dev/null +++ b/benchmarks/FluxFlow.Engine.Benchmarks/Program.cs @@ -0,0 +1,5 @@ +using BenchmarkDotNet.Running; + +BenchmarkSwitcher + .FromAssembly(typeof(Program).Assembly) + .Run(args); diff --git a/docs/01-getting-started.md b/docs/01-getting-started.md index 3840fdaf..f2854044 100644 --- a/docs/01-getting-started.md +++ b/docs/01-getting-started.md @@ -44,10 +44,32 @@ Workflow and component objects are keyed by exact names. Component settings, resource references, and input/output links are flat. A string is one link, an array is several links, and an object adds a condition. +Compiled C# is an independent first-class source. Complete component/resource +contracts carry their executable behavior into the built definition, and typed +handles remove port/address strings from normal application code: + +```csharp +var builder = new ApplicationDefinitionBuilder() + .AddWorkflow("Main", out var main); + +main + .AddComponent("First", SampleComponents.Uppercase, out var first) + .AddComponent("Second", SampleComponents.Uppercase, out var second); + +first.Output.ConnectTo(second.Input); +var definition = builder.Build(); + +services.AddFluxFlow(definition); +``` + +Do not repeat the contracts through service registration. See +[End-To-End Code-First Simplification](41-end-to-end-code-first-simplification.md). + ## Register And Host -There is no assembly scanning. Register the application and each component -family explicitly in one service collection: +There is no assembly scanning. A JSON/configuration host registers the +application and each component/resource family explicitly in one service +collection: ```csharp using FluxFlow.Engine; @@ -84,6 +106,15 @@ var output = await application.Ports.ReceiveAsync( TimeSpan.FromSeconds(10)); ``` +For the compiled-C# definition above, keep the handles instead: + +```csharp +var output = application.Ports.ReceiveAsync(second.Output); +var sent = await application.Ports.SendAsync( + first.Input, + FlowMessage.Create("hello")); +``` + Each component family contributes immutable `ComponentDescriptor` instances. DI builds one `ComponentCatalog`, which validation, link compilation, Designer metadata, and Engine activation share. Composition adapters register diff --git a/docs/02-definitions-and-links.md b/docs/02-definitions-and-links.md index 2aa86194..bb49a5de 100644 --- a/docs/02-definitions-and-links.md +++ b/docs/02-definitions-and-links.md @@ -84,9 +84,12 @@ hold child resources; instances hold `Type` and flat properties. ## C# Authoring `FluxFlow.Composition.Authoring.ApplicationDefinitionBuilder` is the canonical -code-first authoring surface. It builds the same immutable model as JSON while -preserving the document's application, resource-group, resource, workflow, and -component structure: +code-first authoring surface. It preserves the application's resource, +workflow, and component structure while retaining typed links and delegates +directly in memory. It does not serialize or project through JSON. The JSON and +C# sources converge later at normalization, validation, compilation, and the +runtime. See [Typed Code-First Application Authoring](39-typed-code-first-authoring.md) +for the complete contract and condition model. ```csharp using FluxFlow.Components.Mqtt.Client; @@ -120,23 +123,27 @@ var receive = orders.AddMqttReceive("Receive", options => options.Client = client; options.AddSubscription(commands); }); -var handle = orders.AddComponent("Handle", "orders.handle"); +var handle = orders.AddComponent("Handle", OrderComponents.Handle); var publish = orders.AddMqttPublish("Publish", options => { options.Client = client; options.MaximumPendingRequests = 64; }); -orders.Connect( - receive.Output, - handle.Input("Input")); -orders.Connect( - handle.Output("Output"), - publish.Input); +receive.Output.ConnectTo(handle.Input); +handle.Output.ConnectTo(publish.Input); ApplicationDefinition definition = application.Build(); ``` +The MQTT resource calls above capture exact executable application resource +contracts as runtime-only definition state. A compiled-C# host can therefore +run this definition with `services.AddFluxFlow(definition)` plus ordinary host +dependencies such as the transport factory; it does not repeat `.AddMqtt()`. +If the same portable `Resources`/`Workflows` document is loaded from JSON, the +host explicitly registers `.AddMqtt()` because JSON contains no registrar or +CLR delegate. + The same declarations can use fluent capture when several siblings belong to one scope. Every fluent `Add*` overload appends its `out` handle last and returns the exact parent builder instance: @@ -174,7 +181,7 @@ messaging out var client); orders - .AddComponent("Handle", "orders.handle", out var handle) + .AddComponent("Handle", OrderComponents.Handle, out var handle) .AddMqttPublish( "Publish", options => @@ -183,9 +190,7 @@ orders options.MaximumPendingRequests = 64; }, out var publish) - .Connect( - handle.Output("Output"), - publish.Input); + .Connect(handle.Output, publish.Input); ApplicationDefinition fluentDefinition = application.Build(); ``` @@ -198,24 +203,26 @@ Declaration order never creates topology, selects a default port, or crosses a resource/workflow boundary. `workflow.Connect(...)` remains workflow-local; use `application.Connect(...)` only for an intentional cross-workflow link. -Official composition packages expose one flat -`Add{Component}(name, Action<{Component}Builder>)` callback per component. -Each component keeps its own strongly typed settings builder because component -behavior is not uniform. Typed resource and port handles provide references -without manually copying address strings. The lower-level `AddResource`, -`AddComponent`, `Set`, and `UseResource` APIs remain the explicit escape hatch -for application-owned component types. +Official composition packages expose explicit contracts from a +`Components` class and retain the familiar flat +`Add{Component}(name, Action<{Component}Builder>)` methods. Both forms delegate +to the same component-add core. Each component keeps its own strongly typed +settings builder because component behavior is not uniform. Typed resource and +port handles provide named references—including `Events`—without copying type, +port, or address strings. The lower-level string `AddComponent`, `Set`, and +`UseResource` APIs remain the dynamic escape hatch. The authoring boundary has these rules: - callbacks are one level deep; adding a resource or component commits it atomically after the callback succeeds -- component settings remain direct JSON properties; the API adds no hidden - `Options`, `Configuration`, `Resources`, or `Links` wrapper +- component settings remain immutable definition properties; code-first links + are first-class in-memory graph entries rather than hidden JSON properties - use `Set` for JSON configuration values and `UseResource` for handles; passing a handle to `Set` is rejected -- workflow `Connect` creates local links only; use `application.Connect` for an - intentional cross-workflow link +- direct `ConnectTo` returns the source handle and accepts local or same-owner + cross-workflow endpoints; workflow `Connect` stays local, while + `application.Connect` is the explicit application-level form - typed connections require the same message type, while signal inputs remain explicit typed control endpoints - calling `Build()` returns `ApplicationDefinition` and freezes the complete @@ -223,13 +230,11 @@ The authoring boundary has these rules: - handles are definition references, not resolved runtime services, and do not change resource ownership or lifecycle -The resulting definition uses the existing JSON serializer, configuration -loader, link compiler, validation, and runtime. The builder is an authoring -front end, not a second executable model: - -```csharp -var canonicalJson = ApplicationDefinitionJson.Serialize(application.Build()); -``` +The built definition is executed directly in memory. It shares catalog +validation, link compilation, revision planning, and runtime routing with the +portable JSON path, but C# startup never needs JSON serialization or parsing. +The UI/designer continues to create JSON; exporting a compiled builder result is +outside this API. ## JSON And Configuration @@ -279,6 +284,14 @@ case-sensitive address value. | System events | reserved absolute address | `System.Events.Output` | | System diagnostics | reserved absolute address | `System.Diagnostics.Output` | +Component event outputs are ordinary registered workflow ports, not system +addresses. A component package declares one explicitly with +`HasEvents("Events", selector)` or another chosen name, producing an address +such as `Orders.Review.Events` or `Orders.Review.Diagnostics`. Components with +no `HasEvents` declaration have no event output. The separate +`System.Events.Output` address remains reserved for application-level system +events. + Local references require a workflow context: ```csharp diff --git a/docs/03-node-authoring.md b/docs/03-node-authoring.md index c876e5d2..c16223db 100644 --- a/docs/03-node-authoring.md +++ b/docs/03-node-authoring.md @@ -178,27 +178,43 @@ Fatal startup or teardown failures should fault the node or source so ## Optional Component Registration Composition support belongs in an optional adapter package or host registration -extension. Register runtime-only components through the flat Composition -builder: +extension. For normal compiled-C# authoring, expose one complete contract: ```csharp -public static FluxFlowRegistrationBuilder AddSample( - this FluxFlowRegistrationBuilder builder) - => builder.AddRuntimeComponent("sample.uppercase", component => - { - component.UseFactory(context => +public static ComponentContract Uppercase { get; } = + ComponentContract.Create( + "sample.uppercase", + component => { - var node = new UppercaseNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events, - completion: node.Completion)); - }); - component.AddInput("Input"); - component.AddOutput("Output"); - }); + component + .UseFactory(static _ => new UppercaseNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); + }, + static component => new UppercaseHandle(component)); +``` + +Each typed call is authoritative: it creates descriptor metadata during +registration and selects the concrete Dataflow block after node activation. +The `Has...` prefix is intentional: the selected node member already exists; +the call describes the component contract and maps its external port name to +that existing member rather than creating another Dataflow port. +Factories and selectors are not executed during registration. `HasEvents` +selects an `ISourceBlock` and exposes the bridged public +`FlowMessage` output under the chosen name. There is no +implicit or globally reserved `Events` port. + +Signal targets use the same single-declaration model and retain signal +semantics without pretending to carry a message payload: + +```csharp +component + .UseFactory(CreateTriggerNode) + .HasSignalInput("Ack", static node => node.Ack) + .HasSignalInput("Nak", static node => node.Nak) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); ``` Keep reflection scanning, assembly discovery, and host service orchestration out @@ -207,6 +223,11 @@ and presentation authoring in one package-owned `*ComponentDefinition` and register it with the designed `AddComponent(...)` path from the same family extension. Hosts and adapter packages own concrete resources and keyed DI. +JSON or low-level string definitions register the complete contract explicitly +with `AddComponent(Uppercase)`. Reserve +`AddFluxFlowComponents().Advanced.AddDynamicComponent(...)` for a dynamic +runtime-only descriptor that has no reusable typed contract. + ## Lifecycle Rules - Keep input and normal-data output buffers bounded with `FlowNodeOptions`. diff --git a/docs/04-package-authoring.md b/docs/04-package-authoring.md index 2f71825b..e6ea0589 100644 --- a/docs/04-package-authoring.md +++ b/docs/04-package-authoring.md @@ -28,9 +28,11 @@ review.Output.LinkTo(sink.Input, new DataflowLinkOptions { PropagateCompletion = ## Optional Composition Registration -If the package wants fluent/config composition support, expose a small -extension over `FluxFlowRegistrationBuilder`. A single flat component callback -authors both runtime and designer metadata: +If the package wants compiled-C# and configuration composition support, expose +one complete designed contract. A single flat callback authors its exact +runtime descriptor and Designer metadata. Keep family registration familiar: +an `AddOrders(FluxFlowRegistrationBuilder)` extension registers that exact +contract for JSON hosts. ```csharp public sealed record OrderReviewOptions @@ -38,52 +40,70 @@ public sealed record OrderReviewOptions public bool RequireManualApproval { get; init; } = true; } +public static ComponentContract Review { get; } = + DesignedComponentContract.Create( + "order.review", + component => + { + var defaults = new OrderReviewOptions(); + component.WithDisplay( + displayName: "Order Review", + category: "Orders", + summary: "Reviews an order using the host policy."); + component + .UseFactory(CreateOrderReview) + .HasInput("Input", static node => node.Input, displayName: "Input", isPrimary: true) + .HasOutput("Output", static node => node.Output, displayName: "Output", isPrimary: true) + .HasEvents("Diagnostics", static node => node.Events, displayName: "Diagnostics"); + component.AddOption( + "RequireManualApproval", + kind: OptionValueKind.Boolean, + defaultValue: defaults.RequireManualApproval); + }, + static component => new OrderReviewHandle(component)); + public static FluxFlowRegistrationBuilder AddOrders( this FluxFlowRegistrationBuilder builder) - => builder.AddComponent("order.review", component => - { - var defaults = new OrderReviewOptions(); - component.UseFactory(CreateOrderReview); - component.WithDisplay( - displayName: "Order Review", - category: "Orders", - summary: "Reviews an order using the host policy."); - component.AddInput("Input", displayName: "Input", isPrimary: true); - component.AddOutput("Output", displayName: "Output", isPrimary: true); - component.AddOption( - "RequireManualApproval", - kind: OptionValueKind.Boolean, - defaultValue: defaults.RequireManualApproval); - }); - -private static ValueTask CreateOrderReview( + => builder.AddDesignedComponent(Review); + +private static OrderReviewNode CreateOrderReview( ComponentActivationContext context) { var options = context.BindConfiguration(); var policy = context.Services.GetRequiredService(); - var node = new OrderReviewNode(policy, options); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); + return new OrderReviewNode(policy, options); } ``` -Normal component packages do not need engine registration. Keep the default -composition path explicit and reflection-free. `ComponentCatalog` is built once -from all registered descriptors after the service collection is complete; -packages do not own or mutate a separate registry. - -`AddComponent(string, Action)` is the universal -designed-component shape. Runtime-only components use the parallel -`AddRuntimeComponent(string, Action)` -shape. Each callback is flat, executes immediately once, and produces immutable -catalog snapshots. Component families still own separate immutable options -records such as `OrderReviewOptions`; workflow-instance values bind from the -canonical `ApplicationDefinition`/JSON and do not move into DI. Do not add a -universal options type or nested descriptor, metadata, port, option, or resource -callbacks. +The selected node type drives message-type inference. The one public port call +produces immutable descriptor metadata and the runtime binding; no reflection, +scanning, attributes, or property-name convention is involved. Event sources +remain `FlowEvent` streams internally and are bridged to the public +`ComponentEvent` output named by `HasEvents`. Omitting `HasEvents` means the +component has no event output, and a normal output may use the name `Events`. + +For the uncommon case where a package must construct the complete runtime +instance itself, use `UseInstanceFactory(...)` and its metadata-only fluent +builder. Prefer the typed path for normal components. When only extra +completion or cleanup ownership is needed, return +`ComponentNodeActivation` from `UseFactory(...)`; Engine then owns node +and additional cleanup exactly once, including activation-failure cleanup. + +Normal component packages do not depend on Engine. Keep the default composition +path explicit and reflection-free. A code-first definition carries the exact +descriptors introduced by its contracts. JSON hosts build their catalog from +explicit contract/family registrations; packages do not own or mutate a +separate registry. + +`DesignedComponentContract.Create(...)` is the normal designed-component shape. +The low-level `AddComponent(string, Action)` and +`Advanced.AddDynamicComponent(string, Action)` +callbacks remain for dynamic extensions. Each callback is flat, executes once, +and produces immutable catalog facts. Component families still own separate +immutable options records such as `OrderReviewOptions`; workflow-instance +values bind from the canonical `ApplicationDefinition`/JSON and do not move +into DI. Do not add a universal options type or nested descriptor, metadata, +port, option, or resource callbacks. If the package also owns concrete resources, keep those registrations in an adapter-local `IApplicationResourceRegistrar`. `FluxFlow.Engine` resolves those diff --git a/docs/05-hosting-and-observability.md b/docs/05-hosting-and-observability.md index e97a8aec..f88e697a 100644 --- a/docs/05-hosting-and-observability.md +++ b/docs/05-hosting-and-observability.md @@ -28,6 +28,13 @@ Configuration may be the canonical root or a named section. A direct replaceable through standard DI; no source registry or assembly scanning is used. +A direct definition built from complete code-first component and application +resource contracts carries those exact executable contracts into candidate +activation. `AddFluxFlow(definition)` is the complete FluxFlow registration for +that graph; only ordinary host dependencies remain in DI. A JSON/configuration +source carries no executable C# and therefore keeps explicit package-family +registration. + ```csharp services.AddFluxFlow( configuration, @@ -127,6 +134,40 @@ Observer or listener failure is isolated from workflow processing. `FlowError` remains normal workflow data. It can be mapped, filtered, routed, retried, logged, or returned; operational diagnostics do not replace it. +## Optional Application Readiness + +Add `FluxFlow.Engine.HealthChecks` only when the host wants a standard .NET +readiness result for the canonical application: + +```csharp +using FluxFlow.Engine.HealthChecks; + +services.AddFluxFlow(definition); +services.AddHealthChecks() + .AddFluxFlowApplication(); +``` + +This registers one idempotent check named `fluxflow.application` with the exact +tags `fluxflow` and `ready`. It reads the existing `FluxFlowApplication` +singleton when the health service executes: + +- `Healthy` means a usable revision is active. +- `Degraded` means the latest update was rejected while the previous active + revision remains usable. +- `Unhealthy` means FluxFlow is missing, no revision is active, or the + application is stopping or stopped. + +The result includes at most lifecycle state, active revision ID and sequence, +requested revision ID, update status, and the final diagnostic stage and code. +It excludes payloads, definitions, addresses, diagnostic text/details, +exceptions, paths, connections, and secrets. The adapter performs no polling, +I/O, resource probing, reflection, or background work. ASP.NET Core endpoint +wiring remains host-owned, for example `app.MapHealthChecks("/health/ready")`. + +Readiness does not claim process liveness, durable-backlog health, or external +dependency availability. Keep those as separate host policies. See +[Application Health Readiness](42-application-health-readiness.md). + ## Optional Durability Instrumentation The provider-neutral durable-input and durable-output packages publish diff --git a/docs/09-json-conversion.md b/docs/09-json-conversion.md index a7b408f1..55f7d591 100644 --- a/docs/09-json-conversion.md +++ b/docs/09-json-conversion.md @@ -51,6 +51,15 @@ and preserves array order. `JsonElement` copies. Composition does not infer CLR option types or insert mappers at this boundary. +A definition built with complete C# `ComponentContract` values may also own +executable runtime descriptors in memory. Those descriptors, factories, +selectors, handles, and delegates are deliberately omitted by the canonical +writer. Deserializing that portable projection produces a normal JSON +definition with no definition-owned descriptors, so its host must register the +required component contracts or families explicitly. This separation keeps +JSON suitable for configuration, persistence, hot reload, and Designer output +without restricting compiled C# authoring to serializable behavior. + ## Configuration Loading Engine's `ConfigurationApplicationDefinitionSource` reads either an diff --git a/docs/10-expression-mapping.md b/docs/10-expression-mapping.md index 2f2854b9..75017293 100644 --- a/docs/10-expression-mapping.md +++ b/docs/10-expression-mapping.md @@ -73,6 +73,23 @@ expressions or insert conversions. A condition can inspect `isError`, `error.code`, headers, or the mapped value without requiring a parallel error stream. +Compiled code-first applications may instead attach a synchronous typed C# +predicate directly to a typed output: + +```csharp +review.Output.ConnectTo(priority.Input, when: static order => order.Priority); +``` + +This predicate is not an expression string and does not use +`IFlowExpressionEngine`. It is owned by the built definition/revision, may use a +normal C# closure, and is invoked only for successful value messages. Error +messages do not invoke a typed payload predicate and do not traverse that +conditional route; unconditional links continue to propagate them. A thrown +predicate exception rejects only that route and is reported as a link-condition +failure, leaving other fan-out routes and later messages active. Keep predicates +fast, thread-safe, synchronous, and side-effect-light. See +[Typed Code-First Application Authoring](39-typed-code-first-authoring.md). + ## Custom Context Implement `IMappingContextFactory` to add immutable per-message variables: diff --git a/docs/14-public-api-overview.md b/docs/14-public-api-overview.md index b528cceb..d6f6b3d4 100644 --- a/docs/14-public-api-overview.md +++ b/docs/14-public-api-overview.md @@ -52,23 +52,40 @@ their own protocol classification and lifecycle ownership. Owns the canonical application model (`Resources` and `Workflows`), component definitions, addresses, validation, exact canonical registration, flat C# -authoring builders, typed definition handles, link +authoring builders, typed component contracts and handles, first-class +in-memory links, link compilation, processing profiles, code-first runtime ownership, and component event fan-in. Links may be declared at either endpoint and compile into one canonical model. Signal feedback is explicit; ordinary data cycles remain -invalid. Official composition packages add component-specific flat builders on -top of the same generic `ApplicationDefinitionBuilder`; they do not introduce a -second model or own host resource lifecycles. +invalid. Official composition packages expose `Components` contracts +and component-specific flat builders on top of the same generic +`ApplicationDefinitionBuilder`; both delegate to one add core and do not own +host resource lifecycles. +`ComponentContract` and `ComponentContract` combine +the runtime descriptor, typed handle, and optional authoring options in one +explicit declaration. `ApplicationDefinitionBuilder.Build()` retains the exact +descriptors used by compiled C# components, so `AddFluxFlow(definition)` can +activate them without duplicate service registration. JSON definitions keep +their independent explicit host-registration boundary. +`ApplicationResourceContract` and +`ApplicationResourceContract` apply the same rule to +resources: one portable type/options projection, typed handle, and explicit +registrar. The built definition retains exact code-first contracts in the +runtime-only `ApplicationResourceContracts` collection; JSON omits them. Component-family builders expose package-owned `BoundedCapacity` or domain-specific capacity names and persist those values in the canonical definition; an omitted value keeps the package default. The application, resource-group, and workflow builders support both handle-returning declarations and chain-first declarations with a final `out var` handle. Chain-first overloads return the same parent instance, and -`Connect(...)` returns its application or workflow builder for explicit link -chaining. Insertion order never implies a connection, default port, or payload -conversion; both authoring styles build the same immutable -`ApplicationDefinition`. +`Connect(...)` returns its application or workflow builder. `ConnectTo` returns +the same output handle for typed fan-out. Insertion order never implies a +connection, default port, or payload conversion; both workflow-capture styles +build the same directly executable immutable `ApplicationDefinition`. +Synchronous typed predicates are definition-owned and require no expression +engine; portable expression strings retain their existing engine path. +Compiled C# and portable JSON are independent authoring sources that converge +at validation and compilation, not serialization. Designer remains JSON-only. `ApplicationLinkCompilationResult.Declarations` exposes resolved, immutable persistence facts, and `ApplicationLinkCompiler.SerializeDeclarations` writes the same canonical grammar. Resource registrars and canonical keyed DI @@ -81,10 +98,30 @@ Owns `FluxFlowApplication`, definition sources, hosted lifecycle, transactional revision activation, stable `ApplicationPorts`, system events, and diagnostics. A candidate revision is prepared in isolation and becomes active atomically; failed preparation leaves the prior revision running. +Each candidate uses one effective component catalog formed from host-registered +and definition-owned descriptors. Exact descriptor reuse is accepted; a +different descriptor for the same type fails before activation. Revision-owned +resources override ordinary host-service fallback during component activation, +and Engine never owns the fallback host provider. +Engine likewise forms one deterministic effective registrar set from host and +definition resource contracts. Exact registrar identity reuse is idempotent; +conflicts fail before the active revision changes. `ApplicationPorts` accepts +typed input/signal/output handles for send, receive, observe, and request/reply, +while preserving string and `ApplicationAddress` operations. `FluxFlowApplicationOptions.InputCapacity` and `OutputCapacity` configure only the stable application-port layer and do not override component definitions or standalone node options. +### FluxFlow.Engine.HealthChecks 1.x + +Adds the optional `IHealthChecksBuilder.AddFluxFlowApplication()` adapter. It +registers one idempotent standard check named `fluxflow.application` with the +fixed `fluxflow` and `ready` tags. The internal check translates existing +`FluxFlowApplication` state, active revision, and last-update status into +healthy, degraded, or unhealthy readiness with at most seven bounded metadata +fields. It adds no Engine reverse dependency, public options, background work, +I/O, endpoint, or external dependency probe. + ### FluxFlow.Engine.DurableInput 1.x Adds an optional provider-neutral inbox in front of Engine message inputs. @@ -106,6 +143,9 @@ pending, lease, terminal, and dead-letter counts at a caller-supplied time. `IDurableInputRetentionStore` separately performs explicit address-scoped, bounded deletion of old delivered tombstones or dead letters. Purging a delivered identity ends its deduplication window. +Code-first callers may enqueue through `InputPortHandle`; the overload +delegates to the same address-based store path and does not add a signal-input +shortcut. ### FluxFlow.Engine.DurableInput.SqlFile 1.x @@ -139,7 +179,9 @@ Adds optional provider-neutral capture of explicitly selected application outputs before Engine dispatches them to links or live host taps. A flat `AddFluxFlowDurableOutput(...)` builder binds canonical output addresses to stable contract names and explicit `JsonTypeInfo` metadata. The host supplies -one `IDurableOutputStore`. Hosts can independently enable a small serial hosted +one `IDurableOutputStore`. Code-first callers may pass +`OutputPortHandle` directly; it delegates to the same address registration +and has no input/signal shortcut. Hosts can independently enable a small serial hosted dispatcher through `AddFluxFlowDurableOutputDelivery(...)`, one `IDurableOutputDeliveryStore`, and one `IDurableOutputDeliveryHandler`. Leasing, exact renewal for long-running handlers, completion, fixed retry, and optional @@ -191,10 +233,14 @@ change, ORM, worker, or additional dependency. ### FluxFlow.Fluent 4.x -Builds typed code-first graphs over the same node and composition contracts. -Fluent observation receives normal value-or-error output messages rather than a -parallel universal error stream. The graph builder links already configured -node instances and does not apply a second graph-wide capacity setting. +Builds concise typed code-first graphs over the canonical Composition and Engine +contracts. Unique node instances become instance-backed component contracts; +typed `Then`, `Tap`, `Branch`, fan-in, and segment connections become canonical +definition links. `FlowGraph.Definition` exposes the immutable application and +`FlowGraph.Application` exposes the owned `FluxFlowApplication`. There is no +parallel Fluent runtime or direct manual Dataflow-link lifecycle. Fluent event +observation aggregates explicit node event streams; expected processing errors +remain normal value-or-error messages. ## Component Contracts @@ -315,10 +361,12 @@ settings into a universal options object: ```csharp components.AddComponent("orders.review", component => { - component.UseFactory(CreateOrderReview); component.WithDisplay("Order Review", "Orders"); - component.AddInput("Input"); - component.AddOutput("Output"); + component + .UseFactory(CreateOrderReview) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); }); services.AddFluxFlowFileSystemStorage("items-store", storage => @@ -394,6 +442,7 @@ The manifest is authoritative for shipped package identities and project-owned v | `FluxFlow.Components.RequestReply` | `2.0.0` | runtime or support package | | `FluxFlow.Components.Http.AspNetCore` | `2.0.0` | runtime or support package | | `FluxFlow.Engine` | `7.0.0` | unified hosted application lifecycle, revisions, stable ports, and diagnostics | +| `FluxFlow.Engine.HealthChecks` | `1.0.0` | optional standard .NET readiness check over existing Engine application state | | `FluxFlow.Components.Mqtt` | `7.0.0` | runtime or support package | | `FluxFlow.Components.Mqtt.Composition` | `6.0.0` | `AddMqtt`; `MqttComponentDefinition`; revision-owned MQTT controllers over host resources | | `FluxFlow.Components.Mqtt.MqttNet` | `3.0.0` | runtime or support package | @@ -435,8 +484,8 @@ The manifest is authoritative for shipped package identities and project-owned v | `FluxFlow.Components.Storage.Composition` | `6.0.0` | `AddStorage`; `StorageComponentDefinition` | | `FluxFlow.Components.Storage.FileSystem` | `5.0.0` | flat `AddFluxFlowFileSystemStorage` keyed factory registration | | `FluxFlow.Components.Storage.SqlFile` | `5.0.0` | flat `AddFluxFlowSqlFileStorage` keyed factory registration | -| `FluxFlow.Fluent` | `4.0.0` | code-first graphs over `ApplicationRuntime` and component instances | -| `FluxFlow.Fluent.Hosting` | `4.0.0` | hosted Fluent integration for `ApplicationRuntime` | +| `FluxFlow.Fluent` | `4.0.0` | instance-first facade producing canonical `ApplicationDefinition` graphs hosted by `FluxFlowApplication` | +| `FluxFlow.Fluent.Hosting` | `4.0.0` | Generic Host lifecycle integration for canonical-backed `FlowGraph` instances | | `FluxFlow.Engine.DurableInput` | `1.1.0` | optional provider-neutral leased at-least-once input delivery with Engine-accepted or explicit workflow-completed acknowledgement | | `FluxFlow.Engine.DurableInput.SqlFile` | `1.1.0` | SQLite single-file durable-input store with exact lease renewal for local hosts | | `FluxFlow.Engine.DurableInput.TSql` | `1.0.0` | networked T-SQL durable-input store with shared leases, exact renewal, dead-letter inspection, and replay | diff --git a/docs/15-engine-compatibility.md b/docs/15-engine-compatibility.md index e13cc1f6..128d11a7 100644 --- a/docs/15-engine-compatibility.md +++ b/docs/15-engine-compatibility.md @@ -82,4 +82,36 @@ registration through `.Composition`, and optional Designer metadata. They do not reference Engine. Hosts pin package families independently and run activation and port-contract tests after upgrades. +## Typed Component Authoring Break + +The component authoring surface intentionally replaces the old combination of +`UseFactory(ComponentFactory)` plus separate `AddInput`/`AddOutput` calls. +Normal registrations now return a typed builder from `UseFactory` and declare +each input, signal, output, and event once with a node selector. This is a +source- and binary-breaking authoring change, accepted through the public API +baseline process; it does not change canonical application JSON, component +addresses, normal-data delivery, or Engine's exact descriptor/instance +validation. + +The typed builder uses `HasInput`, `HasSignalInput`, `HasOutput`, and +`HasEvents`. These names are declarative: the node already owns the selected +Dataflow member, while the component declaration maps an external port name to +it. The short-lived typed `Add...` names were removed rather than retained as +aliases; this is another intentional authoring-only break with no runtime or +JSON behavior change. + +Event outputs are explicit through `HasEvents(name, selector)`. Engine no +longer injects or reserves `Events`; built-in packages explicitly retain that +name to preserve their established addresses. The low-level +`UseInstanceFactory` path remains for complete-instance ownership, and +`ComponentNodeActivation` carries optional completion or extra cleanup +without weakening revision disposal. + +The manifest's published binary baselines remain unchanged during this +unpublished source round. Consequently, the compatibility-aware packaging gate +continues to report the intentional break against those releases. Any future +publication of the affected packages must use an appropriate major version and +pass that gate; this round neither weakens the comparison nor republishes an +existing version. + Next: [Major Surface Reset](23-engine-2-to-3-migration.md) diff --git a/docs/22-canonical-vnext-migration.md b/docs/22-canonical-vnext-migration.md index 808d75df..2ae15f0e 100644 --- a/docs/22-canonical-vnext-migration.md +++ b/docs/22-canonical-vnext-migration.md @@ -5,6 +5,49 @@ value/result model and adopts typed `FlowMessage` value-or-error contracts. It follows the earlier canonical application migration; the flat `Resources` and `Workflows` document shape is unchanged. +## Migrate string-heavy C# definitions + +Code that manually constructed `ApplicationDefinition`, repeated component type +IDs, or wrote links as strings can move to the typed code-first builder: + +```csharp +var application = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var main); + +main + .AddComponent("source", OrderComponents.Source, out var source) + .AddComponent("sink", OrderComponents.Sink, out var sink); + +source.Output.ConnectTo(sink.Input); +var definition = application.Build(); +``` + +Define one complete `ComponentContract` for each application-owned component. +It replaces the removed authoring-only `ComponentAuthoringContract` and owns +both the runtime factory/bindings and typed authoring handle. Official packages +expose complete contracts from `Components` and retain their `AddX` +methods over the same descriptor. Custom typed handles should expose named +`Input`, `Output`, `Events`, signal, and branch ports using the owning +component's constants. + +When those contracts are added through `ApplicationDefinitionBuilder`, remove +the corresponding duplicate dynamic registrations from the host: + +```csharp +var definition = application.Build(); +services.AddFluxFlow(definition); +``` + +Keep explicit family or `AddComponent(contract)` registration for JSON and +low-level string definitions. Their portable document intentionally contains no +factories or delegates. + +Do not replace a manual C# definition with a C#-to-JSON round trip. The compiled +C# and portable JSON paths are independent and converge at validation and link +compilation. Use JSON for configuration/hot reload and Designer output; use the +C# builder when delegates, closures, and compile-time port checking are desired. +See [Typed Code-First Application Authoring](39-typed-code-first-authoring.md). + ## What Changed Removed from the maintained public model: diff --git a/docs/23-engine-2-to-3-migration.md b/docs/23-engine-2-to-3-migration.md index 3c39a87f..70839de2 100644 --- a/docs/23-engine-2-to-3-migration.md +++ b/docs/23-engine-2-to-3-migration.md @@ -176,13 +176,19 @@ callback creates the exact runtime/design pair and validates it immediately: ```csharp services.AddFluxFlowComponents().AddComponent("orders.review", component => { - component.UseFactory(CreateOrderReviewAsync); component.WithDisplay(displayName: "Order Review", category: "Orders"); - component.AddInput("Input", displayName: "Input"); - component.AddOutput("Output", displayName: "Output"); + component + .UseFactory(CreateOrderReview) + .HasInput("Input", static node => node.Input, displayName: "Input") + .HasOutput("Output", static node => node.Output, displayName: "Output") + .HasEvents("Events", static node => node.Events, displayName: "Events"); }); ``` +Use the declarative `HasInput`, `HasSignalInput`, `HasOutput`, and `HasEvents` +names. The selected node members already exist; these calls expose them through +the component contract. Port-level typed `Add...` aliases are not retained. + There is no public declaration registration, metadata factory, terminal catalog registration, range pairing, reflection scan, provider discovery, or metadata-only fallback. diff --git a/docs/24-reliable-in-process-delivery.md b/docs/24-reliable-in-process-delivery.md index a0ca5048..4957854a 100644 --- a/docs/24-reliable-in-process-delivery.md +++ b/docs/24-reliable-in-process-delivery.md @@ -27,6 +27,12 @@ message is accepted, caller cancellation does not retract it. Normal completion stops new acceptance, drains accepted messages, finishes in-flight delivery, and then propagates completion to links that requested it. +For an acyclic canonical application graph, Engine drains components in +deterministic topological stages: a stage's inputs drain only after upstream +outputs are empty, then its nodes complete and its outputs drain. This prevents +downstream inputs from closing before accepted upstream messages arrive. +Explicit signal-feedback cycles use the coordinated whole-runtime fallback. + Ordering is the output queue's acceptance order. Concurrent node processing can naturally change production order when its configured parallelism is greater than one. @@ -128,6 +134,16 @@ replay. These operations do not make in-process links durable. See [Durable Output Dead-Letter Operations](30-durable-output-dead-letter-operations.md) and [Durable Output Lease Renewal](37-durable-output-lease-renewal.md). +The package-consumer release gate also exercises this boundary across real +process restarts. One package-only process leaves SQL-file input and output +leases unsettled; a second process starts the normal host and recovers both +expired leases, executes the workflow, captures its output, and completes both +deliveries. The fixture's local destination uses the durable output key for an +atomic idempotent effect/receipt file, so the already-applied effect is not +repeated. This is composition evidence for the optional adapters, not durable +internal workflow state or an exactly-once guarantee. See +[Release Validation](38-release-validation.md). + Backend storage settings, Engine stable-port capacity, and component-owned input/output capacities remain separate configuration concerns. The canonical workflow JSON does not expose a delivery-mode switch: normal data is reliable, diff --git a/docs/25-durable-inputs.md b/docs/25-durable-inputs.md index b4df53b7..9aa5add9 100644 --- a/docs/25-durable-inputs.md +++ b/docs/25-durable-inputs.md @@ -79,6 +79,21 @@ payload registrations fail when the registry is resolved. The runtime options. A host may register its own `TimeProvider` before calling the method for deterministic timing. +For a compiled-C# application, retain the component handle and enqueue through +its typed input instead of reconstructing the address: + +```csharp +var durableInputs = provider.GetRequiredService(); +var accepted = await durableInputs.EnqueueAsync( + receiver.Input, + FlowMessage.Create(command)); +``` + +This overload delegates to the same canonical address/store path and preserves +the message identity, explicit durable contract, cancellation, and enqueue +status. The `ApplicationAddress` overload remains the correct boundary for +JSON/configuration and dynamically selected ports. + ## Optional Workflow-Completion Acknowledgement The default `EngineAccepted` mode preserves the original behavior and has no @@ -219,6 +234,22 @@ packages with their own storage, migration, and operational contracts. The SQL-file provider serves local single-machine hosts; the T-SQL provider serves shared multi-process hosts. +### Process-restart acceptance evidence + +The package-only release consumer includes a deterministic two-process proof. +Its seed process enqueues one SQL-file input, leases it at a fixed UTC time, +and exits without settlement. Its recovery process uses a later fixed UTC time, +starts the normal Generic Host and durable-input dispatcher, and requires the +expired record to pass through the configured workflow and finish as the only +delivered input. No wall-clock lease-expiry sleep or internal test hook is +used. + +That proof validates restart composition and persisted lease recovery. It does +not remove the at-least-once window described above: the dispatcher may repeat +the same `MessageId` after a crash, and the host remains responsible for +idempotent business effects. The gate is documented and invoked through +[Release Validation](38-release-validation.md). + ## Optional Dead-Letter Operations `IDurableInputDeadLetterStore` is an optional provider capability independent diff --git a/docs/27-durable-output-capture.md b/docs/27-durable-output-capture.md index 433e77b1..371f39c5 100644 --- a/docs/27-durable-output-capture.md +++ b/docs/27-durable-output-capture.md @@ -60,9 +60,21 @@ services.AddFluxFlowDurableOutput(outputs => }); ``` +When the definition is authored in C#, pass its typed output handle directly: + +```csharp +services.AddFluxFlowDurableOutput(outputs => + outputs.Capture( + complete.Output, + "orders.completed.v1", + ApplicationJsonContext.Default.OrderCompleted)); +``` + The address is the same canonical workflow-port address regardless of whether the application definition came from JSON or the C# authoring DSL. Durability -does not create a second application model. +does not create a second application model. The typed overload delegates to the +same address-based registration and preserves the exact contract name and +`JsonTypeInfo`. The builder is mutable only during registration. It freezes declarations into immutable runtime configuration. Repeating an equivalent declaration is diff --git a/docs/29-durable-output-delivery.md b/docs/29-durable-output-delivery.md index 88a94bc0..e84dfc10 100644 --- a/docs/29-durable-output-delivery.md +++ b/docs/29-durable-output-delivery.md @@ -128,6 +128,21 @@ completion commits, the envelope can be delivered again. Use possible. Dead-lettering bounds handler attempts for one failure cycle; it does not make destination delivery exactly once. +The package-only release consumer makes this crash window executable. Its seed +process leases one captured SQL-file output, applies a fixture-local destination +effect keyed by `DurableOutputEnvelope.Key`, and exits before completing the +lease. A separate recovery process starts the normal delivery dispatcher. The +handler sees the same idempotent effect/receipt content, does not repeat the +effect, returns successfully, and allows the expired lease to complete. The +same host also delivers the newly captured workflow output once. + +For this local proof, one atomically created effect file is also its receipt; +there is no second file transaction to hide. Real destinations must provide an +equivalent idempotent operation or transaction appropriate to that system. The +example does not make arbitrary destination side effects atomic with FluxFlow's +delivery-store completion and does not claim exactly-once delivery. See +[Release Validation](38-release-validation.md). + ## Provider Contract `IDurableOutputStore` owns capture. The separate diff --git a/docs/38-release-validation.md b/docs/38-release-validation.md index e4b568b1..cca754a3 100644 --- a/docs/38-release-validation.md +++ b/docs/38-release-validation.md @@ -11,6 +11,12 @@ manifest baseline and uses the binary-compatibility preflight as the only package-creation path. Provider, baseline restore, SDK compatibility, or pack failure therefore stops the release before archive inspection or publication. +Concurrency, backpressure, revision, shutdown, and lifetime correctness belong +to the normal deterministic test gate. Timing and allocation measurements do +not: run `benchmarks/FluxFlow.Engine.Benchmarks` manually on a controlled +machine and compare like-for-like reports. See +[Performance, Concurrency, And Lifetime Baseline](43-performance-concurrency-lifetime-baseline.md). + ## Local real-provider validation Run the durable-input suite from the repository root: @@ -89,22 +95,53 @@ references only. It restores with a work-directory-local package cache and a temporary package-source configuration that clears machine sources, lists the candidate directory first, and uses the public source only for external dependencies. After restore, the runner rejects project libraries, requires -the exact nine-package FluxFlow closure, and compares the SHA-256 value of every +the exact ten-package FluxFlow closure, and compares the SHA-256 value of every restored FluxFlow archive with the corresponding candidate archive. Source ordering alone is not accepted as proof. -The executable then deserializes and runs a canonical Engine application -through normal dependency injection, runs a typed Fluent graph, and proves real -SQL-file durable-input and durable-output persistence after provider disposal -and reopen. It must emit the exact Engine, Fluent, durability, and final success -markers. A missing marker, archive, candidate-byte match, or behavior fails the -rehearsal. +The executable first deserializes and runs a canonical Engine application with +an explicitly registered complete contract. It reapplies the same portable +definition and requires `Unchanged`, then applies an independently deserialized +unknown-type candidate and requires `Rejected`, exact active revision/definition +retention, and a fresh successful addressed request through the retained route. +It then builds and runs a typed code-first Engine application whose complete +custom contract needs only `AddFluxFlow(definition)`. That code-first path also +uses typed runtime ports and an embedded application resource contract whose +registrar executes without a second host registration. It then runs a +canonical-backed typed Fluent graph and proves real SQL-file durable-input and +durable-output persistence after provider disposal and reopen. The runner then +launches the already-built package-only executable +twice more over one shared restart directory: + +1. seed persists and leases one input and one output, applies one idempotent + destination effect, and exits without settling either lease; +2. recovery uses a deterministic later UTC time, starts the normal Generic + Host plus input/output dispatchers, recovers both expired leases, executes + the workflow, captures and delivers its output, and reaches exactly one + delivered input plus two completed outputs. + +The destination effect file is keyed from `DurableOutputEnvelope.Key` and is +also its receipt. Recovery therefore proves that the already-applied effect is +not repeated while the new workflow effect is applied once. This demonstrates +the host-owned idempotency responsibility of at-least-once delivery; it is not +an exactly-once or durable-workflow-state claim. + +The three process invocations must emit the exact Engine, code-first component, +embedded-resource, canonical Fluent, store-reopen, restart-seed, input-recovery, +workflow-capture, pending-output-resumption, idempotency, application-readiness, +restart, and final +runner markers. A missing marker, archive, +candidate-byte match, or behavior fails the rehearsal. All waits are bounded, +lease expiry is fixed-time rather than sleep-based, and the existing runner +ownership rules remove only runner-owned state. Normal CI runs the same gate with `-PackPackages` after the solution tests. That -mode packs the explicit nine-alias candidate closure from the already completed +mode packs the explicit ten-alias candidate closure from the already completed Release build into a runner-owned temporary source. It does not rebuild runtime projects, contact a network database, publish a package, or replace the -per-package assembly-load smoke. +per-package assembly-load smoke. The deterministic fake-process contract is +therefore fifteen invocations: ten packs, one restore, one build, the default +run, restart seed, and restart recovery. Preparation and dry-run commands do not create a tag, release, or publication. Remove the temporary source and consumer caches only after recording the exact diff --git a/docs/39-typed-code-first-authoring.md b/docs/39-typed-code-first-authoring.md new file mode 100644 index 00000000..3b01a7ef --- /dev/null +++ b/docs/39-typed-code-first-authoring.md @@ -0,0 +1,268 @@ +# Typed Code-First Application Authoring + +FluxFlow provides two independent, first-class ways to describe an application: + +- portable JSON for files, configuration providers, remote configuration, hot reload, and UI/designer output; +- compiled C# for developers who want typed component handles, ordinary delegates, closures, and compiler-checked connections. + +Both paths converge at link normalization, catalog validation, compilation, revision activation, and runtime routing. They do not converge through serialization. A code-first application builds and executes directly in memory; the C# builder has no JSON export or designer API. + +## Workflow scopes + +Use either of the two supported flat shapes: + +```csharp +var application = new ApplicationDefinitionBuilder(); +var main = application.AddWorkflow("main"); +var audit = application.AddWorkflow("audit"); +``` + +or fluent capture: + +```csharp +var application = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var main) + .AddWorkflow("audit", out var audit); +``` + +They are equivalent. There is intentionally no callback-style `AddWorkflow`: the workflow variables keep the graph flat and avoid nested callback trees. + +## Complete component contracts + +A `ComponentContract` is the single compiled-C# declaration of a component. It +owns the canonical type, runtime factory, typed port and event bindings, typed +handle factory, and—when needed—an options-builder factory and apply delegate. +It builds one immutable `ComponentDescriptor`; it does not activate a node or +discover members through reflection. + +```csharp +internal static class OrderComponents +{ + public static ComponentContract Source { get; } = + ComponentContract.Create( + OrderComponentTypes.Source, + runtime => + { + runtime + .UseFactory(static context => new OrderSourceNode( + context.BindConfiguration())) + .HasOutput(OrderComponentPorts.Output, static node => node.Output) + .HasEvents(OrderComponentPorts.Events, static node => node.Events); + }, + static () => new OrderSourceOptions(), + static (options, definition) => options.Apply(definition), + static component => new OrderSourceHandle(component)); +} + +internal sealed class OrderSourceHandle(ComponentHandle component) + : AuthoredComponentHandle(component) +{ + public OutputPortHandle Output { get; } = + component.Output(OrderComponentPorts.Output); + + public OutputPortHandle Events { get; } = + component.Output(OrderComponentPorts.Events); +} +``` + +The declaration is explicit: no reflection, scanning, generated code, global +registry, or convention lookup is involved. Component-specific option builders +retain their own validation and resource references. `UseFactory` executes only +during runtime activation; contract creation, application building, Designer +metadata collection, and JSON serialization do not create a node. + +All official Composition packages expose the same concept through a `Components` class. For example, `HttpComponents.HttpRequest`, `FileSystemComponents.FileRead`, `SerializationComponents.JsonParse`, and `MqttComponents.MqttPublish` can be passed to `AddComponent`. The familiar `AddHttpRequest`, `AddFileRead`, and other `AddX` methods remain and delegate to those same contracts. + +The raw `AddComponent(name, type, ...)`, `ComponentHandle.Input`, `Output`, and `SignalInput` APIs remain the dynamic escape hatch for plugin- or configuration-derived types. Normal code-first application code should prefer contracts and named handle properties. + +## A complete graph + +```csharp +var application = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var main) + .AddWorkflow("audit", out var audit); + +main + .AddComponent( + "source", + OrderComponents.Source, + options => options.Orders = LoadOrders(), + out var source) + .AddComponent("review", OrderComponents.Review, out var review) + .AddComponent("priority", OrderComponents.Sink, out var priority) + .AddComponent("standard", OrderComponents.Sink, out var standard); + +audit.AddComponent("events", OrderComponents.EventCollector, out var events); + +source.Output.ConnectTo(review.Input); +review.Output + .ConnectTo(priority.Input, when: static order => order.Priority) + .ConnectTo(standard.Input, when: static order => !order.Priority); + +review.Events.ConnectTo(events.Input); +priority.Events.ConnectTo(events.Input); +standard.Events.ConnectTo(events.Input); + +ApplicationDefinition definition = application.Build(); +services.AddFluxFlow(definition); +``` + +`Build()` freezes the builder and returns the directly hostable in-memory +definition. It also captures the exact descriptors introduced by complete +contracts. Therefore `services.AddFluxFlow(definition)` is sufficient for the +normal code-first path; do not repeat the same component through the advanced +dynamic-registration surface. + +Application dependencies remain ordinary DI registrations: + +```csharp +services.AddSingleton(orderStore); +services.AddFluxFlow(definition); +``` + +A contract factory can resolve `orderStore` from +`ComponentActivationContext.Services`. Revision-owned keyed resources take +precedence, while ordinary host services remain host-owned. + +Package-specific resource extensions use the same declaration-once rule. +`ApplicationResourceContract` and +`ApplicationResourceContract` own the portable resource type, +typed handle, explicit option projection, and one package registrar. A +code-first definition captures the exact contracts it used, without activating +resources during authoring: + +```csharp +var application = new ApplicationDefinitionBuilder() + .AddResourceGroup("Messaging", out var messaging) + .AddWorkflow("Orders", out var orders); + +messaging.AddMqttBroker("Broker", options => +{ + options.Host = "broker.internal"; + options.Port = 8883; +}, out var broker); + +messaging.AddMqttClient("Client", options => options.Broker = broker, out var client); +orders.AddMqttPublish("Publish", options => options.Client = client, out var publish); + +services.AddFluxFlow(application.Build()); +``` + +This compiled-C# path does not repeat `.AddMqtt()`. The equivalent JSON path +must register `.AddMqtt()` because JSON never contains executable registrars. +Externally owned resources remain explicit keyed DI, using typed handles when +available: `services.AddExternalFluxFlowResource(client, controller)`. + +For a JSON or low-level string definition, register complete contracts +explicitly because JSON contains no executable delegates: + +```csharp +services + .AddFluxFlow(jsonDefinition) + .AddComponent(OrderComponents.Source) + .AddComponent(OrderComponents.Sink); +``` + +`AddFluxFlowComponents().Advanced.AddDynamicComponent(type, configure)` remains +the explicit escape hatch for a dynamic descriptor that has no reusable +complete contract. + +## Runtime operations keep the handles + +Do not reconstruct addresses after building the graph. `ApplicationPorts` +accepts the same typed input, signal-input, and output handles: + +```csharp +var receive = applicationHost.Ports.ReceiveAsync(priority.Output); +var sent = await applicationHost.Ports.SendAsync( + review.Input, + FlowMessage.Create(order)); +var result = await receive; +``` + +Typed `ObserveAsync` and `SendAndReceiveAsync` overloads preserve exact payload +types. Durable input enqueue accepts `InputPortHandle` and durable output +capture accepts `OutputPortHandle`. Every typed overload delegates to the +existing canonical-address operation, retains timeout/cancellation/status +semantics, and keeps the complete `FlowMessage` envelope explicit. String +and `ApplicationAddress` overloads remain for JSON, operations, and dynamic +selection. + +## Connection scopes + +Use the scope that makes ownership clearest: + +```csharp +source.Output.ConnectTo(sink.Input); // concise; same owner, local or cross-workflow +main.Connect(source.Output, sink.Input); // workflow-local only +application.Connect(source.Output, sink.Input); // explicit application scope +``` + +Direct `ConnectTo` returns the same output handle, so fan-out remains readable. A workflow-scoped `Connect` rejects a target from another workflow. Direct `ConnectTo` and application-scoped `Connect` allow cross-workflow endpoints only when both handles belong to the same application builder. + +Input and output generic types must match. Signal inputs are explicit payload-independent targets. Addresses remain fully qualified and stable, and all three forms delegate to one validation and mutation operation. + +## Conditions + +An unconditional link needs no third argument. A portable expression can still be authored in C#: + +```csharp +review.Output.ConnectTo(priority.Input, condition: "input.Priority == true"); +``` + +Expression text is compiled by the configured `IFlowExpressionEngine`, exactly like the portable JSON path. + +For a compiled-only application, use a synchronous typed predicate: + +```csharp +var threshold = 100m; +review.Output.ConnectTo(priority.Input, when: order => order.Total >= threshold); +``` + +Typed predicates do not require an expression engine. They may be static or capture normal C# state. They run synchronously for each successful value message, so keep them fast, thread-safe, and free of surprising side effects. Async predicates, service resolution, retries, and policy execution are intentionally outside this API. + +An error `FlowMessage` never invokes a typed payload predicate and does not traverse that conditional route. Unconditional links continue to propagate error messages unchanged. Portable expression behavior remains unchanged and may inspect the existing expression context. + +If a predicate throws, only that route is rejected. FluxFlow reports the condition failure with source and target context; other fan-out routes and later messages continue running. + +## Revisions and lifetime + +The built definition owns its component descriptors, application resource +contracts, factories, predicates, registrars, and captured closures. There is +no process-global registry. Engine combines host registrations and +definition-owned contracts into one effective component catalog and one +effective registrar set for each candidate revision. Reusing the same exact +descriptor/registrar identity is stable and deduplicated; conflicting contracts +for one type fail before activation. + +A new descriptor identity used by a workflow marks that workflow updated. A +successful replacement retires the old graph and releases its factories and +predicates when the retired revision is no longer referenced. The update result +returned to its caller still reports `PreviousRevision`, while the application's +retained `LastUpdate` copy omits that retired snapshot. Failed planning or +activation leaves the previous revision active and usable. + +## JSON and the designer + +Portable JSON still has exactly the canonical `Resources` and `Workflows` +shape. `ApplicationDefinitionJson`, configuration sources, hot reload, and +Designer persistence continue to parse and emit that portable representation. +Definition-owned runtime descriptors and application resource contracts are +code-only and are never written to JSON. Deserializing a code-first definition's +portable projection therefore produces a JSON definition that again requires +explicit component and resource-family registration. + +The UI/designer authors JSON. It does not load, edit, or export compiled C# builder definitions. Conversely, a C# builder result is not a serialization format: do not round-trip it through `ApplicationDefinitionJson` as part of startup, validation, revision planning, or execution. + +Equivalent JSON and C# graphs should compile to equivalent runtime links, but code-only delegates and closures intentionally have no JSON representation. + +## Relation to FluxFlow.Fluent + +`ApplicationDefinitionBuilder` describes catalog-backed, hostable applications with resources, named workflows, stable addresses, revisions, configuration loading alternatives, and engine ports. + +`FluxFlow.Fluent` builds from already constructed node instances with +`Flow.From(...).Then(...).To(...)`. It remains a smaller instance-first +authoring API, but it now produces the same canonical `ApplicationDefinition` +and runs through an owned `FluxFlowApplication`. `FlowGraph.Definition` and +`FlowGraph.Application` expose those canonical objects; there is no parallel +Fluent runtime. diff --git a/docs/40-unified-component-contracts.md b/docs/40-unified-component-contracts.md new file mode 100644 index 00000000..2d1b6989 --- /dev/null +++ b/docs/40-unified-component-contracts.md @@ -0,0 +1,132 @@ +# Unified Component Contracts + +`ComponentContract` is the complete compiled-C# description of one FluxFlow +component. It removes the former split between a typed authoring declaration and +a separately registered runtime descriptor. + +## Declare once + +```csharp +public static ComponentContract Uppercase { get; } = + ComponentContract.Create( + "sample.uppercase", + component => + { + component + .UseFactory(static _ => new UppercaseNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); + }, + static component => new UppercaseHandle(component)); +``` + +The declaration creates and validates one immutable `ComponentDescriptor`. +`HasInput`, `HasOutput`, and `HasEvents` describe and bind existing node ports; +they do not create a second set of ports. The node factory is retained but is +not executed until Engine activates a workflow instance. + +An options-aware contract adds only the component-specific authoring boundary: + +```csharp +public static ComponentContract Source { get; } = + ComponentContract.Create( + "sample.source", + component => component + .UseFactory(static context => new SourceNode( + context.BindConfiguration())) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events), + static () => new SourceBuilder(), + static (options, definition) => options.Apply(definition), + static component => new SourceHandle(component)); +``` + +## Build and run directly + +```csharp +var application = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var workflow); + +workflow + .AddComponent("source", SampleComponents.Source, out var source) + .AddComponent("upper", SampleComponents.Uppercase, out var upper) + .AddComponent("sink", SampleComponents.Sink, out var sink); + +source.Output.ConnectTo(upper.Input); +upper.Output.ConnectTo(sink.Input); + +var definition = application.Build(); + +var services = new ServiceCollection(); +services.AddSingleton(resultCollector); +services.AddFluxFlow(definition); + +await using var provider = services.BuildServiceProvider(); +await provider.StartFluxFlowApplicationAsync(); +``` + +The definition owns the exact descriptors introduced by its contracts. Engine +merges them with host-registered descriptors once per candidate revision and +uses that effective catalog for validation, links, port surfaces, and +activation. Registering the same descriptor reference in both places is safe; +two different descriptors with the same type are rejected. + +Ordinary application dependencies remain ordinary DI services. During +activation, revision-owned keyed resources are resolved first and host services +are the explicit fallback. Engine disposes only its revision-owned provider; it +never takes ownership of the host provider. + +## JSON stays independent + +Canonical JSON still contains exactly `Resources` and `Workflows`. It never +contains factories, selectors, handles, delegates, or definition-owned +descriptors. A JSON host therefore registers its executable contracts +explicitly: + +```csharp +var definition = ApplicationDefinitionJson.Deserialize(json); + +services + .AddFluxFlow(definition) + .AddComponent(SampleComponents.Uppercase) + .AddComponent(SampleComponents.Sink); +``` + +Serializing a code-first definition produces only its portable projection. +Deserializing that projection returns a JSON definition and intentionally does +not recreate executable C# behavior. + +## Advanced dynamic registration + +Keep the low-level path when a reusable typed contract is not the source of the +component, such as a dynamic plugin or externally selected type: + +```csharp +services.AddFluxFlowComponents() + .Advanced + .AddDynamicComponent("dynamic.transform", component => + { + component + .UseFactory(CreateTransform) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output); + }); +``` + +Do not use this as a second registration for a contract already added to a +code-first definition. + +## Revisions and ownership + +Descriptor reference identity is the explicit identity of executable component +behavior. Reusing one contract is revision-stable. Replacing it with a new +descriptor marks affected workflows updated without inspecting or hashing +delegate bodies. A failed candidate leaves the current revision active. A +successful candidate retires and releases the old component generation and its +captured factory state. + +Official component packages expose their complete declarations through +`Components`. Their family registration extensions register those exact +descriptors for JSON hosts and collect Designer metadata from the same source +without activating factories. diff --git a/docs/41-end-to-end-code-first-simplification.md b/docs/41-end-to-end-code-first-simplification.md new file mode 100644 index 00000000..1dadbe7a --- /dev/null +++ b/docs/41-end-to-end-code-first-simplification.md @@ -0,0 +1,133 @@ +# End-To-End Code-First Simplification + +FluxFlow's compiled-C# path is one declaration-to-execution path. A component +contract declares the node and ports once, an application builder places it and +returns a typed handle, and that same handle is used for links, host interaction, +durability, and explicit resource binding. + +## The normal path + +```csharp +var builder = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var workflow); + +workflow + .AddComponent("first", SampleComponents.Uppercase, out var first) + .AddComponent("second", SampleComponents.Uppercase, out var second); + +first.Output.ConnectTo(second.Input); + +var definition = builder.Build(); + +var services = new ServiceCollection(); +services.AddFluxFlow(definition); + +await using var provider = services.BuildServiceProvider(); +var application = provider.GetRequiredService(); +await application.StartAsync(); + +var receive = application.Ports.ReceiveAsync(second.Output); +await application.Ports.SendAsync(first.Input, FlowMessage.Create("hello")); +var result = await receive; +``` + +There is no second component registration. `ComponentContract` owns the exact +runtime descriptor used by the definition, and Engine builds the candidate +catalog from that definition. + +## Resources follow the same rule + +Package resource extensions add `ApplicationResourceContract` values. A +contract contains one portable type, an explicit option projection, a typed +handle, and the exact registrar that executes that resource family. It does not +contain a live client, service provider, global registry, or serialized +delegate. + +Code-first MQTT therefore needs only its normal host dependencies and the +built definition: + +```csharp +messaging.AddMqttBroker("Broker", configureBroker, out var broker); +messaging.AddMqttClient("Client", options => options.Broker = broker, out var client); +orders.AddMqttPublish("Publish", options => options.Client = client, out var publish); + +services.AddSingleton(transportFactory); +services.AddFluxFlow(builder.Build()); +``` + +The package registrar is embedded as runtime-only definition state. Concrete +controllers created for a revision remain revision-owned; host-supplied +transports, secrets, clocks, and externally bound controllers remain host-owned. + +## C# and JSON stay independent + +| Source | Portable model | Executable contracts | Host registration | +|---|---|---|---| +| Compiled C# | `Resources` and `Workflows` | Exact component and resource contracts captured by the builder | Ordinary host dependencies only | +| JSON/configuration | `Resources` and `Workflows` | None | Explicit component/resource family registration | + +Canonical JSON never contains factories, registrars, handles, CLR types, +predicates, or node instances. Serializing a code-first definition produces +only its portable projection. Deserializing it creates the JSON path again and +therefore requires explicit family registration such as `.AddMqtt()`. + +## Typed handles at every boundary + +`ApplicationPorts` accepts typed handles for send, signal send, receive, +observe, and request/reply. `DurableApplicationInputs` accepts +`InputPortHandle`, and durable output capture accepts +`OutputPortHandle`. Typed keyed-resource helpers accept +`ResourceHandle`. Each overload validates null, then delegates to the +existing canonical address implementation; there is no second behavior and no +payload-only message shortcut. + +String and `ApplicationAddress` overloads remain important for JSON, +operational tools, remote control, and dynamically selected ports. + +## Fluent is a facade over the canonical engine + +`Flow.From(...).Then(...).Tap(...).Branch(...).To(...)` remains the concise +instance-first API. Internally, each unique node becomes one instance-backed +component contract and every connection becomes a canonical definition link. +Shared node identity preserves fan-in, and arbitrary branch outputs use one +explicit non-owning adapter instead of reflection. + +`FlowGraph.Definition` exposes the immutable definition and +`FlowGraph.Application` exposes its owned `FluxFlowApplication`. Start, staged +topological drain, stop, and disposal run through Engine; Fluent does not create +or expose a parallel runtime and does not manually own direct graph links. + +## Dynamic registration is visibly advanced + +Reusable code should publish `ComponentContract` values. Dynamic plugins and +externally selected runtime types retain one explicit escape hatch: + +```csharp +services.AddFluxFlowComponents() + .Advanced + .AddDynamicComponent("plugin.transform", component => + { + component + .UseFactory(CreateNode) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output); + }); +``` + +The advanced path is not an extra registration step after code-first +authoring. The former normal-surface raw-registration API is removed without an +obsolete forwarding alias. + +## Deliberate limits + +- no reflection, assembly scanning, global mutable registry, or package magic; +- no delegate, registrar, handle, or node-instance serialization; +- no hidden resource ownership inference; +- no new hot-reload claim for instance-backed Fluent graphs; +- no change to canonical addresses, JSON shape, durable schemas, or delivery + guarantees; +- no move of package/resource settings into `FluxFlowApplicationOptions`. + +The simplification removes duplicate declarations and parallel execution paths; +it does not remove JSON hosting, hot reload, dynamic plugins, durable delivery, +Designer metadata, or address-based operational APIs. diff --git a/docs/42-application-health-readiness.md b/docs/42-application-health-readiness.md new file mode 100644 index 00000000..57cf858c --- /dev/null +++ b/docs/42-application-health-readiness.md @@ -0,0 +1,120 @@ +# Application Health Readiness + +`FluxFlow.Engine.HealthChecks` is an optional, lightweight bridge from the +canonical `FluxFlowApplication` lifecycle to the standard .NET health-check +abstraction. It answers one question: can this host currently serve work +through an active FluxFlow application revision? + +The adapter is separate from `FluxFlow.Engine`. Applications that do not use +health checks take no dependency on it and pay no registration or runtime +cost. The Engine does not reference the adapter. + +## Registration + +Reference `FluxFlow.Engine.HealthChecks`, then add the application and readiness +check through normal dependency injection: + +```sh +dotnet add package FluxFlow.Engine.HealthChecks +``` + +```csharp +using FluxFlow.Engine; +using FluxFlow.Engine.HealthChecks; + +services.AddFluxFlow(definition); + +services.AddHealthChecks() + .AddFluxFlowApplication(); +``` + +`AddFluxFlowApplication()` returns the same `IHealthChecksBuilder`. Repeating +the call is idempotent and preserves unrelated health-check registrations. It +adds exactly one registration with: + +- name: `fluxflow.application` +- tags: `fluxflow`, `ready` +- configured failure status: `Unhealthy` + +Calling `AddFluxFlow(...)` alone does not register a health check. + +ASP.NET Core hosts may expose the standard result using host-owned endpoint +wiring: + +```csharp +using Microsoft.AspNetCore.Diagnostics.HealthChecks; + +app.MapHealthChecks( + "/health/ready", + new HealthCheckOptions + { + Predicate = static registration => registration.Tags.Contains("ready") + }); +``` + +The package itself has no ASP.NET Core dependency and does not create an +endpoint. The predicate is ordinary host policy; the fixed `ready` tag lets the +host keep readiness separate from liveness or dependency checks. + +## Status Contract + +| Standard status | FluxFlow condition | +|-----------------|--------------------| +| `Healthy` | `Running` or `Reloading`, an active revision exists, and the latest update was not rejected. | +| `Degraded` | `Running` or `Reloading`, an active revision exists, and the latest update was rejected. The previous revision remains ready. | +| `Unhealthy` | FluxFlow is not registered, no active revision exists, lifecycle state is not ready, or the application is stopping or stopped. | + +A rejected hot reload is deliberately `Degraded`, not `Unhealthy`, because +transactional activation preserves the previous usable revision. A rejected +initial start has no active revision and is therefore `Unhealthy`. A later +successful update returns the result to `Healthy`. + +The check fails closed if it cannot observe a stable, ready lifecycle snapshot. +Cancellation is propagated immediately with the caller's token. + +## Bounded Result Data + +The result may contain only these seven keys: + +- `applicationState` +- `activeRevisionId` +- `activeSequence` +- `requestedRevisionId` +- `lastUpdateStatus` +- `diagnosticStage` +- `diagnosticCode` + +Only applicable values are emitted. When FluxFlow is not registered, +`applicationState` is `Unavailable`. When diagnostics exist, only the final +diagnostic stage and stable error code are included. + +The result never includes workflow payloads, application definitions, component +or resource options, port addresses, diagnostic messages or details, exception +objects or text, connection strings, file paths, credentials, secrets, or +arbitrary tags. This keeps the health response bounded and safe to expose +through a host-selected readiness endpoint. + +## Runtime And Ownership Boundary + +Each probe performs a short, observational read of existing in-memory +`FluxFlowApplication` properties. It does not mutate lifecycle state, reload a +definition, activate a revision, resolve workflow resources, query durable +stores, contact dependencies, scan assemblies, or use reflection. + +The package adds no hosted service, worker, timer, polling loop, cache, logger, +database access, or dependency-health aggregation. Readiness evaluation occurs +only when the host invokes the standard health-check service. + +## Deliberate Non-Goals + +This check does not report: + +- process liveness; +- durable input or output backlog thresholds; +- database, broker, HTTP endpoint, or other external dependency health; +- workflow business outcomes or payload errors; +- deployment traffic policy beyond the application-readiness status above. + +Hosts may register separate standard checks for those concerns and select them +with their own endpoint predicates. Keeping them separate preserves FluxFlow's +lightweight in-process core and makes operational policy explicit. diff --git a/docs/43-performance-concurrency-lifetime-baseline.md b/docs/43-performance-concurrency-lifetime-baseline.md new file mode 100644 index 00000000..ae27be51 --- /dev/null +++ b/docs/43-performance-concurrency-lifetime-baseline.md @@ -0,0 +1,167 @@ +# Performance, Concurrency, And Lifetime Baseline + +FluxFlow keeps performance work evidence-driven. Runtime behavior is protected +by deterministic correctness tests, while timing and allocation measurements +live in a separate benchmark project. The benchmark results are not CI +pass/fail thresholds: absolute timings vary by machine, runtime, power policy, +and background load. + +This round changes no public API, package boundary, workflow definition, or +delivery guarantee. It adds a repeatable measurement surface, strengthens +concurrency and lifecycle proof, and applies only two small allocation fixes +that were visible in the measured message path. + +## Permanent benchmark suite + +`benchmarks/FluxFlow.Engine.Benchmarks` is a non-packable .NET 10 console +project. It uses the normal code-first component contract, application builder, +Engine lifecycle, typed runtime ports, and real node processing. Setup and host +lifecycle are outside the measured operation. + +| Benchmark | Comparison axis | Cases | +|-----------|-----------------|------:| +| `ApplicationMessagingBenchmarks` | addressed versus typed request/reply, plus a typed C# condition | 3 | +| `ApplicationTopologyBenchmarks` | one-hop versus eight-hop typed pipelines | 2 | +| `ApplicationLinkCompilationBenchmarks` | definition/revision preparation at 1, 32, and 128 links | 3 | + +The suite has eight cases in total. Message benchmarks return the real +`PortRequestResult` so the work cannot be removed by the JIT. Definitions, +hosts, and nodes are created in `GlobalSetup`; applications are stopped and +providers disposed in `GlobalCleanup`. There are no manual workload loops. + +## Running the suite + +Build once from the repository root: + +```powershell +dotnet build ./benchmarks/FluxFlow.Engine.Benchmarks/FluxFlow.Engine.Benchmarks.csproj -c Release +``` + +First validate every case with a dry run: + +```powershell +dotnet run --project ./benchmarks/FluxFlow.Engine.Benchmarks/FluxFlow.Engine.Benchmarks.csproj ` + -c Release --no-build -- ` + --filter "*" --job Dry --noOverwrite +``` + +Use ShortRun for a quick local comparison: + +```powershell +dotnet run --project ./benchmarks/FluxFlow.Engine.Benchmarks/FluxFlow.Engine.Benchmarks.csproj ` + -c Release --no-build -- ` + --filter "*" --job Short --noOverwrite +``` + +Use the default job for a result worth recording. Keep classes separate so a +single command stays bounded: + +```powershell +dotnet run --project ./benchmarks/FluxFlow.Engine.Benchmarks/FluxFlow.Engine.Benchmarks.csproj ` + -c Release --no-build -- ` + --filter "*ApplicationMessagingBenchmarks*" --noOverwrite + +dotnet run --project ./benchmarks/FluxFlow.Engine.Benchmarks/FluxFlow.Engine.Benchmarks.csproj ` + -c Release --no-build -- ` + --filter "*ApplicationTopologyBenchmarks*" --noOverwrite + +dotnet run --project ./benchmarks/FluxFlow.Engine.Benchmarks/FluxFlow.Engine.Benchmarks.csproj ` + -c Release --no-build -- ` + --filter "*ApplicationLinkCompilationBenchmarks*" --noOverwrite +``` + +The benchmark runner writes Markdown and CSV reports under +`BenchmarkDotNet.Artifacts`; that generated directory is ignored by Git. Use +`--artifacts ` when retaining several named runs for comparison. + +## Current local baseline + +Recorded on 2026-08-08 with benchmark runner 0.15.8, Windows 11, a 12th Gen Intel +Core i7-12700H, .NET SDK 10.0.302, and .NET runtime 10.0.10. These numbers +describe this machine only. + +### Runtime messaging + +| Case | Mean | Allocated | +|------|-----:|----------:| +| addressed unconditional request | 71.62 microseconds | 12.95 KB | +| typed unconditional request | 78.45 microseconds | 12.99 KB | +| typed conditional request | 75.55 microseconds | 13.49 KB | + +The timing distributions overlap and the typed/addressed allocation is +equivalent. Typed handles therefore do not show a meaningful runtime tax in +this baseline. A real C# condition adds about 0.5 KB for its condition context. + +### Pipeline scale + +| Hops | Mean | Allocated | +|-----:|-----:|----------:| +| 1 | 36.95 microseconds | 7.87 KB | +| 8 | 192.26 microseconds | 43.18 KB | + +### Link compilation scale + +| Links | Mean | Allocated | +|------:|-----:|----------:| +| 1 | 6.493 microseconds | 7.69 KB | +| 32 | 64.956 microseconds | 91.04 KB | +| 128 | 274.492 microseconds | 365.33 KB | + +Compilation is a definition/revision preparation cost, not a per-message cost. +The suite intentionally reports it separately from runtime throughput. + +## Measured internal improvements + +The pre-change ShortRun allocated 53.25 KB for the eight-hop request. The final +ShortRun allocates 43.29 KB, a reduction of approximately 18.7 percent. + +Two internal changes account for that result: + +1. Unconditional links no longer allocate a `FlowMapContext` and three-entry + dictionary. Conditional links still build the exact context required by + expression and typed-predicate semantics. +2. Runtime activity/request diagnostics no longer allocate `params` arrays and + LINQ iterators merely to construct their small two- or three-field attribute + dictionaries. + +Both changes preserve existing routing, condition failure isolation, +diagnostic content, and lifecycle behavior. No new cache, pool, reflection, +background worker, global state, or dependency was introduced. + +## Correctness under pressure + +Timing is never used as correctness evidence. Engine tests use causal gates and +exact counts to verify concurrent request batches, bounded backpressure and +cancellation, repeated compatible and rejected revisions, retained active +routes, shutdown with accepted work in flight, and exact disposal/retirement. +Bounded `WaitAsync` calls may guard against a deadlock, but elapsed time is not +asserted and there are no sleeps, polling loops, throughput thresholds, or +retry-until-green behavior. + +Normal CI continues to run the deterministic tests. Benchmark jobs remain +manual evidence and should be compared only on the same controlled machine. + +## Deliberate limits + +- This is an in-process runtime baseline, not a distributed-system or durable + store throughput claim. +- Results do not establish a universal service-level objective. +- No automatic regression percentage is enforced in CI. +- Optional runtime telemetry or exported performance counters remain a future, + separately designed adapter; they are not part of this round. +- The one manually reviewed synchronous system-event publication path keeps its + existing backpressure semantics. It was not changed without a demonstrated + defect and should remain part of future contention profiling. + +## Verification + +The completed round passed: + +- all eight benchmark cases in a final dry validation; +- 134/134 complete Engine tests; +- 189/189 complete Release governance tests; +- a warning-free CI-style Release build of 137 projects; +- 2,673/2,673 complete solution tests across 67 projects; +- the benchmark project's direct/transitive vulnerability audit; +- whole-worktree whitespace validation; and +- scoped format verification for every touched C# file. diff --git a/docs/README.md b/docs/README.md index e86e0553..661cbd49 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,20 +2,21 @@ FluxFlow is standalone-node-first. Use `FluxFlow.Nodes` for transport-neutral exact content, error contracts, and typed node authoring; add -`FluxFlow.Composition` for the canonical application document, addressing, and -static link compilation. Add `FluxFlow.Engine` when a .NET host should activate +`FluxFlow.Composition` for portable JSON or typed compiled-C# application +authoring, addressing, and link compilation. Add `FluxFlow.Engine` when a .NET host should activate revisions through DI, stable ports, and adapter-owned keyed resources. Convert retired workflows/nodes/links documents outside normal startup before loading them; the runtime accepts only the canonical document shape and names. ## Current Samples -- `samples/FluxFlow.CompositionSample`: canonical application hosting with an in-memory component graph. +- `samples/FluxFlow.CompositionSample`: typed code-first application contracts, handles, `ConnectTo`, and direct in-memory hosting. - `samples/FluxFlow.DurabilityOperationsSample`: one local durable cycle with host-owned BCL diagnostics and explicit persisted-status snapshots. -- `samples/FluxFlow.FluentSample`: the same pipeline built with the type-safe fluent DSL, plus a branching/fan-in example. +- `samples/FluxFlow.FluentSample`: the concise node-instance fluent facade over + the canonical definition and Engine, including branching and fan-in. - `samples/FluxFlow.MqttCompositionSample`: MQTT-shaped hosted composition with an in-memory logical client controller. - `samples/FluxFlow.HttpTriggerSample`: host-owned HTTP trigger wiring without the engine. -- `samples/FluxFlow.SampleApp`: advanced canonical host sample with workspace projection, conditional links, and Events fan-in. +- `samples/FluxFlow.SampleApp`: advanced typed application builder with C# predicates, cross-scope handles, and Events fan-in. - `samples/FluxFlow.ComponentPackageTemplate`: copyable standalone component package shape. - `samples/FluxFlow.DesignerHost`: headless Designer host-model layer projecting component design metadata into palette, inspector, and resource picker view @@ -63,6 +64,11 @@ loading them; the runtime accepts only the canonical document shape and names. 36. [Durable Terminal Retention](36-durable-terminal-retention.md) 37. [Durable Output Lease Renewal](37-durable-output-lease-renewal.md) 38. [Release Validation](38-release-validation.md) +39. [Typed Code-First Application Authoring](39-typed-code-first-authoring.md) +40. [Unified Component Contracts](40-unified-component-contracts.md) +41. [End-To-End Code-First Simplification](41-end-to-end-code-first-simplification.md) +42. [Application Health Readiness](42-application-health-readiness.md) +43. [Performance, Concurrency, And Lifetime Baseline](43-performance-concurrency-lifetime-baseline.md) Retired documents require an external, one-time conversion. Current runtime guidance uses only the canonical application and component model. diff --git a/eng/package-consumer-acceptance.ps1 b/eng/package-consumer-acceptance.ps1 index 4e708171..d32ea6ef 100644 --- a/eng/package-consumer-acceptance.ps1 +++ b/eng/package-consumer-acceptance.ps1 @@ -26,6 +26,7 @@ $requiredAliases = @( "mapping", "composition", "engine", + "engine-healthchecks", "fluent", "engine-durable-input", "engine-durable-input-sqlfile", @@ -34,16 +35,33 @@ $requiredAliases = @( ) $topLevelVersionProperties = [ordered]@{ "engine" = "FluxFlowEngineVersion" + "engine-healthchecks" = "FluxFlowEngineHealthChecksVersion" "fluent" = "FluxFlowFluentVersion" "engine-durable-input-sqlfile" = "FluxFlowDurableInputSqlFileVersion" "engine-durable-output-sqlfile" = "FluxFlowDurableOutputSqlFileVersion" } -$requiredMarkers = @( +$defaultRequiredMarkers = @( "PACKAGE_ACCEPTANCE_ENGINE_OK=True", + "PACKAGE_ACCEPTANCE_CODE_FIRST_OK=True", + "PACKAGE_ACCEPTANCE_RESOURCE_OK=True", + "PACKAGE_ACCEPTANCE_HEALTH_OK=True", "PACKAGE_ACCEPTANCE_FLUENT_OK=True", "PACKAGE_ACCEPTANCE_DURABILITY_OK=True", "PACKAGE_ACCEPTANCE_OK=True" ) +$restartSeedMarkers = @( + "PACKAGE_ACCEPTANCE_RESTART_SEED_INPUT=restart-input", + "PACKAGE_ACCEPTANCE_RESTART_SEED_OUTPUT=restart-preapplied-output", + "PACKAGE_ACCEPTANCE_RESTART_SEED_OK=True" +) +$restartRecoveryMarkers = @( + "PACKAGE_ACCEPTANCE_RESTART_INPUT_RECOVERED=True", + "PACKAGE_ACCEPTANCE_RESTART_WORKFLOW_OUTPUT_CAPTURED=True", + "PACKAGE_ACCEPTANCE_RESTART_PENDING_OUTPUT_RESUMED=True", + "PACKAGE_ACCEPTANCE_RESTART_OUTPUT_RECOVERED=True", + "PACKAGE_ACCEPTANCE_RESTART_IDEMPOTENCY_OK=True", + "PACKAGE_ACCEPTANCE_RESTART_OK=True" +) function Invoke-Step { param( @@ -312,9 +330,11 @@ if (-not (Test-Path -LiteralPath $resolvedFixturePath -PathType Container)) { $fixtureProject = Join-Path $resolvedFixturePath "FluxFlow.PackageConsumerAcceptance.csproj" $fixtureProgram = Join-Path $resolvedFixturePath "Program.cs" +$fixtureRestartScenario = Join-Path $resolvedFixturePath "RestartDurabilityScenario.cs" if (-not (Test-Path -LiteralPath $fixtureProject -PathType Leaf) -or - -not (Test-Path -LiteralPath $fixtureProgram -PathType Leaf)) { - throw "Consumer fixture must contain FluxFlow.PackageConsumerAcceptance.csproj and Program.cs." + -not (Test-Path -LiteralPath $fixtureProgram -PathType Leaf) -or + -not (Test-Path -LiteralPath $fixtureRestartScenario -PathType Leaf)) { + throw "Consumer fixture must contain FluxFlow.PackageConsumerAcceptance.csproj, Program.cs, and RestartDurabilityScenario.cs." } [xml] $fixtureXml = Get-Content -LiteralPath $fixtureProject -Raw @@ -344,6 +364,7 @@ else { $consumerProject = Join-Path $workRoot "FluxFlow.PackageConsumerAcceptance.csproj" $packageCache = Join-Path $workRoot "packages" $nugetConfig = Join-Path $workRoot "NuGet.config" +$restartDataDirectory = Join-Path $workRoot "restart-durability" $versionArguments = @() foreach ($entry in $topLevelVersionProperties.GetEnumerator()) { @@ -382,6 +403,16 @@ $runArguments = @( "--no-build", "--no-restore" ) + $versionArguments +$restartSeedArguments = $runArguments + @( + "--", + "durability-restart-seed", + $restartDataDirectory +) +$restartRecoveryArguments = $runArguments + @( + "--", + "durability-restart-recover", + $restartDataDirectory +) Write-Host "PACKAGE_ACCEPTANCE_PACKAGE_SOURCE=$sourcePath" Write-Host "PACKAGE_ACCEPTANCE_WORK_DIR=$workRoot" @@ -393,6 +424,8 @@ foreach ($package in $requiredPackages) { Write-Host "PACKAGE_ACCEPTANCE_RESTORE_COMMAND=$(Format-CommandLine 'dotnet' $restoreArguments)" Write-Host "PACKAGE_ACCEPTANCE_BUILD_COMMAND=$(Format-CommandLine 'dotnet' $buildArguments)" Write-Host "PACKAGE_ACCEPTANCE_RUN_COMMAND=$(Format-CommandLine 'dotnet' $runArguments)" +Write-Host "PACKAGE_ACCEPTANCE_RESTART_SEED_COMMAND=$(Format-CommandLine 'dotnet' $restartSeedArguments)" +Write-Host "PACKAGE_ACCEPTANCE_RESTART_RECOVERY_COMMAND=$(Format-CommandLine 'dotnet' $restartRecoveryArguments)" if ($PrepareOnly) { Write-Host "PACKAGE_ACCEPTANCE_PREPARED=True" @@ -444,7 +477,10 @@ try { } Copy-Item -LiteralPath $fixtureProject -Destination $consumerProject - Copy-Item -LiteralPath $fixtureProgram -Destination (Join-Path $workRoot "Program.cs") + Get-ChildItem -LiteralPath $resolvedFixturePath -File -Filter "*.cs" | + ForEach-Object { + Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $workRoot $_.Name) + } $escapedCandidateSource = Escape-Xml $sourcePath $escapedPublicSource = Escape-Xml $PublicPackageSource @@ -468,7 +504,7 @@ try { Invoke-Step "dotnet" $buildArguments "Package-consumer build failed." $runOutput = @(Invoke-CapturedStep "dotnet" $runArguments "Package-consumer execution failed.") - foreach ($marker in $requiredMarkers) { + foreach ($marker in $defaultRequiredMarkers) { $count = @($runOutput | Where-Object { [string]::Equals($_, $marker, [System.StringComparison]::Ordinal) }).Count @@ -477,6 +513,38 @@ try { } } + $seedOutput = @( + Invoke-CapturedStep ` + "dotnet" ` + $restartSeedArguments ` + "Package-consumer restart seed execution failed." + ) + foreach ($marker in $restartSeedMarkers) { + $count = @($seedOutput | Where-Object { + [string]::Equals($_, $marker, [System.StringComparison]::Ordinal) + }).Count + if ($count -ne 1) { + throw "Package consumer restart seed must emit '$marker' exactly once; observed $count." + } + } + + $recoveryOutput = @( + Invoke-CapturedStep ` + "dotnet" ` + $restartRecoveryArguments ` + "Package-consumer restart recovery execution failed." + ) + foreach ($marker in $restartRecoveryMarkers) { + $count = @($recoveryOutput | Where-Object { + [string]::Equals($_, $marker, [System.StringComparison]::Ordinal) + }).Count + if ($count -ne 1) { + throw "Package consumer restart recovery must emit '$marker' exactly once; observed $count." + } + } + + Write-Host "PACKAGE_ACCEPTANCE_RESTART_COMPLETE=True" + Write-Host "PACKAGE_ACCEPTANCE_COMPLETE=True" } finally { diff --git a/eng/package-consumer-acceptance/FluxFlow.PackageConsumerAcceptance.csproj b/eng/package-consumer-acceptance/FluxFlow.PackageConsumerAcceptance.csproj index fb69d0b0..d0d1e3ed 100644 --- a/eng/package-consumer-acceptance/FluxFlow.PackageConsumerAcceptance.csproj +++ b/eng/package-consumer-acceptance/FluxFlow.PackageConsumerAcceptance.csproj @@ -11,13 +11,16 @@ + + + diff --git a/eng/package-consumer-acceptance/Program.cs b/eng/package-consumer-acceptance/Program.cs index 6483b610..0a2ed709 100644 --- a/eng/package-consumer-acceptance/Program.cs +++ b/eng/package-consumer-acceptance/Program.cs @@ -1,9 +1,11 @@ using System.Text.Json; using FluxFlow.Composition; using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; using FluxFlow.Composition.Model; using FluxFlow.Data; using FluxFlow.Engine; +using FluxFlow.Engine.HealthChecks; using FluxFlow.Engine.DurableInput; using FluxFlow.Engine.DurableInput.SqlFile; using FluxFlow.Engine.DurableOutput; @@ -12,10 +14,43 @@ using FluxFlow.Fluent; using FluxFlow.Nodes; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; + +if (args.Length > 0) +{ + if (args.Length != 2) + { + throw new ArgumentException( + "Restart durability modes require exactly one absolute data-directory argument."); + } + + if (!Path.IsPathFullyQualified(args[1])) + throw new ArgumentException("The restart durability data directory must be absolute."); + + var restartDataDirectory = Path.GetFullPath(args[1]); + switch (args[0]) + { + case "durability-restart-seed": + await RestartDurabilityScenario.SeedAsync(restartDataDirectory); + return 0; + + case "durability-restart-recover": + await RestartDurabilityScenario.RecoverAsync(restartDataDirectory); + return 0; + + default: + throw new ArgumentException($"Unknown package-consumer acceptance mode '{args[0]}'."); + } +} await RunEngineScenarioAsync(); Console.WriteLine("PACKAGE_ACCEPTANCE_ENGINE_OK=True"); +await RunCodeFirstEngineScenarioAsync(); +Console.WriteLine("PACKAGE_ACCEPTANCE_CODE_FIRST_OK=True"); +Console.WriteLine("PACKAGE_ACCEPTANCE_RESOURCE_OK=True"); +Console.WriteLine("PACKAGE_ACCEPTANCE_HEALTH_OK=True"); + await RunFluentScenarioAsync(); Console.WriteLine("PACKAGE_ACCEPTANCE_FLUENT_OK=True"); @@ -40,47 +75,97 @@ static async Task RunEngineScenarioAsync() } } """; + const string invalidDefinitionJson = """ + { + "Resources": {}, + "Workflows": { + "Acceptance": { + "Unavailable": { + "Type": "acceptance.unavailable" + } + } + } + } + """; + var definition = ApplicationDefinitionJson.Deserialize(definitionJson); var services = new ServiceCollection(); services.AddFluxFlow( - ApplicationDefinitionJson.Deserialize(definitionJson), + definition, options => options.StartWithHost = false); services.AddFluxFlowComponents() - .AddRuntimeComponent("acceptance.uppercase", component => - { - component.UseFactory(_ => - { - var node = new UppercaseNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); - }); - component.AddInput("Input"); - component.AddOutput("Output"); - }); + .AddComponent(AcceptanceComponents.Uppercase); await using var provider = services.BuildServiceProvider(); var application = provider.GetRequiredService(); var started = await application.StartAsync(); Ensure(started.IsApplied, "The canonical package application was not applied."); + await AssertJsonRouteAsync(application, "package-json", "PACKAGE-JSON"); + + var activeRevision = application.Current; + var activeDefinition = application.CurrentDefinition; + Ensure(activeRevision is not null, "The canonical package application has no active revision."); + Ensure(activeDefinition is not null, "The canonical package application has no active definition."); + Ensure( + ReferenceEquals(activeDefinition, definition), + "The canonical package application did not retain the exact loaded definition."); + + var unchanged = await application.ApplyAsync("package-json-unchanged", definition); + Ensure( + unchanged.Status == ApplicationUpdateStatus.Unchanged, + "Applying the unchanged JSON definition did not report unchanged."); + Ensure( + ReferenceEquals(unchanged.ActiveRevision, activeRevision), + "Applying the unchanged JSON definition replaced the active revision."); + Ensure( + ReferenceEquals(application.Current, activeRevision), + "Applying the unchanged JSON definition changed the current revision."); + Ensure( + ReferenceEquals(application.CurrentDefinition, activeDefinition), + "Applying the unchanged JSON definition changed the current definition."); + + var invalidDefinition = ApplicationDefinitionJson.Deserialize(invalidDefinitionJson); + var rejected = await application.ApplyAsync("package-json-invalid", invalidDefinition); + Ensure( + rejected.Status == ApplicationUpdateStatus.Rejected, + "The invalid JSON candidate was not rejected."); + Ensure( + ReferenceEquals(rejected.ActiveRevision, activeRevision), + "The rejected JSON candidate did not report the retained active revision."); + Ensure( + ReferenceEquals(application.Current, activeRevision), + "The rejected JSON candidate changed the current revision."); + Ensure( + ReferenceEquals(application.CurrentDefinition, activeDefinition), + "The rejected JSON candidate changed the current definition."); + + await AssertJsonRouteAsync( + application, + "package-json-after-rejection", + "PACKAGE-JSON-AFTER-REJECTION"); + + await application.StopAsync(); +} + +static async Task AssertJsonRouteAsync( + FluxFlowApplication application, + string input, + string expectedOutput) +{ var receive = application.Ports.ReceiveAsync( "Acceptance.Uppercase.Output", TimeSpan.FromSeconds(10)); var sent = await application.Ports.SendAsync( "Acceptance.Uppercase.Input", - FlowMessage.Create("package-json")); + FlowMessage.Create(input)); Ensure(sent.Status == PortSendStatus.Accepted, "The canonical package input was not accepted."); var received = await receive; Ensure(received.Status == PortReceiveStatus.Received, "The canonical package output was not received."); Ensure( - string.Equals(received.Message?.Value, "PACKAGE-JSON", StringComparison.Ordinal), + string.Equals(received.Message?.Value, expectedOutput, StringComparison.Ordinal), "The canonical package output was not transformed exactly."); - - await application.StopAsync(); } static async Task RunFluentScenarioAsync() @@ -101,6 +186,80 @@ static async Task RunFluentScenarioAsync() "The Fluent package graph did not transform the exact value."); } +static async Task RunCodeFirstEngineScenarioAsync() +{ + var definitionBuilder = new ApplicationDefinitionBuilder() + .AddResource("Prefix", AcceptanceResources.Prefix, out var prefix) + .AddWorkflow("Acceptance", out var workflow); + + Ensure( + string.Equals(prefix.Type, AcceptanceResourceTypes.Prefix, StringComparison.Ordinal), + "The typed code-first resource handle did not retain its exact type."); + + workflow + .AddComponent( + "First", + AcceptanceComponents.Uppercase, + out var first) + .AddComponent( + "Second", + AcceptanceComponents.PrefixedUppercase, + out var second); + + first.Output.ConnectTo( + second.Input, + when: static value => string.Equals(value, "PACKAGE-CODE", StringComparison.Ordinal)); + + var services = new ServiceCollection(); + services.AddLogging(); + services.AddFluxFlow( + definitionBuilder.Build(), + options => options.StartWithHost = false); + services.AddHealthChecks() + .AddFluxFlowApplication(); + + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + var started = await application.StartAsync(); + Ensure(started.IsApplied, "The typed code-first package application was not applied."); + + var receive = application.Ports.ReceiveAsync( + second.Output, + TimeSpan.FromSeconds(10)); + var sent = await application.Ports.SendAsync( + first.Input, + FlowMessage.Create("package-code")); + Ensure(sent.Status == PortSendStatus.Accepted, "The typed code-first package input was not accepted."); + + var received = await receive; + Ensure(received.Status == PortReceiveStatus.Received, "The typed code-first package output was not received."); + Ensure( + string.Equals(received.Message?.Value, "RESOURCE-PACKAGE-CODE", StringComparison.Ordinal), + "The embedded resource contract did not affect the code-first output exactly."); + + var health = await provider + .GetRequiredService() + .CheckHealthAsync(static registration => + string.Equals( + registration.Name, + "fluxflow.application", + StringComparison.Ordinal)); + Ensure(health.Status == HealthStatus.Healthy, "The package application was not healthy."); + Ensure(health.Entries.Count == 1, "The package application check was not registered exactly once."); + var healthEntry = health.Entries["fluxflow.application"]; + Ensure( + healthEntry.Tags.Order(StringComparer.Ordinal).SequenceEqual(["fluxflow", "ready"]), + "The package application check tags changed."); + Ensure( + string.Equals( + healthEntry.Data["activeRevisionId"] as string, + application.Current?.RevisionId, + StringComparison.Ordinal), + "The package application check did not report the active revision exactly."); + + await application.StopAsync(); +} + static async Task RunDurabilityScenarioAsync() { var dataDirectory = Path.Combine( @@ -239,6 +398,91 @@ protected override async Task RunAsync(CancellationToken cancellationToken) } } +internal static class AcceptanceComponentTypes +{ + public const string Uppercase = "acceptance.uppercase"; +} + +internal static class AcceptanceComponentPorts +{ + public const string Input = "Input"; + public const string Output = "Output"; + public const string Events = "Events"; +} + +internal static class AcceptanceComponents +{ + public static ComponentContract Uppercase { get; } = + ComponentContract.Create( + AcceptanceComponentTypes.Uppercase, + static runtime => + { + runtime + .UseFactory(static _ => new UppercaseNode()) + .HasInput(AcceptanceComponentPorts.Input, static node => node.Input) + .HasOutput(AcceptanceComponentPorts.Output, static node => node.Output) + .HasEvents(AcceptanceComponentPorts.Events, static node => node.Events); + }, + static component => new UppercaseComponentHandle(component)); + + public static ComponentContract PrefixedUppercase { get; } = + ComponentContract.Create( + "acceptance.prefixed-uppercase", + static runtime => + { + runtime + .UseFactory(static context => new PrefixedUppercaseNode( + context.Services.GetRequiredService())) + .HasInput(AcceptanceComponentPorts.Input, static node => node.Input) + .HasOutput(AcceptanceComponentPorts.Output, static node => node.Output) + .HasEvents(AcceptanceComponentPorts.Events, static node => node.Events); + }, + static component => new UppercaseComponentHandle(component)); +} + +internal static class AcceptanceResourceTypes +{ + public const string Prefix = "acceptance.prefix"; +} + +internal static class AcceptanceResources +{ + private static readonly AcceptanceResourceRegistrar Registrar = new(); + + public static ApplicationResourceContract Prefix { get; } = + ApplicationResourceContract.Create( + AcceptanceResourceTypes.Prefix, + Registrar, + static resource => new AcceptanceResourceHandle(resource)); +} + +internal sealed class AcceptanceResourceHandle(ResourceHandle definition) + : AuthoredResourceHandle(definition); + +internal sealed class AcceptanceResourceRegistrar : IApplicationResourceRegistrar +{ + public void Register(ApplicationResourceRegistrationContext context) + { + ArgumentNullException.ThrowIfNull(context); + context.Services.AddSingleton(new AcceptancePrefix("RESOURCE-")); + } +} + +internal sealed record AcceptancePrefix(string Value); + +internal sealed class UppercaseComponentHandle(ComponentHandle definition) + : AuthoredComponentHandle(definition) +{ + public InputPortHandle Input { get; } = + definition.Input(AcceptanceComponentPorts.Input); + + public OutputPortHandle Output { get; } = + definition.Output(AcceptanceComponentPorts.Output); + + public OutputPortHandle Events { get; } = + definition.Output(AcceptanceComponentPorts.Events); +} + internal sealed class UppercaseNode : FlowNode { protected override async Task ProcessAsync(FlowMessage message) @@ -248,6 +492,17 @@ await EmitAsync(message.With(message.Value.ToUpperInvariant()), Stopping) } } +internal sealed class PrefixedUppercaseNode(AcceptancePrefix prefix) : FlowNode +{ + protected override async Task ProcessAsync(FlowMessage message) + { + await EmitAsync( + message.With(prefix.Value + message.Value.ToUpperInvariant()), + Stopping) + .ConfigureAwait(false); + } +} + internal sealed class CollectSink(StringCollector collector) : FlowNode { protected override async Task ProcessAsync(FlowMessage message) diff --git a/eng/package-consumer-acceptance/RestartDurabilityScenario.cs b/eng/package-consumer-acceptance/RestartDurabilityScenario.cs new file mode 100644 index 00000000..36e4802d --- /dev/null +++ b/eng/package-consumer-acceptance/RestartDurabilityScenario.cs @@ -0,0 +1,483 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using FluxFlow.Composition; +using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Model; +using FluxFlow.Engine; +using FluxFlow.Engine.DurableInput; +using FluxFlow.Engine.DurableInput.SqlFile; +using FluxFlow.Engine.DurableOutput; +using FluxFlow.Engine.DurableOutput.SqlFile; +using FluxFlow.Nodes; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +internal static class RestartDurabilityScenario +{ + private const string InputContract = "acceptance.restart.input.v1"; + private const string WorkflowOutputContract = "acceptance.restart.output.v1"; + private const string PreappliedOutputContract = "acceptance.restart.preapplied.v1"; + private const string InputValue = "restart durability"; + private const string WorkflowOutputValue = "RESTART DURABILITY"; + private const string PreappliedOutputValue = "already applied before restart"; + private const string InputMessageId = "restart-input"; + private const string PreappliedOutputMessageId = "restart-preapplied-output"; + + private static readonly DateTimeOffset SeedAt = + new(2026, 8, 7, 8, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset LeaseUntil = SeedAt.AddMinutes(1); + private static readonly DateTimeOffset RecoveryAt = SeedAt.AddMinutes(2); + private static readonly ApplicationAddress InputAddress = + ApplicationAddress.WorkflowPort("Restart", "Uppercase", "Input"); + private static readonly ApplicationAddress WorkflowOutputAddress = + ApplicationAddress.WorkflowPort("Restart", "Uppercase", "Output"); + private static readonly ApplicationAddress PreappliedOutputAddress = + ApplicationAddress.WorkflowPort("Restart", "External", "Output"); + private static readonly ApplicationDefinition Definition = new( + workflows: + [ + new("Restart", new WorkflowDefinition( + [ + new("Uppercase", new ComponentDefinition("acceptance.restart.uppercase")) + ])) + ]); + + internal static async Task SeedAsync(string dataDirectory) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory); + EnsureFreshDirectory(dataDirectory); + + var input = CreateInputEnvelope(); + var preappliedOutput = CreatePreappliedOutputEnvelope(); + + await using var provider = CreateStoreProvider(dataDirectory); + var inputStore = provider.GetRequiredService(); + var outputStore = provider.GetRequiredService(); + var outputDeliveryStore = provider.GetRequiredService(); + + var inputEnqueue = await inputStore.EnqueueAsync(input); + Ensure( + inputEnqueue.Status == DurableInputEnqueueStatus.Enqueued, + "Restart seed did not persist a new durable input."); + + var outputEnqueue = await outputStore.EnqueueAsync(preappliedOutput); + Ensure( + outputEnqueue.Status == DurableOutputEnqueueStatus.Enqueued, + "Restart seed did not persist a new durable output."); + + var inputLease = (await inputStore.LeaseAsync(new DurableInputLeaseRequest( + "restart-seed-input", + SeedAt, + LeaseUntil, + maxCount: 1))).Single(); + var outputLease = await outputDeliveryStore.TryLeaseAsync( + new DurableOutputDeliveryLeaseRequest( + "restart-seed-output", + SeedAt, + LeaseUntil)); + + Ensure(inputLease.Envelope.Key == input.Key, "Restart seed leased the wrong input."); + Ensure( + string.Equals(inputLease.OwnerId, "restart-seed-input", StringComparison.Ordinal), + "Restart seed input lease owner changed."); + Ensure(inputLease.LeasedAt == SeedAt, "Restart seed input lease time changed."); + Ensure(inputLease.Attempt == 1, "Restart seed input lease did not start at attempt 1."); + Ensure(inputLease.LeaseToken != Guid.Empty, "Restart seed input lease token was empty."); + Ensure( + inputLease.LeaseUntil == LeaseUntil, + "Restart seed input lease expiry changed."); + Ensure(outputLease is not null, "Restart seed did not lease the durable output."); + Ensure( + outputLease!.Envelope.Key == preappliedOutput.Key, + "Restart seed leased the wrong output."); + Ensure( + string.Equals(outputLease.OwnerId, "restart-seed-output", StringComparison.Ordinal), + "Restart seed output lease owner changed."); + Ensure(outputLease.LeasedAt == SeedAt, "Restart seed output lease time changed."); + Ensure(outputLease.Attempt == 1, "Restart seed output lease did not start at attempt 1."); + Ensure(outputLease.LeaseToken != Guid.Empty, "Restart seed output lease token was empty."); + Ensure( + outputLease.LeaseUntil == LeaseUntil, + "Restart seed output lease expiry changed."); + + await RestartEffectDestination.ApplyAsync( + EffectsDirectory(dataDirectory), + preappliedOutput, + CancellationToken.None); + + var inputStatus = await provider + .GetRequiredService() + .GetStatusAsync(new DurableInputStatusQuery(SeedAt)); + var outputStatus = await provider + .GetRequiredService() + .GetStatusAsync(new DurableOutputStatusQuery(SeedAt)); + + Ensure( + inputStatus.LeasedCount == 1 && + inputStatus.ExpiredLeaseCount == 0 && + inputStatus.DeliveredCount == 0, + "Restart seed did not leave exactly one active input lease."); + Ensure( + outputStatus.LeasedCount == 1 && + outputStatus.ExpiredLeaseCount == 0 && + outputStatus.CompletedCount == 0, + "Restart seed did not leave exactly one active output lease."); + Ensure( + RestartEffectDestination.Count(EffectsDirectory(dataDirectory)) == 1, + "Restart seed did not record exactly one idempotent external effect."); + + Console.WriteLine($"PACKAGE_ACCEPTANCE_RESTART_SEED_INPUT={input.MessageId.Value}"); + Console.WriteLine($"PACKAGE_ACCEPTANCE_RESTART_SEED_OUTPUT={preappliedOutput.MessageId.Value}"); + Console.WriteLine("PACKAGE_ACCEPTANCE_RESTART_SEED_OK=True"); + } + + internal static async Task RecoverAsync(string dataDirectory) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory); + RequireSeedState(dataDirectory); + + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + var effectDirectory = EffectsDirectory(dataDirectory); + var deliveryHandler = new RestartOutputDeliveryHandler(effectDirectory); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + + builder.Services.AddSingleton(new FixedUtcTimeProvider(RecoveryAt)); + builder.Services.AddFluxFlow(Definition); + builder.Services.AddFluxFlowComponents() + .Advanced.AddDynamicComponent("acceptance.restart.uppercase", component => + { + component + .UseFactory(static _ => new UppercaseNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); + }); + + AddStores(builder.Services, dataDirectory); + builder.Services.AddFluxFlowDurableInput(options => + { + options.LeaseDuration = TimeSpan.FromMinutes(1); + options.PollInterval = TimeSpan.FromMilliseconds(20); + options.RetryDelay = TimeSpan.FromMilliseconds(50); + options.StoreFailureDelay = TimeSpan.FromMilliseconds(50); + }); + builder.Services.AddFluxFlowDurableInputContract( + InputContract, + RestartJsonContext.Default.String); + builder.Services.AddFluxFlowDurableOutput(outputs => + outputs.Capture( + WorkflowOutputAddress, + WorkflowOutputContract, + RestartJsonContext.Default.String)); + builder.Services.AddSingleton(deliveryHandler); + builder.Services.AddFluxFlowDurableOutputDelivery(options => + { + options.LeaseDuration = TimeSpan.FromMinutes(1); + options.IdleDelay = TimeSpan.FromMilliseconds(20); + options.RetryDelay = TimeSpan.FromMilliseconds(50); + }); + + using var host = builder.Build(); + var inputStatusStore = host.Services.GetRequiredService(); + var outputStatusStore = host.Services.GetRequiredService(); + + var beforeInput = await inputStatusStore.GetStatusAsync( + new DurableInputStatusQuery(RecoveryAt), + timeout.Token); + var beforeOutput = await outputStatusStore.GetStatusAsync( + new DurableOutputStatusQuery(RecoveryAt), + timeout.Token); + Ensure( + beforeInput.LeasedCount == 1 && beforeInput.ExpiredLeaseCount == 1, + "Restart recovery did not observe the expired input lease."); + Ensure( + beforeOutput.LeasedCount == 1 && beforeOutput.ExpiredLeaseCount == 1, + "Restart recovery did not observe the expired output lease."); + Ensure( + RestartEffectDestination.Count(effectDirectory) == 1, + "Restart recovery did not observe the one pre-applied effect."); + + await host.StartAsync(timeout.Token); + try + { + Ensure( + host.Services.GetRequiredService().State == + ApplicationState.Running, + "Restart recovery FluxFlow application did not start with the host."); + + var deliveredValue = await deliveryHandler.WorkflowOutputDelivered + .WaitAsync(timeout.Token); + Ensure( + string.Equals(deliveredValue, WorkflowOutputValue, StringComparison.Ordinal), + "Restart recovery delivered the wrong transformed workflow output."); + + var finalState = await WaitForTerminalStateAsync( + inputStatusStore, + outputStatusStore, + timeout.Token); + EnsureFinalInputStatus(finalState.Input); + EnsureFinalOutputStatus(finalState.Output); + EnsureExactEffects(effectDirectory); + } + finally + { + await host.StopAsync(CancellationToken.None) + .WaitAsync(TimeSpan.FromSeconds(5)); + } + + Console.WriteLine("PACKAGE_ACCEPTANCE_RESTART_INPUT_RECOVERED=True"); + Console.WriteLine("PACKAGE_ACCEPTANCE_RESTART_WORKFLOW_OUTPUT_CAPTURED=True"); + Console.WriteLine("PACKAGE_ACCEPTANCE_RESTART_PENDING_OUTPUT_RESUMED=True"); + Console.WriteLine("PACKAGE_ACCEPTANCE_RESTART_OUTPUT_RECOVERED=True"); + Console.WriteLine("PACKAGE_ACCEPTANCE_RESTART_IDEMPOTENCY_OK=True"); + Console.WriteLine("PACKAGE_ACCEPTANCE_RESTART_OK=True"); + } + + private static ServiceProvider CreateStoreProvider(string dataDirectory) + { + var services = new ServiceCollection(); + AddStores(services, dataDirectory); + return services.BuildServiceProvider(); + } + + private static void AddStores(IServiceCollection services, string dataDirectory) + { + services.AddFluxFlowSqlFileDurableInput(options => + { + options.DatabasePath = InputDatabase(dataDirectory); + options.AllowAbsoluteDatabasePath = true; + }); + services.AddFluxFlowSqlFileDurableOutput(options => + { + options.DatabasePath = OutputDatabase(dataDirectory); + options.AllowAbsoluteDatabasePath = true; + }); + } + + private static DurableInputEnvelope CreateInputEnvelope() + => new( + InputAddress, + InputContract, + isError: false, + JsonSerializer.SerializeToElement(InputValue, RestartJsonContext.Default.String), + error: null, + new MessageId(InputMessageId), + new TraceId("restart-input-trace"), + SeedAt, + SeedAt, + headers: new Dictionary { ["source"] = "restart-seed" }); + + private static DurableOutputEnvelope CreatePreappliedOutputEnvelope() + => new( + PreappliedOutputAddress, + PreappliedOutputContract, + isError: false, + JsonSerializer.SerializeToElement( + PreappliedOutputValue, + RestartJsonContext.Default.String), + error: null, + new MessageId(PreappliedOutputMessageId), + new TraceId("restart-preapplied-output-trace"), + SeedAt, + SeedAt, + headers: new Dictionary { ["source"] = "restart-seed" }); + + private static async Task<(DurableInputStatusSnapshot Input, DurableOutputStatusSnapshot Output)> + WaitForTerminalStateAsync( + IDurableInputStatusStore inputStore, + IDurableOutputStatusStore outputStore, + CancellationToken cancellationToken) + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + var input = await inputStore.GetStatusAsync( + new DurableInputStatusQuery(RecoveryAt), + cancellationToken); + var output = await outputStore.GetStatusAsync( + new DurableOutputStatusQuery(RecoveryAt), + cancellationToken); + if (input.DeliveredCount == 1 && output.CompletedCount == 2) + return (input, output); + + await Task.Delay(TimeSpan.FromMilliseconds(20), cancellationToken); + } + } + + private static void EnsureFinalInputStatus(DurableInputStatusSnapshot status) + => Ensure( + status.TotalCount == 1 && + status.PendingCount == 0 && + status.LeasedCount == 0 && + status.DeliveredCount == 1 && + status.DeadLetteredCount == 0, + "Restart recovery input state was not exactly one delivered record."); + + private static void EnsureFinalOutputStatus(DurableOutputStatusSnapshot status) + => Ensure( + status.CapturedCount == 2 && + status.UnmaterializedCount == 0 && + status.PendingCount == 0 && + status.LeasedCount == 0 && + status.CompletedCount == 2 && + status.DeadLetteredCount == 0, + "Restart recovery output state was not exactly two completed records."); + + private static void EnsureExactEffects(string effectDirectory) + { + var records = RestartEffectDestination.ReadAll(effectDirectory); + Ensure(records.Count == 2, "Restart recovery did not retain exactly two effects."); + Ensure( + records.Count(record => record.Contains( + PreappliedOutputValue, + StringComparison.Ordinal)) == 1, + "Restart recovery repeated or lost the pre-applied effect."); + Ensure( + records.Count(record => record.Contains( + WorkflowOutputValue, + StringComparison.Ordinal)) == 1, + "Restart recovery repeated or lost the workflow effect."); + } + + private static void EnsureFreshDirectory(string dataDirectory) + { + if (Directory.Exists(dataDirectory) && + Directory.EnumerateFileSystemEntries(dataDirectory).Any()) + { + throw new InvalidOperationException( + $"Restart seed data directory '{dataDirectory}' must be empty."); + } + + Directory.CreateDirectory(dataDirectory); + } + + private static void RequireSeedState(string dataDirectory) + { + Ensure(File.Exists(InputDatabase(dataDirectory)), "Restart input database was not found."); + Ensure(File.Exists(OutputDatabase(dataDirectory)), "Restart output database was not found."); + Ensure( + RestartEffectDestination.Count(EffectsDirectory(dataDirectory)) == 1, + "Restart seed effect evidence was not found exactly once."); + } + + private static string InputDatabase(string dataDirectory) + => Path.Combine(dataDirectory, "restart-input.db"); + + private static string OutputDatabase(string dataDirectory) + => Path.Combine(dataDirectory, "restart-output.db"); + + private static string EffectsDirectory(string dataDirectory) + => Path.Combine(dataDirectory, "effects"); + + private static void Ensure(bool condition, string message) + { + if (!condition) + throw new InvalidOperationException(message); + } + + private sealed class FixedUtcTimeProvider(DateTimeOffset utcNow) : TimeProvider + { + public override DateTimeOffset GetUtcNow() => utcNow; + } +} + +internal sealed class RestartOutputDeliveryHandler(string effectDirectory) : + IDurableOutputDeliveryHandler +{ + private readonly TaskCompletionSource _workflowOutputDelivered = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + internal Task WorkflowOutputDelivered => _workflowOutputDelivered.Task; + + public async ValueTask DeliverAsync( + DurableOutputEnvelope envelope, + CancellationToken cancellationToken) + { + if (envelope.IsError) + throw new InvalidOperationException("Restart recovery expects value outputs."); + + var value = envelope.Payload.Deserialize(RestartJsonContext.Default.String) + ?? throw new InvalidOperationException("Restart recovery output cannot be null."); + await RestartEffectDestination.ApplyAsync( + effectDirectory, + envelope, + cancellationToken); + + if (string.Equals( + envelope.ContractName, + "acceptance.restart.output.v1", + StringComparison.Ordinal)) + { + _workflowOutputDelivered.TrySetResult(value); + } + } +} + +internal static class RestartEffectDestination +{ + internal static async Task ApplyAsync( + string directory, + DurableOutputEnvelope envelope, + CancellationToken cancellationToken) + { + Directory.CreateDirectory(directory); + var content = Content(envelope); + var path = Path.Combine(directory, FileName(envelope)); + + try + { + await using var stream = new FileStream( + path, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + bufferSize: 4096, + useAsync: true); + await using var writer = new StreamWriter(stream, new UTF8Encoding(false)); + await writer.WriteAsync(content.AsMemory(), cancellationToken); + await writer.FlushAsync(cancellationToken); + } + catch (IOException) when (File.Exists(path)) + { + var existing = await File.ReadAllTextAsync(path, cancellationToken); + if (!string.Equals(existing, content, StringComparison.Ordinal)) + { + throw new InvalidOperationException( + "A durable output identity was reused with different effect content."); + } + } + } + + internal static int Count(string directory) + => Directory.Exists(directory) + ? Directory.EnumerateFiles(directory, "*.effect", SearchOption.TopDirectoryOnly).Count() + : 0; + + internal static IReadOnlyList ReadAll(string directory) + => Directory.EnumerateFiles(directory, "*.effect", SearchOption.TopDirectoryOnly) + .OrderBy(path => path, StringComparer.Ordinal) + .Select(File.ReadAllText) + .ToArray(); + + private static string FileName(DurableOutputEnvelope envelope) + { + var identity = $"{envelope.Key.Address.Value}\n{envelope.Key.MessageId.Value}"; + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(identity)); + return $"{Convert.ToHexString(hash).ToLowerInvariant()}.effect"; + } + + private static string Content(DurableOutputEnvelope envelope) + => string.Join( + "\n", + envelope.Key.Address.Value, + envelope.Key.MessageId.Value, + envelope.ContractName, + envelope.Payload.GetRawText()); +} + +[JsonSerializable(typeof(string))] +internal sealed partial class RestartJsonContext : JsonSerializerContext; diff --git a/eng/packages.json b/eng/packages.json index a15b2505..bcc482e5 100644 --- a/eng/packages.json +++ b/eng/packages.json @@ -470,5 +470,13 @@ "project": "src/FluxFlow.Engine.DurableOutput.TSql/FluxFlow.Engine.DurableOutput.TSql.csproj", "notesName": "FluxFlow.Engine.DurableOutput.TSql", "binaryCompatibilityBaseline": "2.0.0" + }, + { + "alias": "engine-healthchecks", + "tagPrefix": "engine-healthchecks", + "packageId": "FluxFlow.Engine.HealthChecks", + "project": "src/FluxFlow.Engine.HealthChecks/FluxFlow.Engine.HealthChecks.csproj", + "notesName": "FluxFlow.Engine.HealthChecks", + "binaryCompatibilityBaseline": null } ] diff --git a/eng/public-api/baseline.txt b/eng/public-api/baseline.txt index d57bea94..c1bff37e 100644 --- a/eng/public-api/baseline.txt +++ b/eng/public-api/baseline.txt @@ -5,58 +5,59 @@ 1|33|2545168EB6968CF01A18F6C1ABBF983DE96AC7B340F55795D79835BB6F55626C 2|34|D9B1D39D0B90ACFA62761A8803488B6E26F754F9B75804B2B251A45308267F96 3|70|A3CB27FEBB5534D87F7A2C5146EB49C1DBD6E139CB4FA1802252E7BBF6B6534A -4|46|E7039056A73D6663DD331012B3FE9B9055E00BFE7B7FDFE542E3BA17EF86F8A2 -5|414|26006DD90EC4F2D9FBF5FDF71A4B57A6C49E2AE8A3C632730E53E6190584645C +4|48|F6E8EB813FB63F2C2E241D5BADC35412F954DDDBB9859B5F8A850F6E3146B9B2 +5|510|9E7B8FD5CD1A6C3F4F9992459D30B0081EC9EE8A3A8C3FF38AE1DD0F5BF39C65 6|24|E0D17FEB66936D323B4F51225057CD5583D6B71D12D9E67EBCFAF7BA805DD945 7|45|5668E1862A4D74837DE5E98809BB1B7F5120EACD5F719263CAFFA574D79EED13 8|30|2C68BF45E40E57070F67FE5EBA6B34FE7D01F68CA7B1EAB7D73563AFEF8BC020 -9|418|F27F8A4AAB5C26AFFEE3AF51294E74CE88593E80A2CDDA5B710B884B948D612D +9|433|F2F47F95CFE57CA455C2D966BC4D387C18425694E1AFC07E536CD492754673CE 10|304|CCB4B470C89172BFC6E5C4678281685B8798A93D4103CE16A3BF739A3A08FD57 -11|174|55ED99C1F528DAE282674D0F3527C6A008ECAF14BC97328BFD7496553C88517B +11|181|90B27C5864451400ED2D6DA7662B31C08AE8C419D1E2D585633C32645FA2BD65 12|16|D293AE12ACD7A232FBD1F638DDED6D55A12ABC7A5261B62F3D4B897EAABF13CB 13|16|E1C6A089B6EE1988D24836D78EDBB68BB51FB540D3DFF0AB6BEF1DBB1A7DB952 14|32|D86ED4710E121B0E7BCF6D0314D404CF5B5349F6313370A770003C78397A77A4 -15|32|4F7DAEAD4F6B5F9564FBDD8E8A2A4631ABC220A2DCE40A4BAE8ED87000965735 +15|35|C7DCFDB3286AC4E7D5989E79D76996866333EA6E6C67F10720D9EDC68827C178 16|40|84DCB2F5AF6F33F9EB8498538543E4E4650000B96818EAB2937C885733203166 -17|34|A9B9A5C4153359ED0CA14A1EFEBA5DCF4C36FD643D43BB941CAC95774748CF87 +17|37|0DE989966D121A7AE0B434371A2877E6C3102E98C2674E4D9E696266EA90204C 18|59|2F27D9E987B9947871DB2A49298615575CC0F89282F0FBFC56DEB7A079F4DCCF -19|37|84C034B45516CFA1F42619B4F7D0C4090191AF1B6C366F88F98E7B17028A143F +19|40|C1CF0157065697C61BB680001B9F7025599A2FBEBEDFB03E41B764722B741899 20|185|7A2A6F3D63160D1E7A7A84DC5EA9D3EDC9DF0F10E545B8992AD76BF6EBCC8798 -21|62|FDC4C5B44264E1B39E2A34AEC820AE229E66D15147E50BC16DA5AD36BCB99047 +21|66|EB70188E8A4917BA44EF3D7C9817682E83BD7FD6246B8F009CCBB6361CEFBBD2 22|50|2926BF73D93950A7CEFCF31C19AB21349F52C99C60CFB3648FCFA1699A93F855 -23|26|A6A7E4CBBAC7A744C32E748FCAF9F5F33033CF48BDBC76D37DBECAD4C5D0FD8E +23|28|D2B19099B89634EB6D51BDF945709ACE0D2ACCD3157D88BF97C648B1B97441F5 24|197|7D77C8E8CED283927836D592B2D42DB542A3C32FAF7D932B3C2102853B7FED4E -25|55|54D157D006B928325E288798B14902543D28F4CEAB7DE3E9EA7A418F2ACF9365 +25|60|A765D2B4188080D86DDD55D9A6E9648A0A08CEA9A6C6E7C07F76BE4A41BDF21D 26|111|201F79EF64977730AF02E2F35FB4DD87FEDFFE12E40184D5CB830C5E23672094 -27|46|7180A519E034E0B1BFB1F7B61603E99948782084F51796603B588D73215E3D84 +27|50|BA073676196ED327EA5755D356F5C3BDE43A5BB9FFD67B3C8668BED717C452B3 28|140|32FA7913E42646C529662A09553451385443F933041EDFCFE26D47BA0E905E47 -29|52|3DB5768880E25D8914ADD0E069FB8A5F874F74A3697E56A88107DCF492D35294 +29|58|F8908CDD20B8D9A7D7CFC31B0EA58E5E9F4C69AB734E3F56AA4D9B097D6E4EEA 30|42|3D4CB653116BE6048F77090DA48A228C74C7D4879197A51265C71F0B209F603A -31|29|021016BA33EDF8FA586AE93C2A4ECFCA91048B69D5F5C1A4941388C766F3CD95 +31|32|0249628773421CDAEF2C7C6A898BACB595CB2DF2802CE075FD76E86E5CE17D3F 32|62|DC9864B21D5239FAB4CBFB49BC86AE55A288CEB5D9127BD4E52ECD0176F67C15 -33|28|7AB0F6BA399FF2ADBB128513A90968F902F0840FDE0D14AE39FC0CEF5671881F +33|31|417284C47526EBE1F967765A2FC9158BCF90B3A6DBBD6C55381779A60B136EEC 34|106|306CB0BF2CE52E8153559318379D52E61F9CA71D434E1ECEC8355D36DB0CAF61 -35|48|C6151D8F697375361E5FBE6C57A12DA792781774296AE8C0715EA98456832526 +35|55|ADBB158D2453CC5C786912E66E2CAA1B9F54DDA7D918CA36942EBD28E3F7D245 36|88|737447236DDF80A3A4E394AF6C13F8783FF405B9F52D662A6F57491896C57A42 -37|31|BC69DA3D7E96D9702E1018383E31C07BA29BEBCD075C1949E032975A76C622F5 +37|33|046CB10D5127B7CD3974CC95BD8C6F7F208710C2E32D8AE89A01FB9BC5A20EAF 38|77|35755D6DD05904443F5E2CF712648F72249A3E78A2D667904CB1E05AC042F7A0 -39|27|2CA1F6180FBC7283B1AA6A456C15C258314B7DDD2C140B78345B86E5AD2E79EC +39|29|E39C1D63A9B3E3033E4AD4E4F910EDA5D440313E948FA5AEC48BB239B24ECB5B 40|45|257459D10E92B7E0F49131B156C606005D2BC228812C86C0BBF9470343AA2F51 -41|27|1E549DE1F310EF473BD2337849B2E95830C030791CC54FF9D404A73A5EDF42CF -42|248|7F7894E49165A3373D3FE7593B03DEE1024BAA4C6C6C3F536A9301E61A47BB46 +41|29|8C6AB4AA1002D1C8047106B18B354BAA518868A449869C65B96A320BA2282111 +42|266|8CA42CB8EEB5434C094E00BB483F04590F46BA98DDA3D452EB9950DFD30E682A 43|196|9EC6133C55B78D7C9DFCCD7D792981112F0CF006D3CE4C03FBA9F51C06706481 -44|58|561B9215494AC5E48FB8BB9D6D01276BCAF0E4F9F05C99BFCCCD0107DCA6DAB4 +44|62|2D8B00E1BD8DD1032BA5145B429303252C357B200D6B8A77F9F82C1C014E61E0 45|54|4579A0AB28CA5098F2AA3E5ABEF2650ECC11DA52096BF6D87B749E0D4F860C80 -46|34|2EEAD8FA3E21EC610F5EE19E01AF51EA588D974851C911BBA57F9CAFC990F6C9 +46|36|C2B41A16F2FD6A1A8B6D79837D201C2B4A327727893DB06A1DCCDD19DFF87833 47|241|2D317953267ECA8B57DACA783F66F91E7BEE7C54F8DE4972DC98D88EECA490B3 -48|45|C146AA8CCE771D4453AEFD1E5E14F51BED17109A7C02E2A040A877941B34F505 +48|50|87F2DC51D8B3C31F9050F9EC87E1D76CA37CCD5A59BA58BCDA02E47B08B7FC76 49|48|0CE7A7E203137C2422BAA7FF7EAA8F88EA42E140F8E39DE0CD25F3A3EC49483A 50|35|F093E45D50762B74537072FC614FC8C5464BC4CCD91E7873906C1407FA7C81BC -51|30|1C6BD59770FA062F361C3586F6E563A7CB3D89324407FB6D9790A0E2D4F51BE7 +51|32|4B55506F2DADE095EE1905570E4424C7CC4CC65AB874AD8A65EE85DB9D526A05 52|6|5CBD53AECC66F9D1D94C1893571063CA7EDB4CD0D8A050DF2D30C155111B1A34 -53|213|6EA9FE587AB03C105CC58D36FC400E4C4A11F79455F75D600C2819DCA61F3550 +53|214|444C6140AEBC2D93A5F93F02BBAEC57E7F28CB018AB611A42F6A7D055C6E0716 54|35|D69BA2F48A9D0D387AB07435D3C702FE5853B1A77428620786DA368E28436391 55|39|8B16DA287B9BD29CDB9BD32FA4B1569EE818C24AE354605EFBE9991F6149457A -56|187|046D5C95413F76BBD7125F4182DA01A72ED7E294DBD662F42AC44F7D62D30355 +56|188|353AB08D508B6CD630CD823CD8E7EF5615A76AEFAB44E8A883F827E6570A8542 57|38|37CFB4E42B59150BAA7D1B535304E0FB270D1D74AA35FEDD1F72FE5E7288DB30 58|40|A7872A40708E186EA7C0EF21BE3707F6175C3B92BA7DD0C496918BDBFCCDEFF4 +59|3|7661FA9E43BC954746438806CC1B10C69962E83BF354BD1311E3DBD233A831C5 diff --git a/goals/2026-08-07-package-consumer-restart-durability-acceptance/README.md b/goals/2026-08-07-package-consumer-restart-durability-acceptance/README.md new file mode 100644 index 00000000..34db3fc4 --- /dev/null +++ b/goals/2026-08-07-package-consumer-restart-durability-acceptance/README.md @@ -0,0 +1,340 @@ +# Goal: Prove Package-Only Durability Recovery Across Process Restart + +## Status + +- State: accepted for execution +- Date: 2026-08-07 +- Repository: `C:\Projects\FluxFlow` +- Accepted base branch: `main` +- Runtime feature scope: none unless the acceptance proof exposes a real defect +- Public API scope: none +- Publication scope: none + +## Objective + +Close the remaining operational evidence gap between FluxFlow's focused +durability tests and its one-process operations sample. Extend the existing +package-only acceptance consumer so two distinct operating-system processes +share SQL-file durable state: + +1. a seed process persists durable input and output work, leases both records, + records one already-applied host-owned side effect, and exits without + settling either lease; and +2. a recovery process opens the same files, starts the normal Generic Host, + FluxFlow application, durable-input dispatcher, durable-output capture, and + durable-output delivery dispatcher, then proves that expired work is + recovered and reaches terminal state. + +This is an acceptance and release-confidence round. It must validate the +existing at-least-once contract without claiming exactly-once delivery and +without adding workflow checkpoints, distributed orchestration, reflection, +runtime discovery, or a second acceptance framework. + +## Current Evidence And Remaining Gap + +- Focused dispatcher and provider suites already prove lease expiry, + redelivery, retry, fencing-token replacement, terminal transitions, and + provider reopen behavior. +- `samples/FluxFlow.DurabilityOperationsSample` proves durable input, workflow + execution, durable output capture, and output delivery through one normal + Generic Host process. +- `eng/package-consumer-acceptance` proves that an isolated package-only + consumer can restore the exact candidate package closure and reopen + SQL-file input/output stores after service-provider disposal. +- The checked-in release gates do not yet prove that the normal hosted + dispatchers compose correctly after a real process boundary. +- The output delivery contract is intentionally at-least-once. A destination + side effect may have succeeded before a process stops and before the durable + completion transition commits. The acceptance proof must demonstrate a + simple host-owned idempotency receipt for that window. + +## Architecture Decision + +Reuse the existing package-only fixture and runner: + +- keep `eng/package-consumer-acceptance/Program.cs` as the small mode router and + existing Engine, Fluent, and store-reopen scenarios; +- add one cohesive + `eng/package-consumer-acceptance/RestartDurabilityScenario.cs` file containing + the restart-specific seed/recover workflow, fixed clock, delivery handler, + receipt handling, and exact assertions; +- extend `eng/package-consumer-acceptance.ps1` to copy all checked-in fixture + C# files into its isolated work directory and invoke the already-built + consumer three times: the existing default mode, restart seed, and restart + recovery; and +- keep the existing nine-package candidate closure, isolated restore, archive + hash verification, build, cleanup, and CI integration. + +Do not create a second console project, duplicate candidate package +resolution, add the fixture to the solution, or generalize the runner into a +process framework. Separate process invocation is the required boundary; a +new reusable abstraction is not. + +## Required Behavior + +### 1. Explicit command modes + +The package-only executable must accept exactly these shapes: + +- no arguments: run the existing Engine, Fluent, and SQL-file reopen checks; +- `durability-restart-seed `: create the restart + state; and +- `durability-restart-recover `: recover it through + normal hosted services. + +Reject missing paths, relative paths, extra arguments, and unknown modes with +clear errors and a non-zero exit code. Mode selection must be a direct switch; +do not use reflection, command frameworks, configuration binding, environment +discovery, or hidden defaults. + +### 2. Deterministic seed process + +The seed mode must: + +1. require that its caller-owned data directory does not already contain + restart state, then create only its required child files/directories; +2. use fixed identities, contracts, addresses, payloads, trace ids, headers, + and a fixed UTC seed time; +3. register the existing SQL-file durable-input and durable-output providers + with explicit allowed absolute paths; +4. enqueue one durable string input targeting the restart workflow input and + require `Enqueued`; +5. enqueue one independent durable output representing an external side + effect and require `Enqueued`; +6. lease the input and output at the fixed seed time with a fixed expiry and + require attempt 1, non-empty lease tokens, exact identities, exact owners, + and exact expiry; +7. write one host-owned idempotent effect file for the pre-leased output; the + file is both the destination effect and its receipt, representing the crash + window after the destination accepted the effect but before FluxFlow + completed the delivery lease; +8. leave both durable leases unsettled and dispose the provider; and +9. emit exact seed success and identity markers only after all assertions + pass. + +The seed process must not kill itself, corrupt a database, sleep until lease +expiry, or use an internal test hook. A normal process exit with intentionally +unsettled leases provides the required process boundary safely. + +### 3. Recovery through normal hosting + +The recovery mode must: + +1. require the input database, output database, receipt, and external-effect + evidence created by seed mode; +2. use a fixed UTC recovery time later than the seeded lease expiry so recovery + is immediate and independent of wall-clock speed; +3. create a normal Generic Host with logging noise disabled; +4. register one explicit uppercase runtime component and a one-node canonical + restart workflow through `AddFluxFlow`; +5. register the existing SQL-file providers over the seed files; +6. register the normal durable-input dispatcher and the exact source-generated + string contract for the workflow input; +7. register durable-output capture for the workflow output and the normal + durable-output delivery dispatcher; +8. replace the default `TimeProvider` with a tiny explicit provider whose UTC + value is fixed for lease decisions while base timers continue to drive the + hosted polling delays; +9. start the host with a bounded cancellation timeout; +10. prove the expired durable input is recovered, delivered to the workflow, + transformed exactly, captured durably, and settled as delivered; +11. prove the expired pre-existing output is recovered by the delivery + dispatcher and settled as completed; +12. prove the captured workflow output is delivered and settled as completed; +13. verify final input status is exactly one delivered record with no pending, + leased, or dead-lettered records; +14. verify final output status is exactly two completed records with no + unmaterialized, pending, leased, or dead-lettered records; +15. verify exactly two idempotent effect/receipt files exist: the already + applied seed effect appears once, and the transformed workflow effect + appears once; +16. stop the host with a separate bounded timeout; and +17. emit exact input-recovery, output-recovery, idempotency, and final restart + success markers only after terminal status and filesystem evidence agree. + +### 4. Host-owned idempotency receipt + +The acceptance handler must model the public contract honestly: + +- use `DurableOutputEnvelope.Key`, including its message identity, as the + idempotency identity; +- represent the local acceptance destination with one small effect file that + is also its receipt and contains the exact contract and payload content; +- create that idempotent destination effect atomically; +- when the same identity and content already have a receipt, return success + without repeating the external effect so the dispatcher can complete the + abandoned lease; +- fail if one identity is reused with different content; and +- remain fixture-local rather than becoming a FluxFlow runtime abstraction. + +This demonstrates a recommended host pattern. It does not make FluxFlow +exactly-once, does not coordinate the receipt transaction with the SQL-file +store, and must not be documented as doing so. + +### 5. Determinism and bounded execution + +- Lease timestamps and observations must use fixed UTC values. +- Do not add arbitrary long sleeps or wait for wall-clock lease expiry. +- Short hosted-service polling intervals are allowed because they exercise the + real dispatcher loop; completion must be observed through explicit task or + persisted-state conditions. +- Every wait must have a cancellation token or explicit timeout. +- Host stop must remain bounded even after a primary failure. +- Failure messages must name the phase and missing invariant. + +### 6. Runner integration + +Extend the existing acceptance runner to: + +1. copy every top-level fixture `*.cs` file, not just `Program.cs`, while + retaining the exact project-file check and project-reference rejection; +2. build the isolated consumer once; +3. run the existing default scenario once and retain its four exact markers; +4. create one restart data directory under the already owned work root; +5. invoke seed and recover as two separate `dotnet run --no-build --no-restore` + processes with the same absolute restart path; +6. print stable default, seed, and recovery command markers during preparation; +7. capture and echo both process outputs; +8. require every seed/recovery marker exactly once and fail closed for missing, + duplicate, or malformed evidence; +9. print `PACKAGE_ACCEPTANCE_RESTART_COMPLETE=True` only after recovery proof; +10. retain caller-owned work roots for diagnostics and remove runner-owned + roots in the existing `finally` block on success or failure; and +11. preserve candidate archive verification, source ownership, package-cache + isolation, and all existing parameters and behaviors. + +Do not add a second script or CI step. The existing CI call already owns the +complete package-only behavioral gate and will gain the restart proof through +the runner. + +## Test Plan + +Use the existing xUnit/Shouldly release-test conventions and the mandatory +test-generation evidence under `.testagent/`. + +Focused tests must prove at least: + +1. the fixture remains `net8.0`, package-only, and free of project references; +2. the fixture contains explicit seed/recover modes, normal hosting + registrations, fixed recovery time, source-generated string metadata, and + exact markers; +3. the fixture-local idempotency handler uses durable output identity and + rejects identity/content conflict; +4. the runner copies all fixture C# files; +5. preparation prints separate default, seed, and recovery commands without + creating work or package directories; +6. real isolated execution starts seed and recovery as distinct processes over + one shared restart directory; +7. output contains exact input recovery, output recovery, idempotency, restart, + and runner-completion markers; +8. a missing seed/recovery marker fails the runner; +9. failure cleanup removes runner-owned work while caller-owned diagnostic work + remains; +10. the complete CI rehearsal still invokes the one acceptance runner exactly + once after solution tests; and +11. all pre-existing package source, hash, restore, build, marker, and ownership + contracts continue to pass. + +Before closeout, review the new tests for assertion quality and gaps. Each +required behavior must map to an exact test name or an explicit non-behavioral +artifact/command in `.testagent/status.md`. + +## Documentation And Memory + +Update: + +- `docs/24-reliable-in-process-delivery.md` to point to the process-restart + acceptance evidence while preserving the in-process/durable boundary; +- `docs/25-durable-inputs.md` with the expired-lease restart proof and its + at-least-once limitation; +- `docs/29-durable-output-delivery.md` with the fixture-local idempotency + receipt proof and the remaining crash/transaction boundary; +- `docs/38-release-validation.md` so the existing package-consumer command is + documented as a three-process durability restart gate in addition to the + existing scenarios; +- `docs/README.md` only if a new documentation page is added; none is planned; +- `memory/00-index.md`; +- `memory/01-current-state.md`; and +- one new numbered memory record containing implementation, validation, + boundaries, and remaining limitations. + +The repository's Markdown documentation is the documentation-site source for +this round; no separate site directory exists. + +## Non-Negotiable Principles + +1. KISS, SRP, explicit registrations, and one cohesive acceptance slice. +2. Reuse the existing package-only fixture, runner, candidate closure, and CI + invocation. +3. No reflection, assembly scanning, service locator, hidden static mutable + state, command framework, environment inference, or generated runtime graph. +4. No arbitrary lease-expiry sleep and no unbounded wait. +5. No runtime source, public API, schema, package identity, version, or + publication change unless the test exposes a real product defect that is + documented before fixing. +6. No exactly-once claim. The engine and delivery handler remain at-least-once; + host-owned idempotency controls repeated destination effects. +7. No durable workflow checkpointing, internal queue persistence, distributed + transaction, transport acknowledgement, or broker scenario. +8. No new database provider, ORM, container, network service, or credential. +9. No second acceptance project, generalized process harness, or abstraction + hierarchy. +10. Preserve existing Engine, Fluent, store reopen, archive hash, package-only, + per-package smoke, and CI behavior. +11. Preserve unrelated work and do not perform broad cleanup. + +## Explicit Non-Goals + +- durable workflow execution state or checkpoint/replay; +- exactly-once workflow or output semantics; +- crash injection by terminating the process mid-instruction; +- T-SQL or another provider in the restart gate; +- MQTT, HTTP, broker, AI-agent, or IoT integration; +- new health/readiness APIs or telemetry exporters; +- public idempotency-store interfaces; +- runner/framework extraction for hypothetical future acceptance fixtures; +- release publication, tag creation, pull request, or package version change; +- unrelated refactoring or code-size cleanup. + +## Validation Sequence + +1. Build the package-only fixture against controlled local candidate packages. +2. Run the focused `PackageConsumerAcceptanceScriptTests` class using the + repository's VSTest/xUnit filter syntax. +3. Run the package-consumer runner in preparation mode and verify exact + default/seed/recover commands without filesystem mutation. +4. Run the real package-only acceptance gate with locally packed candidates; + require all existing and restart markers. +5. Inspect retained diagnostic work once, then remove only owned temporary + state. +6. Run the complete `FluxFlow.Release.Tests` project. +7. Run the complete solution Release build and tests if the focused gate is + green. +8. Run formatting, diff/whitespace, vulnerable-package, scope, neutral-name, + and repository-status checks. +9. Confirm runtime source, public API baselines, package projects, package + versions, schemas, CI step count, and publication state are unchanged. + +## Acceptance Criteria + +This goal is complete only when: + +- the package-only consumer has explicit default, seed, and recovery modes; +- seed and recovery execute as separate operating-system processes over one + shared SQL-file state directory; +- an input lease and output lease abandoned by seed mode are expired + deterministically without wall-clock waiting; +- normal Generic Host registrations recover the input, execute the workflow, + capture its output, and complete both output deliveries; +- final persisted status proves one delivered input and two completed outputs + with no live or dead-lettered work; +- the pre-applied destination effect is not repeated, the workflow effect is + applied once, and identity/content conflict fails closed; +- exact restart evidence markers are required by the existing runner; +- runner ownership and diagnostics behavior remain correct on success and + failure; +- focused and release validation pass with auditable test names and commands; +- documentation and memory state the proof and its at-least-once boundaries; + and +- no unapproved runtime, API, schema, package, dependency, publication, or + architectural expansion occurs. diff --git a/goals/2026-08-08-application-health-readiness/README.md b/goals/2026-08-08-application-health-readiness/README.md new file mode 100644 index 00000000..578b5cbc --- /dev/null +++ b/goals/2026-08-08-application-health-readiness/README.md @@ -0,0 +1,462 @@ +# Goal: Add a standard optional FluxFlow application readiness check + +- Date: 2026-08-08 +- State: complete +- Scope: one optional Engine health-check adapter package, its tests, package/release governance, package-only acceptance, documentation, and memory +- Compatibility: additive public package; no Engine behavior or existing package API change + +## Objective + +Add a small, explicit integration with the standard .NET health-check system so +hosts can expose FluxFlow application readiness without inventing their own +interpretation of `FluxFlowApplication.State`, `Current`, and `LastUpdate`. + +The normal registration must be familiar and flat: + +```csharp +services.AddFluxFlow(definition); + +services.AddHealthChecks() + .AddFluxFlowApplication(); +``` + +ASP.NET Core hosts may then expose the standard endpoint through their own web +host configuration: + +```csharp +app.MapHealthChecks("/health/ready"); +``` + +The adapter must remain optional. Installing or using `FluxFlow.Engine` alone +must not add health-check dependencies, checks, workers, timers, polling, +database access, or endpoint behavior. + +## Architectural principles + +- KISS: one package, one public extension method, one internal stateless check. +- SRP: Engine owns application lifecycle; the adapter only translates the + existing observable lifecycle into the standard `HealthCheckResult` model. +- IOC: the standard health-check registration factory receives the host service + provider and resolves the optional `FluxFlowApplication` dependency. +- No service locator inside the check: the check receives the resolved + application reference, or `null` when FluxFlow was not registered. +- No parallel status model: do not add a second mutable application state, + cache, monitor, event projection, or health-specific state machine. +- No hidden work: checks are evaluated only when the host asks for them. +- Privacy by construction: expose only bounded operational identifiers and + enum/code values; never expose payloads, component/resource properties, + exception objects, diagnostic messages/details, paths, connections, or + secrets. +- Preserve current behavior: no changes to Engine start, reload, rollback, + ports, revisions, disposal, durability, JSON, Fluent, MQTT, or hosting. + +## Required package boundary + +Create a new packable project: + +```text +src/FluxFlow.Engine.HealthChecks/FluxFlow.Engine.HealthChecks.csproj +``` + +Required project metadata: + +- package/assembly/root namespace: `FluxFlow.Engine.HealthChecks`; +- version: `1.0.0`; +- target frameworks: `net8.0;net10.0`; +- direct project reference only to `FluxFlow.Engine`; +- one direct package reference to the centrally versioned + `Microsoft.Extensions.Diagnostics.HealthChecks` package; +- package-local `README.md` packed at the package root; +- no durability, ASP.NET Core endpoint, database/provider, Fluent, MQTT, + Designer, reflection, or scanning dependency. + +Add `Microsoft.Extensions.Diagnostics.HealthChecks` to central package version +management using the repository's current `Microsoft.Extensions.*` version +line. Do not move this dependency into `FluxFlow.Engine`. + +Add the new package to `eng/packages.json` as an initial release with a null +binary compatibility baseline. Append it to preserve all existing manifest +indices and public API baseline identities. Add a non-empty +`FluxFlow.Engine.HealthChecks 1.0.0` changelog section. + +## Required public API + +Expose exactly one normal public declaration surface in the new package: + +```csharp +namespace FluxFlow.Engine.HealthChecks; + +public static class FluxFlowHealthChecksBuilderExtensions +{ + public static IHealthChecksBuilder AddFluxFlowApplication( + this IHealthChecksBuilder builder); +} +``` + +Rules: + +- validate `builder` with `ArgumentNullException.ThrowIfNull`; +- return the same builder instance; +- register one health check named `fluxflow.application`; +- assign exactly the tags `fluxflow` and `ready`; +- use `HealthStatus.Unhealthy` as the standard registration failure status; +- repeated calls on the same service collection are idempotent and keep one + FluxFlow registration/check; +- do not add overloads, callbacks, custom names, custom status mapping, + thresholds, timeout settings, or options in this round; +- do not expose the check implementation, registration marker, metadata keys, + or a new application-status DTO publicly; +- do not add forwarding APIs to Engine or Fluent. + +Idempotency may use one private registration-marker service in the adapter +package. It must not be hosted, disposable, mutable, or resolved during normal +application execution. + +## Required check behavior + +Implement one internal stateless `IHealthCheck`. Its constructor receives a +nullable `FluxFlowApplication`. The health registration factory resolves the +application with ordinary optional DI resolution, so a missing FluxFlow +registration produces a controlled unhealthy result rather than a resolution +exception. + +At evaluation time: + +1. honor the supplied cancellation token immediately; +2. read the current application state, active snapshot, and last update only; +3. perform no asynchronous I/O, waiting, polling, locking, database access, + service resolution, event subscription, logging, or runtime mutation; +4. return a completed task containing one deterministic result. + +### Health mapping + +| FluxFlow condition | Standard health status | Meaning | +|---|---|---| +| `FluxFlowApplication` is not registered | `Unhealthy` | Host registration is incomplete | +| `Running` with an active revision and no rejected latest update | `Healthy` | The active revision is usable | +| `Reloading` with an active revision and no rejected latest update | `Healthy` | The previous active revision remains usable while the candidate is prepared | +| `Running` or `Reloading` with an active revision and the latest update rejected | `Degraded` | Rollback preserved a usable active revision, but operator attention is appropriate | +| No active revision in `Empty`, `Starting`, or `Degraded` | `Unhealthy` | No usable application revision exists | +| `Stopping` or `Stopped` | `Unhealthy` | The application is not ready to serve workflow traffic | +| Any impossible/inconsistent combination, including a ready state without an active revision | `Unhealthy` | Fail closed without throwing | + +An applied or unchanged update following a rejection must restore `Healthy`. +Stopping and disposal must both produce the same deterministic stopped outcome. + +### Descriptions + +Use short stable descriptions that explain the category but do not repeat +diagnostic messages or exception text: + +- healthy: an active FluxFlow revision is available; +- degraded: the active revision remains available after the latest update was + rejected; +- unhealthy: FluxFlow is not registered, has no active revision, or is stopped. + +Do not attach an exception to any `HealthCheckResult` created by the adapter. + +### Bounded result data + +The result data dictionary must contain at most these seven keys: + +- `applicationState`; +- `activeRevisionId`; +- `activeSequence`; +- `requestedRevisionId`; +- `lastUpdateStatus`; +- `diagnosticStage`; +- `diagnosticCode`. + +Rules: + +- always include `applicationState`; use `Unavailable` when FluxFlow is not + registered; +- include active revision fields only when an active snapshot exists; +- include requested revision and update status only when a last update exists; +- include only the final diagnostic's stage and stable `FlowError.Code` when a + diagnostic exists; +- values are only strings or the active sequence number; +- never include `FlowError.Message`, `FlowError.Details`, exception data, + application definitions, resources, components, port addresses, message + identities, payloads, paths, connection information, or configuration. + +## Concurrency and lifecycle interpretation + +The adapter must not take Engine's internal lifecycle gate or introduce a new +lock. `FluxFlowApplication` already publishes state, active snapshot, and last +update through its established thread-safe read surface. + +The check must classify transitions conservatively: + +- a visible active revision is required for `Healthy` or `Degraded`; +- a rejected update never makes the still-active previous revision + `Unhealthy`; +- starting without an active revision and stopping are never ready; +- impossible/torn observations fail closed as `Unhealthy` and never throw. + +Tests must exercise the check while a candidate reload is deliberately held in +preparation, without sleeps or timing guesses, to prove the active revision +remains healthy during a normal reload. They must also prove rejected reload +rollback becomes degraded while the previous route remains operational. + +## Package-only acceptance + +Extend the existing package-only consumer rather than creating a separate +acceptance harness: + +- add `FluxFlow.Engine.HealthChecks` as a top-level package reference controlled + by `FluxFlowEngineHealthChecksVersion`; +- add `engine-healthchecks` to the exact candidate closure and pack list; +- keep the independent public package source for Microsoft dependencies; +- register the check through `AddHealthChecks().AddFluxFlowApplication()`; +- after the code-first application is active, resolve the standard + `HealthCheckService` and require `fluxflow.application` to be `Healthy` with + the exact `fluxflow`/`ready` tags and safe active-revision metadata; +- emit `PACKAGE_ACCEPTANCE_HEALTH_OK=True` exactly once; +- preserve all existing JSON, code-first resource, Fluent, durability, restart, + candidate-hash, isolated restore/build/run, and cleanup behavior; +- update exact pack and process invocation counts for the additional package. + +## Documentation and memory + +Create `docs/42-application-health-readiness.md` covering: + +- package installation and the two-line registration; +- ASP.NET Core `MapHealthChecks` example as host-owned endpoint wiring; +- exact status mapping; +- exact metadata and privacy boundary; +- fixed name/tags and standard tag filtering; +- the absence of polling, workers, storage queries, and durable backlog + thresholds; +- the distinction between application readiness, process liveness, durable + backlog status, and business-level dependency health. + +Update: + +- root `README.md` package/features and concise usage; +- `src/FluxFlow.Engine/README.md` to point to the optional adapter; +- `docs/05-hosting-and-observability.md`; +- `docs/14-public-api-overview.md` package/API table; +- `docs/README.md` index; +- `docs/38-release-validation.md` package marker/count contract; +- `memory/00-index.md`; +- `memory/01-current-state.md`; +- new `memory/302-application-health-readiness.md` with the final decision and + evidence. + +Do not add an ASP.NET Core dependency or endpoint implementation to the package. +The endpoint mapping in documentation belongs to the consuming host. + +## Tests and governance + +Use the repository's xUnit and Shouldly conventions. Create +`tests/FluxFlow.Engine.HealthChecks.Tests` and cover the real standard +`HealthCheckService` plus focused direct internal behavior where cancellation +or precise mapping requires it. + +Required behavioral evidence: + +1. default registration uses the exact name, tags, failure status, and same + builder return value; +2. duplicate registration is idempotent and yields one report entry; +3. a missing FluxFlow registration is unhealthy without an exception; +4. an unstarted application is unhealthy with bounded `Empty` metadata; +5. successful start is healthy with exact revision metadata; +6. a deliberately held reload remains healthy and reports the still-active + revision; +7. rejected initial activation is unhealthy; +8. rejected hot reload is degraded, reports only safe final diagnostic + stage/code, and preserves the previous active revision/route; +9. a later successful or unchanged update restores healthy status; +10. stop and dispose are deterministically unhealthy/stopped; +11. cancellation throws `OperationCanceledException` with the exact token; +12. malformed/inconsistent inputs to the internal classifier fail closed; +13. result data never exceeds the seven allowed keys and contains no message, + details, exception, definition, resource, component, address, payload, + connection, or secret content. + +Add Release tests asserting: + +- the new project is optional and Engine does not reference it or the health + package; +- only the approved one-method public surface is present; +- source contains no reflection, scanning, global registry, hosted service, + worker, timer, polling, delay, database/provider, durability, ASP.NET endpoint, + logging, or mutable static state; +- project targets and dependencies are exact; +- README/docs contain the required normal usage and boundaries; +- manifest, changelog, API baseline, and package-only closure include the new + package and marker. + +Update the public API baseline only through the repository's explicit baseline +acceptance workflow after the new project and manifest are final. + +## Explicit non-goals + +- Durable input/output backlog health checks or threshold options. +- Broker, database, filesystem, HTTP, MQTT, or other dependency health checks. +- Process liveness, watchdogs, heartbeats, startup probes, or shutdown probes. +- Custom health-check names, tags, statuses, callbacks, options, or endpoints. +- A custom JSON health-response writer. +- ASP.NET Core middleware or a web framework dependency. +- Polling, scheduled observation, caches, hosted services, workers, channels, + timers, or event subscriptions. +- Health-specific Engine state, a new public status DTO, or Engine lifecycle + changes. +- Exposing diagnostic messages/details or exceptions. +- Moving health settings into `FluxFlowApplicationOptions`. +- Publishing packages, committing, pushing, creating a branch/PR, or releasing. + +## Implementation phases + +### Phase 1: package and minimal registration + +1. Add the central Microsoft health-check package version. +2. Create the packable adapter project and package README. +3. Implement the one-method extension, fixed registration, private idempotency + marker, and nullable application factory. +4. Add the production project to the solution and package manifest. + +### Phase 2: readiness classification + +1. Implement the internal stateless check and conservative state mapping. +2. Build the bounded metadata dictionary. +3. Honor cancellation and attach no exceptions. +4. Add no Engine source dependency in the reverse direction. + +### Phase 3: focused tests + +1. Create the net10 test project and internal test access. +2. Add standard registration/report integration tests. +3. Add lifecycle, reload, rollback, recovery, cancellation, privacy, and + inconsistent-observation tests. +4. Run only the new test project until green. + +### Phase 4: package acceptance and release governance + +1. Add the health package to the candidate closure/version arguments. +2. Exercise the check and exact marker in the package-only fixture. +3. Update Release source, manifest, docs, public-surface, pack-count, command, + marker, and cleanup assertions. +4. Accept and then verify the public API baseline. + +### Phase 5: documentation and memory + +1. Add the dedicated documentation page and package README. +2. Update hosting, public API, release, root, docs index, and Engine references. +3. Record the decision in memory and update current-state/index files. + +### Phase 6: verification and closure + +Run sequentially with no overlapping build lanes: + +1. new focused health-check tests; +2. focused Release/public/package/documentation tests; +3. real isolated package-consumer `-PackPackages` gate; +4. Release solution build with zero warnings/errors; +5. full solution tests with zero failures, skips, or warnings; +6. dedicated Release tests; +7. public API baseline verification without acceptance mode; +8. `dotnet format --verify-no-changes`; +9. `git diff --check`; +10. direct/transitive vulnerable-package audit; +11. source scans for the forbidden mechanisms and stale counts/markers. + +Replace the completion section below with exact files, named tests, commands, +counts, warnings, and outcomes before marking the goal complete. + +## Acceptance criteria + +The goal is complete only when: + +1. a normal host can register FluxFlow readiness through the standard two-line + DI shape; +2. healthy/degraded/unhealthy mapping matches the table exactly; +3. failed hot reload remains usable and is reported degraded rather than down; +4. missing, unstarted, failed initial, stopping, stopped, and disposed states + fail closed without exceptions or sensitive data; +5. registration is idempotent and the public API remains one method; +6. Engine and all existing packages remain independent of the optional adapter; +7. no worker, polling, reflection, storage I/O, ASP.NET endpoint, or new runtime + state is introduced; +8. package-only consumption proves the packed adapter works on net8; +9. docs, package manifest, changelog, public API baseline, release governance, + and memory are current; +10. every focused and repository-wide gate is green. + +## Completion evidence + +Completed 2026-08-08 without publishing, committing, pushing, or creating a +branch, pull request, tag, or release. + +### Delivered surface + +- Added the optional `FluxFlow.Engine.HealthChecks` 1.0.0 package targeting + .NET 8 and .NET 10. +- Added the single public + `IHealthChecksBuilder.AddFluxFlowApplication()` extension with fixed name, + tags, unhealthy failure status, same-builder return, and idempotent + registration. +- Added the internal stateless readiness check with the exact + healthy/degraded/unhealthy mapping, forward/reverse stable observation, + immediate cancellation, and the seven-key privacy boundary. +- Added the package manifest entry, changelog, accepted public API baseline, + package README, dedicated documentation, root/Engine/hosting/public/release + guidance, and memory records. +- Extended the existing package-only consumer to exercise the standard + `HealthCheckService` path and emit + `PACKAGE_ACCEPTANCE_HEALTH_OK=True` exactly once. + +### Focused behavioral and governance evidence + +- `FluxFlow.Engine.HealthChecks.Tests`: 32 passed, 0 failed, 0 skipped, + 0 warnings. +- Focused `HealthReadinessConventionTests` plus package acceptance assertions: + 21 passed, 0 failed, 0 skipped, 0 warnings. +- Public API baseline acceptance: 2 passed, 0 warnings; immediate normal-mode + verification: 2 passed, 0 warnings. The new appended baseline is entry 59 + with three public declarations; all prior indices remain unchanged. +- Pack-mode script rehearsal fact + `Acceptance_script_pack_mode_cleans_owned_source_and_workdir_after_success`: + 1 passed, 0 warnings. It proved ten candidate pack operations, fifteen total + subprocesses, every default/seed/recovery marker exactly once including the + health marker, and cleanup of both owned directories. +- Direct `eng/package-consumer-acceptance.ps1 -PackPackages`: exited 0 in + 33.9 seconds. It created all ten real package and symbol archives, restored + them into an isolated .NET 8 package-only consumer, verified every restored + FluxFlow package identity/version/archive, built with zero warnings/errors, + executed Engine/code-first/resource/health/Fluent/durability plus separate + seed/recovery processes, emitted every required marker exactly once, and + removed both runner-owned directories. +- Real held-reload fact + `Active_revision_stays_healthy_and_operational_while_candidate_reload_is_held_in_preparation` + causally blocked candidate preparation without sleeping, observed + `Reloading`, returned healthy readiness, and routed `still-serving` through + the previous active revision before releasing the candidate. + +### Repository-wide evidence + +- Restore: 136 projects, 0 errors, 0 warnings. +- Final Release build: 136 projects, 0 errors, 0 warnings. +- Full solution tests: 2,665 passed across 67 test projects, 0 failures, + 0 warnings. +- Dedicated `FluxFlow.Release.Tests`: 185 passed, 0 warnings. +- `dotnet format FluxFlow.sln --verify-no-changes --no-restore`: passed. +- `git diff --check`: passed. +- Direct/transitive vulnerable-package audit: no vulnerable packages in any + project, including the new production and test projects. + +The first full-suite run exposed a missing repository-required `dataflow` +package tag and one existing resource-registrar closure test whose async helper +could retain a JIT stack root. The package tag was added. The test now performs +setup/replacement on a joined dedicated thread and retains its exact alive +before / collected after assertions with one forced full-GC sequence and no +sleeps, polling, retries, or timeouts. Both exact facts and the repeated full +suite are green. + +The first direct package-only execution additionally exposed that its bare +console `ServiceCollection` had not registered the standard logging service +required by `DefaultHealthCheckService`. The fixture now calls the ordinary +host-owned `services.AddLogging()`; the focused fixture assertion and repeated +direct package-only execution are green. No logging dependency or behavior was +added to the FluxFlow health package. diff --git a/goals/2026-08-08-end-to-end-code-first-simplification/README.md b/goals/2026-08-08-end-to-end-code-first-simplification/README.md new file mode 100644 index 00000000..6814ab27 --- /dev/null +++ b/goals/2026-08-08-end-to-end-code-first-simplification/README.md @@ -0,0 +1,632 @@ +# Goal: Complete the typed code-first path and remove the remaining parallel authoring/runtime seams + +- Date: 2026-08-08 +- State: complete +- Scope: FluxFlow Composition, Engine, durable input/output integration, application resources, MQTT Composition, Fluent and Fluent.Hosting, samples, package acceptance, public API governance, documentation, and memory +- Compatibility: deliberate breaking changes are allowed; do not retain obsolete aliases merely for backward compatibility + +## Objective + +Make compiled-C# FluxFlow applications feel like one coherent, explicit system from declaration through execution: + +1. typed component handles created during application authoring remain useful when the application is running; +2. code-first resource declarations carry their executable resource behavior so a second package/resource registration is not required; +3. `FluxFlow.Fluent` keeps its concise `From`/`Then`/`Tap`/`Branch`/`Apply` syntax but executes through the canonical `ApplicationDefinition`, `ComponentContract`, and `FluxFlowApplication` path instead of constructing a second live runtime model; +4. raw/dynamic component registration remains possible, but it is visibly advanced and no longer competes with normal `ComponentContract` authoring; +5. JSON/configuration applications remain portable, serializable, hot-reloadable definitions and continue to register executable package behavior explicitly. + +The result must be powerful but lightweight: direct C#, small explicit objects, ordinary dependency injection, deterministic ownership, no reflection, no assembly scanning, no global registries, and no hidden convention-based activation. + +## User intent + +The normal code-first experience should read as a single declaration and execution path: + +```csharp +var application = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var workflow); + +workflow + .AddComponent("source", SampleComponents.Source, out var source) + .AddComponent("processor", SampleComponents.Processor, out var processor) + .AddComponent("sink", SampleComponents.Sink, out var sink); + +source.Output.ConnectTo(processor.Input); +processor.Output.ConnectTo(sink.Input); + +var definition = application.Build(); + +services.AddFluxFlow(definition); +``` + +The same typed handles should work at the host boundary: + +```csharp +await fluxFlow.Ports.SendAsync( + processor.Input, + FlowMessage.Create(value)); + +var output = await fluxFlow.Ports.ReceiveAsync( + sink.Output, + timeout: TimeSpan.FromSeconds(10)); +``` + +For code-first MQTT, adding MQTT resources to the definition must be sufficient to make their registrar available: + +```csharp +var application = new ApplicationDefinitionBuilder() + .AddResourceGroup("messaging", out var messaging) + .AddWorkflow("main", out var workflow); + +messaging + .AddMqttBroker("broker", options, out var broker) + .AddMqttClient("client", clientOptions, out var client); + +services.AddFluxFlow(application.Build()); +``` + +The code-first path above must not require a duplicate `AddFluxFlowComponents().AddMqtt()` call solely to supply the resource registrar or descriptors already captured by the definition. + +## Architectural principles + +- KISS: prefer small immutable contracts and thin delegating overloads. +- SRP: authoring describes the application; contracts describe executable behavior; Engine activates and owns revisions; DI supplies host dependencies. +- IOC/DIP: component and resource factories receive explicit contexts and use ordinary DI. Do not introduce service locators or static mutable registries. +- Exact identity: executable C# behavior is identified by the exact contract/descriptor/registrar object, not delegate hashing, structural guessing, reflection, or generated IDs. +- Atomic builders: a failed option callback, property projection, handle factory, contract conflict, or validation must not partially mutate the application builder. +- Clear ownership: host-owned services are never disposed by revision snapshots; revision-owned resources and components are disposed exactly once and in deterministic order. +- Flat authoring: normal samples should remain at one fluent level, with at most one component/resource-specific options callback. +- Independent JSON: portable JSON and executable C# are parallel sources for the same Engine, not serializers for one another. +- No feature loss: preserve hot reload, revision rollback, typed predicates, durability, MQTT lifecycle, Fluent fan-out/fan-in/segments, events, completion, and hosting. + +## Current problems + +### 1. Typed handles stop at the runtime boundary + +`ApplicationDefinitionBuilder` produces `InputPortHandle`, `SignalInputPortHandle`, and `OutputPortHandle`, but `ApplicationPorts`, `ApplicationPortRuntime`, durable input enqueue, and durable output capture primarily accept strings or `ApplicationAddress`. Fully code-first callers therefore return to string/address plumbing after authoring. + +### 2. Resources still use split declaration and execution registration + +Code-first MQTT declares broker, retry, subscription, and client resources in the application definition, then separately calls `AddMqtt()` so Engine can discover `MqttCompositionResourceRegistrar`. This is the same split source-of-truth problem that `ComponentContract` removed for components. + +Host-owned external resources also require callers to manually reconstruct address keys or write an `IApplicationResourceRegistrar`, even when a typed `ResourceHandle` already exists. + +### 3. Fluent is a separate execution model + +`FluxFlow.Fluent` currently creates and directly links node instances, then runs them through `ApplicationRuntime.Create`. Canonical code-first applications use `ApplicationDefinitionBuilder`, `ComponentContract`, stable application ports, revisions, resource snapshots, and `FluxFlowApplication`. The two models duplicate lifecycle, completion, hosting, event aggregation, and user concepts. + +### 4. Dynamic registration is too prominent + +`AddRuntimeComponent` sits beside the normal registration APIs even though complete `ComponentContract` declarations are now the intended path. The raw path remains necessary for dynamic plugins and externally selected types, but its current name and placement make it look like a second normal authoring model. + +## Required final public shape + +Exact names may be adjusted only when the implementation proves a name ambiguous, but the semantic surface must remain this small. + +### A. Typed runtime port overloads + +Add typed overloads that delegate to the existing address-based implementation without duplicating runtime logic: + +```csharp +ValueTask SendAsync( + InputPortHandle input, + FlowMessage message, + CancellationToken cancellationToken = default); + +ValueTask SendAsync( + SignalInputPortHandle input, + FlowMessage message, + CancellationToken cancellationToken = default); + +Task> ReceiveAsync( + OutputPortHandle output, + TimeSpan? timeout = null, + CancellationToken cancellationToken = default); + +ValueTask> ObserveAsync( + OutputPortHandle output, + int capacity = 128, + CancellationToken cancellationToken = default); + +Task> SendAndReceiveAsync( + InputPortHandle input, + OutputPortHandle output, + FlowMessage request, + TimeSpan? timeout = null, + CancellationToken cancellationToken = default); +``` + +Add corresponding typed overloads to the low-level runtime attachment surface where semantically valid: + +- `AttachInputAsync(InputPortHandle, ...)`; +- `AttachSignalInputAsync(SignalInputPortHandle, ...)`; +- `GetSignalTarget(SignalInputPortHandle)`; +- `AttachOutput(OutputPortHandle, ...)`. + +Do not add payload-only overloads that silently discard or invent message metadata. `FlowMessage` remains explicit. + +Keep all existing string and `ApplicationAddress` overloads for JSON, dynamic selection, remote/operational tooling, and advanced hosting. + +### B. Typed durability overloads + +Add only the overloads whose port direction and payload type make semantic sense: + +```csharp +ValueTask EnqueueAsync( + InputPortHandle input, + FlowMessage message, + CancellationToken cancellationToken = default); + +DurableOutputRegistrationBuilder Capture( + OutputPortHandle output, + string contractName, + JsonTypeInfo jsonTypeInfo); +``` + +They must delegate to existing address-based behavior and retain all validation, identity, retention, leasing, delivery, and error semantics. + +### C. Typed host resource registration + +Add `ResourceHandle` overloads to the existing explicit DI helpers: + +```csharp +IServiceCollection AddFluxFlowResource( + ResourceHandle resource, + Func factory); + +IServiceCollection AddExternalFluxFlowResource( + ResourceHandle resource, + TService service); +``` + +These overloads use `resource.Address` and remain ordinary keyed DI registration. They must not introduce ownership inference: `AddExternalFluxFlowResource` remains non-owning from the revision snapshot's perspective, while ordinary DI owns services it constructs according to standard DI rules. + +### D. Executable application resource contracts + +Introduce a small `ApplicationResourceContract` family analogous to `ComponentContract`: + +```csharp +public abstract class ApplicationResourceContract +{ + public string Type { get; } +} + +public class ApplicationResourceContract : ApplicationResourceContract + where THandle : AuthoredResourceHandle; + +public class ApplicationResourceContract : ApplicationResourceContract + where TOptions : class + where THandle : AuthoredResourceHandle; +``` + +A contract owns: + +- one normalized portable resource `Type`; +- the explicit option-builder factory when options are needed; +- the explicit option-to-`ResourceDefinitionBuilder` projection; +- the typed handle factory; +- the exact `IApplicationResourceRegistrar` responsible for executing resources of that contract/family. + +The contract must not own a serialized delegate representation, global registration, service-provider instance, or mutable runtime resource. + +Add `AuthoredResourceHandle` as the controlled base for package-specific handles, mirroring `AuthoredComponentHandle`. Existing `ResourceHandle` remains the general typed handle. + +`IResourceDefinitionContainerBuilder`, `ApplicationDefinitionBuilder`, and `ResourceGroupBuilder` must support contract-based resource creation with return-handle and fluent `out var` forms. Normal package extensions continue to provide flat domain names such as `AddMqttBroker`; callers should not normally invoke generic resource-contract APIs directly. + +Resource addition must be atomic: + +1. validate name and contract; +2. construct options; +3. run the caller's options callback; +4. project properties into a temporary definition builder; +5. validate the portable `ResourceInstanceDefinition`; +6. create the typed handle; +7. validate contract compatibility against contracts already captured by the application; +8. commit the resource entry and contract together. + +Any exception before the final commit leaves both resource entries and captured contracts unchanged. + +### E. Definition-owned resource contracts + +`ApplicationDefinition` gains a read-only runtime-only collection of exact application resource contracts. This collection: + +- is populated only by compiled-C# contract authoring; +- is empty for the public portable constructor and JSON deserialization; +- is excluded from JSON serialization; +- is copied defensively and ordered deterministically; +- deduplicates reuse of the exact same contract reference; +- rejects different contracts claiming the same resource type; +- never serializes registrars, factories, delegates, handles, or CLR types. + +Canonical JSON must remain exactly `Resources` plus `Workflows`; first-class code-only links and executable component/resource contracts remain excluded. + +### F. Engine registrar merge and revision semantics + +For every candidate revision, Engine computes one effective resource-registrar set from: + +- host-registered `IApplicationResourceRegistrar` instances; and +- registrars carried by definition-owned application resource contracts. + +Rules: + +- exact registrar reference reuse is idempotent; +- deterministic ordering is required; +- no reflection or registrar-type scanning; +- different contracts for the same resource type conflict before activation; +- code-first definition registrars are candidate-revision inputs, not mutations of the root service collection; +- JSON definitions have no embedded registrars and therefore continue to rely on explicit package registration such as `.AddMqtt()`; +- a failed candidate does not alter the active revision or dispose its resources; +- successful replacement disposes the retired revision-owned resources exactly once; +- host-owned fallback services are never disposed by Engine; +- changing an exact resource contract while keeping identical portable properties must still be visible to revision planning for resources of that type and their dependent workflows; +- removed code-first contracts and captured registrar closures become collectible after successful retirement. + +### G. MQTT migration + +Expose one complete contract for each MQTT application resource type: + +- broker; +- retry policy; +- subscription; +- client. + +The resource contracts may share the exact same stateless MQTT registrar instance. `AddMqtt()` must register that exact registrar for JSON/configuration hosts and register the official component contracts, preserving Designer metadata and all MQTT resource validation. + +The code-first MQTT authoring extensions must add these contracts to the definition. A code-first application that uses only embedded MQTT component/resource contracts must run with: + +```csharp +services.AddFluxFlow(definition); +``` + +It must not require a second `.AddMqtt()` call. A JSON/configuration application must still call `.AddMqtt()` explicitly. + +External MQTT controller resources remain explicitly host supplied, but should use the typed `AddExternalFluxFlowResource(resourceHandle, controller)` helper instead of a custom sample registrar. + +Preserve: + +- logical client ownership and controller lifetimes; +- broker, retry, subscription, and client validation; +- keyed resource addresses; +- reconnect behavior; +- acknowledgement behavior; +- subscriptions and publish behavior; +- configuration conversion; +- Designer metadata; +- exact error diagnostics. + +### H. Fluent consolidation + +Retain the concise public authoring features: + +- `Flow.From`; +- `Then`; +- `Tap`; +- `Branch`; +- shared-node fan-in; +- `FlowSegment` and `Apply`; +- `To`; +- `OnEvent`; +- `StartAsync`, `StopAsync`, `Completion`, and `DisposeAsync`; +- Generic Host integration. + +Replace the internal direct-link/runtime path: + +- `FlowGraphBuilder` must build one canonical `ApplicationDefinitionBuilder` and one workflow; +- every unique node instance becomes one explicit instance-backed component contract with deterministic internal component/type/port names; +- main inputs and outputs become descriptor ports and typed definition links; +- shared node references map to one component, preserving fan-in; +- `Tap` maps to an additional canonical link while retaining the main continuation; +- arbitrary branch output blocks are adapted through a small explicit internal non-owning port-source component when they are not already a known canonical output; do not use reflection to discover a property owner; +- node event streams are attached explicitly to one owned aggregate so `FlowGraph.Events` and `OnEvent` retain their current `FlowEvent` behavior; +- the resulting `FlowGraph` wraps an owned `FluxFlowApplication` and owned service-provider scope, not `ApplicationRuntime.Create`; +- `FlowGraph` exposes the canonical `ApplicationDefinition` and `FluxFlowApplication` for inspection instead of exposing the old parallel `ApplicationRuntime`; +- start activates the canonical application revision; +- stop completes entry nodes, waits for graph drain, and stops the application; +- disposal is idempotent, releases subscriptions, disposes the canonical application/provider once, and never double-disposes shared nodes; +- no hot-reload promise is added to instance-backed Fluent graphs; the canonical application object is used for lifecycle and inspection, while already-constructed node instances remain single-use. + +After migration, `FluxFlow.Fluent` must no longer call `ApplicationRuntime.Create`, manually own direct Dataflow links, or maintain a second completion/lifecycle algorithm that competes with Engine. + +`FluxFlow.Fluent.Hosting` may remain as a compatibility feature package, but it must host the canonical-backed `FlowGraph`; it must not restore a separate runtime. + +### I. Advanced dynamic registration + +Keep dynamic/plugin registration through an explicit advanced entry point, for example: + +```csharp +services.AddFluxFlowComponents() + .Advanced + .AddDynamicComponent("dynamic.transform", component => { ... }); +``` + +Required behavior: + +- introduce a small `AdvancedFluxFlowRegistrationBuilder` owned by `FluxFlowRegistrationBuilder`; +- expose it through a read-only `Advanced` property; +- move/rename `AddRuntimeComponent` to `AddDynamicComponent` on the advanced builder; +- remove the old normal-surface `AddRuntimeComponent` API and migrate repository-owned callers; +- keep `RuntimeComponentRegistrationBuilder` because complete contracts use it to describe factories and ports; +- keep `UseInstanceFactory` as the explicit low-level binding escape hatch used by Fluent's instance adapter and truly dynamic registrations; +- do not create obsolete forwarding aliases; +- normal samples and getting-started docs must not mention the advanced path except in a clearly labeled advanced section. + +### J. Public API and overload discipline + +- Do not remove the user-approved `Connect` and `ConnectTo` alternatives. +- Do not merge JSON string conditions with C# delegates. +- Do not add callback-style `AddWorkflow` nesting. +- Do not introduce payload-only send shortcuts in this goal. +- Do not proliferate duplicate overloads beyond typed handle/address/string boundaries with distinct purposes. +- Keep package-specific options and handles package-specific. +- Prefer immutable state and init-only/record options where already established; do not force mutable `IOptions` semantics into application definitions. + +## Explicit non-goals + +- Serializing C# predicates, factories, registrars, contracts, handles, or node instances. +- Reconstructing executable contracts when JSON is deserialized. +- Assembly scanning, reflection-based discovery, source-generated global registration, or static mutable registries. +- Automatically installing packages or discovering MQTT from resource type strings. +- Moving backend, MQTT, durability, or resource settings into `FluxFlowApplicationOptions`. +- Changing canonical address syntax or portable JSON property names. +- Replacing `FlowMessage` with raw payloads. +- Changing durable delivery guarantees, schemas, lease semantics, retention, or storage providers. +- Changing component processing profiles or port cardinality semantics. +- Publishing packages, creating a release, pushing a branch, or creating a pull request. + +## Implementation phases + +### Phase 1: typed runtime and durability handles + +1. Add typed overloads to `ApplicationPorts`. +2. Add typed attachment/signal/output overloads to `ApplicationPortRuntime` only where the low-level API already has the equivalent address operation. +3. Add typed durable input enqueue and durable output capture overloads. +4. Add typed resource DI overloads. +5. Delegate all behavior to existing address methods. +6. Migrate code-first samples/docs to retain and use typed handles. +7. Keep address and string regression tests. + +### Phase 2: executable application resource contracts + +1. Add `AuthoredResourceHandle` and the contract types. +2. Add a shared application-level contract collection. +3. Extend resource containers with atomic contract-based additions. +4. Capture contracts in `ApplicationDefinition`. +5. Keep JSON projection unchanged. +6. Merge embedded and host registrars per revision. +7. Update revision planning for resource-contract identity. +8. Prove rollback, retirement, ownership, and collectible closure behavior. +9. Add typed host external-resource registration. + +### Phase 3: MQTT contract migration + +1. Create the four complete MQTT resource contracts. +2. Reuse one exact stateless registrar. +3. Update all MQTT resource authoring extensions. +4. Make `.AddMqtt()` the explicit JSON/configuration registration path. +5. Remove duplicate `.AddMqtt()` from the code-first sample path. +6. Replace the sample registrar for external client binding with typed DI registration. +7. Verify configuration and code-first outputs remain equivalent. + +### Phase 4: Fluent canonicalization + +1. Add the Engine dependency required by the canonical runner. +2. Replace direct node/link accumulation with canonical component registrations and definition links. +3. Preserve deterministic node identity and shared-node fan-in. +4. Add the explicit branch-port adapter. +5. Preserve FlowEvent aggregation without reflection. +6. Rebuild `FlowGraph` around `FluxFlowApplication` and an owned provider. +7. Remove the `ApplicationRuntime` exposure and direct-create path. +8. Keep Fluent.Hosting behavior over the canonical-backed graph. +9. Update samples and package acceptance. + +### Phase 5: advanced API separation + +1. Introduce the advanced registration builder. +2. Rename/move raw registration to `AddDynamicComponent`. +3. Migrate dynamic fixtures, tests, and advanced documentation. +4. Add public-surface guards preventing `AddRuntimeComponent` from returning. + +### Phase 6: governance and documentation + +Update at minimum: + +- root `README.md`; +- Composition, Engine, Fluent, Fluent.Hosting, and MQTT READMEs; +- getting started; +- definitions and links; +- hosting and observability; +- durable input/output documentation; +- public API overview; +- typed code-first authoring; +- unified component contracts; +- canonical migration guidance; +- release validation; +- docs index; +- package-consumer acceptance source/script assertions; +- public API baseline; +- `memory/00-index.md`; +- `memory/01-current-state.md`; +- a new memory record for this goal. + +Document the two intentionally independent paths: + +| Source | Portable definition | Embedded executable contracts | Required host registration | +|---|---:|---:|---| +| Compiled C# | Yes | Component and resource contracts used by the builder | Ordinary host dependencies only | +| JSON/configuration | Yes | None | Explicit component/resource family registration | + +## Required tests and evidence + +Use existing xUnit and Shouldly conventions. The dedicated testing agent owns test implementation and `.testagent` artifacts. + +### Typed ports + +- typed send reaches the same input and returns the same result as address send; +- typed signal send preserves signal behavior; +- typed receive/observe/request-reply use exact generic payload types; +- typed attach input/signal/output delegates to the same runtime port; +- null handles, unavailable revisions, completion, cancellation, timeout, and wrong-address regression behavior remain deterministic; +- string and `ApplicationAddress` overloads remain present and green. + +### Durability + +- typed durable enqueue preserves message identity and address key; +- typed durable capture preserves exact output address, contract identity, and JSON type info; +- input handles cannot be used for capture and output handles cannot be used for enqueue at compile time/source-surface level; +- all existing provider conformance suites remain green. + +### Resource contracts + +- construction validates type, factories, projections, handles, and registrar; +- exact contract reuse deduplicates; +- distinct contracts for the same type conflict; +- nested resource groups share one contract collection; +- failed options/projection/handle/conflict operations are atomic; +- JSON omits contracts and deserialization produces none; +- portable JSON round-trips unchanged; +- Engine executes embedded registrars without host registration; +- exact host+definition registrar reuse is idempotent; +- candidate conflicts fail before active revision mutation; +- add/remove/replace contract revisions are detected; +- failed replacement retains the active resource generation; +- successful replacement disposes retired revision resources and releases captured closures; +- host fallback resources are not disposed by Engine. + +### MQTT + +- all four resource authoring extensions capture the expected exact contract; +- code-first MQTT runs without `.AddMqtt()`; +- JSON/configuration MQTT still requires and succeeds with `.AddMqtt()`; +- exact mixed registration deduplicates; +- external typed resource registration resolves by the resource handle address; +- broker/retry/subscription/client validation remains unchanged; +- MQTT configuration and code-first sample outputs remain equivalent. + +### Fluent + +- linear pipeline behavior remains identical; +- `Tap` fan-out preserves the main continuation; +- arbitrary branch ports work without reflection; +- shared node fan-in completes only after all upstreams; +- reusable segments build fresh nodes per graph; +- null/invalid builder guards remain; +- events are observed from the first active message and throwing handlers remain isolated; +- completion faults for node failures; +- start/stop/dispose are idempotent and dispose each shared node once; +- `FlowGraph.Definition` contains the canonical workflow, components, links, and descriptors; +- `FlowGraph.Application` is the canonical application; +- source-shape tests prove `ApplicationRuntime.Create` and manual Dataflow linking are absent from `FluxFlow.Fluent`; +- Fluent.Hosting still builds, starts, stops, and supports multiple graphs. + +### Advanced surface + +- normal `FluxFlowRegistrationBuilder` exposes `Advanced`; +- `AddDynamicComponent` exists only on the advanced builder; +- `AddRuntimeComponent` is absent from public source/baseline; +- dynamic factory, raw instance binding, validation, cleanup, and duplicate behavior remain green; +- normal samples contain no advanced registration. + +### Package and repository gates + +- package-only consumer exercises typed runtime handles, embedded resource contracts, canonical-backed Fluent, JSON explicit registration, durability restart, and advanced dynamic registration where appropriate; +- exact package closure remains correct; +- all public API baseline and family/convention tests pass; +- focused project tests pass with zero warnings; +- full Release solution build passes with zero warnings and errors; +- full solution tests pass with no failures or skips; +- dedicated Release tests pass; +- `dotnet format --verify-no-changes` passes; +- `git diff --check` passes; +- vulnerability audit reports no vulnerable direct or transitive packages; +- scans find no reflection/scanning/global registry, obsolete `AddRuntimeComponent`, normal-sample advanced APIs, TODO/FIXME, or skipped tests in the touched slice. + +## Acceptance criteria + +The goal is complete only when all of the following are true: + +1. A code-first caller can author components and use the same typed handles for runtime and durability operations without reconstructing addresses. +2. A code-first MQTT definition runs without a duplicate `.AddMqtt()` registration. +3. A JSON/configuration MQTT application remains portable and succeeds through explicit `.AddMqtt()` registration. +4. Resource contract addition and Engine activation are atomic, revision-aware, deterministic, and lifecycle-correct. +5. `FluxFlow.Fluent` retains its user-visible composition features but no longer creates `ApplicationRuntime` or manually owns a second direct-link runtime. +6. Dynamic registration remains available through an obviously advanced surface, while the old normal `AddRuntimeComponent` API is removed. +7. No reflection, assembly scanning, delegate serialization, global mutable registry, or hidden package discovery is introduced. +8. Existing component contracts, JSON, hot reload, durability, MQTT, Designer metadata, and package behavior remain intact. +9. Samples, documentation, public API baseline, goal evidence, and memory describe the final implementation accurately. +10. Every required focused and repository-wide verification gate is green. + +## Completion evidence + +Completed on 2026-08-08. + +### Implemented boundaries + +- Typed runtime operations were added in `ApplicationPorts` and + `ApplicationPortRuntime`; durable input/output and resource DI helpers now + accept the matching typed handles and delegate to the existing address-based + implementations. +- `ApplicationResourceContract`, `ApplicationResourceContractCollection`, and + `AuthoredResourceHandle` make compiled-C# resources executable definition + inputs. `ApplicationDefinition.ApplicationResourceContracts` is immutable, + runtime-only, and excluded from portable JSON. +- Engine merges explicit host registrars and definition-owned registrars by + exact registration identity for each candidate revision. Planning, rollback, + replacement, disposal, host fallback, and captured-closure retirement are + covered without changing JSON semantics. +- MQTT exposes four resource contracts backed by one stateless registrar. + Code-first MQTT runs from `AddFluxFlow(definition)`; configuration-driven + MQTT retains explicit `.AddMqtt()` registration. The sample demonstrates and + executes both paths. +- `FluxFlow.Fluent` now compiles graphs to a canonical + `ApplicationDefinition` and runs an owned `FluxFlowApplication`. Its prior + parallel `ApplicationRuntime.Create` path is absent while linear flows, + branching, fan-in, taps, segments, events, errors, completion, and hosting + remain available. +- A deterministic topological drain plan preserves finite-source delivery in + acyclic canonical graphs; cyclic graphs keep the coordinated fallback. +- Raw registration moved to + `AddFluxFlowComponents().Advanced.AddDynamicComponent(...)`; the normal + `AddRuntimeComponent` surface and forwarding aliases were removed. +- Samples, package acceptance, public API baseline, documentation, docs index, + current-state memory, and this decision record describe the final two-path + model. + +### Requirement evidence + +| Requirement | Evidence | +|---|---| +| Typed send, signal, receive, observe, request/reply, and attachment | `ApplicationPortHandleTests.Typed_handles_send_receive_observe_and_request_through_their_exact_addresses`; `Typed_handle_attachments_bind_message_signal_and_output_to_exact_runtime_ports`; complete Engine suite | +| Typed durable enqueue and capture | `DurableApplicationInputsTests.Typed_input_handle_enqueue_uses_exact_address_contract_and_cancellation`; `DurableOutputRegistrationTests.Typed_output_handle_capture_uses_exact_address_type_and_atomic_conflict_rules` | +| Atomic, exact-identity resource authoring and JSON omission | `TypedCodeFirstResourceAuthoringTests` and `ApplicationDefinitionJsonTests.Code_first_resource_contracts_are_omitted_from_json_and_deserialization_is_contract_free` | +| Resource execution, revision rollback, ownership, and retirement | `ApplicationResourceContractRuntimeTests`, including code-first activation, exact registrar dedupe, replace/remove, failure rollback, disposal, and closure retirement | +| MQTT code-first without duplicate registration; JSON explicit registration | `MqttServiceCollectionExtensionsTests.Code_first_definition_embeds_mqtt_components_and_resources_without_AddMqtt`; existing configuration registration tests; successful MQTT sample execution through both paths | +| Canonical Fluent behavior without a parallel runtime | `FlowBuilderTests`, `FlowObservationTests`, `FlowGraphHostingTests`, and Release source-governance facts; 21 Fluent and 5 Fluent.Hosting focused tests passed | +| Advanced-only dynamic registration | `FluxFlowRegistrationBuilderTests`, `RuntimeComponentBindingBuilderTests`, Engine raw-instance validation, and Release public/source surface assertions | +| Official package/family completeness | Release 19-family/44-contract convention and matrix tests; accepted public API baseline | +| Package-only execution and cleanup | `PackageConsumerAcceptanceScriptTests.Acceptance_script_pack_mode_cleans_owned_source_and_workdir_after_success`; every JSON, code-first, resource, Fluent, durability, seed/recovery, and completion marker occurred exactly once, all 14 expected child invocations ran, and both owned temporary directories were removed | + +### Verification results + +| Gate | Result | +|---|---| +| Focused Composition | 160 passed, 0 failed/skipped, 0 warnings | +| Focused Engine | 130 passed, 0 failed/skipped, 0 warnings; deterministic replacement lifetime pair 2/2 | +| Focused DurableInput / DurableOutput | 157 / 181 passed, 0 warnings | +| Focused Fluent / Fluent.Hosting | 21 / 5 passed, 0 warnings | +| Focused MQTT Composition | 23 passed, 0 warnings | +| Focused Release governance, docs, source, and package facts | 41 + 5 + 2 passed, 0 warnings | +| Public API baseline | 2 passed after intentional baseline acceptance; stable in the full Release run | +| Real isolated package-consumer pack gate | 1 passed, 0 warnings; exact markers/invocations and cleanup verified | +| MQTT sample | Both configuration and code-first definitions published the two expected messages | +| `dotnet build FluxFlow.sln -c Release --no-restore --nologo` | 134 projects, 0 errors, 0 warnings | +| `dotnet test FluxFlow.sln -c Release --no-build --no-restore --nologo` | 2,627 passed in 66 projects, 0 failed, 0 skipped, 0 warnings | +| Dedicated `FluxFlow.Release.Tests` | 179 passed, 0 warnings | +| `dotnet format FluxFlow.sln --verify-no-changes --no-restore --severity warn` | Passed | +| Vulnerability audit, direct and transitive | No vulnerable packages in any solution project | +| `git diff --check` | Passed | + +The final source scan found no current normal-surface +`AddRuntimeComponent`, no `ApplicationRuntime.Create` use in +`FluxFlow.Fluent`, no reflection/scanning/global executable registry in the new +authoring path, and no new TODO/FIXME, skipped test, or arbitrary sleep in the +touched slice. The one `ComponentAuthoringContract` documentation occurrence is +intentional migration text naming the removed API. diff --git a/goals/2026-08-08-release-candidate-consolidation/README.md b/goals/2026-08-08-release-candidate-consolidation/README.md new file mode 100644 index 00000000..15e6da14 --- /dev/null +++ b/goals/2026-08-08-release-candidate-consolidation/README.md @@ -0,0 +1,499 @@ +# Goal: Consolidate FluxFlow into a clean release candidate and prove both consumer paths + +- Date: 2026-08-08 +- State: active +- Scope: accumulated code-first, JSON, resource, durability, health, performance, package, sample, documentation, and release-validation changes +- Compatibility: freeze the intended public API and portable JSON format; remove only obsolete or contradictory material already superseded by the accepted design +- Publication: no push, pull request, tag, release, or package publication without a separate explicit user request + +## Objective + +Turn the accumulated FluxFlow work into one coherent, distributable, and +independently consumable release candidate. + +This is a consolidation and proof round, not a feature-development round. The +repository already contains the intended core capabilities: + +- typed, flat C# application authoring; +- portable JSON application definitions and hot reload; +- complete component contracts and typed port handles; +- executable code-first application resource contracts; +- canonical Engine execution for both code-first and Fluent applications; +- explicit advanced dynamic registration; +- optional durable input and durable output packages; +- optional application readiness integration; +- deterministic lifecycle, revision, rollback, drain, and ownership behavior; +- a permanent Engine benchmark baseline and focused concurrency hardening. + +The purpose of this goal is to make those capabilities read, build, package, +install, run, and operate as one trustworthy product surface. + +The decisive outcome is: + +> A new developer can restore only locally packed FluxFlow packages and build +> and run either a typed C# application or a JSON-defined application without +> project references, internal repository knowledge, duplicate code-first +> registration, reflection-driven discovery, or undocumented setup. + +## Architectural principles + +- **KISS:** prefer one obvious normal path for each authoring mode and keep + advanced escape hatches visually separate. +- **SRP:** authoring builds definitions, contracts carry executable code-first + behavior, Engine owns execution and revisions, optional packages own their + integrations, and the host owns external process configuration. +- **IOC/DIP:** factories receive explicit contexts and ordinary dependency + injection. Do not add service locators, assembly scanning, static mutable + registries, or hidden global state. +- **No magic:** no reflection dispatch, convention-only activation, generated + runtime IDs, delegate hashing, or inferred ownership. +- **Flat normal API:** normal C# code-first composition should remain at one + fluent level, with at most one component- or resource-specific options + callback. +- **Independent authoring paths:** C# and JSON are two inputs to the same + Engine. The C# builder is not constrained by JSON serialization. JSON remains + portable and does not embed executable delegates or runtime objects. +- **Exact ownership:** host-owned services are never disposed by a revision; + revision-owned components and resources are disposed exactly once. +- **Evidence before change:** do not alter runtime behavior, allocation, or + synchronization without a reproduced defect or focused measurement. +- **Small dependency graph:** prefer the BCL and the existing package set. Do + not add a new runtime dependency in this round. + +## Frozen supported product paths + +### 1. Typed C# code-first path + +The normal compiled-C# path is: + +1. select package-owned `ComponentContract` and + `ApplicationResourceContract` declarations; +2. build an `ApplicationDefinition` with `ApplicationDefinitionBuilder` or the + canonical `FluxFlow.Fluent` facade; +3. capture typed component/resource/port handles during authoring; +4. connect typed ports with `ConnectTo` or the workflow/application `Connect` + methods, including C# predicates where required; +5. call `services.AddFluxFlow(definition)` once; +6. start or host the resulting `FluxFlowApplication`; +7. use the same typed handles at the runtime and durability boundaries. + +The definition owns the exact executable component/resource contracts used by +this path. A code-first consumer must not repeat ordinary component or resource +registration solely to make the authored definition executable. + +### 2. Portable JSON path + +The normal configuration path is: + +1. deserialize a portable `ApplicationDefinition` from JSON; +2. explicitly register the package component/resource behavior referenced by + portable type names; +3. call `services.AddFluxFlow(definition)`; +4. start, host, or reload the same `FluxFlowApplication` runtime. + +JSON must remain free of delegates, CLR types, service providers, contract +instances, runtime resource objects, and code-first predicate identities. +Portable JSON loading, validation, persistence, and hot reload must continue to +work without requiring the C# builder. + +### 3. Advanced dynamic path + +Dynamic registration remains available only through the explicit advanced +surface. It must not compete with complete `ComponentContract` authoring in +normal samples or getting-started documentation. + +## Current accepted baseline + +The immediately preceding hardening round established: + +- a non-packable `FluxFlow.Engine.Benchmarks` project with eight real Engine + scenarios; +- equivalent typed and addressed request allocation in the recorded baseline; +- an approximately 18.7 percent allocation reduction in the eight-hop typed + pipeline; +- deterministic concurrent request, compatible revision, rejected revision, + graceful drain, and disposal tests; +- complete Engine tests: 134 passed, zero warnings; +- complete Release tests: 189 passed, zero warnings; +- complete solution tests: 2,673 passed across 67 test projects, zero warnings; +- solution build: 137 project targets, zero errors, zero warnings; +- a clean dependency vulnerability and formatting audit. + +These are the starting facts. This goal must preserve them and add clean, +packed-package, release-candidate evidence rather than reinterpret them. + +## Non-goals + +Do not add or redesign: + +- workflow semantics, scheduling, or delivery guarantees; +- component package families; +- application-definition fields or JSON schema; +- public configuration callbacks or options merely for future flexibility; +- another registration abstraction; +- another runtime, Fluent execution model, or host lifecycle model; +- another health, metrics, or telemetry framework; +- persistence engines, ORMs, provider abstractions, or generic repositories; +- background polling, caching, pooling, retries, or unbounded workers; +- reflection, assembly scanning, dynamic proxying, source generation, or + convention-based activation; +- speculative optimization of link compilation or message routing; +- the synchronous rejection-to-system-event backpressure behavior without + focused contention evidence; +- package versions, tags, releases, or publication. + +Do not retain obsolete aliases merely for backward compatibility when the +accepted breaking-change goals already replaced them. Conversely, do not +remove a supported public or JSON capability merely to reduce line count. + +## Phase 1: Preserve and inventory the accumulated work + +Before editing implementation: + +1. record the exact branch, head, and working-tree inventory; +2. distinguish tracked modifications, tracked deletions, and untracked files; +3. verify that untracked files are intended source, test, benchmark, goal, + documentation, or memory artifacts rather than build output, results, + databases, credentials, secrets, caches, editor state, or logs; +4. inspect repository-level instructions, central package management, solution + membership, package manifest, public API baseline, CI, publication workflow, + package acceptance runner, and real-provider runners; +5. query the existing repository knowledge graph before doing manual + relationship discovery; +6. preserve all unrelated user changes and never use destructive reset or + checkout operations; +7. create a neutral work branch before recording commits so the accumulated + work is not committed directly on `main`. + +## Phase 2: Consolidate the product surface + +Perform a bounded review of the files changed by the accepted recent goals. + +### Public API and registration + +- Confirm the accepted public API baseline matches the intended typed + code-first, JSON, health, durability, Fluent, and advanced registration + surfaces. +- Confirm normal documentation and samples use `ComponentContract` and + `ApplicationResourceContract`, not retired authoring-contract names. +- Confirm code-first definitions execute embedded component/resource contracts + without duplicate ordinary service registration. +- Confirm JSON applications still resolve executable package registrations by + portable type name. +- Confirm raw runtime component registration is available only from the + explicit advanced surface. +- Confirm typed handle overloads delegate to the same address-based runtime and + durability implementation rather than creating parallel logic. +- Confirm component events are explicit named output ports and that declaration + terminology remains `HasInput`, `HasSignalInput`, `HasOutput`, and + `HasEvents`. +- Remove only declarations, aliases, samples, or documentation that contradict + this frozen surface. + +### Application definition and JSON + +- Confirm portable definition equality, revision planning, and JSON round trips + exclude executable contract collections and C# predicates. +- Confirm C#-authored definitions retain exact executable contract identity for + revision decisions and lifetime ownership. +- Confirm first-class links preserve local, cross-workflow, fan-out, signal, + unconditional, portable condition, and C# predicate behavior. +- Confirm failed construction and failed revision preparation remain atomic and + do not partially mutate or activate the application. +- Do not add C#-to-JSON export as a required code-first feature. + +### Packages and dependency closure + +- Reconcile `eng/packages.json`, central package versions, project references, + package READMEs, changelog entries, and public API baseline identities. +- Every packable project must have intentional target frameworks, package + metadata, repository-local dependencies, and package documentation. +- The benchmark project and every test/sample project must remain non-packable. +- The package-only consumer must have no `ProjectReference` and must restore + FluxFlow packages only from the isolated candidate source. +- Microsoft/framework dependencies may come from the explicitly configured + public dependency source; FluxFlow candidates must resolve to exact locally + packed bytes. +- No package may gain an accidental dependency on Designer, MQTT, durability, + health checks, a database provider, or a benchmark package. + +### Samples and documentation + +- Keep one compact canonical C# sample that demonstrates application/resource + construction, typed handles, typed connections, registration, start, message + exchange, and stop. +- Keep one compact JSON sample that demonstrates portable loading and the + explicit package behavior registration needed by JSON. +- Keep Fluent as a concise facade over the canonical definition/application + runtime, not a second runtime. +- Ensure README and docs distinguish code-first embedded contracts from JSON + explicit registration in the first relevant section. +- Ensure advanced dynamic registration is documented separately and not shown + as the normal path. +- Ensure health, durability, observability, delivery guarantees, and operational + limits are stated honestly and consistently. +- Remove stale snippets, names, duplicate setup, and references to deleted + types; do not expand prose merely to repeat existing documents. + +## Phase 3: Strengthen release-candidate acceptance evidence + +Reuse the existing package-consumer acceptance fixture and runner. Do not create +a competing harness. + +The isolated package consumer must prove, from package references only: + +### Typed C# scenario + +- build a definition from complete component contracts; +- capture typed handles with the flat fluent API; +- use at least one definition-owned application resource contract; +- connect typed output and input handles; +- register the definition once with `AddFluxFlow` and no duplicate normal + component/resource registrar call; +- start the real Engine; +- send and receive through typed runtime handles; +- prove the exact transformed value and metadata/trace behavior; +- stop and dispose cleanly; +- emit one exact code-first success marker. + +### JSON scenario + +- deserialize a portable definition from JSON; +- register the corresponding executable component behavior explicitly; +- start the same Engine runtime; +- send and receive through the portable/addressed boundary; +- prove the exact transformed value; +- prove a compatible JSON reload is applied or unchanged as intended; +- prove an invalid candidate is rejected while the active route remains usable; +- stop and dispose cleanly; +- emit one exact JSON success marker. + +### Existing acceptance preservation + +Preserve and continue proving: + +- exact candidate package closure and archive hashes; +- health-check registration and safe readiness metadata; +- canonical Fluent execution; +- SQL-file durable input and output behavior; +- restart seed/recovery, abandoned lease recovery, pending output resumption, + captured workflow output, and receipt idempotency; +- exact marker multiplicity; +- isolated restore/build/run; +- rejection of project or non-candidate resolution; +- deterministic owned temporary source/work-directory cleanup on success and + failure. + +Tests must assert the fixture source, package graph, runner behavior, failure +cleanup, and real pack-mode execution. Use xUnit and Shouldly. Avoid sleeps, +polling, retry-until-pass, elapsed-time performance assertions, and fragile +test-order dependence. + +## Phase 4: Create a coherent local release-candidate history + +After the working tree is audited and focused validation is green: + +1. create or use a neutral branch named for release-candidate consolidation; +2. stage only audited intended files; +3. scan new names and user-facing text for neutral repository terminology; +4. prefer a small number of coherent commits over artificial file-type commits; +5. every implementation commit should represent an internally understandable + state; do not manufacture a split that knowingly leaves an intermediate + public surface incoherent; +6. keep the final validation/memory closeout separate when that produces a + clearer audit trail; +7. do not rewrite, squash, push, open a pull request, tag, release, or publish. + +An acceptable shape is: + +1. one authoritative accumulated implementation commit for the already agreed + code-first/JSON/durability/health/performance surface; +2. one release-candidate validation/governance correction commit if validation + discovers test, script, package, sample, or documentation defects; +3. one final evidence record commit. + +If a smaller logical split can be proven buildable without risky history +surgery, it may be used. Do not split merely to increase commit count. + +## Phase 5: Clean committed-snapshot validation + +Create a detached temporary worktree from the exact candidate commit. Resolve +its absolute path and keep every owned temporary path outside the main working +tree. Run all validation from that clean snapshot so untracked source or stale +build output cannot satisfy a gate accidentally. + +Required clean-snapshot gates: + +1. report the exact SDK selected by `global.json`; +2. restore the solution; +3. build the Release solution with zero warnings and zero errors; +4. run the complete solution test suite with zero failures, skips introduced by + this round, or warnings; +5. run the complete Release governance test project; +6. execute the package-consumer acceptance script in real pack mode; +7. verify the isolated consumer contains no project references and resolves + exact candidate package bytes; +8. run the canonical executable samples from the intended build output; +9. run public API baseline acceptance; +10. run solution-wide formatting verification; +11. run whole-worktree whitespace/diff verification; +12. audit direct and transitive packages for known vulnerabilities; +13. run the real durable-input T-SQL integration runner; +14. run the real durable-output T-SQL integration runner; +15. verify both runners execute all expected tests with zero skips and clean up + owned containers/resources; +16. verify the clean worktree remains clean apart from ignored build output; +17. remove the temporary worktree through Git, prune it, and verify its exact + path no longer exists. + +External provider gates may stop only for a genuine environment/permission +blocker. They must not be silently skipped or replaced by SQL-file tests. Never +print or persist full connection strings, credentials, secrets, or container +environment values. + +## Test-generation workflow + +Use the repository testing workflow before writing any new tests: + +1. record a bounded inventory and requirement checklist in + `.testagent/research.md`; +2. run the static source/test pairing analyzer exactly once for this goal; +3. map every required new assertion to an exact planned test in + `.testagent/plan.md`; +4. add tests only for material missing evidence; +5. compile and run the narrowest relevant project during correction cycles; +6. audit assertion strength and pseudo-mutation gaps; +7. record exact results and a `Requirement | Evidence` map in + `.testagent/status.md`; +8. run broad validation once after focused lanes are green. + +Tests must preserve the existing framework and assertion style. Do not add a +test framework, mocking library, coverage package, test-only production hook, +or InternalsVisibleTo solely for this round. + +## Required audits + +### Public surface + +- accepted public API baseline is unchanged except for already approved recent + additions; +- no obsolete authoring-contract or normal raw-registration alias remains; +- no accidental public helper, marker, runtime implementation, mutable + collection, delegate identity, or reflection helper is exposed; +- XML/package documentation and README snippets compile against the public + packages. + +### Complexity and dependency + +- no new runtime package dependency; +- no assembly scan, reflection dispatch, service locator, static mutable + registry, unbounded channel/queue, polling worker, or hidden retry; +- code-first and JSON converge on `FluxFlowApplication` rather than separate + runtime implementations; +- normal and advanced registration remain visibly separate; +- no provider details leak into core Composition or Engine; +- benchmark code remains outside shipped packages. + +### Ownership and lifecycle + +- revision-owned factories/resources/nodes are retired and disposed exactly + once; +- host-owned dependencies remain non-owned by revision snapshots; +- rejected candidates leave the prior active route operational; +- reload and stop preserve deterministic drain/cancellation semantics; +- package-consumer processes and temporary directories are bounded and cleaned. + +### Privacy and diagnostics + +- package and health output contains only bounded operational identifiers; +- no payloads, connection strings, exception objects, secrets, or arbitrary + diagnostic details are exposed through readiness or validation logs; +- marker output is exact, stable, and asserted once. + +## Documentation and memory deliverables + +Update only the authoritative documents needed to describe the final result: + +- root `README.md` if the first-use distinction between C# and JSON is not + already clear; +- `docs/01-getting-started.md` for the two supported entry paths; +- `docs/02-definitions-and-links.md` for portable versus code-first link rules; +- `docs/05-hosting-and-observability.md` for lifecycle/readiness boundaries; +- `docs/14-public-api-overview.md` for the final package/API surface; +- `docs/38-release-validation.md` for exact clean-candidate commands and + package-consumer markers; +- `docs/README.md` index if a new closeout document is added; +- package-local READMEs and samples only when a stale or contradictory snippet + is proven; +- `memory/00-index.md` and `memory/01-current-state.md`; +- new `memory/304-release-candidate-consolidation.md` containing decisions, + changes, exact commands/results, commit hashes, clean-worktree path and + cleanup, provider evidence, remaining risks, and no-publication statement. + +Do not duplicate the full implementation history. Link to the accepted detailed +documents for typed authoring, unified contracts, end-to-end code-first +simplification, health readiness, and performance hardening. + +## Acceptance criteria + +The goal is complete only when all of the following are true: + +1. The goal exists in this README and its state is `complete`. +2. The accumulated working tree has been audited; no unintended generated, + credential, database, log, result, cache, or editor artifact is committed. +3. The intended changes are recorded on a neutral local branch in coherent + commits. +4. The public API baseline and portable JSON shape are frozen and accepted. +5. Normal C# code-first use requires one definition registration and no + duplicate ordinary component/resource registration. +6. Portable JSON use remains explicit, serializable, reloadable, and executable + through package registration. +7. The isolated packed-package consumer proves both paths with exact outputs + and marker multiplicity, plus all previously accepted health, Fluent, + durability, restart, hash, and cleanup behavior. +8. No package-only consumer project reference or non-candidate FluxFlow package + resolution is possible. +9. Complete Release build and tests are warning-free and green from the exact + committed clean snapshot. +10. Public API, package manifest, archive, dependency, vulnerability, + formatting, and whitespace gates are green. +11. Real durable-input and durable-output T-SQL runners execute with zero skips + and clean up their owned infrastructure. +12. Canonical samples build and run through their intended paths. +13. Documentation and memory describe the final supported paths and exact + evidence without contradictory setup. +14. No new workflow feature, runtime dependency, reflection, magic activation, + worker, polling loop, cache, pool, or speculative public option was added. +15. No push, pull request, tag, release, package publication, or external + product mutation occurred. + +## Stop conditions + +Stop and report rather than guessing when: + +- the inventory includes files whose ownership cannot be determined; +- a requested clean commit would require discarding or overwriting user work; +- a public API or JSON change is required but was not already approved; +- package acceptance resolves a FluxFlow dependency outside the candidate + source; +- a real-provider gate requires new credentials, license acceptance, or + authority not already configured by the project runner; +- a release/publish action would be required; +- the same external blocker repeats and no safe local progress remains. + +## Final report contract + +The final handoff must state: + +- the branch and exact candidate commit(s); +- material consolidation changes, if any; +- the final supported C# and JSON paths; +- package-consumer markers and exact pack/restore/build/run results; +- solution, Release, public API, formatting, vulnerability, sample, and + real-provider results; +- cleanup status for worktrees, package sources, directories, processes, and + provider infrastructure; +- remaining risks and deliberately deferred work; +- confirmation that nothing was pushed, tagged, released, or published; +- a compact `Requirement | Evidence` table citing exact tests, commands, or + documents. diff --git a/goals/2026-08-08-typed-code-first-application-authoring/README.md b/goals/2026-08-08-typed-code-first-application-authoring/README.md new file mode 100644 index 00000000..05c6b4ae --- /dev/null +++ b/goals/2026-08-08-typed-code-first-application-authoring/README.md @@ -0,0 +1,1548 @@ +# GOAL: Add a Typed, Code-First Application Authoring DSL + +## Status + +- State: complete +- Created: 2026-08-08 +- Clarified: 2026-08-08 — the C# DSL is a developer-only compiled-code path; C# export, JSON serialization, and designer interoperability are outside this goal +- Repository: C:\Projects\FluxFlow +- Execution started: 2026-08-08 +- Execution completed: 2026-08-08 +- Breaking changes: allowed when they produce a smaller and clearer final API +- Backward-compatibility aliases: not required +- Commit, push, pull request, package publication, and release: not authorized by this goal +- Required result: implementation, migration, focused and full verification, documentation, website content, and memory updates + +## Execution Instruction + +Execute this goal completely in the existing FluxFlow repository. + +Do not stop after creating interfaces, prototypes, tests, or documentation. Implement the smallest complete production design, migrate the repository-owned consumers, run the required verification, and record evidence in this file. + +Preserve all unrelated user work already present in the working tree. The repository is intentionally dirty from the durability, package-consumer restart acceptance, typed component port-binding, and HasInput/HasOutput/HasEvents rounds. Never reset, discard, overwrite, or silently reformat unrelated changes. + +At the start of execution: + +1. Read the repository instructions and memory files required for the touched areas. +2. Inspect the current working tree and identify overlapping edits. +3. Read this goal completely. +4. Use the dotnet-vertical-slice-senior skill as the architecture anchor. +5. Use graph-aware repository inspection before changing cross-project contracts. +6. Before writing or changing tests, use the mandatory code-testing-agent entry skill and follow its required workflow. +7. Update the Status section to in progress. +8. Keep this file current with decisions, scope adjustments, test evidence, and final results. + +## Objective + +Create a first-class C# application-definition authoring experience that is: + +- strongly typed for component contracts, handles, ports, and C# predicates; +- visually close to the existing JSON application structure; +- flat and fluent, with no callback nesting for workflow scopes; +- capable of local and cross-workflow connections; +- explicit, predictable, and free of reflection or hidden runtime registration; +- fully compatible with the existing JSON definition format and JSON hot-reload path; +- capable of representing code-only behavior when the application is intentionally authored and hosted in C#; +- lightweight enough to preserve FluxFlow's in-process character. + +The completed public experience must let application authors write ordinary C# without repeating component type identifiers or port names: + +~~~csharp +var application = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var main) + .AddWorkflow("audit", out var audit); + +main + .AddComponent( + "source", + SampleComponents.Source, + options => options.Messages = ["alpha", "beta"], + out var source) + .AddComponent( + "review", + SampleComponents.Review, + out var review) + .AddComponent( + "priority", + SampleComponents.Sink, + out var priority) + .AddComponent( + "standard", + SampleComponents.Sink, + out var standard); + +audit.AddComponent( + "events", + SampleComponents.EventCollector, + out var events); + +source.Output.ConnectTo(review.Input); + +review.Output + .ConnectTo(priority.Input, when: static order => order.Priority) + .ConnectTo(standard.Input, when: static order => !order.Priority); + +review.Events.ConnectTo(events.Input); +priority.Events.ConnectTo(events.Input); +standard.Events.ConnectTo(events.Input); + +var definition = application.Build(); +~~~ + +This is a true code-first application definition. It is not another syntax whose purpose is to produce JSON. Building, registering, validating, compiling, revising, and executing this application must not call or round-trip through JSON. + +The developer writes C#, compiles the application, and runs the built definition directly in memory. The C# builder may use the full appropriate power of C#, including typed objects, typed handles, delegates, closures, and component-specific builders. It has no responsibility to produce JSON. + +## Product Boundary + +FluxFlow must continue to support two distinct, equally valid application-authoring paths: + +### Portable definition path + +- JSON, files, configuration providers, remote configuration, and hot reload. +- Component type names, port addresses, and link conditions are represented in the existing portable schema. +- Conditions are portable expression strings compiled by the configured IFlowExpressionEngine. +- A UI/designer authors this portable JSON representation. +- The current JSON wire shape and configuration behavior remain supported. + +### Code-first definition path + +- The application graph is authored directly in C# through ApplicationDefinitionBuilder. +- This API is for developers writing and compiling C# source code. +- Components and ports are represented through typed contracts and handles. +- Links may use no condition, a portable expression string, or a synchronous typed C# predicate. +- The built definition is registered and executed directly in memory. +- Normal code-first startup does not serialize, parse, or project through JSON. +- The C# builder is not required to produce a portable or serializable result, even when a particular graph happens to use only portable features. +- Static C# registration through the existing AddFluxFlow definition path remains supported. + +### Shared runtime boundary + +The authoring paths converge at normalization, validation, and compilation: + +~~~text +JSON source -> parse ---------+ + +-> normalize -> validate -> compile -> runtime +C# builder -------------------+ +~~~ + +They do not converge at serialization, UI editing, or source representation. “The same application” means that equivalent graphs produce the same validated runtime behavior. It does not mean that every in-memory C# behavior has a JSON representation. + +The governing rules are: + +> Successful execution of a code-first application must never depend on calling, projecting through, or round-tripping through JSON. + +> The UI/designer creates and persists JSON definitions; it does not create, open, edit, or export compiled C# builder definitions. + +> Exporting a C# builder result to JSON is not part of this goal. + +Do not weaken the JSON use case to implement the C# use case. Do not constrain the C# use case to the JSON feature set when the application author explicitly chooses code-first hosting. Do not make JSON the internal interchange format between ApplicationDefinitionBuilder and the runtime. Do not add C# export, portability metadata, serializer adapters, or designer bridges in this round. + +## Non-Negotiable Design Principles + +### Simplicity + +- Prefer the smallest cohesive design that satisfies the complete behavior. +- Avoid framework-building around the DSL. +- Avoid universal option bags, generic repositories, service locators, and indirect registries. +- Do not add a dependency unless the existing runtime and BCL cannot express the requirement cleanly. +- Do not add a new project unless a real package boundary requires it. + +### Explicit behavior + +- No reflection. +- No assembly scanning. +- No source generation. +- No runtime compilation. +- No dynamic invocation. +- No hidden string keys standing in for delegates. +- No JSON sentinel value that secretly refers to process memory. +- No global or static delegate registry. +- No ambient current-builder state. +- No mutation after Build. + +### SRP and IOC + +- Authoring contracts describe how a known component is represented in an application definition. +- Component-specific builders own component-specific configuration. +- Application authoring owns graph construction. +- Link compilation owns conversion from authored conditions to executable matchers. +- Runtime ports own delivery and invoke only the compiled matcher abstraction. +- JSON parsing/serialization owns only the independent portable JSON path. +- The C# builder has no serialization or designer responsibility. +- Hosting and dependency injection remain responsible for component implementation activation. + +### Flat fluent authoring + +- Keep workflow creation and component authoring at one or two levels. +- Do not introduce nested AddWorkflow callbacks. +- Do not introduce nested component, port, connection, or condition callback trees. +- One component-specific Action configuration callback is acceptable. +- The main graph should read top-to-bottom like the JSON hierarchy while remaining ordinary typed C#. + +## Current Baseline to Preserve + +The current repository already contains important foundations. Reuse and simplify them rather than replacing them: + +- ApplicationDefinitionBuilder owns resources, resource groups, workflows, application-level cross-workflow connections, validation, and immutable Build behavior. +- AddWorkflow(string) returns WorkflowDefinitionBuilder. +- AddWorkflow(string, out WorkflowDefinitionBuilder) returns ApplicationDefinitionBuilder for fluent capture. +- WorkflowDefinitionBuilder already supports component creation and local Connect calls. +- ApplicationDefinitionBuilder already supports explicit cross-workflow Connect calls. +- AuthoringScope already enforces common ownership and builder mutability. +- ComponentHandle, ComponentHandle, AuthoredComponentHandle, InputPortHandle, OutputPortHandle, and SignalInputPortHandle already exist. +- Reusable authored handle shapes such as InputOutputComponentHandle already exist. +- Official component Composition packages already provide typed AddX authoring extension methods and component-specific builders. +- ApplicationLinkCompiler validates addresses, directions, types, cardinality, and portable conditions. +- CompiledApplicationLink already centralizes condition matching and exception isolation. +- ApplicationOutputPort already provides condition context and rejection observability. +- ApplicationDefinitionJsonConverter and ApplicationDefinitionJson own the JSON boundary. +- IApplicationDefinitionSource and the revision planner own reload and revision behavior. +- FluxFlow.Fluent is a separate node-instance graph API. It is not the same DSL and must remain separate. + +The implementation must be incremental over these foundations. + +## Authoritative Workflow API + +Keep exactly these two workflow-authoring shapes: + +### Handle-returning shape + +~~~csharp +var application = new ApplicationDefinitionBuilder(); +var main = application.AddWorkflow("main"); +var audit = application.AddWorkflow("audit"); +~~~ + +### Fluent capture shape + +~~~csharp +var application = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var main) + .AddWorkflow("audit", out var audit); +~~~ + +Both shapes must produce equivalent definitions. + +Do not add any of these: + +- AddWorkflow(name, workflow => ...) +- nested workflow configuration callbacks; +- BeginWorkflow/EndWorkflow state; +- ambient current workflow; +- implicit workflow selection; +- a third DSL entry point such as App.Main that duplicates the builder. + +The callback shape is intentionally rejected because it creates nesting and does not improve type safety. + +## Typed Component Authoring Contracts + +### Required concept + +Introduce one small explicit typed authoring-contract abstraction that contains only the information required to add a known component: + +- the canonical component type identifier; +- the explicit function that creates the public typed authored handle from the underlying ComponentHandle; +- when applicable, the explicit function that creates/applies the component-specific configuration builder. + +Use a repository-appropriate final name. The preferred naming is: + +- ComponentAuthoringContract for a component without configuration; +- ComponentAuthoringContract for a component with component-specific configuration. + +THandle must be an AuthoredComponentHandle or another existing repository-approved typed handle shape. TOptions is the component-specific builder already owned by the component package. + +The contract is data plus explicit delegates. It must not: + +- discover ports through reflection; +- resolve services; +- instantiate runtime nodes; +- duplicate runtime component descriptors; +- become a second component catalog; +- contain mutable global state; +- validate runtime registration; +- infer component types from CLR generic types. + +The canonical component type and port names remain declared by the owning component package. The contract refers to those constants explicitly. + +### Required AddComponent overloads + +Add strongly typed overloads to WorkflowDefinitionBuilder with this effective shape: + +~~~csharp +public WorkflowDefinitionBuilder AddComponent( + string name, + ComponentAuthoringContract component, + out THandle handle); + +public WorkflowDefinitionBuilder AddComponent( + string name, + ComponentAuthoringContract component, + Action configure, + out THandle handle); +~~~ + +It is acceptable to provide corresponding handle-returning overloads when they reduce implementation duplication and match existing conventions: + +~~~csharp +THandle AddComponent( + string name, + ComponentAuthoringContract component); + +THandle AddComponent( + string name, + ComponentAuthoringContract component, + Action configure); +~~~ + +The out overloads are required because they enable flat fluent component declarations while retaining typed references. + +All overloads must delegate to the same existing component-add core. There must be one authority for: + +- component-name validation; +- duplicate detection; +- type storage; +- property configuration; +- commit/rollback behavior; +- ownership; +- immutable snapshots. + +### Low-level escape hatch + +The existing string-based AddComponent(name, type, ...) surface may remain as the low-level path for: + +- dynamic plugins; +- application types not known at compile time; +- adapters built from external configuration; +- advanced/custom authoring; +- raw compatibility fixtures. + +It must be documented as the dynamic/low-level escape hatch, not the preferred normal C# authoring path. + +Do not remove dynamic authoring capability merely to make the normal path typed. + +### Application-owned custom components + +An application must be able to define its own explicit contract without a framework extension or generated code. + +The API must make this straightforward: + +~~~csharp +internal static class SampleComponents +{ + public static ComponentAuthoringContract Source { get; } + = ComponentAuthoringContract.Create( + SampleComponentTypes.Source, + static definition => new SourceHandle( + definition, + SampleComponentPorts.Output), + static options => options.Apply); +} +~~~ + +The exact factory syntax may be simplified to fit the final implementation, but the following are mandatory: + +- declaration is explicit; +- no reflection; +- no registration scan; +- no hidden convention based on property names; +- no repeated type or port strings at each application call site; +- a custom handle can expose meaningful named ports such as Input, Output, Events, Approved, Rejected, or Diagnostics. + +### Official component families + +Bring official Composition authoring onto the same core without creating two competing systems. + +For every official authored component declaration: + +- retain the familiar AddX extension when it remains useful; +- make AddX delegate to the typed contract/AddComponent core, or make both delegate to one smaller internal primitive; +- expose an explicit typed contract when required for the generic AddComponent(name, contract, out handle) experience; +- reuse existing component-specific option builders; +- reuse existing typed handle shapes or add a small feature-specific handle only when port names/shape require it; +- do not repeat canonical type IDs, port names, option application, or validation logic across AddX and contract code. + +Preserve the current repository coverage matrix: + +- all 19 component families; +- all 44 official component declarations; +- the 18 root composition families and the nested MQTT composition family; +- their typed option builders, resource handles, component handles, events, and signal inputs. + +Do not mechanically invent a new type per declaration if an existing shared handle is clear. Do not force unlike components into an overly generic handle. + +## Typed Component Handles and Ports + +Normal authoring must expose ports as named properties: + +~~~csharp +source.Output +upper.Input +upper.Output +review.Events +router.Matched +router.Unmatched +~~~ + +Normal code must not require: + +~~~csharp +component.Input("Input") +component.Output("Output") +component.Output("Events") +~~~ + +The raw ComponentHandle.Input, Output, and SignalInput methods may remain for dynamic/custom escape-hatch scenarios. + +### Port requirements + +- InputPortHandle and OutputPortHandle remain the type-safety foundation. +- Events are ordinary explicitly named typed output ports. +- There is no implicit Events port. +- There is no special UseEvents or ForwardEvents concept. +- The public property name should reflect the component contract, commonly Events. +- Port addresses remain fully qualified and stable. +- Handles remain bound to one AuthoringScope. +- Handle creation must not mutate the component definition. +- Component option configuration and handle construction must not execute runtime component factories. + +The recently completed HasInput, HasOutput, HasSignalInput, and HasEvents terminology applies to runtime/designer component declaration. Do not regress those APIs back to AddInput/AddOutput/AddEvents. + +## Connection API + +Keep all three useful scopes, with one internal connection operation. + +### Direct output-port connection + +~~~csharp +source.Output.ConnectTo(upper.Input); +source.Output.ConnectTo(trigger.Signal); +~~~ + +This is the preferred concise form when both handles are already available. + +### Workflow-scoped connection + +~~~csharp +main.Connect(source.Output, upper.Input); +main.Connect(source.Output, trigger.Signal); +~~~ + +This remains explicit and must accept only endpoints belonging to the same workflow. + +### Application-scoped connection + +~~~csharp +application.Connect(source.Output, audit.Input); +application.Connect(source.Output, auditTrigger.Signal); +~~~ + +This remains the explicit builder-level form for cross-workflow connections. + +### Naming + +Use ConnectTo for direct port fluent calls. + +Do not use LinkTo. In the .NET dataflow ecosystem, LinkTo normally means creating a live runtime link. This API records an application definition and does not immediately connect runtime objects. + +### Fan-out + +ConnectTo must return the same OutputPortHandle, enabling readable fan-out: + +~~~csharp +review.Output + .ConnectTo(priority.Input) + .ConnectTo(standard.Input); +~~~ + +The returned source handle must be reference-identical to the receiver. Do not create wrapper chains. + +### Cross-workflow behavior + +- Direct ConnectTo may connect across workflows when source and target belong to the same ApplicationDefinitionBuilder/AuthoringScope. +- ApplicationDefinitionBuilder.Connect may connect across workflows under the same owner. +- WorkflowDefinitionBuilder.Connect must reject a cross-workflow target. +- Any connection between different application owners must fail before mutation. +- Full addresses, not local string concatenation at the call site, determine source and target. + +### One internal operation + +ConnectTo, workflow.Connect, and application.Connect must delegate to one internal connection-add operation so they share: + +- ownership validation; +- workflow-scope validation; +- source/target direction validation; +- exact message type validation; +- signal-input rules; +- target link-cardinality validation; +- duplicate connection rules; +- condition representation; +- declaration ordering; +- error messages; +- transactional mutation behavior. + +Do not maintain parallel connection logic in extension methods. + +## Link Conditions + +Support three explicit condition forms. + +### Unconditional + +~~~csharp +review.Output.ConnectTo(sink.Input); +~~~ + +### Portable expression + +~~~csharp +review.Output.ConnectTo( + priority.Input, + when: "input.Priority == true"); +~~~ + +This remains compatible with JSON, configuration sources, storage, hot reload, and IFlowExpressionEngine. + +### Typed synchronous C# predicate + +~~~csharp +review.Output.ConnectTo( + priority.Input, + when: static order => order.Priority); +~~~ + +The same typed predicate must be supported by workflow.Connect and application.Connect. + +### Required overload shape + +For typed input ports, provide non-ambiguous overloads equivalent to: + +~~~csharp +OutputPortHandle ConnectTo( + InputPortHandle target); + +OutputPortHandle ConnectTo( + InputPortHandle target, + string when); + +OutputPortHandle ConnectTo( + InputPortHandle target, + Func when); +~~~ + +Mirror the condition forms for signal-input targets using the existing signal semantics. Mirror them on WorkflowDefinitionBuilder.Connect and ApplicationDefinitionBuilder.Connect. + +Avoid a single object condition parameter, optional delegate/string ambiguity, or overloads that make null resolve unpredictably. + +Null string/delegate arguments must fail immediately with the correct parameter name. An absent condition uses the unconditional overload. + +### Predicate type safety + +- TMessage comes from OutputPortHandle. +- The target input must accept the exact compatible message type under existing FluxFlow link rules. +- Wrong message types must fail at compile time for ordinary typed calls. +- No boxing-based dynamic predicate dispatch. +- No reflection-based generic invocation. +- No expression-tree translation. + +### Predicate execution semantics + +- Predicates are synchronous. +- Predicates execute once per candidate route and message. +- A true result delivers to that route. +- A false result rejects only that route. +- Other fan-out routes continue independently. +- A predicate exception is caught at the existing condition boundary. +- A predicate exception must emit the existing LinkConditionFailed diagnostic/system event with link context and exception details. +- A predicate exception must not terminate the application runtime. +- A successful null payload for a nullable/reference TMessage is passed to the predicate. +- For an error FlowMessage, the payload predicate is not invoked. The conditional route is treated as not matched through normal condition-rejection observability; other routes continue. +- Unconditional error delivery behavior remains unchanged. +- Portable expression behavior for error messages remains unchanged. + +Do not add an advanced FlowMessage predicate overload in this round. Fault-specific routing should use existing explicit error/system-event facilities or a component. This keeps the primary contract understandable. + +### Predicate responsibilities + +Document that a code predicate should be: + +- fast; +- side-effect free; +- non-blocking; +- safe for concurrent invocation when the runtime can route concurrently. + +Captured closures are allowed. The application author owns the thread safety and lifetime implications of captured objects. I/O, service calls, retries, and stateful processing belong in a component, not in a link predicate. + +Do not add: + +- async predicates; +- CancellationToken predicate overloads; +- IServiceProvider injection; +- predicate dependency injection; +- retries; +- timeouts; +- policy pipelines; +- state stores; +- caching; +- automatic delegate serialization. + +## First-Class Condition Ownership + +A typed C# predicate must be owned immutably by the built code-first definition/result and its runtime revision. + +Required lifetime behavior: + +- Build snapshots the condition along with the graph. +- Mutating the builder after Build remains impossible under existing rules. +- The built definition keeps captured closure state alive for exactly as long as the definition/revision needs it. +- Replacing or retiring the revision releases the old definition and predicates when no runtime work references them. +- There is no process-global registry. +- There is no static dictionary keyed by generated IDs. +- There is no service locator. +- There is no sidecar whose lifetime can drift from the built code-first definition/result. +- There is no serialization attempt over a delegate. + +Use a small explicit internal/public condition representation, such as a discriminated abstraction with: + +- no condition; +- portable expression condition; +- typed code predicate condition. + +The exact type names are implementation decisions, but the representation must be immutable, definition-owned, and type-safe. + +## Shared Link Validation and Compilation + +The JSON and C# source models may remain separate. Do not redesign the JSON model merely to store C# delegates. + +They should converge at the smallest internal link-validation/compilation boundary: + +- the JSON path continues to read portable link declarations from the established JSON/ApplicationDefinition representation; +- the C# builder produces immutable typed in-memory link declarations directly; +- a small shared compiler input describes source, target, message type, cardinality context, and condition; +- both adapters use the same address, direction, type, cardinality, duplicate, and diagnostic rules; +- both produce the same CompiledApplicationLink/runtime matcher form; +- runtime planning consumes compiled links without knowing their authoring source. + +For any one built graph, each link must have one authoritative declaration. Do not store the same C# link once as a raw JSON-style property and again in a delegate registry. + +Choose the smallest implementation after inspecting constructors, equality/revision behavior, runtime planning, and ApplicationLinkCompiler. It may extend the existing hostable result with immutable code link state, or use a small code-first hostable result accepted by the same runtime compiler. + +Do not create a large public model hierarchy solely to distinguish “JSON” from “C#.” A small explicit code-first result is acceptable when it keeps the JSON DTO clean and reduces special cases. Source-model separation is allowed; duplicated validation, compilation, diagnostics, and runtime routing are not. + +Whichever direction is chosen: + +- raw JSON-shaped ApplicationDefinition construction continues to work where it is a supported low-level surface; +- the existing JSON shape remains canonical; +- code-first Build remains a direct in-memory operation; +- the runtime accepts the built code-first result directly; +- no JSON conversion occurs during C# Build, registration, compilation, revision planning, or execution; +- no production InternalsVisibleTo is added; +- no hidden global condition storage is used. + +## Link Compilation and Runtime Matching + +ApplicationLinkCompiler and CompiledApplicationLink must converge all condition kinds into one runtime matcher boundary. + +### Portable expressions + +- Continue to compile through IFlowExpressionEngine. +- Continue to expose the same input, message, and payload variables. +- Continue to fail clearly when an expression is present and no expression engine is configured. +- Preserve existing expression text and diagnostics. + +### Typed predicates + +- Must not require IFlowExpressionEngine. +- Must not be converted to a string. +- Must not compile through reflection or expression trees. +- Must retain its exact TMessage contract. +- Must use the same TryMatch exception-isolation boundary as portable conditions. +- Must produce the same route-level match/no-match result understood by ApplicationOutputPort. + +The runtime port should not need to know whether the author used JSON, a string expression, or a C# predicate. It should invoke one compiled condition/matcher abstraction. + +Avoid adding condition-type branching throughout the engine. + +## Revision, Equality, and Reload Semantics + +Inspect and update: + +- ApplicationRevisionPlanner; +- application definition equality/comparison; +- runtime plan creation; +- revision replacement; +- rollback behavior; +- retained/restarted runtime behavior. + +Required semantics: + +- Adding or removing a link changes the revision plan. +- Changing a portable expression changes the route. +- Changing a code predicate changes the route. +- A new definition containing a new delegate must never be incorrectly classified as unchanged. +- Do not hash delegate targets, inspect closures, reflect over methods, or invent process-stable semantic equality for arbitrary code. +- Reusing the same already-built definition may reuse its stable immutable condition identity where current planner behavior allows. +- Rebuilding the application with a new predicate instance may conservatively rebuild that route/revision. +- A conservative rebuild is acceptable; an incorrect unchanged classification is not. +- Revision activation failure must retain current rollback guarantees. +- Retired revisions must release their predicate/closure references after in-flight work completes. + +JSON/configuration hot reload remains portable-expression-only. Do not attempt to hot-reload executable delegates from JSON. + +## Independent JSON and Designer Path + +Preserve: + +- the current JSON property names and structure; +- existing resource, resource-group, workflow, component, view, check, and link representations; +- canonical ordering and formatting expectations; +- ApplicationDefinitionJson parsing and serialization; +- IApplicationDefinitionSource; +- file/configuration loading; +- hot reload; +- designer persistence and load behavior; +- portable expression compilation; +- existing raw definition examples that intentionally demonstrate JSON equivalence. + +The UI/designer path is strictly JSON-based: + +- it creates, edits, validates, loads, and saves portable JSON definitions; +- it continues to retain all existing port metadata and explicit Events semantics; +- it does not consume ApplicationDefinitionBuilder; +- it does not open or edit C# builder results; +- it does not need typed C# component handles; +- it does not need delegate conditions; +- it does not generate C# source. + +Do not add or modify designer behavior for the C# DSL. Do not add a designer-to-C# bridge, C#-to-JSON exporter, portability capability API, serializer adapter, or code-condition converter in this round. + +Only make a JSON/designer implementation change if the shared compiler refactor would otherwise break existing JSON loading, validation, persistence, or hot reload. Such changes must be compatibility preservation, not new cross-path functionality. + +## Validation and Transactional Behavior + +All authoring entry points must reject invalid input before partially changing builder state. + +Cover: + +- null contract; +- null configure callback; +- null predicate; +- empty/invalid application names where applicable; +- empty/invalid workflow names; +- empty/invalid component instance names; +- duplicate workflow names; +- duplicate component names; +- contract with invalid canonical type; +- invalid or duplicate port declarations in a custom handle; +- source and target from different applications; +- workflow.Connect with endpoints from different workflows; +- wrong direction; +- incompatible message types; +- invalid signal connection; +- target link-cardinality overflow; +- duplicate identical links; +- conflicting conditions for a cardinality-limited target; +- connect-after-Build; +- component-add-after-Build; +- Build after a failed operation. + +Failed operations must not leave: + +- a partially added component; +- a reserved component name; +- a partial property update; +- a partial connection; +- a consumed target cardinality slot; +- a mutated previously built definition; +- a leaked predicate reference in global state. + +Error messages must include useful component/link addresses and the invalid operation. Do not expose implementation-only registry IDs. + +## Required Sample Migration + +Migrate samples/FluxFlow.SampleApp/SampleWorkspaceDefinition.cs from raw constructor/string-link authoring to the typed code-first DSL. + +Remove normal sample patterns such as: + +~~~csharp +new ApplicationDefinition( + workflows: + [ + new("main", new ApplicationWorkflowDefinition( + [ + new("source", Component( + "sample.source", + ("messages", new[] { "alpha", "beta" }), + ("Output", "upper.Input"))), + new("upper", Component( + "sample.uppercase", + ("Output", "sink.Input"))), + new("sink", Component("sample.sink")) + ])) + ]); +~~~ + +Replace them with: + +- ApplicationDefinitionBuilder; +- the two approved workflow shapes as appropriate; +- sample-local explicit typed component contracts; +- sample-local component-specific option builders; +- typed authored component handles; +- named typed port properties; +- ConnectTo or scoped Connect calls; +- at least one typed C# predicate; +- explicit Events port connections where the sample uses events. + +Preserve all sample behavior: + +- source data; +- review/uppercase/processing behavior; +- sinks; +- events; +- views; +- checks; +- resources; +- console output relied on by process tests; +- startup and shutdown behavior. + +The sample must demonstrate: + +- configuration through a component-specific builder; +- out-var fluent capture; +- local typed connection; +- fan-out; +- typed predicate; +- cross-workflow connection if the sample already has a meaningful second workflow; +- explicit event output. + +Do not distort the sample merely to demonstrate every overload. Documentation tests may cover alternate forms. + +## Fluent Package Boundary + +FluxFlow.Fluent remains a distinct runtime node-instance DSL. + +Do not: + +- merge FluxFlow.Fluent into ApplicationDefinitionBuilder; +- rename the current fluent package; +- change node-instance execution semantics; +- make ApplicationDefinitionBuilder activate nodes directly; +- imply that code-first ApplicationDefinition authoring replaces the node-instance DSL. + +Update documentation and the Fluent sample to explain the distinction: + +- ApplicationDefinitionBuilder creates a hostable application definition using registered component types and supports resources, workflows, revisions, JSON-equivalent definitions, and code-only predicates. +- FluxFlow.Fluent builds a direct in-process graph from node instances. + +The two APIs may share conceptual words such as Connect, but they must not share hidden mutable state. + +## Files and Areas to Inspect + +Inspect all current locations before deciding the final edit list. At minimum, trace: + +### Composition authoring + +- src/FluxFlow.Composition/Authoring/ApplicationDefinitionBuilder.cs +- src/FluxFlow.Composition/Authoring/WorkflowDefinitionBuilder.cs +- src/FluxFlow.Composition/Authoring/AuthoringHandles.cs +- src/FluxFlow.Composition/Authoring/ComponentDefinitionBuilder.cs +- authoring scope, resource builders, component builder helpers, and definition rules + +### Definition model and JSON + +- src/FluxFlow.Composition/ApplicationModel/ApplicationDefinition.cs +- src/FluxFlow.Composition/ApplicationModel/ApplicationDefinitionJson.cs +- src/FluxFlow.Composition/ApplicationModel/ApplicationDefinitionJsonConverter.cs +- workflow/component definition types +- JSON converter fixtures and canonical snapshots + +### Link compilation + +- src/FluxFlow.Composition/ApplicationLinks/ApplicationLinkCompiler.cs +- src/FluxFlow.Composition/ApplicationLinks/CompiledApplicationLink.cs +- link projection/declaration types +- port metadata/cardinality validation + +### Runtime and revisions + +- src/FluxFlow.Engine/Ports/ApplicationOutputPort.cs +- application port binder/runtime assembler +- ApplicationRuntimePlanFactory +- ApplicationRevisionPlanner +- revision activation/rollback code +- application definition source and reload handling +- ApplicationPortEventPublisher and ApplicationSystemEventNames + +### Component authoring packages + +- every src/FluxFlow.Components.*.Composition project +- MQTT nested composition authoring +- shared authored handle helpers +- the complete family/declaration matrix + +### Samples and fixtures + +- samples/FluxFlow.SampleApp/SampleWorkspaceDefinition.cs +- samples/FluxFlow.SampleApp component contracts/registration +- samples/FluxFlow.CompositionSample +- samples/FluxFlow.FluentSample +- package-consumer acceptance fixture +- process/sample acceptance tests + +### Documentation and memory + +- README.md +- src/FluxFlow.Composition/README.md +- src/FluxFlow.Fluent/README.md +- component Composition package READMEs +- documentation site sources +- docs/02 or current application-definition documentation +- docs/10 or current expression/mapping documentation +- docs/14 or current public API documentation +- docs/15 or current compatibility documentation +- docs/23 or current migration documentation +- memory/00-index.md +- memory/01-current-state.md +- memory/297-typed-component-port-binding.md +- memory/298-declarative-component-port-naming.md + +Use actual current paths if documentation has moved. Do not create duplicate documentation trees. + +## Implementation Sequence + +### Phase 1: Freeze the contract with tests + +After using the mandatory testing skill: + +1. Add focused failing tests for the two workflow shapes and explicit absence of callback workflow APIs. +2. Add typed component-contract/add overload tests. +3. Add typed handle/port tests. +4. Add direct ConnectTo tests. +5. Add local/cross-workflow ownership tests. +6. Add portable and code-condition tests. +7. Add C#-path/JSON-path isolation and JSON regression tests. +8. Add runtime routing/exception tests. +9. Add public surface/family convention tests. + +Tests must assert public behavior, not private implementation names. + +### Phase 2: Add the minimal typed contract core + +1. Add the small explicit contract abstraction. +2. Add the required WorkflowDefinitionBuilder overloads. +3. Reuse AddComponentCore. +4. Preserve transactional behavior. +5. Support custom AuthoredComponentHandle construction. +6. Do not touch runtime activation. + +### Phase 3: Add direct typed connections + +1. Add ConnectTo overloads to OutputPortHandle. +2. Return the same output handle. +3. Delegate to the existing owner/workflow connection operation. +4. Permit same-owner cross-workflow direct connections. +5. Preserve workflow-local Connect restrictions. +6. Keep application-level cross-workflow Connect. +7. Eliminate duplicated connection validation. + +### Phase 4: Introduce first-class condition ownership + +1. Design the smallest immutable condition representation. +2. Store it with the built code-first definition/result and revision. +3. Add the smallest shared compiler input/adapters for JSON links and typed C# links. +4. Ensure one authoritative connection set per built graph. +5. Update immutable snapshots and mutation guards. +6. Preserve the independent JSON construction path without converting C# links to JSON. + +Do not begin with a global delegate lookup workaround. + +### Phase 5: Compile and execute both condition kinds + +1. Adapt ApplicationLinkCompiler. +2. Compile portable expressions through IFlowExpressionEngine. +3. Wrap typed predicates directly without expression services. +4. Converge on one CompiledApplicationLink matcher. +5. Preserve exception isolation and diagnostics. +6. Implement the explicit error-message behavior. +7. Verify fan-out independence. + +### Phase 6: Preserve revision correctness and JSON-path isolation + +1. Update revision comparison/planning. +2. Verify replace/retire/rollback behavior. +3. Prove a code-only definition registers and executes without any JSON operation. +4. Preserve the existing canonical JSON definition path independently. +5. Verify configuration source/hot reload behavior remains portable. +6. Verify no new dependency connects the UI/designer to C# authoring contracts. +7. Do not implement C# builder serialization or export. + +### Phase 7: Migrate official authoring + +1. Move official AddX implementations onto the typed contract core. +2. Add contract access for generic AddComponent usage. +3. Remove duplicate type/port/configuration declarations created by the migration. +4. Verify the 19-family/44-declaration matrix. +5. Preserve public package boundaries. + +### Phase 8: Migrate samples + +1. Introduce explicit sample-local contracts/options/handles. +2. Rewrite SampleWorkspaceDefinition. +3. Preserve all views, checks, resources, and markers. +4. Update Composition examples. +5. Clarify the separate Fluent DSL. +6. Run samples as real processes. + +### Phase 9: Documentation and memory + +1. Update all affected README and documentation site pages. +2. Add migration guidance from raw string DSL to typed C# authoring. +3. Document code-only predicate portability. +4. Create memory/299-typed-code-first-application-authoring.md. +5. Update memory/00-index.md. +6. Update memory/01-current-state.md. +7. Record durable architectural decisions and exact verification evidence. + +### Phase 10: Cleanup and full verification + +1. Remove stale helpers and duplicated code made obsolete by the final design. +2. Scan for obsolete AddInput/AddOutput/AddEvents authoring terminology. +3. Scan samples/docs for avoidable component type and port-name strings. +4. Accept intentional public API baseline changes using the repository process. +5. Run focused and full gates. +6. Update this goal to complete only after every required result is green. + +## Detailed Testing Requirements + +Use the repository's existing xUnit and Shouldly conventions. Do not introduce a second test framework. + +### ApplicationDefinitionBuilder tests + +Verify: + +- AddWorkflow(name) returns the workflow handle. +- AddWorkflow(name, out workflow) returns the application builder. +- both shapes build equivalent immutable definitions; +- no public AddWorkflow callback overload exists; +- chaining two out-var workflows works; +- duplicate/invalid workflow names remain correct; +- application Build freezes all child builders. + +### Typed component contract tests + +Verify: + +- configuration-free contract; +- configured contract; +- handle-returning overload if exposed; +- out-var fluent overload; +- concrete inferred handle type; +- component-specific option builder; +- canonical type ID emitted once; +- canonical property shape; +- handle named ports use canonical addresses; +- custom application-owned contract; +- custom multi-port/event handle; +- null contract; +- null configure action; +- invalid type; +- duplicate component; +- option-builder failure leaves no partial component; +- handle-factory failure leaves no partial component; +- runtime factory is never executed during definition authoring; +- Build snapshot is immutable. + +### Direct connection tests + +Verify: + +- Output.ConnectTo(Input); +- Output.ConnectTo(SignalInput); +- returned output handle is the same instance; +- fluent fan-out creates two routes in declaration order; +- same-workflow direct connection; +- cross-workflow direct connection under one owner; +- different-owner rejection; +- connect after Build rejection; +- duplicate route behavior; +- target cardinality; +- wrong direction/type is unavailable or rejected at the correct boundary; +- failed connect performs no mutation. + +### Scoped Connect tests + +Verify: + +- workflow.Connect local success; +- workflow.Connect cross-workflow rejection; +- application.Connect local success; +- application.Connect cross-workflow success; +- all forms produce equivalent link declarations; +- all forms share validation and diagnostics; +- both typed input and signal input variants. + +### Condition authoring tests + +Verify: + +- unconditional overload; +- exact string-expression preservation; +- typed predicate preservation; +- true and false predicates; +- static predicate; +- captured closure; +- successful null reference payload; +- null string rejection; +- null predicate rejection; +- no ambiguous public overload surface; +- condition identity retained in immutable Build; +- new predicate definition is treated as changed; +- no process-global delegate storage. + +### ApplicationLinkCompiler tests + +Verify: + +- unconditional matcher; +- portable expression compilation; +- typed predicate compilation without IFlowExpressionEngine; +- portable expression still fails clearly without required engine; +- true/false match behavior; +- predicate exception returned through TryMatch rather than escaping; +- source/target/type/declaration metadata preserved; +- normal and signal target support; +- exact message type enforcement; +- error FlowMessage does not invoke payload predicate; +- portable error-message semantics unchanged. + +### Engine routing tests + +Use real application runtime assembly for: + +- true predicate delivers; +- false predicate rejects only that route; +- fan-out route independence; +- local typed link; +- cross-workflow typed link; +- signal-input typed condition; +- captured closure result; +- predicate exception emits LinkConditionFailed; +- diagnostic contains source and target; +- runtime remains active after exception; +- later messages continue to process; +- unconditional error propagation unchanged; +- conditional error message does not invoke payload predicate; +- revision replacement changes routing; +- failed revision activation rolls back safely; +- retired revision/closure can be collected when no longer referenced, using a deterministic lifetime test without arbitrary sleeps. + +### C# and JSON path-isolation tests + +Verify: + +- a code-only builder definition builds without invoking JSON; +- a code-only builder definition registers, compiles, and executes without invoking JSON; +- revision replacement for a code-only definition does not invoke JSON; +- ApplicationDefinitionBuilder exposes no ToJson, Serialize, Export, or designer-oriented API; +- the UI/designer receives no new dependency on C# builder contracts; +- existing portable JSON parsing and serialization remain unchanged; +- existing portable JSON round trip remains equivalent; +- existing JSON fixtures are unchanged; +- parsing JSON never creates a code predicate; +- JSON hot reload remains functional. + +Treat JSON assertions only as regression coverage for the independent JSON feature. Do not serialize a C# builder result in these tests. Do not route C# execution through JSON merely to reuse JSON fixtures. + +### Revision planner tests + +Verify: + +- unchanged portable definition behavior; +- added/removed link; +- changed expression; +- changed code predicate; +- same built definition behavior; +- no delegate reflection/hash dependency; +- rollback and old revision retention; +- old predicate ownership ends after retirement. + +### Component-family convention tests + +Verify the complete official matrix: + +- every official AddX remains correctly typed where retained; +- every AddX and generic contract path produce equivalent component definitions; +- component type ID has one authority; +- port names have one authority; +- option builder application has one authority; +- all 19 families are covered; +- all 44 declarations are covered; +- MQTT nested family is covered; +- explicit Events ports remain explicit; +- HasInput/HasOutput/HasSignalInput/HasEvents naming remains enforced; +- no old AddInput/AddOutput/AddEvents invocation leaks into production/sample documentation. + +### Sample and documentation tests + +Verify: + +- SampleWorkspaceDefinition uses the typed application builder; +- no raw helper recreates string links under a new name; +- sample has no avoidable component type/port-name string at call sites; +- sample process output/markers remain correct; +- Composition sample compiles and runs; +- Fluent sample compiles and its boundary documentation is correct; +- documentation snippets compile where the repository supports snippet tests; +- package README/documentation matrix remains complete. + +### Test quality rules + +- No skipped tests. +- No arbitrary Thread.Sleep or Task.Delay for synchronization. +- No order-dependent global state. +- No tests that pass only because they inspect an implementation-private class name. +- No mock-heavy substitute for runtime acceptance. +- Use deterministic synchronization for concurrency/lifetime tests. +- Assert both positive behavior and failure diagnostics. +- Preserve zero-warning builds. + +## Public API and Compatibility + +Breaking changes are allowed, but the final surface must be deliberate and smaller. + +During implementation: + +- inventory all new public types and overloads; +- avoid exposing internal condition plumbing; +- avoid duplicate convenience aliases; +- do not keep obsolete methods solely for backward compatibility; +- do not remove the low-level dynamic path without proving replacement coverage; +- update PublicApi.Shipped/Unshipped or the repository's current API baseline through its accepted process; +- run the normal public API verification after accepting intended changes; +- do not suppress baseline failures. + +Do not add production InternalsVisibleTo for tests. + +Do not change package versions, release metadata, or publish packages unless a separate explicit instruction authorizes it. + +## Documentation Requirements + +Update all relevant documentation in the same round. + +Documentation must explain: + +1. JSON and C# are independent first-class authoring sources. +2. Both sources converge at normalization, validation, and compilation—not serialization. +3. C# Build, registration, revision planning, and execution never require JSON. +4. The two supported workflow-authoring shapes. +5. Why callback-style workflow nesting is intentionally absent. +6. Typed component contracts. +7. How official and custom components expose typed handles. +8. Component-specific option builders. +9. Direct ConnectTo. +10. Workflow-local Connect. +11. Application-level cross-workflow Connect. +12. Fan-out chaining. +13. Typed Events outputs. +14. Portable expression conditions. +15. Typed C# predicates. +16. Predicate concurrency/side-effect guidance. +17. Error-message predicate semantics. +18. The separation between compiled C# authoring and portable JSON authoring. +19. JSON/configuration/hot-reload behavior as an independent path. +20. The UI/designer creates JSON and does not consume the C# DSL. +21. Code-first replacement through a newly built in-memory definition. +22. The low-level string escape hatch. +23. The distinction from FluxFlow.Fluent. +24. Migration from raw ApplicationDefinition constructors and string link addresses. + +Include concise before/after examples and one complete realistic example. + +Update: + +- root README; +- FluxFlow.Composition README; +- affected component Composition package READMEs; +- FluxFlow.Fluent README/sample explanation; +- documentation site content; +- public API and compatibility pages; +- migration guide; +- conditional-link/expression documentation. + +Do not duplicate the same long explanation across every component package. Put shared concepts in Composition documentation and link to them. + +## Memory Requirements + +Create memory/299-typed-code-first-application-authoring.md containing: + +- problem statement; +- agreed public authoring shapes; +- typed contract architecture; +- handle/port design; +- connection scope semantics; +- the shared normalization/validation/compilation boundary; +- confirmation that C# execution has no JSON dependency; +- portable expression and typed C# predicate choices; +- predicate execution/error semantics; +- explicit exclusion of C# serialization/export and designer integration; +- revision/lifetime decision; +- component family migration result; +- sample migration result; +- final changed-file summary; +- exact test/build/sample/package evidence; +- any explicitly deferred follow-up. + +Update: + +- memory/00-index.md; +- memory/01-current-state.md. + +The memory must describe the implemented reality, not the initial plan. + +## Non-Goals + +Do not include any of the following: + +- workflow callback DSL; +- an App.Main third authoring syntax; +- async link predicates; +- DI-aware predicates; +- predicate retries/timeouts/policies; +- predicate expression-tree translation; +- delegate serialization; +- remote code loading; +- script compilation; +- reflection; +- source generation; +- assembly scanning; +- global condition registry; +- service locator; +- ambient builder context; +- JSON as the internal transport between the C# builder and runtime; +- mandatory C#-to-JSON projection; +- optional C#-to-JSON export or serialization; +- portability metadata for C# builder results; +- serializer/converter support for C# predicates; +- a JSON round trip during code-first startup, validation, revision planning, or execution; +- JSON schema redesign; +- designer C# editor; +- designer consumption of C# builder results; +- C# source generation from the designer; +- automatic conversion of arbitrary delegates to portable expressions; +- changes to FluxFlow.Fluent execution semantics; +- new orchestration/distributed execution features; +- changes to durability/storage providers; +- package version bumps; +- publishing or releasing. + +## Dependency and Complexity Guardrails + +- Prefer zero new package dependencies. +- Prefer zero new project dependencies. +- Keep dependency direction consistent with existing Composition and Engine boundaries. +- Do not make Composition depend on a concrete component family. +- Do not make component contracts activate runtime nodes. +- Do not make Engine depend on component-specific option builders. +- Use small immutable records/classes and explicit delegates. +- Keep the public abstraction count minimal. +- Avoid one interface plus multiple factories when one sealed value object suffices. +- Avoid a generic abstraction when an existing AuthoredComponentHandle already expresses the behavior. +- Remove duplicated helpers after migration. +- Keep hot-path allocations no worse than the current expression-condition path; a typed predicate should normally be cheaper. +- Do not add per-message dictionaries solely for typed predicates when the current context can be adapted once. +- Do not optimize with unsafe caching before measurements. + +## Verification Sequence + +Use the repository's current exact commands and project names. Record command, count, warnings, duration where available, and result. + +Run sequentially where repository-wide builds share outputs. + +### Focused verification + +1. FluxFlow.Composition.Tests authoring, definition, JSON, and link compiler tests. +2. FluxFlow.Engine.Tests application assembler, output routing, system event, and revision tests. +3. Each affected component Composition test project. +4. Component family convention/matrix tests. +5. Sample/documentation source-shape tests. +6. Public API tests/baseline verification. + +### Sample verification + +Run the affected samples as real processes: + +- FluxFlow.SampleApp; +- FluxFlow.CompositionSample; +- FluxFlow.FluentSample if touched. + +Assert their expected markers and clean termination. + +### Full repository verification + +Run the current equivalents of: + +- full Release solution build; +- full solution tests; +- full FluxFlow.Release.Tests; +- documentation verification; +- dotnet format --verify-no-changes; +- git diff --check; +- package vulnerability audit; +- repository hygiene/source convention scans. + +Current baselines at goal creation are approximately: + +- Release build: 134 projects; +- full solution tests: 2,563 tests; +- public component matrix: 19 families and 44 declarations. + +Treat these as orientation, not permission to ignore legitimate count changes from new tests. + +### Package consumer acceptance + +Because this changes public authoring packages, run the existing package-only consumer acceptance in real pack mode unless repository inspection proves the public package closure is unaffected. + +Verify: + +- all expected public packages are packed from the current source; +- consumer restore resolves only the candidate package closure; +- no ProjectReference is present; +- the typed code-only ApplicationDefinition example compiles and runs directly without JSON; +- existing JSON definition acceptance remains green through its existing independent gate; +- existing restart/durability seed and recovery markers remain green; +- isolated work directories are cleaned under the existing acceptance rules. + +Do not weaken the established package-consumer gate. + +### Hygiene scans + +Scan touched production, samples, tests, and docs for: + +- obsolete AddInput/AddOutput/AddEvents invocations; +- avoidable raw component type strings in normal C# authoring; +- avoidable raw port-name/address strings in normal C# authoring; +- LinkTo naming; +- global delegate registries; +- reflection APIs; +- dynamic invocation; +- TODO/FIXME placeholders; +- skipped tests; +- arbitrary sleeps; +- production InternalsVisibleTo additions; +- duplicate condition/link authorities; +- C# builder serialization/export methods; +- new designer dependencies on C# authoring contracts. + +Classify intentional low-level/dynamic examples rather than deleting them blindly. + +## Acceptance Criteria + +This goal is complete only when all statements are true: + +- ApplicationDefinitionBuilder supports the two approved workflow shapes. +- No callback-style AddWorkflow API was added. +- WorkflowDefinitionBuilder supports typed component contracts with out-var capture. +- Component-specific configuration remains component-specific. +- Custom application components can define explicit typed contracts without reflection. +- Normal authoring no longer repeats component type IDs or port names. +- Typed handles expose named Input, Output, Events, and other ports. +- OutputPortHandle.ConnectTo exists and returns the same output handle. +- Direct ConnectTo supports same-owner cross-workflow links. +- Workflow Connect remains workflow-local. +- Application Connect remains the explicit cross-workflow builder form. +- Every connection path delegates to one validation/mutation core. +- Unconditional, portable expression, and typed synchronous predicate conditions work. +- Typed predicate execution does not require IFlowExpressionEngine. +- False and exception behavior are route-local and fan-out safe. +- Predicate exceptions emit LinkConditionFailed and do not stop the runtime. +- Error FlowMessage predicate behavior is explicit and tested. +- Predicates are owned by the built definition/revision with no global registry. +- Link compilation uses one runtime matcher boundary. +- Revision planning cannot misclassify a changed code predicate as unchanged. +- JSON and C# are independent authoring sources that converge at normalization, validation, and compilation. +- A code-first definition builds, registers, revises, and executes without JSON serialization or parsing. +- JSON is not used as an internal interchange format for code-first execution. +- The C# builder has no JSON serialization/export surface added by this goal. +- The UI/designer remains a JSON-only authoring path and has no dependency on the C# DSL. +- Portable JSON shape and hot reload remain compatible. +- Official component authoring converges on the same core. +- The 19-family/44-declaration matrix remains green. +- SampleWorkspaceDefinition uses the typed DSL and preserves behavior. +- FluxFlow.Fluent remains separate and documented accurately. +- Public API baselines are intentionally updated and verified. +- Documentation site and READMEs are current. +- memory/299, memory index, and current-state memory are current. +- Focused tests are green with zero warnings. +- Full solution tests are green with zero warnings. +- Release tests are green. +- Sample processes are green. +- Package-only consumer acceptance is green. +- Format, vulnerability, diff, and hygiene gates are green. +- No unrelated working-tree changes were lost. + +## Final Report Requirements + +When execution is complete, report: + +1. The final public authoring API. +2. One complete typed code-first example. +3. Confirmation that code-first execution has no JSON dependency. +4. The shared normalization/validation/compilation boundary. +5. The separation between the developer C# path and UI/designer JSON path. +6. The exact error-message predicate semantics. +7. The condition model. +8. The revision/lifetime solution. +9. Component family and sample migrations. +10. Any intentional breaking changes. +11. Exact focused and full verification results. +12. Exact package-consumer acceptance result. +13. Documentation and memory files updated. +14. Any remaining limitations or intentionally deferred work. +15. Confirmation that no commit, push, publication, or release was performed. + +## Execution Evidence + +| Requirement | Evidence | +|---|---| +| Repository and dirty-tree inspection | Completed before editing; the existing durability, package-consumer, typed binding, and `Has*` work was preserved. | +| Architecture/dependency trace | `ApplicationDefinitionBuilder` → immutable definition links → `ApplicationLinkCompiler` → runtime matcher → revision planner/activation traced with Graphify and source inspection. | +| Testing skill workflow | `code-testing-agent` workflow completed; research, plan, audit, and Requirement/Evidence records are in `.testagent`. | +| Two workflow shapes | `AddWorkflow(name)` and fluent `AddWorkflow(name, out workflow)` are implemented; reflection tests reject callback/third entry forms. | +| Typed component contracts | `ComponentAuthoringContract` and `ComponentAuthoringContract` use explicit delegates and no reflection. | +| Typed out-var AddComponent | Required typed `AddComponent` overloads return the workflow and capture the inferred handle through `out`. | +| Custom component contract | Sample-local and package-consumer contracts prove application-owned custom handles/options. | +| Named typed ports and Events | Shared and custom handles expose typed named ports; all 44 official contracts expose explicit typed `Events`. | +| Direct ConnectTo | Input and signal-input overload triplets implemented; direct calls return the same output handle. | +| Workflow-local Connect | Implemented through the shared connection core and rejects cross-workflow use. | +| Application/cross-workflow Connect | Implemented through the shared connection core for local and cross-workflow links. | +| Fan-out | Declaration-ordered fluent fan-out is covered in authoring and assembled runtime tests. | +| Portable expressions | Exact expression text remains supported through `IFlowExpressionEngine`. | +| Typed C# predicates | Synchronous `Func` links compile directly and need no expression engine. | +| Predicate exception isolation | A thrown predicate reports `LinkConditionFailed`, skips only that route, and permits siblings/later messages. | +| Error-message semantics | Conditional typed predicates are not invoked for error messages; unconditional error propagation is unchanged. | +| Definition/revision predicate ownership | Immutable `ApplicationLinkDefinition` owns executable predicates and opaque revision identity; no global registry exists. | +| Revision comparison and rollback | Planner covers added/removed/expression/predicate changes; rejected activation preserves the old generation. | +| Direct code-first execution without JSON | Engine and isolated package-consumer acceptance execute typed definitions directly in memory. | +| Shared normalization/validation/compilation boundary | JSON declarations and first-class C# links converge in `ApplicationLinkCompiler` and the same `CompiledApplicationLink` matcher. | +| Independent JSON-path compatibility | Existing JSON parsing, round-trip, source loading, hot reload, and runtime acceptance remain green. | +| UI/designer remains JSON-only | Source/convention scans and tests show no Designer dependency on C# authoring contracts or export API. | +| No C# serialization/export surface | Public-surface tests verify no `ToJson`, `Serialize`, `Export`, or designer bridge on the builder. | +| Official 19-family/44-declaration migration | Release matrix test verifies all 19 families and 44 typed contracts, including MQTT and Events. | +| Sample migration | SampleApp, CompositionSample, and MqttCompositionSample use the typed code-first path; obsolete SampleApp expression infrastructure was removed. | +| Fluent boundary documentation | Composition and Fluent documentation describe their separate hostable-definition and live-node graph purposes. | +| Public API baseline | Regenerated through `FLUXFLOW_ACCEPT_PUBLIC_API_BASELINE=1`, then independently reverified green. | +| Focused Composition tests | 150 passed, 0 failed/skipped, 0 warnings. | +| Focused Engine tests | 111 passed, 0 failed/skipped, 0 warnings, including deterministic retired-closure collection. | +| Component Composition tests | Included in the green 2,584-test full-solution run; stale MQTT JSON-link assertion migrated to first-class links. | +| Sample process verification | SampleApp, CompositionSample, MqttCompositionSample, and FluentSample all exited 0 with expected output. | +| Full Release build | 134 projects, 0 errors, 0 warnings. | +| Full solution tests | 2,584 passed across 66 projects, 0 failed/skipped, 0 warnings. | +| Full Release tests | 174 passed, 0 warnings. | +| Package-only consumer acceptance | Real pack mode exited 0 in 111.9 seconds: nine candidate packages, isolated `net8.0` build, candidate-only resolution, all JSON/C#/Fluent/durability/restart markers once, cleanup complete. | +| Documentation verification | 20 focused documentation/sample-documentation tests passed; the full Release suite is green. | +| Format and diff hygiene | Full `dotnet format --verify-no-changes` and full `git diff --check` exited 0; source scans found no new prohibited patterns. | +| Vulnerability audit | `dotnet list FluxFlow.sln package --vulnerable --include-transitive --no-restore` reported no vulnerable packages for every project. | +| Memory 299 and indexes | `memory/299-typed-code-first-application-authoring.md`, `memory/00-index.md`, and `memory/01-current-state.md` reflect the implemented result and exact evidence. | + +No commit, push, pull request, package publication, or release was performed. diff --git a/goals/2026-08-08-typed-component-port-binding/README.md b/goals/2026-08-08-typed-component-port-binding/README.md new file mode 100644 index 00000000..730ad2cf --- /dev/null +++ b/goals/2026-08-08-typed-component-port-binding/README.md @@ -0,0 +1,922 @@ +# Goal: Unify Component Port Declaration and Runtime Binding + +## Status + +- State: complete +- Date: 2026-08-08 +- Repository: `C:\Projects\FluxFlow` +- Accepted base branch: `main` +- Breaking changes: allowed +- Backward-compatibility shims: not required +- Runtime behavior: preserve +- Component functionality: preserve +- Package publication: out of scope +- Commit, push, pull request, or release: do not perform unless separately authorized + +## Objective + +Simplify FluxFlow component registration by eliminating the duplicated declaration of input names, output names, message types, and runtime Dataflow bindings. + +The current authoring model requires component authors to declare ports twice: + +1. inside `ComponentInstance.Create(...)`, using `ComponentPorts.Input(...)`, `ComponentPorts.Output(...)`, and optionally `events: node.Events`; and +2. again on `RuntimeComponentRegistrationBuilder` or `ComponentRegistrationBuilder`, using `AddInput(...)` and `AddOutput(...)`. + +Although the two declarations currently serve different internal purposes—static descriptor metadata versus activated runtime bindings—the public authoring API must make one explicit declaration authoritative for both. + +Implement a typed, flat component-factory builder where: + +- `UseFactory(...)` establishes the concrete node type; +- `AddInput(name, selector)` declares input metadata and binds the activated input; +- `AddSignalInput(name, selector)` declares signal metadata and binds the activated signal target; +- `AddOutput(name, selector)` declares output metadata and binds the activated output; +- `AddEvents(name, selector)` declares a named event output and binds its event source; +- message types are inferred from the selected node members wherever C# type inference permits; +- component authors never repeat the same port name or message type between descriptor and runtime construction; +- normal authoring does not directly construct `ComponentInstance`; +- normal authoring does not directly call `ComponentPorts.Input`, `Output`, or `SignalInput`; +- every port is explicit—no event port is injected automatically; +- the design remains flat, strongly typed, reflection-free, deterministic, and understandable. + +Do not lose runtime validation, event conversion, lifecycle ownership, custom cleanup, processing capabilities, options, resources, Designer metadata, application linking, JSON compatibility, or existing component behavior. + +## Mandatory Initial Repository Handling + +Before modifying code: + +1. Inspect `git status`, the active branch, and recent history. +2. Preserve every existing user change. +3. The working tree currently contains the completed package-consumer process-restart durability work. Do not discard, reset, overwrite, or accidentally rewrite it. +4. Pay particular attention to the existing changes in: + - `eng/package-consumer-acceptance`; + - `tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs`; + - durability documentation; + - `memory`; + - the existing restart-durability goal. +5. Update affected parts of those changes to the new component API when necessary, but do not change their durability behavior or acceptance contract. +6. Do not use destructive Git operations. +7. Before implementation, create: + - `goals/2026-08-08-typed-component-port-binding/README.md` +8. Store this accepted goal in that file and maintain its status and verification evidence during execution. +9. Do not stage, commit, push, or publish unless separately authorized. + +## Authoritative Public Authoring Shape + +The normal runtime-only component API must support this flat form: + +```csharp +services.AddFluxFlowComponents() + .AddRuntimeComponent("sample.uppercase", component => + { + component + .UseFactory(static _ => new UppercaseNode()) + .AddInput("Input", static node => node.Input) + .AddOutput("Output", static node => node.Output) + .AddEvents("Events", static node => node.Events); + }); +``` + +The port name must appear exactly once. The `string` message type in this example must be inferred from the selected node input and output members. + +A source component should read naturally: + +```csharp +component + .UseFactory(static context => + { + var options = context.BindConfiguration(); + return new StringSourceNode(options.Messages); + }) + .AddOutput("Output", static node => node.Output) + .AddEvents("Events", static node => node.Events); +``` + +A sink should read naturally: + +```csharp +component + .UseFactory(context => new CollectSinkNode(collector)) + .AddInput("Input", static node => node.Input) + .AddEvents("Events", static node => node.Events); +``` + +Signal inputs must use the same model: + +```csharp +component + .UseFactory(CreateTriggerNode) + .AddSignalInput("Ack", static node => node.Ack) + .AddSignalInput("Nak", static node => node.Nak) + .AddOutput("Output", static node => node.Output) + .AddEvents("Events", static node => node.Events); +``` + +Support synchronous and asynchronous node factories without forcing callers to write unnecessary `ValueTask.FromResult(...)` wrappers: + +```csharp +component.UseFactory(static _ => new UppercaseNode()); +``` + +```csharp +component.UseFactory(static context => CreateNodeAsync(context)); +``` + +Use clear overloads and constraints. The activated node type must implement `IFlowNode`. + +## Fluent Builder Requirements + +`UseFactory(...)` must return a node-typed fluent builder. The exact internal type name may be selected during implementation, but the public behavior must be clear and cohesive. + +The typed builder must provide: + +```csharp +AddInput( + string name, + nodeSelector, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) +``` + +```csharp +AddSignalInput( + string name, + nodeSelector, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) +``` + +```csharp +AddOutput( + string name, + nodeSelector, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) +``` + +```csharp +AddEvents( + string name, + nodeSelector, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) +``` + +Each method must return the same typed builder so the calls remain fluent. + +Port selectors must be strongly typed delegates: + +- input selectors return an `ITargetBlock>`; +- signal selectors return an `IFlowSignalTarget`; +- normal output selectors return an `ISourceBlock>`; +- event selectors return an `ISourceBlock`. + +Do not use: + +- reflection; +- expression-tree inspection; +- property-name conventions; +- runtime type scanning; +- attributes for port discovery; +- assembly discovery; +- dynamic dispatch; +- `object`-based selector contracts; +- service-location tricks; +- factory execution during registration; +- nested port callbacks; +- terminal `Build`, `Commit`, or `Apply` calls. + +The component configuration callback must still execute synchronously and exactly once during registration. + +## One Authoritative Port Declaration + +Each typed port call must create both parts of the component contract. + +At registration time it must create immutable descriptor metadata: + +- normalized port name; +- message type; +- signal versus message semantics; +- link cardinality; +- input or output direction; +- Designer metadata where applicable. + +At activation time it must use the stored selector to create the corresponding runtime binding against the activated node. + +Conceptually: + +```csharp +.AddInput("Input", static node => node.Input) +``` + +must generate both: + +```csharp +ComponentPortMetadata.Create("Input") +``` + +and: + +```csharp +ComponentPorts.Input("Input", node.Input) +``` + +The component author must not write those two forms independently. + +Selectors must not execute during registration. They execute only after the node factory successfully returns a node instance. + +## Explicit Event Ports + +Events must behave as explicitly declared named ports. + +Use: + +```csharp +.AddEvents("Events", static node => node.Events) +``` + +or: + +```csharp +.AddEvents("Diagnostics", static node => node.Events) +``` + +The author chooses the port name. `"Events"` is a normal explicit choice, not an automatically injected or globally reserved name. + +Required event behavior: + +- Remove automatic event-output insertion from `ComponentDescriptor`. +- Remove the assumption that every component has an output named `"Events"`. +- Remove the global reservation that prevents a normal output from using the name `"Events"`. +- A component that does not call `AddEvents(...)` must not receive an implicit event output. +- `AddEvents(...)` creates output metadata whose externally visible payload type is `ComponentEvent`. +- The selected node source continues to produce `FlowEvent`. +- Preserve the existing bridge that converts `FlowEvent` into addressable `ComponentEvent`. +- Preserve correlation identity, timestamps, component address, event name, level, message, and sanitized invariant attributes. +- Preserve bounded, ordered, best-effort event behavior. +- Preserve the rule that component failure remains observable through component completion and does not fault the event output. +- Preserve event-output completion and disposal behavior. +- Unconsumed events must not hold component completion open. +- The selected event port name must be used in the runtime output dictionary and application address. +- An event port must participate in descriptor validation, Designer metadata, runtime validation, application linking, stable port surfaces, and authoring handles like other output ports. +- Permit zero or more explicitly named event ports if the implementation remains small and follows the same output-name uniqueness rules. +- Event ports and normal output ports share the same output-name namespace. +- Duplicate output/event names fail immediately. +- Do not add a new `ComponentPortKind.Event` unless an unavoidable existing runtime requirement proves it necessary. Prefer representing the externally linkable event port as a normal typed `ComponentEvent` output while retaining `AddEvents(...)` as the explicit source-conversion operation. +- Do not confuse component event ports with the separate reserved application-level system addresses such as `System.Events.Output`. + +Audit `ComponentEvents.PortName`. It must no longer control registration, validation, or runtime attachment. Remove it if it has no honest remaining purpose. Do not retain a compatibility constant that suggests the name is still globally reserved. + +## Runtime Instance Construction + +The typed factory path must internally construct the final `ComponentInstance`. + +After node activation: + +1. evaluate input selectors in declaration order; +2. evaluate signal selectors in declaration order; +3. evaluate normal output selectors in declaration order; +4. evaluate event selectors in declaration order; +5. reject null bindings with a clear error containing the component and port context; +6. build immutable or detached runtime port collections; +7. create the `ComponentInstance`; +8. attach named event bridges; +9. retain existing completion, startup, linking, and disposal semantics. + +Do not expose mutable builder collections through descriptors or runtime instances. + +The runtime must continue validating that an activated instance exactly matches its descriptor. The typed path should make mismatches structurally difficult, but `ApplicationRuntimeComponentActivator.ValidateInstance(...)` remains defense in depth and must continue protecting advanced factories. + +If activation, selector evaluation, event attachment, or validation fails: + +- dispose the created node; +- dispose any additional owned activation resource; +- dispose any event bridges already created; +- do not leak a partially created component; +- preserve the original failure; +- preserve existing aggregate-failure behavior when cleanup also fails; +- do not perform cleanup twice. + +## Processing and Source Behavior + +Preserve: + +- `CompositionProcessingCapabilities`; +- processing configuration before node construction where currently required; +- `IFlowSource` detection and source startup; +- component completion; +- normal completion and fault propagation; +- application revision ownership; +- stable input/output addressing; +- link cardinality enforcement; +- reliable normal-data delivery; +- best-effort diagnostic events; +- resource scoping; +- component option binding; +- keyed resources; +- application revision disposal. + +The new binding builder must not start nodes or resolve services during registration. + +## Options, Resources, and Display Metadata + +Options and resources remain explicit root-level component declarations. Do not fold them into a universal object or add nested builders. + +A designed component should remain flat: + +```csharp +builder.AddComponent("sample.uppercase", component => +{ + component.WithDisplay( + displayName: "Uppercase", + category: "Samples"); + + component.AddOption( + "boundedCapacity", + OptionValueKind.Number, + displayName: "Bounded Capacity", + defaultValue: 256, + min: 1); + + component + .UseFactory(static context => + { + var options = context.BindConfiguration(); + return new UppercaseNode(options); + }) + .AddInput( + "Input", + static node => node.Input, + displayName: "Input", + isPrimary: true) + .AddOutput( + "Output", + static node => node.Output, + displayName: "Output", + isPrimary: true) + .AddEvents( + "Events", + static node => node.Events, + displayName: "Events"); +}); +``` + +The typed builder returned from a designed `UseFactory(...)` must support the current flat port presentation arguments: + +- display name; +- group; +- order; +- summary; +- primary-port flag; +- link cardinality. + +Do not require a second `DescribePort(...)` call that repeats the port name. + +Preserve: + +- `WithDisplay(...)`; +- option choices and attributes; +- resource metadata and attributes; +- port attributes; +- component attributes; +- metadata finalization; +- immutable catalog snapshots; +- canonical processing hints; +- immediate validation; +- idempotent equivalent registration; +- clear conflicting-registration errors. + +Keep `FluxFlow.Composition` independent from the Designer package. Add the smallest explicit extension seam needed for the Designer builder to return its designed typed binding builder. Do not introduce circular references or move Designer concepts into the Composition core. + +## Factory and Lifecycle Escape Hatch + +Some existing Storage and Sessions component factories attach additional cleanup for component-owned store instances. Preserve that behavior. + +Provide one explicit advanced path for factories that genuinely need to construct a complete `ComponentInstance` or carry additional completion/disposal ownership. Prefer a name that distinguishes it from normal node factories, such as: + +```csharp +component.UseInstanceFactory(CreateSpecialComponentInstance); +``` + +Requirements: + +- Normal packages and samples must use the typed node-factory path. +- Keep the advanced path only for concrete lifecycle needs. +- Do not make the advanced path the normal documentation example. +- Do not add obsolete overloads solely for compatibility. +- Do not weaken cleanup ownership. +- Do not move store disposal responsibility into unrelated node classes merely to avoid designing an honest activation boundary. +- If Storage and Sessions can use a single small typed activation result containing a node plus optional extra cleanup, prefer that over keeping their duplicated port declarations. +- Do not create a hierarchy of activation-result abstractions. +- A single small immutable generic activation value is acceptable when justified by the existing Storage and Sessions ownership cases. +- Preserve failure cleanup when store acquisition succeeds but later node construction or binding fails. +- Preserve node disposal plus additional cleanup aggregation. +- Keep `ComponentInstance.Create(...)` and `ComponentPorts` available only where they remain legitimate low-level runtime tools; remove them from normal component-authoring guidance. + +## Registration Identity and Idempotency + +Equivalent repeated family registration currently succeeds, while conflicting registration fails. Preserve that behavior. + +Typed factory wrapping must not accidentally make every repeated registration look different merely because a new wrapper delegate or binding collection was allocated. + +The descriptor or registration snapshot must retain an explicit comparable registration identity containing the meaningful original declarations: + +- original node or instance factory delegate; +- processing capabilities; +- input binding declarations; +- signal binding declarations; +- normal output binding declarations; +- event binding declarations; +- options; +- resources. + +Use explicit delegate/value comparisons. Do not use reflection, source-code text, expression-tree serialization, or last-write-wins behavior. + +Tests must prove: + +- repeating an equivalent built-in family registration remains idempotent; +- changing a factory conflicts; +- changing a selector conflicts; +- changing a port name, type, kind, cardinality, or event declaration conflicts; +- changing options, resources, processing, or design metadata conflicts as before. + +## Validation and Error Behavior + +Preserve or add immediate, clear failures for: + +- null builders; +- null factory delegates; +- blank component types; +- blank port names; +- null selectors; +- duplicate input names; +- duplicate normal output/event names; +- duplicate signal names; +- duplicate options; +- duplicate resources; +- invalid link cardinality; +- missing factory; +- multiple incompatible factory modes; +- factory returning null; +- selector returning null; +- descriptor/runtime port mismatch; +- runtime message-type mismatch; +- runtime signal-kind mismatch; +- event source mismatch; +- conflicting repeated registration. + +Error messages should identify the component type and relevant port where practical. Do not expose payload data, configuration values, secrets, or resource contents. + +Do not catch and replace exceptions when doing so would discard their cause. Wrap only at established activation boundaries and preserve inner exceptions. + +## Core Files to Inspect and Refactor + +At minimum, inspect and update the cohesive contracts around: + +- `src/FluxFlow.Composition/Registration/RuntimeComponentRegistrationBuilder.cs` +- `src/FluxFlow.Composition/Registration/FluxFlowRegistrationExtensions.cs` +- `src/FluxFlow.Composition/Factories/ComponentDescriptor.cs` +- `src/FluxFlow.Composition/Factories/ComponentFactory.cs` +- `src/FluxFlow.Composition/Factories/ComponentPortMetadata.cs` +- `src/FluxFlow.Composition/Runtime/ComponentPorts.cs` +- `src/FluxFlow.Composition/Runtime/ComponentInstance.cs` +- `src/FluxFlow.Composition/Runtime/ComponentEvents.cs` +- `src/FluxFlow.Composition/Runtime/ComponentEventBridge.cs` +- `src/FluxFlow.Components.Designer/ComponentRegistrationBuilder.cs` +- `src/FluxFlow.Components.Designer/ComponentRegistrationExtensions.cs` +- `src/FluxFlow.Engine/Hosting/ApplicationRuntimeComponentActivator.cs` +- `src/FluxFlow.Engine/Hosting/ApplicationRuntimePortBinder.cs` +- relevant application port-surface and link-compilation code. + +Do not modify Engine code merely because it was inspected. Change it only where the explicit named event-port or generated binding contract requires it. + +## Built-In Component Migration + +Migrate all normal component composition packages to the authoritative typed binding API. + +Audit at least these families: + +- Assertions +- Expectations +- FileSystem +- HTTP +- Mapping +- Metrics +- MQTT +- Observability +- Payloads +- Projections +- Resilience +- Routing +- Serialization +- Sessions +- Sources +- State +- Storage +- Timers +- Validation + +The release matrix currently covers 19 families and 44 component declarations. Preserve that complete registration inventory. + +For every migrated component: + +- declare every input once; +- declare every signal input once; +- declare every normal output once; +- explicitly declare its event port with `AddEvents(...)`; +- use the existing external name `"Events"` where necessary to preserve the current built-in address; +- add or reuse a family-owned `Ports.Events` constant where that family already centralizes port names; +- do not reintroduce a global reserved-name convention; +- preserve option and resource metadata; +- preserve Designer labels, groups, order, summaries, primary flags, and attributes; +- preserve node configuration and resource resolution; +- preserve processing capabilities; +- preserve external type names and existing canonical port names; +- preserve component output types and link cardinalities; +- preserve runtime behavior and disposal. + +Review MQTT separately and carefully because it owns signals, transport resources, controller/session lifecycle, and multiple component shapes. Do not simplify away its ownership semantics. + +Review Storage and Sessions carefully because of additional store cleanup. + +## Sample and Fixture Migration + +Update normal authoring examples in: + +- `samples/FluxFlow.CompositionSample` +- `samples/FluxFlow.DurabilityOperationsSample` +- `samples/FluxFlow.SampleApp` +- `samples/FluxFlow.MqttCompositionSample` +- `eng/package-consumer-acceptance` +- any other sample or acceptance consumer using `AddRuntimeComponent(...)`. + +The canonical sample should visibly demonstrate: + +```csharp +component + .UseFactory(...) + .AddInput(...) + .AddOutput(...) + .AddEvents(...); +``` + +Do not leave the old duplicated authoring shape in any public sample or primary documentation. + +Do not rewrite low-level `FluxFlow.Fluent` graph construction merely because it legitimately uses runtime instances and ports outside component registration. Keep that lower-level API unless the new implementation requires a focused correction. + +## Testing Requirements + +Follow the repository-required test-generation and test-quality workflow before changing tests. Preserve xUnit and Shouldly conventions. Do not add a new test project unless no existing project can own the behavior. + +### Composition tests + +Add or update focused tests proving: + +- sync node factory inference; +- async node factory inference; +- the factory is not called during registration; +- selectors are not called during registration; +- descriptor metadata exists before activation; +- each selector runs exactly once per activated instance; +- input message type is inferred correctly; +- output message type is inferred correctly; +- signal binding retains signal semantics; +- cardinality is preserved; +- declaration order is preserved; +- the activated runtime ports bind the exact selected node blocks; +- no duplicated manual `ComponentPorts` declaration is needed; +- component registration callbacks still run exactly once; +- catalogs remain immutable and detached from retained builders; +- equivalent registration remains idempotent; +- conflicting registration remains explicit. + +### Event tests + +Update `ComponentEventTests` and related tests to prove: + +- no event output is added implicitly; +- a component without `AddEvents(...)` has no event port; +- `AddEvents("Events", ...)` creates an output named `"Events"`; +- `AddEvents("Diagnostics", ...)` creates an output named `"Diagnostics"`; +- the external payload type is `ComponentEvent`; +- the selected source is `FlowEvent`; +- event conversion preserves address, identity, timestamp, name, level, message, and attributes; +- custom event ports can fan out; +- multiple event ports work if supported; +- duplicate normal-output/event names fail; +- a normal output may use `"Events"` when no event port uses that name; +- component faults remain on component completion; +- event output completion remains successful under the established contract; +- unconsumed events do not block completion; +- all bridges and sources are disposed exactly once. + +Do not keep tests asserting automatic `Events` injection or global reservation. + +### Designer tests + +Prove: + +- designed typed port calls create runtime metadata and design metadata from one call; +- designed event ports use the chosen name; +- event ports have output direction and `ComponentEvent` value type; +- display metadata and attributes remain intact; +- no implicit event metadata is added; +- metadata finalization remains immutable; +- equivalent registration remains idempotent; +- conflicting design registration still fails before mutating DI. + +### Engine tests + +Prove: + +- generated typed instances pass exact descriptor/runtime validation; +- advanced raw instances still fail when they omit, add, rename, or mistype ports; +- validation failure cleans up the node and additional ownership; +- application links bind selected normal and event outputs correctly; +- a custom-named event output has the expected workflow address; +- application revision lifecycle remains unchanged; +- sources still start normally; +- failure cleanup remains exact. + +### Component-family tests + +Update affected composition test projects without replacing useful behavioral assertions with source-shape checks. + +Preserve tests for: + +- factory configuration; +- resource resolution; +- option binding; +- expected ports; +- Designer metadata; +- processing capabilities; +- controller/store ownership; +- disposal; +- family idempotency. + +Update the release family matrix so all 19 families and 44 declarations remain covered with their explicit event ports. + +### Sample and acceptance tests + +Update release tests that inspect sample source or package-consumer source. Preserve the existing package-only restart durability behavior and exact markers. + +Run the real package-consumer acceptance gate after migration because its fixture directly uses runtime component registration. + +## Public API and Compatibility Baseline + +This is an intentional breaking authoring-API simplification. + +Audit: + +- `eng/public-api/baseline.txt` +- `tests/FluxFlow.Release.Tests/PublicApiBaselineTests.cs` +- `tests/FluxFlow.Release.Tests/PackageBinaryCompatibilityPolicyTests.cs` +- `docs/15-engine-compatibility.md` +- the binary-compatibility release gate. + +Update the accepted public API baseline through the repository’s documented intentional-change process. Do not disable, skip, weaken, or bypass compatibility verification. + +Do not add obsolete compatibility wrappers solely to preserve the redundant API. + +Document clearly: + +- which old authoring calls were removed or moved to the advanced path; +- the new typed fluent shape; +- why the change is intentional; +- that runtime component behavior and canonical application JSON remain preserved. + +Do not bump package versions or publish packages unless repository validation makes a version change mandatory and that requirement is explicitly justified in the final report. + +## Documentation Requirements + +Update all affected public documentation, including at minimum: + +- root `README.md`; +- `docs/03-node-authoring.md`; +- `docs/04-package-authoring.md`; +- `docs/02-definitions-and-links.md` where component-event addressing is described; +- `src/FluxFlow.Composition/README.md`; +- `src/FluxFlow.Components.Designer/README.md`; +- affected component-package READMEs; +- affected sample READMEs; +- compatibility documentation. + +Documentation must show: + +- the new typed factory chain; +- single-authoritative input/output declaration; +- signal input declaration; +- explicit named `AddEvents(...)`; +- event-source versus public `ComponentEvent` conversion; +- absence of implicit event ports; +- custom event port names; +- the advanced instance-factory escape hatch; +- lifecycle ownership; +- no reflection or scanning; +- unchanged JSON/application-definition behavior; +- unchanged normal-data and event-delivery semantics. + +Remove outdated examples containing both: + +```csharp +ComponentPorts.Input/Output(...) +``` + +and: + +```csharp +component.AddInput/AddOutput(...) +``` + +for the same registered component. + +## Memory Requirements + +Update the repository memory as part of the implementation: + +1. Add a new numbered memory entry using the next available number. +2. Record: + - the duplication that motivated the change; + - the selected typed factory-binding design; + - why descriptor metadata and runtime bindings remain internally distinct; + - how one public declaration now generates both; + - explicit named `AddEvents(...)`; + - removal of implicit globally reserved component event ports; + - advanced lifecycle escape-hatch decision; + - migration scope; + - public API break; + - verification evidence; + - remaining limitations. +3. Update `memory/00-index.md`. +4. Update `memory/01-current-state.md`. +5. Update the progress log only where repository convention requires it. +6. Do not rewrite historical memory entries merely to make them look current. +7. Record exact final test/build evidence, not intended commands. + +## Non-Goals + +Do not include: + +- durability readiness adapters; +- new storage providers; +- workflow checkpointing; +- durable internal graph state; +- transactional outbox work; +- changes to SQL-file or T-SQL schemas; +- changes to delivery guarantees; +- component discovery; +- assembly scanning; +- reflection; +- source generators; +- attributes for port inference; +- nested callback builders; +- a universal component-options object; +- dependency additions without a demonstrated requirement; +- redesign of the canonical JSON document; +- redesign of the C# workflow-definition DSL; +- unrelated formatting cleanup; +- arbitrary file splitting; +- unrelated performance refactoring; +- provider or package version changes without necessity; +- new background workers; +- new test infrastructure; +- test retries or arbitrary sleeps. + +## Dependency and Complexity Guardrails + +- Add no dependency unless unavoidable. +- Prefer direct generic delegates, small immutable records, and explicit lists. +- Keep the dependency graph unchanged if possible. +- Do not create a large hierarchy of builder interfaces. +- Do not create generic abstractions beyond the concrete typed node-binding need. +- Keep Composition independent from Engine and Designer. +- Keep Designer dependent on Composition, not the reverse. +- Keep Engine consuming immutable descriptors and runtime instances. +- Preserve SRP: + - registration builder owns declarations; + - typed binding builder owns node selectors; + - descriptor owns immutable static contract; + - component instance owns activated bindings and lifecycle; + - event bridge owns `FlowEvent` to `ComponentEvent` conversion; + - Engine owns activation validation and linking. +- Prefer one or two small new types over a broad framework. +- No hidden ambient state. +- No static mutable registration state. +- No service locator. +- No factory execution at registration time. + +## Verification Sequence + +Run focused verification first, then broaden. + +At minimum: + +1. Restore the solution if required. +2. Build: + - `FluxFlow.Composition`; + - `FluxFlow.Components.Designer`; + - `FluxFlow.Engine`; + - affected component composition projects; + - affected samples; + - Release tests. +3. Run: + - complete Composition tests; + - complete Designer tests; + - relevant Engine activation/linking tests; + - every affected component composition test project; + - component-family registration matrix tests; + - public API baseline tests; + - binary compatibility policy tests; + - sample/documentation tests; + - package-consumer acceptance script tests. +4. Run the real package-consumer acceptance gate. +5. Run the complete Release test project. +6. Run the complete Release solution build with zero warnings. +7. Run the complete Release solution test suite. +8. Run formatting verification for every touched project. +9. Run `git diff --check`. +10. Confirm no unexpected package dependency changes. +11. If dependencies changed for a justified reason, run the repository vulnerability audit. +12. Confirm no database schema, migration, generated artifact, credential, secret, or local build output was accidentally added. +13. Confirm the working tree contains the pre-existing durability restart changes plus this coherent component-authoring work, with no unrelated user changes lost. + +Do not run unrelated server-backed integration suites unless a changed dependency boundary or failing test shows they are relevant. + +## Final Acceptance Criteria + +The goal is complete only when all of the following are true: + +- The canonical runtime-only sample uses the new typed fluent chain. +- Each input name appears once. +- Each output name appears once. +- Each signal-input name appears once. +- Each event-port name appears once. +- Port message types are inferred from node selectors in normal usage. +- Normal component authors do not construct `ComponentInstance`. +- Normal component authors do not call `ComponentPorts`. +- `AddEvents(name, selector)` explicitly declares a named event output. +- No component event output is injected automatically. +- `"Events"` is not globally reserved. +- Existing built-in components explicitly retain their established `"Events"` address where required. +- Event conversion and completion behavior remain correct. +- Runtime descriptor/instance validation remains active. +- Advanced completion and additional-disposal ownership remain supported. +- Storage and Sessions cleanup remains exact. +- MQTT ownership and signal behavior remain exact. +- Options, resources, processing, Designer metadata, and application linking remain intact. +- All 19 component families and 44 declarations remain registered. +- Equivalent repeated registration remains idempotent. +- Conflicting registration remains explicit. +- Canonical application JSON behavior remains unchanged. +- No reflection, scanning, hidden convention, nested callback, or new dependency graph was introduced. +- Public API and binary compatibility baselines honestly record the intentional break. +- Samples, documentation, goal records, and memory are updated. +- Focused and full verification are green with zero warnings. +- No unrelated functionality was removed. +- No unrelated cleanup was mixed into the change. + +## Final Report + +At completion, report: + +- the final public authoring API; +- the internal ownership design; +- how port metadata and runtime binding are generated from one declaration; +- event-port behavior and naming; +- the advanced lifecycle escape hatch; +- migrated component families and samples; +- intentional public API changes; +- files and documentation updated; +- focused test results; +- full build and test results; +- package-consumer acceptance result; +- formatting and compatibility results; +- dependency status; +- any remaining limitations or consciously deferred work. + +Do not claim completion until implementation, migration, documentation, memory, compatibility baselines, and required verification are all finished. + +## Execution Evidence + +Completed 2026-08-08. + +- Added the typed runtime and designed binding builders, immutable typed node + activation result, and named low-level event-source contract. +- Removed duplicated normal authoring, automatic event-port insertion, the + global `Events` reservation, and the obsolete `ComponentEvents` constant. +- Migrated every one of the 19 component families and 44 declarations plus all + named samples and the package-consumer fixture. Storage/Sessions additional + cleanup and MQTT resource/signal ownership remain explicit and tested. +- Updated root/package documentation, compatibility guidance, the documented + public source-declaration baseline, goals, and memory. Published binary + baselines remain active so the intentional break cannot pass future package + validation without an appropriate major release. +- Focused results: Composition 139/139, Designer 120/120, Engine assembler + 18/18, Storage composition 21/21, and Release convention/matrix/docs 59/59; + all completed with zero warnings. +- Complete `FluxFlow.Release.Tests`: 169/169, zero warnings. +- Complete CI-style Release build: 134 projects, zero errors and zero warnings. +- Complete Release solution test: 2,561/2,561 across 66 projects, zero warnings + and zero skips. +- The real package-consumer `-PackPackages` gate passed exact nine-package + archive verification, external `net8.0` build, canonical behavior, SQL-file + reopen, and all process-restart recovery/idempotency markers. +- Full formatting verification, `git diff --check`, public API/binary-policy + tests, and the transitive vulnerable-package audit passed. +- No typed-authoring dependency, package version, database schema, migration, + publication, tag, release, commit, push, or pull request was introduced. diff --git a/goals/2026-08-08-unified-code-first-component-contracts/README.md b/goals/2026-08-08-unified-code-first-component-contracts/README.md new file mode 100644 index 00000000..4dd329e1 --- /dev/null +++ b/goals/2026-08-08-unified-code-first-component-contracts/README.md @@ -0,0 +1,498 @@ +# GOAL: Unify Code-First Component Authoring and Runtime Registration + +## Status + +- State: complete +- Created: 2026-08-08 +- Repository: `C:\Projects\FluxFlow` +- Execution started: 2026-08-08 +- Breaking changes: allowed when they remove the split contract model and produce a smaller final API +- Backward-compatibility aliases: not required +- Commit, push, pull request, package publication, and release: not authorized by this goal +- Required result: production implementation, repository-owned migration, focused and full verification, documentation-site content, and memory updates + +## Execution Instruction + +Execute this goal completely in the existing FluxFlow repository. Do not stop after producing an API sketch, adding compatibility wrappers, updating a sample, or making focused tests pass. + +Preserve all unrelated user work in the intentionally dirty working tree. The existing durability, package-consumer, typed component binding, explicit event naming, `HasInput`/`HasOutput`/`HasEvents`, and typed code-first authoring changes are the authoritative starting point. Never reset, discard, overwrite, or broadly reformat unrelated changes. + +Use these engineering rules throughout execution: + +1. Keep FluxFlow an explicit, lightweight, in-process workflow engine. +2. Apply KISS, SRP, IoC, and cohesive vertical-slice principles. +3. Prefer one small shared implementation over parallel authoring and runtime abstractions. +4. Do not add reflection, assembly scanning, source generation, hidden global registries, service locators, ambient builders, or convention-based magic. +5. Do not mutate `IServiceCollection` or the built service provider during application activation or hot reload. +6. Keep dependency injection standard: component factories receive the existing activation context and resolve normal application dependencies from it. +7. Keep fluent authoring flat. A component contract may use one ordinary configuration callback internally, but application authors must not enter nested callback scopes or repeat runtime declarations. +8. Do not create a large dependency graph, a universal registry abstraction, or a new package solely for this feature. +9. Use the existing descriptor, catalog, definition, revision, and activation mechanisms wherever they already express the required behavior. +10. Preserve the independent JSON definition and hot-reload path exactly; do not make JSON depend on executable C# delegates. +11. Before changing tests, follow the repository's mandatory code-testing workflow and maintain `.testagent/research.md`, `.testagent/plan.md`, and `.testagent/status.md`. +12. Keep this file current. Replace pending evidence with exact commands, counts, and outcomes before marking the goal complete. + +## Problem Statement + +The typed C# DSL currently requires two separate declarations of the same component: + +1. `WorkflowDefinitionBuilder.AddComponent(..., SampleComponents.Uppercase, ...)` uses an authoring-only contract that knows the component type, options mapping, and typed handle. +2. `services.AddFluxFlowComponents().AddRuntimeComponent(...)` separately declares the node factory and the same named input, output, signal, and event bindings. + +That split makes the normal code-first experience verbose and error-prone. A component package or application can accidentally let its typed handle, design metadata, and runtime descriptor drift apart. The host also repeats registration that is already implied by choosing a complete typed contract in compiled C#. + +The repeated application code must disappear. A code-first application that adds a complete component contract must already contain everything required to validate, activate, and run that component. + +## Objective + +Replace the authoring-only contract with one complete, explicit component contract that is the single authority for: + +- the stable component type identifier; +- the executable runtime node factory; +- typed input bindings; +- typed signal-input bindings; +- typed output bindings; +- the explicitly named event output binding; +- component processing capabilities and existing descriptor metadata; +- optional C# authoring-options construction and mapping into `ComponentDefinitionBuilder`; +- the typed authoring handle exposed to application code. + +When a complete contract is added through the C# application builder, the resulting immutable `ApplicationDefinition` must own the runtime descriptors used by that definition. `services.AddFluxFlow(definition)` must then be sufficient to execute the application; the caller must not repeat `AddFluxFlowComponents().AddRuntimeComponent(...)` for those contracts. + +## Required Normal Code-First Experience + +The final normal application usage must have this shape: + +~~~csharp +var application = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var workflow); + +workflow + .AddComponent( + "first", + SampleComponents.Uppercase, + out var first) + .AddComponent( + "second", + SampleComponents.Uppercase, + out var second); + +first.Output.ConnectTo(second.Input); + +var definition = application.Build(); + +var services = new ServiceCollection(); +services.AddFluxFlow(definition); + +await using var provider = services.BuildServiceProvider(); +await provider.StartFluxFlowApplicationAsync(); +~~~ + +The normal code-first host must not also call: + +~~~csharp +services.AddFluxFlowComponents() + .AddRuntimeComponent(...); +~~~ + +Application dependencies remain ordinary DI registrations next to `AddFluxFlow`; for example, a sink service or HTTP client is still added to `IServiceCollection`, and the component factory resolves it through `ComponentActivationContext.Services`. + +## Required Single Component Declaration + +Introduce the final public concept as `ComponentContract`, replacing the narrower `ComponentAuthoringContract` terminology. The exact implementation must remain small and may reuse the existing `RuntimeComponentRegistrationBuilder`; it must not duplicate descriptor construction or binding validation. + +The supported declaration must be explicit and statically typed. A representative no-options declaration is: + +~~~csharp +public static ComponentContract Uppercase { get; } = + ComponentContract.Create( + SampleComponentTypes.Uppercase, + runtime => + { + runtime + .UseFactory(static _ => new UppercaseNode()) + .HasInput(SampleComponentPorts.Input, static node => node.Input) + .HasOutput(SampleComponentPorts.Output, static node => node.Output) + .HasEvents(SampleComponentPorts.Events, static node => node.Events); + }, + static component => new UppercaseHandle(component)); +~~~ + +A representative options-aware declaration is: + +~~~csharp +public static ComponentContract Source { get; } = + ComponentContract.Create( + SampleComponentTypes.Source, + runtime => + { + runtime + .UseFactory(static context => + { + var options = context.BindConfiguration(); + return new StringSourceNode(options.Messages); + }) + .HasOutput(SampleComponentPorts.Output, static node => node.Output) + .HasEvents(SampleComponentPorts.Events, static node => node.Events); + }, + static () => new SourceOptionsBuilder(), + static (options, definition) => options.Apply(definition), + static component => new SourceHandle(component)); +~~~ + +The implementation may improve the delegate ordering if that produces clearer overload inference, but it must retain these semantics: + +- one complete declaration; +- one runtime configuration scope at most; +- a flat typed `UseFactory(...).HasInput(...).HasOutput(...).HasEvents(...)` chain; +- no second descriptor declaration; +- no node activation while declaring, registering, designing, validating, or building an application; +- factories execute only during runtime activation. + +## Public API Requirements + +### Complete contracts + +1. Provide a non-generic `ComponentContract` factory surface. +2. Provide typed contracts for: + - components without authoring options: `ComponentContract`; + - components with authoring options: `ComponentContract`. +3. Keep normal construction factory-only. The typed contract classes may expose + controlled protected construction solely so the Designer package can attach + metadata to the exact same descriptor without a registry or second + declaration. +4. Keep the existing `AuthoredComponentHandle` constraint. +5. Expose the normalized `Type` and the complete immutable `ComponentDescriptor` as read-only contract state. +6. Validate null/empty type, runtime configuration, factory, options creation, options mapping, and handle creation at the narrowest useful boundary with component-type context. +7. Reject a runtime declaration without a factory through the existing descriptor validation. +8. Preserve sync, `ValueTask`, activation-owner cleanup, and advanced instance-factory capabilities already supported by `RuntimeComponentRegistrationBuilder`. +9. Remove the old `ComponentAuthoringContract` public types rather than leaving two overlapping normal paths. Breaking changes are allowed and every repository-owned caller must migrate. + +### Workflow authoring + +1. Keep the familiar `AddComponent(name, contract, out handle)` signature. +2. Keep the handle-returning counterparts where already present. +3. Keep the options-aware overload with `Action` and `out THandle`. +4. Adding a complete contract must atomically add both the component definition and its descriptor ownership to the builder. +5. If options mapping, handle creation, or descriptor validation fails, no partial component or contract entry may remain in the workflow/application builder. +6. Reusing the exact same contract for many component instances and across workflows must deduplicate the descriptor by component type/reference. +7. Conflicting contracts for the same type must fail deterministically and name the conflicting component type. +8. Preserve the existing low-level string-based `AddComponent(name, type, ...)` overloads for dynamic/advanced scenarios. Those overloads do not invent a runtime descriptor and therefore still require explicit host registration. + +### Explicit host registration + +1. Add a concise `FluxFlowRegistrationBuilder.AddComponent(ComponentContract contract)` path for JSON and dynamic definitions. +2. That method must register the contract's exact descriptor through the existing descriptor-registration/conflict logic. +3. Official family registration extensions must call this contract-based path rather than repeat factories and ports. +4. Keep `AddRuntimeComponent(type, Action)` as the low-level advanced escape hatch. +5. Document `AddRuntimeComponent` as advanced/dynamic infrastructure, not the normal code-first application path. + +## Definition Ownership and Serialization Boundary + +Extend the immutable application definition with definition-owned runtime descriptors for complete C# contracts. + +Required behavior: + +1. `ApplicationDefinitionBuilder.Build()` captures an immutable, deterministic, read-only set of the descriptors actually introduced by complete contracts. +2. The set is ordered by component type for deterministic diagnostics and inspection. +3. A plain constructor-created or JSON-loaded `ApplicationDefinition` has no definition-owned runtime descriptors. +4. The code-only descriptor collection must never be emitted into canonical JSON. +5. JSON parsing must never try to create delegates, factories, handles, or descriptors. +6. Serializing a code-first definition continues to serialize only the existing portable resources and workflows. This is a diagnostic/portable projection, not a round-trip guarantee for executable C# behavior. +7. Deserializing that JSON produces a normal JSON definition that requires explicit host/package component registration. +8. Do not add C# export, source generation, UI-designer integration, delegate serialization, or a generalized polymorphic JSON contract. + +## Effective Runtime Catalog + +The runtime must resolve one deterministic effective catalog for every candidate definition: + +~~~text +host-registered descriptors + definition-owned descriptors -> one effective ComponentCatalog +~~~ + +Required rules: + +1. JSON definitions use only the host catalog and preserve current behavior. +2. Complete C# definitions use their embedded descriptors without requiring service registration. +3. Mixed definitions may use both complete contracts and low-level string component types. +4. The same descriptor instance registered in the host and embedded in the definition is accepted and deduplicated. +5. Two different descriptor instances for the same type are treated as a conflict, even if their metadata appears similar. No source silently wins. +6. Conflict diagnostics name the component type and make the host-versus-definition conflict understandable. +7. Unknown component types preserve the existing clear component-address/type diagnostic. +8. Resolve the effective catalog per candidate revision without modifying global state or the service provider. +9. Use that same effective catalog for link compilation, port-surface creation, descriptor validation, and component activation. +10. Avoid resolving/merging separate catalogs independently in multiple runtime stages; compute once per plan/candidate and pass it explicitly. + +## Runtime and Revision Semantics + +1. Initial activation from `services.AddFluxFlow(codeFirstDefinition)` must run with no manual component registration. +2. A later successful `ApplyAsync(nextCodeFirstDefinition)` may introduce, remove, or replace complete contracts without rebuilding the service provider. +3. Revision planning must treat a changed definition-owned descriptor identity used by a workflow as a workflow update. +4. Do not inspect, serialize, compile, or hash delegate bodies. Descriptor reference identity is the explicit code-behavior identity. +5. Reusing the same complete contract/descriptor produces stable revision comparison. +6. A changed contract for the same type must not silently reuse an old runtime generation. +7. Failed planning, conflict validation, factory activation, port validation, or candidate adoption must leave the active revision and generation unchanged. +8. Candidate cleanup must preserve existing component instance, activation-owner, resource snapshot, and port-generation disposal guarantees. +9. The active definition owns its descriptor/factory delegates. After a successful replacement, the host must not retain the retired definition-owned factory closure through `LastUpdate` or another cache. +10. Add deterministic lifetime coverage using a captured object plus forced full collection, following the existing typed-predicate retirement test pattern. +11. A failed replacement must retain the old active definition and keep its route/factory usable. + +## Designer and Metadata Semantics + +1. A complete contract's descriptor is also the single source for Designer metadata. +2. Official Designer registration must continue to collect metadata without executing component factories. +3. Explicit event names and direction-local deterministic orders remain unchanged. +4. A normal port may still be named `Events` when no explicit event binding reserves that name; do not reintroduce implicit event injection. +5. The existing designed-component low-level builder remains available for metadata-only/dynamic extensions, but official complete contracts must not duplicate their metadata there. + +## Official Component Family Migration + +Migrate all official typed component declarations, currently covering 19 component families and 44 contracts, to the complete `ComponentContract` model. + +For every official contract: + +1. Move or reuse the existing runtime factory/binding declaration so it is owned exactly once by the contract. +2. Preserve the public typed options builder and handle. +3. Preserve all option names, defaults, required flags, resource requirements, processing capabilities, input/output/signal/event types, names, and link cardinalities. +4. Preserve explicit typed `Events` on every official handle where currently promised. +5. Change the family service-registration extension to register the exact contract descriptor. +6. Ensure family registration remains idempotent and conflict-safe. +7. Ensure Designer metadata still matches runtime metadata without activation. +8. Preserve MQTT registrar, keyed resource, client ownership, subscription, and lifecycle semantics; only remove duplicate component descriptor declarations. +9. Do not move backend/resource settings into `FluxFlowApplicationOptions`. + +## Samples and Package Consumer + +### Composition sample + +Rewrite `samples/FluxFlow.CompositionSample/Program.cs` so it demonstrates: + +- each custom component declared once as a complete contract; +- workflow construction through typed `AddComponent` handles; +- typed `ConnectTo` links; +- `services.AddFluxFlow(definition)` with no redundant runtime component registration; +- normal DI registration only for genuine application services such as the collector; +- successful execution with the existing observable output. + +### Other repository samples + +Update SampleApp, MQTT composition, durability operations, and any other code-first sample that currently registers descriptors duplicated by the contracts it adds. Preserve explicit family/resource registration only where it is genuinely required by JSON loading, resource registrars, or low-level string components. + +### Package-only acceptance + +Extend the isolated `net8.0` package consumer so one marker proves a complete custom component contract can be: + +1. declared from candidate packages only; +2. added to a code-first definition; +3. executed after only `services.AddFluxFlow(definition)` plus real dependency registrations; +4. linked through typed handles; +5. restored, built, and run without project references or fallback packages. + +Preserve all existing JSON, Fluent, engine, durability, restart, cleanup, and exact-marker assertions. + +## Testing Requirements + +Use xUnit and Shouldly in the existing test projects. Do not create a new test project unless the existing ownership boundaries make coverage impossible. + +### Composition tests + +Cover at minimum: + +- complete no-options and options-aware contract construction; +- exact descriptor factory and binding metadata; +- no factory execution during contract creation, builder use, `Build`, JSON serialization, or explicit registration; +- typed handle and options mapping behavior; +- atomic failure for null options, throwing options/configuration, null handle, and duplicate component names; +- descriptor deduplication when one contract is used repeatedly; +- deterministic conflict rejection for two contracts with the same type; +- immutable deterministic definition-owned descriptor collection; +- code-only descriptors omitted from JSON; +- JSON round-trip returns an empty definition-owned descriptor collection; +- contract-based service registration reuses the exact descriptor; +- idempotent same-contract registration and conflicting-contract rejection; +- public-surface reflection tests for the final names and removal of `ComponentAuthoringContract`. + +### Engine tests + +Cover at minimum: + +- direct initial code-first activation with no manual descriptor registration; +- local and cross-workflow typed routing using embedded descriptors; +- mixed embedded-contract and host-registered string component execution; +- JSON definition execution remains host-registration based; +- same embedded descriptor also registered by the host is accepted; +- conflicting host and embedded descriptors are rejected before activation; +- hot reload introduces a new contract/type without rebuilding DI; +- changed descriptor identity marks the affected workflow updated; +- unchanged descriptor identity remains stable; +- successful replacement activates the new factory and retires the old generation; +- failed replacement preserves the old active generation; +- retired captured factory closure becomes collectible after successful replacement; +- factory, validation, and cleanup diagnostics remain contextual and deterministic. + +### Official family, Designer, release, and source-shape tests + +Cover at minimum: + +- 19 families and 44 declarations are complete contracts; +- every contract exposes an exact runtime descriptor and typed handle/events surface; +- family registration uses the contract descriptor rather than an independent `AddRuntimeComponent` declaration; +- metadata/runtime equivalence remains green; +- Designer does not activate factories; +- normal code-first samples contain no redundant runtime registration; +- low-level `AddRuntimeComponent` remains available but is absent from the normal typed samples; +- public API baseline is updated intentionally; +- documentation distinguishes complete code-first contracts, JSON registration, and the low-level escape hatch. + +## Documentation and Memory Requirements + +Update all affected user-facing material, including: + +- root `README.md`; +- `src/FluxFlow.Composition/README.md`; +- `src/FluxFlow.Engine/README.md` when host behavior is described; +- relevant official component-composition READMEs; +- `docs/README.md`; +- typed code-first authoring documentation; +- public API overview; +- definition/JSON boundary documentation; +- migration documentation for the breaking `ComponentAuthoringContract` to `ComponentContract` change; +- release-validation/package-consumer documentation; +- sample comments and snippets. + +Add `memory/300-unified-code-first-component-contracts.md` and update `memory/00-index.md` and `memory/01-current-state.md` with: + +- the architectural decision; +- final API shape; +- code-first versus JSON boundary; +- effective-catalog conflict rules; +- revision/lifetime behavior; +- official-family migration; +- exact verification evidence; +- remaining intentional limitations. + +Do not leave stale examples containing both typed `AddComponent(contract)` and a duplicate `AddRuntimeComponent` registration. + +## Explicit Non-Goals + +This goal does not authorize: + +- serializing factories, delegates, handles, or executable contracts into JSON; +- generating C# from JSON or from a UI designer; +- making the UI designer consume or emit C# application builders; +- reflection or assembly scanning to discover contracts; +- source generators; +- an ambient/global component registry; +- automatic registration based on loaded assemblies; +- rebuilding or mutating the service provider during revision activation; +- removing explicit registration required by JSON/dynamic definitions; +- removing the low-level string `AddComponent` or `AddRuntimeComponent` escape hatches; +- changing component business behavior, option schemas, resource semantics, delivery guarantees, or storage-provider configuration; +- redesigning MQTT resources or lifecycle ownership; +- unrelated cleanup outside the touched authoring/registration/runtime slice; +- package publication or a release. + +## Implementation Sequence + +1. Record repository, graph, and test-ownership research. +2. Add the complete `ComponentContract` types by reusing the existing runtime registration builder and descriptor validation. +3. Replace workflow contract overloads and capture descriptor ownership atomically. +4. Add immutable definition-owned descriptors while preserving canonical JSON. +5. Add contract-based explicit service registration for JSON/dynamic hosts. +6. Resolve one effective catalog per runtime candidate and pass it through compilation, port-surface creation, and activation. +7. Add descriptor-aware revision comparison and retired-factory lifetime correctness. +8. Migrate official families and Designer metadata to the single descriptor source. +9. Migrate samples and package-only acceptance. +10. Update public API baseline, documentation site, READMEs, migration guidance, and memory. +11. Run focused tests after each owned slice. +12. Run sample processes and real package-only candidate acceptance. +13. Run the full Release build, full solution tests, full Release tests, format, diff, hygiene, and vulnerability gates. +14. Audit requirements against evidence, complete this file, and mark the goal complete only when every required result is satisfied. + +## Verification Matrix + +Run and record exact results for: + +1. focused `FluxFlow.Composition.Tests`; +2. focused `FluxFlow.Components.Designer.Tests`; +3. focused `FluxFlow.Engine.Tests`; +4. affected official component-composition test projects; +5. focused Release convention, public API, documentation, family-matrix, and package-script tests; +6. CompositionSample, SampleApp, MQTT composition sample, and any other changed executable sample; +7. real `eng/package-consumer-acceptance.ps1 -PackPackages` candidate-only gate; +8. full Release build with zero warnings and errors; +9. full solution tests with zero failures, skips, and warnings; +10. full Release tests; +11. full `dotnet format --verify-no-changes`; +12. full `git diff --check`; +13. source hygiene scans for reflection, scanning, hidden registries, duplicate sample registration, sleeps/skips, TODO/FIXME markers, and accidental compatibility aliases; +14. transitive vulnerability audit without restore. + +Do not run overlapping build/test/package commands. Coordinate the build lane with the test agent and verify that timed-out child processes have exited before retrying. + +## Acceptance Criteria + +This goal is complete only when all of the following are true: + +- A component's authoring and runtime behavior have one complete contract declaration. +- The old authoring-only contract types are removed. +- Typed code-first workflow use automatically carries the exact runtime descriptors it needs. +- `services.AddFluxFlow(codeFirstDefinition)` executes complete contracts without redundant runtime registration. +- Low-level string components still require explicit host registration. +- JSON loading, persistence, canonical serialization, and hot reload remain portable and independently registered. +- Code-only descriptors never appear in JSON. +- One effective catalog is used consistently throughout each runtime candidate. +- Same-descriptor reuse is accepted; conflicting descriptors fail deterministically. +- Revisions can introduce and replace code-first contracts without rebuilding DI. +- Failed revisions preserve the old application; successful revisions release retired factory closures. +- Official 19-family/44-contract behavior and metadata are preserved from one declaration source. +- MQTT ownership and lifecycle semantics are preserved. +- Normal samples contain no duplicate runtime declarations. +- Isolated package-only acceptance proves the simplified path from candidate packages. +- Documentation site, READMEs, public API baseline, migration guidance, and memory are current. +- Focused and full verification are green with zero warnings and no unexplained skips. +- No unrelated working-tree changes were lost. +- No commit, push, pull request, package publication, or release was performed. + +## Final Report Requirements + +The final report must include: + +1. the final component-contract API; +2. the simplified complete code-first example; +3. the explicit JSON registration example; +4. the advanced/dynamic escape-hatch example; +5. the definition-owned descriptor and effective-catalog architecture; +6. conflict, revision, rollback, and lifetime semantics; +7. official family, Designer, sample, and package-consumer migrations; +8. all intentional breaking changes; +9. exact focused and full verification results; +10. documentation and memory files updated; +11. any remaining limitations or deferred work; +12. confirmation that no commit, push, publication, or release was performed. + +## Execution Evidence + +| Requirement | Evidence | +|---|---| +| Repository and dirty-tree inspection | Completed before production edits; existing work is preserved. | +| Architecture/dependency trace | Graph and source trace completed for contracts, workflow builder, immutable definition, catalog, link compiler, runtime plan, port surface, activation, revision planner, official families, samples, and package acceptance. | +| Testing workflow | Mandatory analyzer invoked once; `.testagent/research.md`, `plan.md`, and `status.md` maintained by the test owner. | +| Complete contract public API | `ComponentContract`, typed variants, exact descriptor state, workflow overloads, and explicit registration implemented; old public type removed. | +| Definition-owned runtime descriptors | Immutable deterministic `ApplicationDefinition.ComponentDescriptors` implemented and omitted from JSON. | +| Effective runtime catalog | Host and definition descriptors merge once per candidate; exact reuse deduplicates and conflicts reject. | +| Code-first execution without duplicate registration | Composition sample runs with only `AddFluxFlow(definition)` and prints `ALPHA` / `BETA`. | +| Independent JSON registration and hot reload | Focused Composition/Engine regression coverage green; full gate pending. | +| Revision, rollback, and lifetime behavior | Focused Engine filter 52 passed, including introduce/remove/replace, rollback, and collectible factory closure. | +| Official 19-family/44-contract migration | Production migration complete; focused Release matrix pending. | +| Designer metadata equivalence and no activation | Focused Designer filter 17 passed with exact descriptor identity and zero activation. | +| Sample migration | Composition, SampleApp, MQTT, and package consumer source migration complete; remaining process gates pending. | +| Package-only candidate acceptance | Real `-PackPackages` acceptance passed from candidate archives with JSON, embedded-contract code-first, durability restart, exact markers, and cleanup. | +| Public API baseline | Intentional baseline accepted through the documented variable and independently verified: 2 passed, 0 warnings. | +| Documentation and memory | Root/package READMEs, docs 03/04/09/14/22/38/39/40/index, and memory 00/01/299/300 updated. | +| Focused tests | Composition 51 passed; Designer 17 passed; Engine 52 passed; zero failures, skips, and warnings. | +| Full Release build | `dotnet build FluxFlow.sln -c Release --no-restore -p:ContinuousIntegrationBuild=true`: 134 projects, 0 warnings, 0 errors. | +| Full solution and Release tests | Full solution: 2,597 passed across 66 projects, 0 failed/skipped/warnings. Dedicated Release: 174 passed, 0 warnings. | +| Format, diff, hygiene, and vulnerability gates | Full format verify and `git diff --check` exit 0; legacy/magic/duplicate/skip/TODO scans clean; every solution project reports no vulnerable direct or transitive packages. | + +No commit, push, pull request, package publication, or release is authorized. diff --git a/memory/00-index.md b/memory/00-index.md index 13f1df66..92891cb5 100644 --- a/memory/00-index.md +++ b/memory/00-index.md @@ -1,6 +1,6 @@ # FluxFlow Memory Index -Date: 2026-08-02 +Date: 2026-08-08 This folder records the extraction work for `FluxFlow.Engine`. @@ -748,6 +748,35 @@ This folder records the extraction work for `FluxFlow.Engine`. - `295-package-consumer-acceptance-gate.md`: isolated package-only Engine, Fluent, and SQL-file durability execution, exact candidate-byte verification, automatic CI/rehearsal integration, and the no-runtime-change boundary. +- `296-package-consumer-restart-durability-acceptance.md`: deterministic + package-only seed/recovery processes proving SQL-file lease recovery, + hosted workflow/output completion, and host-owned idempotent effects without + an exactly-once claim. +- `297-typed-component-port-binding.md`: one typed authoritative port + declaration, explicit named component-event outputs, lifecycle ownership, + complete family/sample migration, and intentional public API simplification. +- `298-declarative-component-port-naming.md`: clean `HasInput`/`HasOutput`/ + `HasSignalInput`/`HasEvents` terminology for mapping existing node members to + the component contract without implying duplicate port creation. +- `299-typed-code-first-application-authoring.md`: typed component contracts, + named handles and Events, flat workflow capture, local/cross-workflow + connections, definition-owned C# predicates, independent JSON/C# sources, + family/sample migration, and verification evidence. +- `300-unified-code-first-component-contracts.md`: complete component contracts + as the single runtime/authoring authority, definition-owned descriptors, + effective-catalog and revision rules, JSON separation, official-family and + sample migration, and verification evidence. +- `301-end-to-end-code-first-simplification.md`: typed handles through runtime + and durability, executable code-first resource contracts, MQTT registrar + consolidation, canonical-backed Fluent lifecycle, advanced dynamic + registration, and preserved JSON/ownership boundaries. +- `302-application-health-readiness.md`: optional standard .NET readiness over + existing Engine lifecycle state, exact healthy/degraded/unhealthy semantics, + bounded privacy-safe data, package-only proof, and zero-worker ownership. +- `303-performance-concurrency-lifetime-baseline.md`: permanent benchmark + coverage, bounded hot-path audit, measured allocation reductions, + deterministic concurrency/revision/shutdown proof, and manual-only timing + policy. - `report.md`: original FluxMq migration spike report supplied for review. - `legacy-docs/`: historical pre-cleanup docs; current decisions override older API descriptions in this folder. diff --git a/memory/01-current-state.md b/memory/01-current-state.md index d1aa218b..950fd1c2 100644 --- a/memory/01-current-state.md +++ b/memory/01-current-state.md @@ -1,14 +1,50 @@ # Current State -Updated 2026-08-04 after the coordinated canonical package release train and -its concurrency, binary-compatibility, and external-consumer reliability gates. +Updated 2026-08-08 after the code-first path was completed end to end, an +optional standard .NET application-readiness adapter was added, and a bounded +performance/concurrency/lifetime hardening round established a permanent +benchmark baseline. Component and resource contracts carry executable +behavior into definitions, typed handles continue through runtime and +durability operations, Fluent uses the canonical Engine lifecycle, and dynamic +registration is explicitly advanced. Portable JSON/hot reload and package-only +process-restart durability remain independent and preserved. + +## Performance And Reliability Boundary + +- `benchmarks/FluxFlow.Engine.Benchmarks` is a permanent non-packable .NET 10 + suite over real code-first Engine applications. Eight cases compare typed and + addressed request/reply, conditional routing, one/eight-hop pipelines, and + 1/32/128-link compilation. +- Benchmark timing is manual, machine-local evidence. CI asserts deterministic + behavior only; it has no elapsed-time or allocation threshold. +- Two measured internal changes preserve the public surface: unconditional + routes skip condition-context allocation, and small runtime diagnostic maps + avoid `params` arrays plus LINQ iterators. +- On the recorded machine, eight-hop ShortRun allocation fell from 53.25 KB to + 43.29 KB (about 18.7 percent). The final default job reports 36.95 + microseconds/7.87 KB for one hop and 192.26 microseconds/43.18 KB for eight. +- Typed and addressed requests allocate equivalently (12.99 KB versus 12.95 KB + in the final default job); no meaningful typed-handle runtime tax is visible. +- Engine reliability tests use causal gates and exact counts for concurrent + requests, compatible/rejected revisions, retained routes, in-flight stop, + drain, cleanup, and retirement. There are no sleeps, polling loops, + Stopwatch thresholds, or retry-until-green assertions in the new slice. +- Detailed scan counts, before/after measurements, environment, commands, and + limits are recorded in + `memory/303-performance-concurrency-lifetime-baseline.md` and + `docs/43-performance-concurrency-lifetime-baseline.md`. +- Final proof is a warning-free 137-project CI-style Release build, 2,673/2,673 + solution tests across 67 projects, 134/134 Engine tests, 189/189 Release + governance tests, all eight dry benchmark cases, clean formatting/whitespace, + and no known vulnerable dependency in the new benchmark project. ## Published Package Boundary -- All 59 maintained manifest package versions are available from the public - package feed. Fifty-eight versions were newly published from commit +- The 59 previously maintained package versions remain available from the + public package feed. Fifty-eight versions were newly published from commit `d54f1f4a`; `FluxFlow.Mapping` 1.0.3 was the audited reused prerequisite and - was not republished. + was not republished. `FluxFlow.Engine.HealthChecks` 1.0.0 is the new sixtieth + manifest entry and has not been published in this workspace round. - Every new package tag and repository release targets the exact publication commit and contains the exact package plus symbol assets. - All 59 packages restore and load through isolated public-feed-only consumers. @@ -28,14 +64,64 @@ its concurrency, binary-compatibility, and external-consumer reliability gates. package-only consumer for representative behavior. Its isolated restore rejects project libraries and proves every restored FluxFlow archive exactly matches the candidate source before executing canonical Engine, Fluent, and - SQL-file durable-input/output reopen scenarios. The existing per-package - restore/load smoke remains the inventory-wide check. + SQL-file durable-input/output reopen scenarios. The same runner then starts + separate seed and recovery processes over one SQL-file state directory. It + proves expired input/output leases recover through normal hosted dispatch, + workflow output is captured and delivered, and a host-owned effect keyed by + `DurableOutputEnvelope.Key` is not repeated. The contract remains + at-least-once and does not persist workflow execution state. The existing + per-package restore/load smoke remains the inventory-wide check. - The complete execution, workflow run ids, recoveries, and cleanup evidence are recorded in `memory/292-coordinated-release-train.md`. +- `FluxFlow.Engine.HealthChecks` 1.0.0 is an optional leaf package. One + idempotent `AddFluxFlowApplication()` call registers the standard check + `fluxflow.application` with the exact tags `fluxflow` and `ready`. It reports + a usable active revision as healthy, a rejected update with the previous + revision still active as degraded, and missing/inactive/stopped application + state as unhealthy. It reads existing in-memory state only and emits at most + seven bounded, non-secret lifecycle and diagnostic identity fields; Engine + has no reverse dependency, and no worker, polling, I/O, reflection, endpoint, + or external dependency probing is added. ## Canonical Boundary - Application JSON has one root shape: `Resources` and `Workflows`. +- Compiled C# and portable JSON are independent first-class authoring sources. + `ApplicationDefinitionBuilder` builds a directly executable in-memory graph; + it does not serialize or round-trip through JSON. Both sources converge at + normalization, catalog validation, link compilation, revision activation, + and runtime routing. Designer remains JSON-only. +- The C# builder keeps exactly the workflow-return and flat `out var` capture + shapes. `ComponentContract` values centralize the component type, runtime + factory/bindings, options application, and typed handle without reflection or + declaration-time activation. All 19 Composition families expose 44 complete + contracts through `Components`; retained family registration methods + register the exact same descriptor. +- A code-first `ApplicationDefinition` owns the exact immutable descriptors + introduced by its contracts. `services.AddFluxFlow(definition)` executes that + application without duplicate runtime registration. JSON-loaded and low-level + string definitions remain explicitly host-registered. +- Code-first application resource extensions capture exact + `ApplicationResourceContract` values. Each contract owns one portable + type/options projection, typed handle, and explicit registrar; Engine merges + definition and host registrars per candidate by exact identity. JSON contains + no executable contract and therefore retains explicit package registration. +- Typed component handles remain authoritative after activation: + `ApplicationPorts`, durable input enqueue, durable output capture, and keyed + resource helpers accept the same typed ports/resources and delegate to the + existing canonical-address behavior. +- Engine resolves one effective catalog per candidate from host and + definition-owned descriptors. Exact descriptor reuse deduplicates; a + different descriptor for the same type fails before activation. Ordinary + host DI is an explicit non-owned fallback behind revision-owned resources. +- Named handles expose component-specific inputs, outputs, signals, and + explicit `Events`. `OutputPortHandle.ConnectTo` returns the same output for + fan-out and permits same-owner cross-workflow links. Workflow `Connect` is + local; application `Connect` is the explicit cross-workflow scope. +- Link conditions may be portable expression strings or synchronous typed C# + predicates. Predicates require no expression engine, skip error messages, + isolate exceptions to one route, and are owned by the built definition and + revision with no global delegate registry. - Composition `6.0.0` owns canonical definitions, addressing, link compilation, immutable component descriptors/catalogs, and the focused `IApplicationResourceRegistrar` extension boundary. @@ -46,6 +132,13 @@ its concurrency, binary-compatibility, and external-consumer reliability gates. - Engine `7.0.0` owns `AddFluxFlow(...)`, definition sources, the single `FluxFlowApplication` lifecycle, transactional revisions, runtime assembly, stable ports, diagnostics, generations, rollback, and disposal. +- `FluxFlow.Fluent` is an instance-first facade over that same definition and + Engine lifecycle. `FlowGraph.Definition` and `FlowGraph.Application` expose + the canonical objects; no parallel runtime or manual graph-link lifecycle + remains. Acyclic graphs drain in deterministic topological stages. +- Dynamic/plugin-only descriptors are isolated behind + `AddFluxFlowComponents().Advanced.AddDynamicComponent(...)`; the former + normal-surface registration name is removed. - Component and resource type resolution is exact. Runtime and Designer expose canonical identities only; obsolete aliases are rejected. - Component configuration uses canonical option names. The counter option is @@ -60,6 +153,18 @@ its concurrency, binary-compatibility, and external-consumer reliability gates. registers both immutable catalogs. Public declarations, metadata-only family factories, mutable catalog methods, and terminal catalog registration are gone. +- Normal component factories now return typed nodes. One selector-based + `HasInput`, `HasSignalInput`, `HasOutput`, or named `HasEvents` declaration + produces both immutable descriptor metadata and the activated Dataflow + binding without reflection or factory execution during registration. + The declarative `Has...` prefix is intentional: each selected Dataflow member + already exists on the node, so the call describes and maps the component + contract rather than creating another port. No port-level `Add...` aliases + remain. + Component event ports are explicit, `Events` is not globally reserved, and + all 19 families preserve their established address through family-owned + constants. `UseInstanceFactory` remains the validated low-level escape hatch; + `ComponentNodeActivation` carries the small additional-cleanup case. - Nineteen active component composition packages remain. The empty Control runtime and composition migration markers are retired from source, solution, and release inventory; previously published versions remain restorable for @@ -268,14 +373,51 @@ its concurrency, binary-compatibility, and external-consumer reliability gates. (Designer plus 19 composition adapters), removes the two unmaintained marker entries, and advances no package version. - `eng/packages.json` is authoritative for the complete retained inventory. - It contains 59 maintained packages after both T-SQL durability providers - joined DurableInput, DurableOutput, and their SQL-file providers, and after - the two Control markers were retired. -- The solution now contains 133 projects. The current serialized Release build - completes 134 build targets and remains acyclic and warning-free. + It contains 60 maintained packages after the optional health-check adapter + was appended as an unpublished initial release. +- The solution now restores and builds 136 projects and remains acyclic and + warning-free. ## Documentation And Verification +- The optional application-readiness round adds one leaf package and one public + registration method without changing Engine behavior. Final evidence is a + warning-free 136-project Release build, 2,665/2,665 solution tests across 67 + test projects, 185/185 Release tests, an accepted and normally verified + public API baseline, a real ten-package/fifteen-process isolated consumer, + clean format/diff checks, and no vulnerable packages. The package has not + been published. Detailed decisions and evidence are in + `memory/302-application-health-readiness.md`. +- The unified complete-contract round removes duplicate runtime registration + from normal code-first applications. Final evidence is a warning-free + 134-project Release build, 2,597/2,597 solution tests across 66 projects, + 174/174 Release tests, real candidate-package acceptance, four executable + samples, clean format/diff/public-API/source-policy gates, and no vulnerable + packages. Detailed decisions and evidence are in + `memory/300-unified-code-first-component-contracts.md`. +- The declarative component-port naming refinement exposes only `HasInput`, + `HasSignalInput`, `HasOutput`, and `HasEvents` from normal and advanced + runtime/Designer binding builders. It intentionally retains no public + port-level `Add...` aliases. Final evidence is a warning-free 134-project + Release build, 2,563/2,563 solution tests across 66 projects, a real + nine-package isolated consumer/restart pass, accepted and normally verified + public API baseline, clean formatting/diff hygiene, and no vulnerable + packages. Detailed rationale and evidence are recorded in + `memory/298-declarative-component-port-naming.md`. +- The typed component-binding round replaces duplicated descriptor/runtime port + authoring with one flat selector declaration, makes component event outputs + explicit and named, and preserves all 19 families/44 declarations. Its final + evidence is a warning-free 134-project Release build, 2,561/2,561 solution + tests across 66 projects, 169/169 Release tests, a real nine-package isolated + consumer/restart pass, clean formatting/API/policy/hygiene gates, and no + vulnerable packages. Detailed evidence is recorded in + `memory/297-typed-component-port-binding.md`. +- The package-only process-restart durability round changes the external + fixture, its existing runner, focused release-governance tests, + documentation, goals, and memory only. Runtime assemblies, public APIs, + schemas, package versions, and publication state are unchanged. Detailed + evidence is recorded in + `memory/296-package-consumer-restart-durability-acceptance.md`. - The package-consumer acceptance round changes release/CI tooling, a checked-in external fixture, release governance tests, documentation, goals, and memory only. It changes no runtime assembly, API, schema, dependency, diff --git a/memory/296-package-consumer-restart-durability-acceptance.md b/memory/296-package-consumer-restart-durability-acceptance.md new file mode 100644 index 00000000..fdd8bbe9 --- /dev/null +++ b/memory/296-package-consumer-restart-durability-acceptance.md @@ -0,0 +1,125 @@ +# Package-Consumer Process-Restart Durability Acceptance + +Date: 2026-08-07 + +## Result + +The existing package-only behavioral gate now proves that FluxFlow's optional +SQL-file durability features compose correctly across a real process boundary. +One seed process persists and leases durable input/output work and exits without +settlement. A distinct recovery process opens the same files, starts the normal +Generic Host and FluxFlow hosted services, recovers both expired leases, +executes the workflow, captures its transformed output, and reaches terminal +input/output states. + +No runtime assembly, public API, provider schema, package identity, package +version, publication state, or CI step was changed. The round extends the +existing external fixture, existing acceptance runner, release-governance +tests, documentation, goal records, and memory only. + +## Implementation + +- `eng/package-consumer-acceptance/Program.cs` now has one direct argument + switch for the existing default behavior plus + `durability-restart-seed ` and + `durability-restart-recover `. +- `RestartDurabilityScenario.cs` owns the complete bounded restart slice: + deterministic envelopes and UTC times, SQL-file store registration, one + explicit uppercase component/workflow, source-generated string JSON, + Generic Host setup, durable-input dispatch, durable-output capture and + delivery, terminal status assertions, and exact evidence markers. +- Seed mode enqueues one input and one independent output, acquires attempt-1 + leases with exact owners/times/non-empty tokens, applies one destination + effect, and intentionally leaves both leases unsettled. +- Recovery mode observes both leases as expired at a fixed later UTC value. + The registered `TimeProvider` fixes lease decisions while its base timers + continue to run the real bounded hosted-service polling loops. +- The fixture-local destination derives its identity from + `DurableOutputEnvelope.Key`. One atomically created `.effect` file contains + the exact address, message identity, contract, and JSON payload and is both + destination effect and idempotency receipt. Equivalent redelivery succeeds + without rewriting the effect; identity/content conflict fails closed. +- Final persisted state is exactly one delivered input and two completed + outputs, with no pending, leased, unmaterialized, or dead-lettered work. The + two destination effects are the pre-applied seed effect once and the + transformed workflow effect once. +- The external fixture now references the same four top-level FluxFlow + candidates plus `Microsoft.Extensions.Hosting` 8.0.1. It remains `net8.0`, + package-only, outside the solution, and free of project references. +- `eng/package-consumer-acceptance.ps1` copies all top-level fixture C# files, + builds once, and launches default, seed, and recovery as three distinct + processes. Seed and recovery receive the same runner-owned restart path. + Exact per-phase markers are required once; missing or duplicate evidence + fails closed. Existing restore isolation, candidate SHA-256 verification, + caller/runner ownership, diagnostics retention, and cleanup remain intact. +- Normal CI still invokes the same acceptance runner once after solution + tests. No second runner, project, workflow step, process framework, provider, + or reusable runtime abstraction was added. + +## Test Evidence + +Focused `PackageConsumerAcceptanceScriptTests` passed 15/15 in Release with +zero warnings. Exact added or strengthened contracts include: + +- `Acceptance_fixture_is_a_net8_package_only_consumer`; +- `Acceptance_restart_fixture_uses_explicit_hosted_recovery_and_idempotent_receipts`; +- `Acceptance_script_prepare_only_resolves_exact_closure_without_mutation`; +- `Acceptance_script_restores_verifies_builds_and_runs_from_retained_isolated_workdir`; +- `Acceptance_script_stops_before_recovery_when_seed_marker_is_missing`; +- `Acceptance_script_cleans_owned_workdir_after_invalid_recovery_marker_count`; +- `Acceptance_script_pack_mode_cleans_owned_source_and_workdir_after_success`; + and +- `Acceptance_gate_is_part_of_the_complete_ci_rehearsal`. + +The post-generation assertion and pseudo-mutation review added duplicate-marker +rejection, CI ordering, and explicit missing/relative/extra/unknown command-line +guard coverage. It found no assertion-free, trivial-only, self-referential, +skipped, timing-dependent, or network-dependent test. The mandatory static +test inventory analyzer ran once, but its result payload was lost when an +adjacent read-only inspection command failed to parse; no coverage claim relies +on that lost payload and the analyzer was not rerun. + +## End-To-End And Repository Validation + +- The final real `eng/package-consumer-acceptance.ps1 -PackPackages` run packed + and hash-verified the exact nine-package candidate closure, restored into an + isolated package cache, built the external `net8.0` consumer with zero errors + and zero warnings, and passed every existing and restart marker. +- The seed and recovery command evidence shows two separate `dotnet run` + processes over one absolute `restart-durability` directory. The final output + included input recovery, workflow output capture, pending-output resumption, + output recovery, idempotency, restart, runner restart-completion, and overall + completion markers. +- Runner-owned candidate, consumer, package-cache, SQL-file, and effect paths + were removed by the existing `finally` ownership boundary. +- Complete `FluxFlow.Release.Tests`: 166 passed, zero warnings. +- Complete Release build: 134 projects, zero errors, zero warnings. +- Complete Release solution tests: 2,534 passed across 66 projects, zero + warnings. +- Solution `dotnet format --verify-no-changes` passed. +- Folder-mode whitespace verification for the package-consumer C# fixture + passed. +- Full transitive vulnerable-package audit reported no vulnerable package for + every solution project. +- `git diff --check`, the focused hygiene scan, and scoped formatting passed. + +## Guarantee Boundary + +This gate proves persisted lease recovery and normal hosted-service composition +for the local SQL-file providers. It does not make the workflow itself durable. +Engine queues, links, active revisions, node state, resources, checkpoints, +business transactions, broker acknowledgements, and arbitrary external effects +remain outside the persisted boundary. + +Input and output delivery remain at-least-once. Provider-level suites continue +to own exact fencing-token, retry-attempt, compare-and-set, concurrency, schema, +and corruption proofs. The process-restart fixture proves the abandoned work is +recovered and settled, but does not expose internal lease tokens through a new +public or test-only seam merely to repeat those provider assertions. + +The local effect file demonstrates the host's idempotency responsibility +without hiding a second receipt/effect transaction: the atomic idempotent +destination operation is the receipt. Real destinations must provide their own +equivalent idempotent operation or transaction. FluxFlow does not coordinate +that destination operation with delivery-store completion and does not claim +exactly-once behavior. diff --git a/memory/297-typed-component-port-binding.md b/memory/297-typed-component-port-binding.md new file mode 100644 index 00000000..20e24fe3 --- /dev/null +++ b/memory/297-typed-component-port-binding.md @@ -0,0 +1,134 @@ +# Typed Component Port Declaration And Binding + +Date: 2026-08-08 + +## Result + +Component registration now has one authoritative, flat, strongly typed port +declaration. Normal authors return an `IFlowNode` from `UseFactory(...)` and +chain `AddInput`, `AddSignalInput`, `AddOutput`, and explicit named +`AddEvents` selectors. The port name and inferred message type are no longer +repeated inside a manually created `ComponentInstance`. + +This is an intentional source- and binary-breaking authoring simplification. +Canonical application JSON, component type names, built-in port addresses, +processing behavior, resource resolution, and delivery semantics remain +unchanged. No package was published and no compatibility shim was retained. + +## Ownership Design + +- `RuntimeComponentRegistrationBuilder` owns factory mode, immutable metadata, + and the ordered binding declarations. +- `RuntimeComponentBindingBuilder` exposes typed selectors and returns + itself, keeping normal registration to one flat fluent level. +- A selector call creates static descriptor metadata immediately and stores a + typed delegate for later activation. Factories and selectors do not run at + registration time. +- After a node is activated, the runtime evaluates input, signal, normal + output, and event selectors in deterministic declaration order and creates + the low-level `ComponentInstance` internally. +- Descriptor/instance validation remains Engine-owned defense in depth. The + typed path makes mismatch difficult; the explicit `UseInstanceFactory` + escape hatch continues to be checked exactly. +- Original factory and selector delegates remain part of registration + identity. Equivalent repeated family registration stays idempotent, while + changed factories, selectors, metadata, or factory modes conflict. + +Descriptor metadata and activated Dataflow bindings are still separate +internal concepts because linking and Designer tooling need a static contract +before any node exists. The simplification makes one public typed declaration +generate both rather than pretending the two runtime responsibilities are the +same object. + +## Explicit Event Ports + +Component events are no longer injected and the name `Events` is no longer +globally reserved. `AddEvents(name, selector)` records a normal public output +of `ComponentEvent`, selects an `ISourceBlock` after activation, and +creates the existing bounded ordered best-effort conversion bridge under the +chosen runtime output name. + +Components may omit event ports or choose names such as `Diagnostics`. Normal +outputs and event outputs share one output-name namespace. Built-in families +explicitly use their family-owned `Ports.Events` constant, preserving their +established `Workflow.Component.Events` addresses without a global naming +convention. Application-level `System.Events.Output` remains a separate +reserved system address. + +## Lifecycle Escape Hatch + +`UseInstanceFactory(...)` is the explicit low-level route for a factory that +must construct an entire `ComponentInstance`. Normal packages and samples do +not use it. The small immutable `ComponentNodeActivation` value covers +the narrower Storage and Sessions requirement: a typed node plus optional +completion and additional asynchronous cleanup. + +Selector, event-attachment, and later Engine validation failures dispose the +node and additional owned resource exactly once, aggregating cleanup failure +without hiding the activation failure. Storage and Sessions preserve their +factory-owned store leases; shared stores remain host-owned. MQTT continues to +resolve and start revision-owned controllers and preserves its Ack/Nak signal +targets and node lifecycle. + +## Migration And Public Surface + +- All 19 maintained component composition families and all 44 declarations use + typed node factories, selector-based ports, and explicit event ports. +- Composition, durability operations, sample application, MQTT composition, + and package-consumer acceptance sources use the canonical shape. +- Low-level `FluxFlow.Fluent` graph construction intentionally retains + `ComponentInstance` because it is not component registration. +- Designer mirrors the typed chain while keeping display name, group, nullable + explicit order, summary, primary flag, cardinality, attributes, immutable + catalog finalization, and immediate conflict validation. An omitted order + preserves deterministic direction-local declaration order. +- `ComponentEvents` was removed. Low-level named event construction is + represented by `ComponentEventSource` and `ComponentPorts.Events(...)`. +- The documented source-declaration baseline was accepted for the intentional + API change. Published binary comparison baselines remain unchanged so a + future package operation still detects the break and requires an appropriate + major release; no existing version was republished. + +## Verification Evidence + +- `FluxFlow.Composition.Tests`: 139 passed, zero warnings. +- `FluxFlow.Components.Designer.Tests`: 120 passed, zero warnings. +- `ApplicationRuntimeAssemblerTests`: 18 passed, zero warnings. +- Storage composition: 21 passed, including transferred lease cleanup and + construction-failure cleanup, zero warnings. +- Focused Release conventions, family matrix, metadata, and documentation: 59 + passed, zero warnings. +- Complete `FluxFlow.Release.Tests`: 169 passed, zero warnings. This includes + the public API baseline, binary compatibility policy, all 19 families/44 + declarations, samples, documentation, and package-consumer script contracts. +- `PublicApiBaselineTests`: 2 passed through the documented acceptance process; + the reviewed source-declaration baseline changed for the 21 intended package + entries and then passed normally without the acceptance switch. +- Complete CI-style Release build: 134 projects, zero errors, zero warnings. +- Complete Release solution suite: 2,561 passed across 66 projects, zero + warnings and zero skips. +- The real package-consumer `-PackPackages` gate packed and byte-verified the + exact nine-package closure, restored and built the isolated external `net8.0` + consumer with zero warnings, and passed Engine, Fluent, SQL-file reopen, + seed/recovery, workflow capture, pending-output resumption, output recovery, + idempotency, restart, and final completion markers. +- Full-solution `dotnet format --verify-no-changes --no-restore` and + `git diff --check` passed. +- The full transitive vulnerable-package audit reported no vulnerable package + for every solution project. +- No typed-authoring project dependency, package version, provider schema, + migration, generated artifact, credential, or secret was added. The only + project-file dependency diff is the pre-existing restart fixture's direct + Generic Host reference recorded in memory 296. + +## Remaining Boundaries + +- This change does not add reflection, discovery, source generation, dynamic + binding, nested callbacks, dependencies, or persistence behavior. +- It does not redesign workflow JSON, the C# workflow DSL, durability, + checkpointing, providers, schemas, or delivery guarantees. +- Event delivery remains bounded best-effort diagnostics. Normal data delivery + and component completion remain the reliable/fault-observable channels. +- Binary compatibility is intentionally not claimed against the currently + published authoring packages; publication and version advancement remain a + separate release operation. diff --git a/memory/298-declarative-component-port-naming.md b/memory/298-declarative-component-port-naming.md new file mode 100644 index 00000000..9d59705c --- /dev/null +++ b/memory/298-declarative-component-port-naming.md @@ -0,0 +1,80 @@ +# Declarative Component Port Naming + +Date: 2026-08-08 + +## Result + +The typed component-binding DSL now uses `HasInput`, `HasSignalInput`, +`HasOutput`, and `HasEvents`. The short-lived public port-level `Add...` +methods were removed without obsolete aliases. + +This is a terminology-only breaking refinement of the typed binding work in +memory 297. Runtime descriptors, activated bindings, event bridges, component +addresses, Designer metadata, registration identity, lifecycle ownership, +canonical JSON, and delivery behavior are unchanged. + +## Decision + +The selected `ITargetBlock`, `IFlowSignalTarget`, `ISourceBlock`, or event +source already exists on the activated node. A component author is not creating +that Dataflow port. The author is declaring that the component has an external +port with a chosen name and mapping it to the existing node member. + +`Has...` therefore describes the authoring model more honestly than `Add...`: + +```csharp +component + .UseFactory(static _ => new UppercaseNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); +``` + +`Bind...` was not selected because each call also creates immutable static +metadata before activation. `With...` was not selected because the operation +is a component-contract declaration rather than optional configuration. + +## Scope And Boundaries + +- Both `RuntimeComponentBindingBuilder` and the advanced + `RuntimeComponentInstanceBindingBuilder` expose only the four `Has...` names. +- Both designed binding builders mirror the same names and retain all display, + grouping, ordering, summary, primary, cardinality, and attribute behavior. +- Internal `RuntimeComponentRegistrationBuilder` methods still use imperative + `Add...` names because they actually add metadata and binding records to the + registration snapshot. +- Engine's unrelated application-port runtime builder retains its own + `AddSignalInput` operation. +- All 19 component composition families, 44 declarations, samples, and the + package-only acceptance fixture use the declarative names. +- Options, resources, components, services, and standalone node APIs retain + their existing `Add...` methods because those operations genuinely add an + item or registration. +- No compatibility alias, reflection, scanning, dependency, package version, + schema, or migration was introduced. + +## Compatibility + +This rename is intentionally source- and binary-breaking for the unpublished +typed builder surface. The public source-declaration baseline is updated through +the documented acceptance process. Published binary baselines stay unchanged, +so future package validation continues to require an appropriate major release +for the accumulated component-authoring break. + +## Verification Evidence + +- Focused Composition tests: 140/140 passed with zero warnings. +- Focused Designer tests: 121/121 passed with zero warnings. +- Focused release conventions, family matrix, metadata, and documentation + tests: 59/59 passed with zero warnings. +- The accepted public API baseline records the intentional rename, and its two + normal baseline tests pass without the acceptance environment variable. +- The CI-style Release build completes 134 projects with zero errors and zero + warnings; the complete solution suite passes 2,563/2,563 tests across 66 + projects with zero warnings. +- The real package-only consumer packs, restores, verifies, builds, and runs + all nine candidate packages in isolation. Engine, Fluent, SQL-file durable + input/output, separate-process restart recovery, and receipt idempotency all + pass. +- Full-solution formatting verification and the transitive vulnerability audit + pass. Final whitespace, stale-name, and diff hygiene checks are clean. diff --git a/memory/299-typed-code-first-application-authoring.md b/memory/299-typed-code-first-application-authoring.md new file mode 100644 index 00000000..1c14ec41 --- /dev/null +++ b/memory/299-typed-code-first-application-authoring.md @@ -0,0 +1,135 @@ +# Typed Code-First Application Authoring + +> Historical note: the authoring-only `ComponentAuthoringContract` described +> here was replaced by the complete `ComponentContract` in +> `memory/300-unified-code-first-component-contracts.md`. The workflow, link, +> predicate, JSON-separation, and verification history below remains relevant. + +## Problem + +The existing C# application builder preserved the JSON document shape, but normal application code still repeated component type identifiers, port names, and string addresses. Connections were written back into component JSON properties, so the builder behaved too much like an alternate JSON syntax. It could not safely own normal C# predicates or give application-owned components a small reusable typed contract. + +The agreed boundary is two independent authoring sources: + +- portable JSON for files, configuration providers, hot reload, and UI/designer persistence; +- compiled C# for developers using typed handles, ordinary delegates, closures, and direct in-memory hosting. + +They converge at normalization, catalog validation, link compilation, revision activation, and runtime routing—not at serialization. + +## Public authoring shape + +`ApplicationDefinitionBuilder` retains exactly two workflow forms: + +```csharp +var main = application.AddWorkflow("main"); + +var application = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var main) + .AddWorkflow("audit", out var audit); +``` + +No callback-style workflow scope, ambient current workflow, or third DSL entry point was added. + +`WorkflowDefinitionBuilder` now accepts: + +- `ComponentAuthoringContract` for components without an options builder; +- `ComponentAuthoringContract` for components with component-specific configuration; +- handle-returning and flat `out var` overloads for both forms. + +The existing string `AddComponent` surface remains the explicit dynamic/plugin escape hatch. + +## Contract and handle architecture + +A contract is a sealed value object created through `ComponentAuthoringContract.Create`. It stores only: + +- one canonical component type identifier; +- an explicit typed-handle factory; +- for configured components, an explicit options factory and apply delegate. + +There is no reflection, scanning, generated code, runtime node activation, service resolution, global registry, or inferred type identity. Name/type validation, duplicate checks, options commit, handle creation, rollback, and immutable snapshots share one component-add core. Failed options or handle factories leave no partial component. + +`AuthoredComponentHandle` is externally derivable and exposes its underlying read-only `ComponentHandle`. Shared input/output handle shapes now require the explicit Events port name and expose a non-null `OutputPortHandle Events`. FlowRetry and MQTT feature-specific handles likewise expose Events alongside their data and signal ports. + +## Connections + +All connection forms delegate to one mutation/validation core: + +- `output.ConnectTo(input)` is concise, returns the same output for fan-out, and allows local or same-owner cross-workflow endpoints; +- `workflow.Connect(output, input)` is workflow-local; +- `application.Connect(output, input)` is the explicit application-level form and supports cross-workflow endpoints. + +Typed input and signal-input overloads exist for unconditional links, required nonblank portable expression strings, and required synchronous `Func` predicates. Ownership, mutability, duplicate, cardinality, and workflow-scope checks are applied before mutation. + +## In-memory links and conditions + +`ApplicationDefinition` now owns an immutable read-only list of `ApplicationLinkDefinition`. The public link exposes source, target, message type, optional portable expression text, conditional state, and declaration side. Executable predicate and revision identity remain internal. + +Code-first `Build()` no longer writes links into component JSON properties. `ApplicationLinkCompiler` combines portable declarations parsed from JSON component properties with first-class in-memory links, validates both through the same catalog/type/cardinality/cycle pipeline, and produces the same `CompiledApplicationLink` matcher boundary. + +Portable expressions still require `IFlowExpressionEngine`. Typed predicates compile directly to a synchronous matcher and require no expression engine. A predicate: + +- receives the successful payload value; +- is not invoked for an error `FlowMessage`; +- returns false to skip only its route; +- reports a thrown exception as a route condition failure without stopping sibling fan-out routes or later messages. + +Unconditional error propagation and portable-expression semantics are unchanged. + +## Revision ownership and lifetime + +Each newly authored predicate link receives an opaque definition-owned identity. Reusing the same built definition compares stable; rebuilding a predicate link is intentionally a behavior change, even when a compiler-cached static delegate instance might otherwise be reference-equal. No delegate reflection, hash inference, or process-global storage is used. + +The revision planner compares first-class links for every source and target workflow. Added, removed, changed-expression, and changed-predicate links update the affected workflow revision units. Runtime compiled links retain predicates only for the active/prepared revision; normal retirement releases the old graph and its closures. A successful replacement's returned result reports `PreviousRevision`, but the application's retained `LastUpdate` copy removes that retired snapshot so it cannot keep executable predicates alive. Failed revision activation retains the prior working revision. + +## Independent JSON boundary + +`ApplicationDefinitionJsonConverter` continues to read and write the canonical portable `Resources` and `Workflows` document only. JSON parsing, configuration sources, persistence, hot reload, and Designer behavior remain independent and receive regression coverage. + +The C# builder has no `ToJson`, `Serialize`, `Export`, or designer bridge. Code-first build, registration, planning, and execution do not invoke JSON. The UI/designer authors JSON and does not consume compiled C# builder definitions. C#-to-JSON export and portability metadata are explicitly outside this round. + +## Official families and samples + +All 19 active Composition families expose all 44 component contracts through public `Components` classes. Property names match retained `AddX` methods without the `Add` prefix. Every retained `AddX` delegates to the same typed contract and component-add core; option application, type IDs, and port names each have one family-owned authority. + +`FluxFlow.SampleApp` now uses flat workflow capture, application-owned typed contracts/handles, direct `ConnectTo`, typed priority predicates, and Events fan-in. Its obsolete sample expression engine and Mapping project reference were removed because typed predicates need neither. `FluxFlow.CompositionSample` now demonstrates the same minimal typed custom-component pattern. `FluxFlow.MqttCompositionSample` uses typed source and MQTT contracts and compares JSON/C# by runtime behavior rather than serializing the C# definition. + +`FluxFlow.Fluent` remains a separate live node-instance graph API and is documented as such. + +## Documentation + +The root README, Composition/Fluent READMEs, all 19 component Composition READMEs, public API overview, definitions/links guide, expression guide, migration guide, documentation index, and `docs/39-typed-code-first-authoring.md` describe the implemented boundary and usage. + +## Verification evidence + +Final verification completed on 2026-08-08: + +- full Release solution build: 134 projects, 0 errors, 0 warnings; +- full solution tests: 2,584 passed across 66 projects, 0 failed/skipped, 0 warnings; +- full `FluxFlow.Release.Tests`: 174 passed, 0 warnings; +- focused `FluxFlow.Composition.Tests`: 150 passed, 0 warnings; +- focused `FluxFlow.Engine.Tests`: 111 passed, 0 warnings; +- focused Release authoring/family/package assertions: all 16 selected assertions green; +- documentation boundary and sample-documentation checks: 20 passed, 0 warnings; +- real package-only pack acceptance: exit 0 in 111.9 seconds, nine candidate packages verified, isolated `net8.0` consumer built with 0 errors/warnings, candidate-only closure enforced, JSON/code-first/Fluent/durability/restart markers emitted exactly once, and script-owned directories cleaned; +- `FluxFlow.SampleApp`: three correctly routed orders and six component events; +- `FluxFlow.CompositionSample`: `ALPHA`, `BETA`; +- `FluxFlow.MqttCompositionSample`: configuration and definition paths each published the two expected messages; +- `FluxFlow.FluentSample`: expected linear uppercase and even/odd branched output; +- full `dotnet format --verify-no-changes`: exit 0; +- full `git diff --check`: exit 0; +- package vulnerability audit: every solution project reported no vulnerable direct or transitive packages; +- public API baseline regenerated through the documented acceptance variable and independently reverified green; +- hygiene scans found no new delegate registry, reflection/dynamic invocation, TODO/FIXME, skipped test, C# builder export API, or Designer dependency on the code-first authoring layer. + +The first full-solution run exposed two stale integration expectations: the final lifecycle fix changed the public API source hash, and an MQTT test still expected links inside component JSON properties. The baseline was accepted through the repository workflow, the MQTT assertion was migrated to first-class `ApplicationDefinition.Links`, both were individually verified, and the complete 2,584-test rerun passed. + +## Intentionally deferred + +- async or DI-aware predicates; +- predicate retries, timeouts, or policies; +- delegate/expression-tree translation or serialization; +- C# builder export or Designer integration; +- JSON schema redesign; +- changes to `FluxFlow.Fluent` execution semantics; +- durability/storage-provider changes; +- package version changes or publication. diff --git a/memory/300-unified-code-first-component-contracts.md b/memory/300-unified-code-first-component-contracts.md new file mode 100644 index 00000000..725ff8c2 --- /dev/null +++ b/memory/300-unified-code-first-component-contracts.md @@ -0,0 +1,148 @@ +# Unified Code-First Component Contracts + +Date: 2026-08-08 + +## Decision + +FluxFlow now uses `ComponentContract` as the complete compiled-C# declaration of +a component. The former authoring-only contract required application authors to +add a typed component to a workflow and then repeat its factory and ports in +`AddRuntimeComponent`. That split was verbose and allowed the handle, metadata, +and executable descriptor to drift. + +The complete contract owns: + +- the canonical component type; +- one immutable `ComponentDescriptor`; +- the runtime node or instance factory; +- typed input, signal-input, output, and explicitly named event bindings; +- the typed authoring handle; +- optional component-specific options creation and application. + +Construction remains explicit and flat. It reuses +`RuntimeComponentRegistrationBuilder`; there is no reflection, scanning, +source generation, ambient state, global registry, or delegate inference. +Factories are retained at declaration time but execute only during activation. + +## Application definition ownership + +`ApplicationDefinitionBuilder` shares a small descriptor collection across its +workflow builders. Adding a complete contract first validates options and the +handle, then atomically commits the component and descriptor. Reusing the exact +contract across components or workflows stores one descriptor. A different +descriptor for the same type is rejected with the type in the diagnostic. + +`ApplicationDefinition.ComponentDescriptors` is immutable, read-only, and +deterministically ordered by type. Plain constructor-created and JSON-loaded +definitions have an empty collection. The JSON converter continues to read and +write only `Resources` and `Workflows`; it never serializes factories, +selectors, handles, descriptors, or delegates. + +## Runtime catalog and revisions + +Engine resolves one effective `ComponentCatalog` per candidate revision: + +```text +host-registered descriptors + definition-owned descriptors -> effective catalog +``` + +The same effective catalog is passed to link compilation, port-surface +creation, validation, and activation. Exact descriptor-reference reuse is +accepted. Different descriptor instances with the same type conflict; no source +wins silently. + +Descriptor reference identity is the explicit identity of code behavior. +Reusing one contract is revision-stable. Introducing, removing, or replacing a +used descriptor updates the affected workflow without reflecting over or +hashing delegate bodies. Failed candidates preserve the active generation. +Successful replacement retires the old generation and allows captured factory +state to be collected after normal retirement. + +Revision resource snapshots remain primary during activation and are owned by +Engine. Ordinary host services are an explicit fallback through +`ComponentActivationContext.Services`; the fallback host provider is never +disposed by a revision. + +## Registration boundaries + +Normal compiled-C# hosting is: + +```csharp +var definition = application.Build(); +services.AddFluxFlow(definition); +``` + +JSON and dynamic string definitions contain no executable C# and therefore +register required complete contracts or family extensions explicitly. The +low-level `AddRuntimeComponent(type, configure)` path remains for genuinely +dynamic descriptors; it is not a second step after typed code-first authoring. + +## Designer and official families + +`DesignedComponentContract.Create` adapts the existing flat designed-component +builder into one exact descriptor plus presentation metadata. Official family +registration consumes that contract, so Designer metadata and runtime behavior +share one declaration and metadata inspection never activates factories. + +All 19 active Composition families and 44 contracts use the complete model. +Their typed options, handles, port names, explicit Events outputs, resource +requirements, processing capabilities, and MQTT lifecycle boundaries remain +unchanged. + +## Samples and package consumer + +The Composition sample, SampleApp, MQTT composition sample, and isolated package +consumer declare custom components once and omit redundant runtime registration +in their code-first modes. Genuine services remain normal DI registrations. +JSON modes still register contracts explicitly, and MQTT still registers its +resource registrar because it owns client/resource lifecycle rather than merely +describing a component. + +## Verification evidence + +Final verification completed on 2026-08-08: + +- focused Composition contract/JSON/registration coverage: 51 passed, zero + failures, skips, and warnings; +- focused Designer exact-descriptor/metadata/no-activation coverage: 17 passed, + zero failures, skips, and warnings; +- focused Engine catalog/revision/rollback/lifetime/DI coverage: 52 passed, + zero failures, skips, and warnings; +- focused Release public-surface, 19-family/44-contract, source-shape, and + package-fixture coverage: 12 passed; the four legacy metadata-governance + facts and 14 documentation-boundary facts also pass; +- real isolated `-PackPackages` acceptance: candidate package closure, explicit + JSON registration, embedded-contract code-first execution, durability restart + markers, and runner cleanup all passed; +- full Release build: 134 projects, zero warnings and errors; +- full solution: 2,597 tests across 66 projects, zero failures, skips, and + warnings; +- dedicated Release governance: 174 tests, zero warnings; +- public API baseline: intentionally accepted and independently verified 2/2; +- full `dotnet format --verify-no-changes` and `git diff --check`: exit 0; +- dependency audit: no vulnerable direct or transitive package in any solution + project; +- hygiene scans: no removed authoring-contract use, reflection/scanning/dynamic + invocation/global contract registry, normal-sample duplicate runtime + registration, skipped test, TODO, or FIXME in the touched slice. + +Executable evidence: + +- Composition sample: `ALPHA`, `BETA` using only `AddFluxFlow(definition)` for + its complete contracts; +- SampleApp: three correctly routed orders and six component events; +- MQTT sample: JSON/configuration and compiled code-first paths each published + the two expected acknowledgements; +- durability operations sample: one input delivered, one output captured and + completed, with explicit terminal status snapshots. + +## Intentional limits + +- Executable contracts are not serialized to JSON. +- JSON does not discover contracts automatically. +- No assembly scanning, source generation, UI-to-C# export, or global registry + was added. +- Dynamic string components still require explicit host registration. +- Resource/backend settings, durability guarantees, and MQTT resource ownership + were not redesigned. +- No package was published and no release was created in this round. diff --git a/memory/301-end-to-end-code-first-simplification.md b/memory/301-end-to-end-code-first-simplification.md new file mode 100644 index 00000000..a5d23075 --- /dev/null +++ b/memory/301-end-to-end-code-first-simplification.md @@ -0,0 +1,79 @@ +# End-To-End Code-First Simplification + +Date: 2026-08-08 + +## Decision + +FluxFlow's compiled-C# experience is one explicit declaration-to-execution +path. `ComponentContract` and `ApplicationResourceContract` are the code-first +authorities; their typed handles continue through definition links, runtime +ports, durability, and keyed resource binding. Portable JSON remains a separate +first-class source and never contains executable C# state. + +## Changes + +- `ApplicationPorts` and the low-level port runtime accept typed input, + signal-input, and output handles for the operations that match their + direction. They delegate to canonical address behavior and retain explicit + `FlowMessage` envelopes. +- Durable input enqueue accepts `InputPortHandle` and durable output capture + accepts `OutputPortHandle`. No signal or direction-breaking shortcuts were + added. +- Typed resource DI helpers accept `ResourceHandle` without changing normal + DI ownership. +- `ApplicationResourceContract` pairs one portable type/options projection and + typed handle with an explicit resource registrar. The application builder + commits the resource and contract atomically and stores exact contracts in a + runtime-only definition collection excluded from JSON. +- Engine merges host and definition registrars by exact registration identity + for each candidate revision. Conflicts fail before activation; rollback, + retirement, host fallback ownership, and captured-closure release follow the + existing revision boundary. +- MQTT broker, retry-policy, subscription, and client authoring use four + complete resource contracts backed by one shared stateless registrar. + Code-first definitions run without `.AddMqtt()`; JSON/configuration hosts + continue to call `.AddMqtt()` explicitly. +- `FluxFlow.Fluent` retains `From`, `Then`, `Tap`, `Branch`, shared-node fan-in, + segments, `Apply`, `To`, events, and lifecycle. It now authors canonical + component contracts and links, owns a `FluxFlowApplication`, and exposes + `FlowGraph.Definition` and `FlowGraph.Application` instead of a parallel + runtime. +- Engine performs deterministic topological stage draining for acyclic + definition graphs. Each stage drains only its own inputs after all upstream + outputs have drained, then completes nodes and outputs. Cyclic signal graphs + retain coordinated fallback shutdown. +- Raw/plugin registration moved to + `AddFluxFlowComponents().Advanced.AddDynamicComponent(...)`. The old normal + `AddRuntimeComponent` entry point has no forwarding alias. + +## Preserved boundaries + +- Canonical JSON remains exactly `Resources` plus `Workflows`. +- JSON deserialization creates no executable component/resource contracts. +- Host-owned services and external resources are never disposed by Engine. +- Component/event ports, typed predicates, hot reload, rollback, Designer + metadata, MQTT semantics, stable addresses, durable schemas, leases, + retention, and at-least-once guarantees remain unchanged. +- No reflection, scanning, global mutable registry, delegate serialization, or + hidden package discovery was introduced. + +## Verification + +Focused Composition, Engine, Fluent, Fluent.Hosting, MQTT, DurableInput, and +DurableOutput suites cover the new public shape and lifecycle. The final gates +completed with: + +- 134 Release-build projects, zero errors and zero warnings; +- 2,627 tests across 66 projects, zero failures, skips, or warnings; +- 179 dedicated Release tests, zero warnings; +- a real isolated package-consumer pack/run with every JSON, code-first, + resource, Fluent, durability, restart, and completion marker exactly once; +- successful MQTT sample execution through both the explicit JSON registration + path and the self-describing code-first path; +- clean public API baseline, formatter, whitespace, and direct/transitive + vulnerability checks. + +Exact commands, focused counts, named behavioral evidence, and package cleanup +proof are recorded in +`goals/2026-08-08-end-to-end-code-first-simplification/README.md` and +`.testagent/status.md`. diff --git a/memory/302-application-health-readiness.md b/memory/302-application-health-readiness.md new file mode 100644 index 00000000..1ce0928e --- /dev/null +++ b/memory/302-application-health-readiness.md @@ -0,0 +1,110 @@ +# Application Health Readiness + +Date: 2026-08-08 + +## Decision + +FluxFlow now offers one optional standard .NET readiness integration in the +separate `FluxFlow.Engine.HealthChecks` 1.0.0 package. The package is a leaf +adapter over `FluxFlowApplication`; `FluxFlow.Engine` does not reference it. + +The public surface intentionally contains one extension: + +```csharp +services.AddHealthChecks() + .AddFluxFlowApplication(); +``` + +It registers exactly one health check named `fluxflow.application` with the +exact tags `fluxflow` and `ready`. Repeated calls are idempotent and do not +replace unrelated standard health checks. `AddFluxFlow(...)` alone remains +unchanged and registers no health check. + +## Readiness Semantics + +- Healthy: lifecycle state is `Running` or `Reloading`, an active snapshot + exists, and the latest update was not rejected. +- Degraded: lifecycle state is `Running` or `Reloading`, an active snapshot + exists, and the latest update was rejected. Transactional rollback keeps the + previous revision usable. +- Unhealthy: FluxFlow is missing, no active snapshot exists, lifecycle state is + not ready, or the application is stopping or stopped. + +A rejected initial start is unhealthy because there is no active revision. A +successful update after a rejected reload restores healthy status. The adapter +derives readiness from `Current` and `LastUpdate`; it does not equate the +Engine's lifecycle enum with the standard health status. + +## Data And Privacy Boundary + +Results may contain only: + +- `applicationState` +- `activeRevisionId` +- `activeSequence` +- `requestedRevisionId` +- `lastUpdateStatus` +- `diagnosticStage` +- `diagnosticCode` + +Only applicable keys are present. The check never returns payloads, +definitions, component/resource configuration, addresses, diagnostic messages +or details, exceptions, connection strings, file paths, credentials, secrets, +or arbitrary high-cardinality values. + +## Runtime Boundary + +The check performs a bounded observational read of existing in-memory +application state when the host invokes `HealthCheckService`. It adds no hosted +service, background worker, polling loop, timer, cache, storage query, resource +activation, network request, reflection, assembly scanning, logging pipeline, +ASP.NET Core dependency, or endpoint. + +Liveness, durable queue thresholds, and external dependency health remain +separate host policies. ASP.NET Core hosts may expose the check through their +own `MapHealthChecks` endpoint and selection predicate. + +## Packaging And Verification Boundary + +The package targets .NET 8 and .NET 10, references only Engine plus the +standard health-check abstractions, is listed in the package manifest as the +initial release, and participates in public API governance. The isolated +package-only acceptance consumer references the packed candidate and proves a +healthy code-first application through the standard `HealthCheckService` path +with the exact marker `PACKAGE_ACCEPTANCE_HEALTH_OK=True`. + +## Verification Evidence + +- Focused health project: 32/32 passed, no failures, skips, or warnings. +- Focused Release health/package governance: 21/21 passed, no failures, skips, + or warnings. +- Public API baseline: explicitly accepted and then verified normally, 2/2 + both times with no warnings. The appended entry is index 59; prior indices + did not move. +- Pack-script rehearsal: 1/1 passed. The controlled process harness proved ten + pack commands, fifteen total invocations, exact markers, and cleanup. +- Direct package-only acceptance: exit 0 in 33.9 seconds. Ten real package and + symbol archives were created, restored and hash-verified from the isolated + candidate source, the .NET 8 consumer built with zero warnings/errors, and + all Engine/code-first/resource/health/Fluent/durability/restart markers were + emitted. Both runner-owned directories were removed. +- Final Release restore/build: 136 projects, zero errors and warnings. +- Full solution: 2,665/2,665 tests across 67 projects, zero failures and + warnings. +- Dedicated Release suite: 185/185 tests, zero warnings. +- Full formatting verification and `git diff --check`: passed. +- Direct and transitive dependency audit: no vulnerable packages. + +The held-reload test uses a causal preparation gate, not a sleep: while the +candidate is blocked and the application reports `Reloading`, readiness is +healthy and the old typed route still returns `still-serving`. Release then +allows the candidate to apply. Rejected reload, failed initial start, recovery, +stopping/stopped/disposed, missing registration, cancellation, privacy, +idempotency, and non-mutation paths are all independently asserted. + +No package was published and no branch, commit, pull request, tag, or release +was created. + +The direct run initially identified a missing host logging registration in the +bare console fixture. Adding standard `services.AddLogging()` fixed the host; +the FluxFlow health adapter gained no logging dependency or behavior. diff --git a/memory/303-performance-concurrency-lifetime-baseline.md b/memory/303-performance-concurrency-lifetime-baseline.md new file mode 100644 index 00000000..bb807390 --- /dev/null +++ b/memory/303-performance-concurrency-lifetime-baseline.md @@ -0,0 +1,198 @@ +# Performance, Concurrency, And Lifetime Baseline + +Date: 2026-08-08 + +## Decision + +FluxFlow now has a permanent, non-packable benchmark project and a +deterministic Engine reliability slice. This round preserves every public API, +definition format, package boundary, and delivery guarantee. Production code +was changed only where a before-change measurement exposed repeatable avoidable +allocation. + +Benchmark timing is manual evidence, never a CI threshold. Concurrency and +lifetime correctness remain ordinary tests with causal synchronization and +exact assertions. + +## Benchmark surface + +Project: `benchmarks/FluxFlow.Engine.Benchmarks` + +- target: `net10.0`; +- benchmark runner 0.15.8 through central package management; +- entry point: `BenchmarkSwitcher` with caller-supplied filters; +- diagnostics: `MemoryDiagnoser` and rank columns; +- setup: real code-first contracts, definitions, DI provider, Engine startup, + and typed handles in `GlobalSetup`; +- cleanup: application stop and provider disposal in `GlobalCleanup`; +- measured methods: real `PortRequestResult` or compilation result returns; +- no manual benchmark loops, fake node path, reflection, internal visibility, + or benchmark-only production hook. + +Eight cases cover: + +1. addressed unconditional request/reply; +2. typed unconditional request/reply; +3. typed conditional request/reply; +4. a one-hop typed pipeline; +5. an eight-hop typed pipeline; +6. one-link compilation; +7. 32-link compilation; +8. 128-link compilation. + +## Hot-path audit + +The bounded static scan covered `src/FluxFlow.Engine/Ports` and +`src/FluxFlow.Composition/ApplicationLinks`. + +| Recipe | Exact hits | Disposition | +|--------|-----------:|-------------| +| `async void` | 0 | clean | +| `.Result` / parameterless `.Wait()` review | 1 | `Task.Result` is guarded by `IsCompletedSuccessfully`; it does not block | +| `.GetResult()` review | 1 | existing synchronous system-event rejection publication; retained to preserve explicit backpressure semantics without a measured defect | +| `IndexOf` string review | 0 | clean | +| `Substring` | 0 | clean | +| `StartsWith` / `EndsWith` string review | 0 | clean | +| `Contains` string review | 0 | clean | +| parameterless `ToLower` / `ToUpper` | 0 | clean | +| static `Dictionary` | 0 | no frozen-read-table candidate | +| static `FrozenDictionary` inverse | 0 | consistent with no candidate | +| `StringComparer.CurrentCulture` | 0 | clean | +| three-deep `Replace` chain | 0 | clean | +| `params` signatures | 2 | both small diagnostic builders; removed by the measured fix | +| `new List` | 12 | revision/compiler preparation or subscriber snapshots; no unsupported hot-path rewrite | +| `new Dictionary` | 14 | two per-message condition contexts were the measured issue; other hits are construction/revision/compiler state | +| selected LINQ chains | 25 | compiler/revision/lifecycle work plus two small diagnostic builders; the measured builders were removed | +| `ContainsKey` | 4 | compiler graph/port classification, not a same-key hot-path double lookup | + +The inverse and cross-file checks confirmed the routing fast path and +diagnostic construction were the only bounded changes justified by the current +measurements. The compiler remains intentionally straightforward and readable; +its work is revision preparation, not per-message execution. + +The final inverse scan reports zero `params` signatures, one +`FlowMapContext` construction site, one matching condition dictionary site, 23 +selected LINQ chains, and zero frozen dictionaries in the same scope. The one +remaining context/dictionary site is guarded by `IsConditional`; it is required +only when a link actually has a condition. The reduced LINQ count reflects the +two removed diagnostic-builder chains, and the zero frozen-dictionary count is +still consistent with the absence of a static dictionary candidate. + +## Before and after + +Pre-change ShortRun on the same machine: + +- eight-hop typed request: 53.25 KB allocated; +- addressed unconditional request: 13.86 KB allocated; +- typed unconditional request: 14.12 KB allocated. + +Final ShortRun: + +- eight-hop typed request: 43.29 KB allocated; +- addressed unconditional request: 13.12 KB allocated; +- typed unconditional request: 13.00 KB allocated. + +The eight-hop reduction is 9.96 KB, approximately 18.7 percent. + +The first internal fix checks `CompiledApplicationLink.IsConditional` before +constructing `FlowMapContext`. Unconditional routes now deliver directly; +conditional routes retain the exact mapping context and failure reporting. + +The second replaces two small `params` plus LINQ dictionary builders with +explicit two- and three-field helpers. It keeps diagnostic names, levels, +subjects, attributes, correlation, trace, and causation semantics unchanged. + +No pooling, cache, background worker, reflection, global mutable state, new +runtime dependency, or public option was added. + +## Final default-job baseline + +Environment: + +- benchmark runner 0.15.8; +- Windows 11 10.0.26200.8973; +- 12th Gen Intel Core i7-12700H, 20 logical / 14 physical cores; +- .NET SDK 10.0.302; +- .NET runtime 10.0.10, X64 RyuJIT x86-64-v3. + +Runtime messaging: + +| Case | Mean | Allocated | +|------|-----:|----------:| +| addressed unconditional | 71.62 microseconds | 12.95 KB | +| typed unconditional | 78.45 microseconds | 12.99 KB | +| typed conditional | 75.55 microseconds | 13.49 KB | + +Pipeline scale: + +| Hops | Mean | Allocated | +|-----:|-----:|----------:| +| 1 | 36.95 microseconds | 7.87 KB | +| 8 | 192.26 microseconds | 43.18 KB | + +Link compilation: + +| Links | Mean | Allocated | +|------:|-----:|----------:| +| 1 | 6.493 microseconds | 7.69 KB | +| 32 | 64.956 microseconds | 91.04 KB | +| 128 | 274.492 microseconds | 365.33 KB | + +Typed and addressed request allocation is equivalent and timing distributions +overlap. The typed authoring/runtime surface therefore shows no meaningful +runtime penalty in this baseline. Conditional routing owns a small explicit +context cost. + +## Reliability contract + +The focused Engine slice adds deterministic proof for: + +- four concurrent batches of sixteen request/reply operations, with every + value and trace observed exactly once; +- eight compatible revisions with stable port identity, exact routing, and one + retirement per replaced generation; +- eight rejected revisions with the prior route retained and every candidate + disposed exactly once; and +- stop while processing is causally held, followed by complete drain of every + already accepted message and exact one-time disposal. + +Existing directly related timing-based tests are converted only when the same +contract can be expressed through causal gates. A bounded `WaitAsync` is a +deadlock guard, not elapsed-time evidence. There are no sleeps, polling loops, +Stopwatch thresholds, throughput assertions, or retry-until-pass behavior. + +## Commands and evidence policy + +Always run `--job Dry` over `--filter "*"` first. Use ShortRun for iteration and +the default job for a recorded baseline. Redirect verbose output and read the +generated GitHub Markdown reports. + +Generated `BenchmarkDotNet.Artifacts` content is ignored. Repository docs store +only the environment and summary necessary to interpret the current baseline. + +Correctness tests run in normal CI. Benchmark timing is intentionally manual, +machine-local, and non-blocking for release validation. + +## Deferred work + +Optional runtime performance telemetry, exported counters, and deeper +contention profiling remain separate future adapter work. The existing +synchronous rejection-to-system-event publication path was manually reviewed +and retained because it carries explicit backpressure semantics; it should not +be changed without focused behavioral and contention evidence. + +## Final verification + +| Gate | Result | +|------|--------| +| benchmark project build | 5 projects, 0 errors, 0 warnings | +| final dry benchmark validation | 8/8 cases produced reports | +| complete Engine tests | 134 passed, 0 warnings | +| complete Release governance tests | 189 passed, 0 warnings | +| CI-style Release solution build | 137 projects, 0 errors, 0 warnings | +| complete Release solution tests | 2,673 passed across 67 projects, 0 warnings | +| benchmark dependency audit | no known vulnerable direct or transitive package | +| hygiene | whole-worktree diff check and scoped format verification passed | + +No package was packed or published, no tag or release was created, and no +external service was contacted by a runtime test. diff --git a/samples/FluxFlow.CompositionSample/Program.cs b/samples/FluxFlow.CompositionSample/Program.cs index 46d78904..1f851baa 100644 --- a/samples/FluxFlow.CompositionSample/Program.cs +++ b/samples/FluxFlow.CompositionSample/Program.cs @@ -1,70 +1,36 @@ -using System.Text.Json; using FluxFlow.Composition; -using FluxFlow.Composition.Model; +using FluxFlow.Composition.Authoring; using FluxFlow.Engine; using FluxFlow.Nodes; using Microsoft.Extensions.DependencyInjection; -using ApplicationWorkflowDefinition = FluxFlow.Composition.Model.WorkflowDefinition; +using System.Text.Json; var collector = new StringCollector(); -var services = new ServiceCollection(); -services.AddFluxFlowComponents() - .AddRuntimeComponent("sample.source", component => - { - component.UseFactory(context => - { - var options = context.BindConfiguration(); - var node = new StringSourceNode(options.Messages); - return ValueTask.FromResult(ComponentInstance.Create( - node, - outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); - }); - component.AddOutput("Output"); - }) - .AddRuntimeComponent("sample.uppercase", component => - { - component.UseFactory(_ => - { - var node = new UppercaseNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); - }); - component.AddInput("Input"); - component.AddOutput("Output"); - }) - .AddRuntimeComponent("sample.sink", component => - { - component.UseFactory(_ => - { - var node = new CollectSinkNode(collector); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - events: node.Events)); - }); - component.AddInput("Input"); - }); - -var definition = new ApplicationDefinition( - workflows: - [ - new("main", new ApplicationWorkflowDefinition( - [ - new("source", Component( - "sample.source", - ("messages", new[] { "alpha", "beta" }), - ("Output", "upper.Input"))), - new("upper", Component( - "sample.uppercase", - ("Output", "sink.Input"))), - new("sink", Component("sample.sink")) - ])) - ]); +var definitionBuilder = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var main); + +main + .AddComponent( + "source", + SampleComponents.Source, + options => options.Messages = ["alpha", "beta"], + out var source) + .AddComponent( + "upper", + SampleComponents.Uppercase, + out var upper) + .AddComponent( + "sink", + SampleComponents.Sink, + out var sink); + +source.Output.ConnectTo(upper.Input); +upper.Output.ConnectTo(sink.Input); + +var definition = definitionBuilder.Build(); +var services = new ServiceCollection(); +services.AddSingleton(collector); services.AddFluxFlow(definition, options => options.StartWithHost = false); await using var provider = services.BuildServiceProvider(); @@ -74,7 +40,8 @@ { foreach (var diagnostic in result.Diagnostics) { - Console.Error.WriteLine(diagnostic.Error.Message); + Console.Error.WriteLine( + $"{diagnostic.Error.Message} {JsonSerializer.Serialize(diagnostic.Error.Details)}"); } return 1; @@ -90,15 +57,6 @@ return 0; -static ComponentDefinition Component( - string type, - params (string Name, object? Value)[] properties) - => new( - type, - properties.Select(property => KeyValuePair.Create( - property.Name, - JsonSerializer.SerializeToElement(property.Value)))); - static async Task WaitForItemsAsync( StringCollector collector, int expectedCount, @@ -114,6 +72,99 @@ internal sealed record SourceOptions public string[] Messages { get; init; } = []; } +internal static class SampleComponentTypes +{ + public const string Source = "sample.source"; + public const string Uppercase = "sample.uppercase"; + public const string Sink = "sample.sink"; +} + +internal static class SampleComponentPorts +{ + public const string Input = "Input"; + public const string Output = "Output"; + public const string Events = "Events"; +} + +internal static class SampleComponentOptions +{ + public const string Messages = "messages"; +} + +internal static class SampleComponents +{ + public static ComponentContract Source { get; } = + ComponentContract.Create( + SampleComponentTypes.Source, + static runtime => + { + runtime + .UseFactory(static context => + { + var options = context.BindConfiguration(); + return new StringSourceNode(options.Messages); + }) + .HasOutput(SampleComponentPorts.Output, static node => node.Output) + .HasEvents(SampleComponentPorts.Events, static node => node.Events); + }, + static () => new SourceComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new SourceComponentHandle(component)); + + public static ComponentContract Uppercase { get; } = + ComponentContract.Create( + SampleComponentTypes.Uppercase, + static runtime => + { + runtime + .UseFactory(static _ => new UppercaseNode()) + .HasInput(SampleComponentPorts.Input, static node => node.Input) + .HasOutput(SampleComponentPorts.Output, static node => node.Output) + .HasEvents(SampleComponentPorts.Events, static node => node.Events); + }, + static component => new UppercaseComponentHandle(component)); + + public static ComponentContract Sink { get; } = + ComponentContract.Create( + SampleComponentTypes.Sink, + static runtime => + { + runtime + .UseFactory(static context => new CollectSinkNode( + context.Services.GetRequiredService())) + .HasInput(SampleComponentPorts.Input, static node => node.Input) + .HasEvents(SampleComponentPorts.Events, static node => node.Events); + }, + static component => new SinkComponentHandle(component)); +} + +internal sealed class SourceComponentBuilder +{ + public string[] Messages { get; set; } = []; + + internal void Apply(ComponentDefinitionBuilder definition) + => definition.Set(SampleComponentOptions.Messages, Messages); +} + +internal sealed class SourceComponentHandle(ComponentHandle definition) : AuthoredComponentHandle(definition) +{ + public OutputPortHandle Output { get; } = definition.Output(SampleComponentPorts.Output); + public OutputPortHandle Events { get; } = definition.Output(SampleComponentPorts.Events); +} + +internal sealed class UppercaseComponentHandle(ComponentHandle definition) : AuthoredComponentHandle(definition) +{ + public InputPortHandle Input { get; } = definition.Input(SampleComponentPorts.Input); + public OutputPortHandle Output { get; } = definition.Output(SampleComponentPorts.Output); + public OutputPortHandle Events { get; } = definition.Output(SampleComponentPorts.Events); +} + +internal sealed class SinkComponentHandle(ComponentHandle definition) : AuthoredComponentHandle(definition) +{ + public InputPortHandle Input { get; } = definition.Input(SampleComponentPorts.Input); + public OutputPortHandle Events { get; } = definition.Output(SampleComponentPorts.Events); +} + internal sealed class StringCollector { private readonly List _items = []; diff --git a/samples/FluxFlow.DurabilityOperationsSample/Program.cs b/samples/FluxFlow.DurabilityOperationsSample/Program.cs index 00724d3b..bc2ab12d 100644 --- a/samples/FluxFlow.DurabilityOperationsSample/Program.cs +++ b/samples/FluxFlow.DurabilityOperationsSample/Program.cs @@ -1,4 +1,4 @@ -using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; using FluxFlow.Engine; using FluxFlow.Engine.DurableInput; using FluxFlow.Engine.DurableInput.SqlFile; @@ -9,8 +9,8 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -var inputAddress = ApplicationAddress.WorkflowPort("Operations", "Transform", "Input"); -var outputAddress = ApplicationAddress.WorkflowPort("Operations", "Transform", "Output"); +var input = SampleWorkflow.Input; +var output = SampleWorkflow.Output; var dataDirectory = Path.Combine( Path.GetTempPath(), "FluxFlow.DurabilityOperationsSample", @@ -20,7 +20,7 @@ try { Directory.CreateDirectory(dataDirectory); - await RunScenarioAsync(dataDirectory, inputAddress, outputAddress); + await RunScenarioAsync(dataDirectory, input, output); return 0; } catch (Exception exception) @@ -43,8 +43,8 @@ static async Task RunScenarioAsync( string dataDirectory, - ApplicationAddress inputAddress, - ApplicationAddress outputAddress) + InputPortHandle input, + OutputPortHandle output) { const string inputContract = "sample.input.v1"; const string outputContract = "sample.output.v1"; @@ -55,7 +55,6 @@ static async Task RunScenarioAsync( builder.Logging.ClearProviders(); builder.Services.AddFluxFlow(SampleWorkflow.Definition); - SampleWorkflow.RegisterComponents(builder.Services); builder.Services.AddFluxFlowSqlFileDurableInput(options => { @@ -79,7 +78,7 @@ static async Task RunScenarioAsync( }); builder.Services.AddFluxFlowDurableOutput(outputs => outputs.Capture( - outputAddress, + output, outputContract, SampleJsonContext.Default.String)); builder.Services.AddSingleton(deliveryHandler); @@ -96,7 +95,7 @@ static async Task RunScenarioAsync( var outputStatusStore = host.Services.GetRequiredService(); var enqueue = await inputs.EnqueueAsync( - inputAddress, + input, FlowMessage.Create("hello durability"), timeout.Token); Ensure(enqueue.IsAccepted, "The durable input was not accepted."); diff --git a/samples/FluxFlow.DurabilityOperationsSample/SampleWorkflow.cs b/samples/FluxFlow.DurabilityOperationsSample/SampleWorkflow.cs index 85e2d608..1e9efa11 100644 --- a/samples/FluxFlow.DurabilityOperationsSample/SampleWorkflow.cs +++ b/samples/FluxFlow.DurabilityOperationsSample/SampleWorkflow.cs @@ -1,34 +1,50 @@ using FluxFlow.Composition; +using FluxFlow.Composition.Authoring; using FluxFlow.Composition.Model; using FluxFlow.Nodes; -using Microsoft.Extensions.DependencyInjection; internal static class SampleWorkflow { - internal static ApplicationDefinition Definition { get; } = new( - workflows: - [ - new("Operations", new WorkflowDefinition( - [ - new("Transform", new ComponentDefinition("sample.uppercase")) - ])) - ]); - - internal static void RegisterComponents(IServiceCollection services) - => services.AddFluxFlowComponents() - .AddRuntimeComponent("sample.uppercase", component => + private static readonly ComponentContract Uppercase = + ComponentContract.Create( + "sample.uppercase", + static component => { - component.UseFactory(_ => - { - var node = new UppercaseNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)])); - }); - component.AddInput("Input"); - component.AddOutput("Output"); - }); + component + .UseFactory(static _ => new UppercaseNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); + }, + static component => new UppercaseHandle(component)); + + static SampleWorkflow() + { + var builder = new ApplicationDefinitionBuilder() + .AddWorkflow("Operations", out var workflow); + + workflow.AddComponent("Transform", Uppercase, out var transform); + Definition = builder.Build(); + Input = transform.Input; + Output = transform.Output; + } + + internal static ApplicationDefinition Definition { get; } + + internal static InputPortHandle Input { get; } + + internal static OutputPortHandle Output { get; } + + private sealed class UppercaseHandle(ComponentHandle definition) + : AuthoredComponentHandle(definition) + { + internal InputPortHandle Input { get; } = definition.Input("Input"); + + internal OutputPortHandle Output { get; } = definition.Output("Output"); + + internal OutputPortHandle Events { get; } = + definition.Output("Events"); + } private sealed class UppercaseNode : FlowNode { diff --git a/samples/FluxFlow.MqttCompositionSample/Program.cs b/samples/FluxFlow.MqttCompositionSample/Program.cs index 0ec05fc3..f46e6436 100644 --- a/samples/FluxFlow.MqttCompositionSample/Program.cs +++ b/samples/FluxFlow.MqttCompositionSample/Program.cs @@ -9,7 +9,6 @@ using FluxFlow.Composition.Addressing; using FluxFlow.Composition.Authoring; using FluxFlow.Composition.DependencyInjection; -using FluxFlow.Composition.Model; using FluxFlow.Data; using FluxFlow.Engine; using FluxFlow.Nodes; @@ -40,6 +39,8 @@ static async Task> RunConfigurationComposition return await RunHostedApplicationAsync( messages, + registerPublishSource: true, + registerMqtt: true, services => services.AddFluxFlow( configuration, options => options.StartWithHost = false)); @@ -86,7 +87,7 @@ static async Task> RunDefinitionApplicationAsy workflow .AddComponent( "source", - SampleNodeTypes.PublishSource, + SampleComponents.PublishSource, out var source) .AddMqttPublish( "outbound", @@ -96,60 +97,46 @@ static async Task> RunDefinitionApplicationAsy publish.MaximumPendingRequests = 16; }, out var outbound) - .Connect( - source.Output(MqttComponentDefinition.Ports.Output), - outbound.Input); + .Connect(source.Output, outbound.Input); var definition = application.Build(); - var configuration = new ConfigurationBuilder() - .SetBasePath(AppContext.BaseDirectory) - .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false) - .Build(); - var configuredDefinition = await new ConfigurationApplicationDefinitionSource(configuration) - .LoadAsync(); - if (!string.Equals( - ApplicationDefinitionJson.Serialize(configuredDefinition), - ApplicationDefinitionJson.Serialize(definition), - StringComparison.Ordinal)) - { - throw new InvalidOperationException( - "The JSON and fluent C# definitions must have the same canonical form."); - } return await RunHostedApplicationAsync( messages, + registerPublishSource: false, + registerMqtt: false, services => services.AddFluxFlow( definition, - options => options.StartWithHost = false)); + options => options.StartWithHost = false), + runtimeClient); } static async Task> RunHostedApplicationAsync( IReadOnlyList messages, - Action addApplication) + bool registerPublishSource, + bool registerMqtt, + Action addApplication, + ResourceHandle? externalClient = null) { var controller = new RecordingMqttController(); var services = new ServiceCollection(); + services.AddSingleton(new PublishSourceMessages(messages)); addApplication(services); - services.AddFluxFlowComponents() - .AddMqtt() - .AddRuntimeComponent(SampleNodeTypes.PublishSource, component => - { - component.UseFactory(_ => - { - var node = new MqttPublishSourceNode(messages); - return ValueTask.FromResult(ComponentInstance.Create( - node, - outputs: - [ - ComponentPorts.Output( - MqttComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); - }); - component.AddOutput(MqttComponentDefinition.Ports.Output); - }); - services.AddApplicationResourceRegistrar(new SampleResourceRegistrar(controller)); + if (externalClient is not null) + services.AddExternalFluxFlowResource(externalClient, controller); + else if (registerMqtt) + services.AddExternalFluxFlowResource( + ApplicationAddress.Resource("messaging", "memory"), + controller); + + if (registerMqtt || registerPublishSource) + { + var components = services.AddFluxFlowComponents(); + if (registerMqtt) + components.AddMqtt(); + if (registerPublishSource) + components.AddComponent(SampleComponents.PublishSource); + } await using var provider = services.BuildServiceProvider(); var application = provider.GetRequiredService(); @@ -158,7 +145,8 @@ static async Task> RunHostedApplicationAsync( { throw new InvalidOperationException(string.Join( Environment.NewLine, - result.Diagnostics.Select(diagnostic => diagnostic.Error.Message))); + result.Diagnostics.Select(diagnostic => + $"{diagnostic.Error.Message} {diagnostic.Error.Details}"))); } await WaitForPublishedAsync(controller, messages.Count, TimeSpan.FromSeconds(5)); @@ -194,17 +182,32 @@ internal static class SampleNodeTypes public const string PublishSource = "sample.mqtt.publish-source"; } -internal sealed record SampleMessage(string Topic, string Content); +internal static class SampleComponents +{ + public static ComponentContract PublishSource { get; } = + ComponentContract.Create( + SampleNodeTypes.PublishSource, + static runtime => + { + runtime + .UseFactory(static context => new MqttPublishSourceNode( + context.Services.GetRequiredService().Messages)) + .HasOutput(MqttComponentDefinition.Ports.Output, static node => node.Output) + .HasEvents(MqttComponentDefinition.Ports.Events, static node => node.Events); + }, + static component => new PublishSourceHandle(component)); +} -internal sealed class SampleResourceRegistrar(IMqttClientController controller) - : IApplicationResourceRegistrar +internal sealed class PublishSourceHandle(ComponentHandle definition) : AuthoredComponentHandle(definition) { - public void Register(ApplicationResourceRegistrationContext context) - => context.Services.AddExternalFluxFlowResource( - ApplicationAddress.Resource("messaging", "memory"), - controller); + public OutputPortHandle Output { get; } = + definition.Output(MqttComponentDefinition.Ports.Output); } +internal sealed record SampleMessage(string Topic, string Content); + +internal sealed record PublishSourceMessages(IReadOnlyList Messages); + internal sealed class MqttPublishSourceNode(IReadOnlyList messages) : FlowSource { diff --git a/samples/FluxFlow.SampleApp/FluxFlow.SampleApp.csproj b/samples/FluxFlow.SampleApp/FluxFlow.SampleApp.csproj index 9751e85d..e8340f75 100644 --- a/samples/FluxFlow.SampleApp/FluxFlow.SampleApp.csproj +++ b/samples/FluxFlow.SampleApp/FluxFlow.SampleApp.csproj @@ -9,7 +9,6 @@ - diff --git a/samples/FluxFlow.SampleApp/OrderNodes.cs b/samples/FluxFlow.SampleApp/OrderNodes.cs index a5b10c78..3cce6440 100644 --- a/samples/FluxFlow.SampleApp/OrderNodes.cs +++ b/samples/FluxFlow.SampleApp/OrderNodes.cs @@ -16,14 +16,10 @@ internal sealed record OrderSinkOptions internal sealed class OrderSourceNode(IReadOnlyList orders) : FlowSource( new FlowSourceOptions { OutputCapacity = 8 }) { - public static ValueTask Create(ComponentActivationContext context) + public static OrderSourceNode Create(ComponentActivationContext context) { var options = context.BindConfiguration(); - var node = new OrderSourceNode(options.Orders); - return ValueTask.FromResult(ComponentInstance.Create( - node, - outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); + return new OrderSourceNode(options.Orders); } protected override async Task RunAsync(CancellationToken cancellationToken) @@ -44,15 +40,8 @@ private OrderReviewNode() { } - public static ValueTask Create(ComponentActivationContext context) - { - var node = new OrderReviewNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); - } + public static OrderReviewNode Create(ComponentActivationContext context) + => new(); protected override async Task ProcessAsync(FlowMessage message) { @@ -90,16 +79,12 @@ private OrderSinkNode(string category, InMemoryOrderStore store) _store = store; } - public static ValueTask Create( + public static OrderSinkNode Create( ComponentActivationContext context, InMemoryOrderStore store) { var options = context.BindConfiguration(); - var node = new OrderSinkNode(options.Category, store); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - events: node.Events)); + return new OrderSinkNode(options.Category, store); } protected override Task ProcessAsync(FlowMessage message) @@ -132,16 +117,10 @@ private EventCollectorNode(InMemoryComponentEventCollector collector) _collector = collector; } - public static ValueTask Create( + public static EventCollectorNode Create( ComponentActivationContext context, InMemoryComponentEventCollector collector) - { - var node = new EventCollectorNode(collector); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - events: node.Events)); - } + => new(collector); protected override Task ProcessAsync(FlowMessage message) { diff --git a/samples/FluxFlow.SampleApp/Program.cs b/samples/FluxFlow.SampleApp/Program.cs index 6a3bd7e3..1e6024aa 100644 --- a/samples/FluxFlow.SampleApp/Program.cs +++ b/samples/FluxFlow.SampleApp/Program.cs @@ -1,7 +1,6 @@ using System.Text.Json; using FluxFlow.Composition; using FluxFlow.Engine; -using FluxFlow.Mapping; using FluxFlow.SampleApp; using Microsoft.Extensions.DependencyInjection; @@ -10,10 +9,10 @@ var observedEvents = new InMemoryComponentEventCollector(); var services = new ServiceCollection(); -services.AddSingleton(new SampleExpressionEngine()); services - .AddFluxFlow(workspace.ToApplicationDefinition(), options => options.StartWithHost = false) - .AddSampleOrderComponents(store, observedEvents); + .AddSingleton(store) + .AddSingleton(observedEvents) + .AddFluxFlow(workspace.ToApplicationDefinition(), options => options.StartWithHost = false); await using var provider = services.BuildServiceProvider(); var application = provider.GetRequiredService(); diff --git a/samples/FluxFlow.SampleApp/SampleComponentRegistration.cs b/samples/FluxFlow.SampleApp/SampleComponentRegistration.cs index eecc0c43..f5e2f617 100644 --- a/samples/FluxFlow.SampleApp/SampleComponentRegistration.cs +++ b/samples/FluxFlow.SampleApp/SampleComponentRegistration.cs @@ -1,4 +1,7 @@ using FluxFlow.Composition; +using FluxFlow.Composition.Authoring; +using FluxFlow.Nodes; +using Microsoft.Extensions.DependencyInjection; namespace FluxFlow.SampleApp; @@ -10,38 +13,116 @@ internal static class SampleComponentTypes public const string EventCollector = "sample.event-collector"; } -internal static class SampleComponentRegistration +internal static class SampleComponentPorts { - public static FluxFlowRegistrationBuilder AddSampleOrderComponents( - this FluxFlowRegistrationBuilder builder, - InMemoryOrderStore store, - InMemoryComponentEventCollector events) - { - ArgumentNullException.ThrowIfNull(builder); - ArgumentNullException.ThrowIfNull(store); - ArgumentNullException.ThrowIfNull(events); + public const string Input = "Input"; + public const string Output = "Output"; + public const string Events = "Events"; +} + +internal static class SampleComponentOptions +{ + public const string Orders = "orders"; + public const string Category = "category"; +} - return builder - .AddRuntimeComponent(SampleComponentTypes.OrderSource, component => +internal static class SampleComponents +{ + public static ComponentContract OrderSource { get; } = + ComponentContract.Create( + SampleComponentTypes.OrderSource, + static runtime => { - component.UseFactory(OrderSourceNode.Create); - component.AddOutput("Output"); - }) - .AddRuntimeComponent(SampleComponentTypes.OrderReview, component => + runtime + .UseFactory(OrderSourceNode.Create) + .HasOutput(SampleComponentPorts.Output, static node => node.Output) + .HasEvents(SampleComponentPorts.Events, static node => node.Events); + }, + static () => new OrderSourceComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new OrderSourceHandle(component)); + + public static ComponentContract OrderReview { get; } = + ComponentContract.Create( + SampleComponentTypes.OrderReview, + static runtime => { - component.UseFactory(OrderReviewNode.Create); - component.AddInput("Input"); - component.AddOutput("Output"); - }) - .AddRuntimeComponent(SampleComponentTypes.OrderSink, component => + runtime + .UseFactory(OrderReviewNode.Create) + .HasInput(SampleComponentPorts.Input, static node => node.Input) + .HasOutput(SampleComponentPorts.Output, static node => node.Output) + .HasEvents(SampleComponentPorts.Events, static node => node.Events); + }, + static component => new OrderReviewHandle(component)); + + public static ComponentContract OrderSink { get; } = + ComponentContract.Create( + SampleComponentTypes.OrderSink, + static runtime => { - component.UseFactory(context => OrderSinkNode.Create(context, store)); - component.AddInput("Input"); - }) - .AddRuntimeComponent(SampleComponentTypes.EventCollector, component => + runtime + .UseFactory(static context => OrderSinkNode.Create( + context, + context.Services.GetRequiredService())) + .HasInput(SampleComponentPorts.Input, static node => node.Input) + .HasEvents(SampleComponentPorts.Events, static node => node.Events); + }, + static () => new OrderSinkComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new OrderSinkHandle(component)); + + public static ComponentContract EventCollector { get; } = + ComponentContract.Create( + SampleComponentTypes.EventCollector, + static runtime => { - component.UseFactory(context => EventCollectorNode.Create(context, events)); - component.AddInput("Input"); - }); - } + runtime + .UseFactory(static context => EventCollectorNode.Create( + context, + context.Services.GetRequiredService())) + .HasInput(SampleComponentPorts.Input, static node => node.Input) + .HasEvents(SampleComponentPorts.Events, static node => node.Events); + }, + static component => new EventCollectorHandle(component)); +} + +internal sealed class OrderSourceComponentBuilder +{ + public SampleOrder[] Orders { get; set; } = []; + + internal void Apply(ComponentDefinitionBuilder definition) + => definition.Set(SampleComponentOptions.Orders, Orders); +} + +internal sealed class OrderSinkComponentBuilder +{ + public string Category { get; set; } = "default"; + + internal void Apply(ComponentDefinitionBuilder definition) + => definition.Set(SampleComponentOptions.Category, Category); +} + +internal sealed class OrderSourceHandle(ComponentHandle definition) : AuthoredComponentHandle(definition) +{ + public OutputPortHandle Output { get; } = definition.Output(SampleComponentPorts.Output); + public OutputPortHandle Events { get; } = definition.Output(SampleComponentPorts.Events); +} + +internal sealed class OrderReviewHandle(ComponentHandle definition) : AuthoredComponentHandle(definition) +{ + public InputPortHandle Input { get; } = definition.Input(SampleComponentPorts.Input); + public OutputPortHandle Output { get; } = definition.Output(SampleComponentPorts.Output); + public OutputPortHandle Events { get; } = definition.Output(SampleComponentPorts.Events); +} + +internal sealed class OrderSinkHandle(ComponentHandle definition) : AuthoredComponentHandle(definition) +{ + public InputPortHandle Input { get; } = definition.Input(SampleComponentPorts.Input); + public OutputPortHandle Events { get; } = definition.Output(SampleComponentPorts.Events); +} + +internal sealed class EventCollectorHandle(ComponentHandle definition) : AuthoredComponentHandle(definition) +{ + public InputPortHandle Input { get; } = definition.Input(SampleComponentPorts.Input); + public OutputPortHandle Events { get; } = definition.Output(SampleComponentPorts.Events); } diff --git a/samples/FluxFlow.SampleApp/SampleExpressionEngine.cs b/samples/FluxFlow.SampleApp/SampleExpressionEngine.cs deleted file mode 100644 index d8eaa123..00000000 --- a/samples/FluxFlow.SampleApp/SampleExpressionEngine.cs +++ /dev/null @@ -1,35 +0,0 @@ -using FluxFlow.Mapping; - -namespace FluxFlow.SampleApp; - -internal sealed class SampleExpressionEngine : IFlowExpressionEngine -{ - public string Name => "sample"; - - public object? Evaluate( - string expression, - FlowMapContext context, - Type resultType) - { - if (resultType != typeof(bool)) - { - throw new InvalidOperationException( - $"Sample expression result type '{resultType.Name}' is not supported."); - } - - var input = context.Variables["input"]; - if (input is not ReviewedOrder order) - { - throw new InvalidOperationException( - $"Sample expression input type '{input?.GetType().Name ?? "null"}' is not supported."); - } - - return expression switch - { - "input.Priority == true" => order.Priority, - "input.Priority == false" => !order.Priority, - _ => throw new InvalidOperationException( - $"Sample expression '{expression}' is not supported.") - }; - } -} diff --git a/samples/FluxFlow.SampleApp/SampleWorkspaceDefinition.cs b/samples/FluxFlow.SampleApp/SampleWorkspaceDefinition.cs index dc58ae73..cda72129 100644 --- a/samples/FluxFlow.SampleApp/SampleWorkspaceDefinition.cs +++ b/samples/FluxFlow.SampleApp/SampleWorkspaceDefinition.cs @@ -1,65 +1,64 @@ -using System.Text.Json; +using FluxFlow.Composition.Authoring; using FluxFlow.Composition.Model; -using ApplicationWorkflowDefinition = FluxFlow.Composition.Model.WorkflowDefinition; namespace FluxFlow.SampleApp; internal sealed record SampleWorkspaceDefinition { public required string Name { get; init; } - public Dictionary Resources { get; init; } = []; - public Dictionary Workflows { get; init; } = []; + public required ApplicationDefinition Application { get; init; } public Dictionary Views { get; init; } = []; public Dictionary Checks { get; init; } = []; - public ApplicationDefinition ToApplicationDefinition() - => new(Resources, Workflows); + public ApplicationDefinition ToApplicationDefinition() => Application; public static SampleWorkspaceDefinition CreateDefault() - => new() + { + var application = new ApplicationDefinitionBuilder() + .AddWorkflow("main", out var main); + + main + .AddComponent( + "source", + SampleComponents.OrderSource, + options => options.Orders = + [ + new SampleOrder("A-100", "Harbor Market", 125m), + new SampleOrder("A-101", "Cedar Supply", 42m), + new SampleOrder("A-102", "Summit Works", 230m) + ], + out var source) + .AddComponent( + "review", + SampleComponents.OrderReview, + out var review) + .AddComponent( + "priority", + SampleComponents.OrderSink, + options => options.Category = "priority", + out var priority) + .AddComponent( + "standard", + SampleComponents.OrderSink, + options => options.Category = "standard", + out var standard) + .AddComponent( + "events", + SampleComponents.EventCollector, + out var events); + + source.Output.ConnectTo(review.Input); + review.Output + .ConnectTo(priority.Input, when: static order => order.Priority) + .ConnectTo(standard.Input, when: static order => !order.Priority); + review.Events.ConnectTo(events.Input); + priority.Events.ConnectTo(events.Input); + standard.Events.ConnectTo(events.Input); + + return new SampleWorkspaceDefinition { Name = "sample-order-workspace", - Workflows = - { - ["main"] = new ApplicationWorkflowDefinition( - [ - new("source", Component( - SampleComponentTypes.OrderSource, - ("orders", new[] - { - new SampleOrder("A-100", "Harbor Market", 125m), - new SampleOrder("A-101", "Cedar Supply", 42m), - new SampleOrder("A-102", "Summit Works", 230m) - }))), - new("review", Component( - SampleComponentTypes.OrderReview, - ("Input", "source.Output"))), - new("priority", Component( - SampleComponentTypes.OrderSink, - ("category", "priority"), - ("Input", new - { - Port = "review.Output", - Condition = "input.Priority == true" - }))), - new("standard", Component( - SampleComponentTypes.OrderSink, - ("category", "standard"), - ("Input", new - { - Port = "review.Output", - Condition = "input.Priority == false" - }))), - new("events", Component( - SampleComponentTypes.EventCollector, - ("Input", new[] - { - "review.Events", - "priority.Events", - "standard.Events" - }))) - ]) - }, + Application = application.Build(), Views = { ["operations"] = new SampleViewDefinition("main", "Order operations") @@ -69,15 +68,7 @@ public static SampleWorkspaceDefinition CreateDefault() ["priority-route"] = new SampleCheckDefinition("main", "priority") } }; - - private static ComponentDefinition Component( - string type, - params (string Name, object? Value)[] properties) - => new( - type, - properties.Select(property => KeyValuePair.Create( - property.Name, - JsonSerializer.SerializeToElement(property.Value)))); + } } internal sealed record SampleViewDefinition(string Workflow, string Title); diff --git a/src/FluxFlow.Components.Assertions.Composition/AssertionsAuthoringExtensions.cs b/src/FluxFlow.Components.Assertions.Composition/AssertionsAuthoringExtensions.cs index f957816d..9d3c7678 100644 --- a/src/FluxFlow.Components.Assertions.Composition/AssertionsAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Assertions.Composition/AssertionsAuthoringExtensions.cs @@ -1,30 +1,29 @@ using System.Text.Json; using FluxFlow.Components.Assertions.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; using FluxFlow.Mapping; namespace FluxFlow.Components.Assertions.Composition; +public static class AssertionsComponents +{ + public static ComponentContract>> Assertion { get; } = + DesignedComponentContract.Create( + AssertionsComponentDefinition.Types.Assertion, + AssertionsServiceCollectionExtensions.ConfigureAssertion, + static () => new AssertionComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle>(component, AssertionsComponentDefinition.Ports.Input, AssertionsComponentDefinition.Ports.Output, AssertionsComponentDefinition.Ports.Events)); +} + public static class AssertionsAuthoringExtensions { public static InputOutputComponentHandle> AddAssertion( this WorkflowDefinitionBuilder workflow, string name, Action configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent( - name, - AssertionsComponentDefinition.Types.Assertion, - definition => - { - var builder = new AssertionComponentBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new(component, AssertionsComponentDefinition.Ports.Input, AssertionsComponentDefinition.Ports.Output); - } + => workflow.AddComponent(name, AssertionsComponents.Assertion, configure); public static WorkflowDefinitionBuilder AddAssertion( this WorkflowDefinitionBuilder workflow, diff --git a/src/FluxFlow.Components.Assertions.Composition/AssertionsComponentDefinition.cs b/src/FluxFlow.Components.Assertions.Composition/AssertionsComponentDefinition.cs index 6bbefdea..06030b60 100644 --- a/src/FluxFlow.Components.Assertions.Composition/AssertionsComponentDefinition.cs +++ b/src/FluxFlow.Components.Assertions.Composition/AssertionsComponentDefinition.cs @@ -22,6 +22,7 @@ public static class Ports { public const string Input = "Input"; public const string Output = "Output"; + public const string Events = "Events"; } public static class Resources diff --git a/src/FluxFlow.Components.Assertions.Composition/AssertionsServiceCollectionExtensions.cs b/src/FluxFlow.Components.Assertions.Composition/AssertionsServiceCollectionExtensions.cs index 98f0ff32..e1d45cd4 100644 --- a/src/FluxFlow.Components.Assertions.Composition/AssertionsServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Assertions.Composition/AssertionsServiceCollectionExtensions.cs @@ -15,14 +15,11 @@ public static FluxFlowRegistrationBuilder AddAssertions( this FluxFlowRegistrationBuilder builder) { ArgumentNullException.ThrowIfNull(builder); - return builder.AddComponent( - AssertionsComponentDefinition.Types.Assertion, - ConfigureAssertion); + return builder.AddDesignedComponent(AssertionsComponents.Assertion); } - private static void ConfigureAssertion(ComponentRegistrationBuilder component) + internal static void ConfigureAssertion(ComponentRegistrationBuilder component) { - component.UseFactory(CreateJsonAssertionNode); component.WithDisplay( displayName: "Assertion", category: "Assertions", @@ -30,20 +27,31 @@ private static void ConfigureAssertion(ComponentRegistrationBuilder component) iconKey: "check-circle", preferredNodeName: "assert", suggestedEditorWidth: 420); - component.AddInput( - AssertionsComponentDefinition.Ports.Input, - displayName: "Input", - group: "Messages", - order: 0, - summary: "Immutable value to evaluate.", - isPrimary: true); - component.AddOutput>( - AssertionsComponentDefinition.Ports.Output, - displayName: "Output", - group: "Results", - order: 1, - summary: "Typed assertion outcome or workflow error.", - isPrimary: true); + component + .UseFactory(CreateJsonAssertionNode) + .HasInput( + AssertionsComponentDefinition.Ports.Input, + static node => node.Input, + displayName: "Input", + group: "Messages", + order: 0, + summary: "Immutable value to evaluate.", + isPrimary: true) + .HasOutput( + AssertionsComponentDefinition.Ports.Output, + static node => node.Output, + displayName: "Output", + group: "Results", + order: 1, + summary: "Typed assertion outcome or workflow error.", + isPrimary: true) + .HasEvents( + AssertionsComponentDefinition.Ports.Events, + static node => node.Events, + displayName: "Events", + group: "Diagnostics", + order: 2, + summary: "Best-effort assertion diagnostics."); component.AddOption( AssertionsComponentDefinition.Options.Expression, @@ -141,7 +149,7 @@ private static void AddTextOption( importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); - private static ValueTask CreateJsonAssertionNode( + private static JsonAssertionNode CreateJsonAssertionNode( ComponentActivationContext context) { var options = context.BindConfiguration(); @@ -151,26 +159,10 @@ private static ValueTask CreateJsonAssertionNode( AssertionsComponentDefinition.Resources.ContextFactory); var clock = context.GetResource( AssertionsComponentDefinition.Resources.Clock); - var node = new JsonAssertionNode( + return new JsonAssertionNode( options, expressionEngine, contextFactory, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - AssertionsComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output>( - AssertionsComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); } } diff --git a/src/FluxFlow.Components.Assertions.Composition/README.md b/src/FluxFlow.Components.Assertions.Composition/README.md index 0dd537cb..c5055bde 100644 --- a/src/FluxFlow.Components.Assertions.Composition/README.md +++ b/src/FluxFlow.Components.Assertions.Composition/README.md @@ -28,3 +28,13 @@ services.AddFluxFlowComponents().AddAssertions(); The resulting `ComponentCatalog` and `ComponentDesignMetadataCatalog` are built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`AssertionsComponents.Assertion` is the typed contract used by both generic `AddComponent` and `AddAssertion`. Its handle exposes named `Input`, `Output`, and `Events` ports. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from this contract retains its executable descriptor. Normal +code-first hosting therefore calls only `AddFluxFlow(definition)` and does not +repeat the family registration above. Use that service registration for +JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contract. diff --git a/src/FluxFlow.Components.Designer/ComponentDesignMetadataFinalizer.cs b/src/FluxFlow.Components.Designer/ComponentDesignMetadataFinalizer.cs index 9d438380..b0553939 100644 --- a/src/FluxFlow.Components.Designer/ComponentDesignMetadataFinalizer.cs +++ b/src/FluxFlow.Components.Designer/ComponentDesignMetadataFinalizer.cs @@ -5,8 +5,6 @@ namespace FluxFlow.Components.Designer; internal static class ComponentDesignMetadataFinalizer { - private const string ComponentEventsPortName = "Events"; - private const string ComponentEventsValueType = "ComponentEvent"; private const string ProcessingOptionName = "processing"; private static readonly IReadOnlyList DesignerCompatibilityOptions = [ @@ -20,7 +18,7 @@ internal static ComponentDesignMetadata Finalize(ComponentDesignMetadata metadat ArgumentNullException.ThrowIfNull(metadata); ComponentDesignMetadataValidator.ThrowIfInvalid(metadata); - var canonicalMetadata = WithComponentEvents(WithCanonicalOptions(metadata)); + var canonicalMetadata = WithCanonicalOptions(metadata); ComponentDesignMetadataValidator.ThrowIfInvalid(canonicalMetadata); return ComponentDesignMetadataSnapshot.Create(canonicalMetadata); } @@ -107,43 +105,4 @@ private static ComponentDesignMetadata WithCanonicalOptions(ComponentDesignMetad }; } - private static ComponentDesignMetadata WithComponentEvents(ComponentDesignMetadata metadata) - { - var eventPort = metadata.Ports.SingleOrDefault(static port => - string.Equals(port.Name.Value, ComponentEventsPortName, StringComparison.Ordinal)); - if (eventPort is not null) - { - if (eventPort.Direction != PortDirection.Output || - !string.Equals( - eventPort.ValueType?.Value, - ComponentEventsValueType, - StringComparison.Ordinal)) - { - throw new InvalidOperationException( - $"Designer port '{ComponentEventsPortName}' is reserved for traced component events."); - } - - return metadata; - } - - return metadata with - { - Ports = - [ - .. metadata.Ports, - new PortDesignMetadata - { - Name = new ComponentPortName(ComponentEventsPortName), - Direction = PortDirection.Output, - DisplayName = new ComponentMetadataText("Events"), - Group = new ComponentPortGroup("Diagnostics"), - Order = int.MaxValue, - Summary = new ComponentMetadataText( - "Traced lifecycle, diagnostic, observation, warning, and metric events."), - ValueType = new ComponentValueTypeHint(ComponentEventsValueType), - MessageType = typeof(ComponentEvent) - } - ] - }; - } } diff --git a/src/FluxFlow.Components.Designer/ComponentRegistrationBuilder.cs b/src/FluxFlow.Components.Designer/ComponentRegistrationBuilder.cs index 1e9d8752..0c9a3629 100644 --- a/src/FluxFlow.Components.Designer/ComponentRegistrationBuilder.cs +++ b/src/FluxFlow.Components.Designer/ComponentRegistrationBuilder.cs @@ -1,5 +1,6 @@ using FluxFlow.Components.Designer.Contracts; using FluxFlow.Composition; +using FluxFlow.Nodes; namespace FluxFlow.Components.Designer; @@ -21,6 +22,62 @@ internal ComponentRegistrationBuilder(string type) { } + public new DesignedComponentBindingBuilder UseFactory( + Func value) + where TNode : IFlowNode + { + ArgumentNullException.ThrowIfNull(value); + var runtime = UseTypedFactory( + value, + context => ValueTask.FromResult(CreateNodeActivation(value(context)))); + return new DesignedComponentBindingBuilder(this, runtime); + } + + public new DesignedComponentBindingBuilder UseFactory( + Func> value) + where TNode : IFlowNode + { + ArgumentNullException.ThrowIfNull(value); + var runtime = UseTypedFactory(value, async context => + CreateNodeActivation(await value(context).ConfigureAwait(false))); + return new DesignedComponentBindingBuilder(this, runtime); + } + + public new DesignedComponentBindingBuilder UseFactory( + Func> value) + where TNode : IFlowNode + { + ArgumentNullException.ThrowIfNull(value); + var runtime = UseTypedFactory(value, context => ValueTask.FromResult(value(context))); + return new DesignedComponentBindingBuilder(this, runtime); + } + + public new DesignedComponentBindingBuilder UseFactory( + Func>> value) + where TNode : IFlowNode + { + ArgumentNullException.ThrowIfNull(value); + return new DesignedComponentBindingBuilder(this, UseTypedFactory(value, value)); + } + + public new DesignedComponentInstanceBindingBuilder UseInstanceFactory(ComponentFactory value) + { + ArgumentNullException.ThrowIfNull(value); + return new DesignedComponentInstanceBindingBuilder(this, UseAdvancedFactory(value)); + } + + private ComponentNodeActivation CreateNodeActivation(TNode node) + where TNode : IFlowNode + { + if (node is null) + { + throw new InvalidOperationException( + $"Factory for component type '{Type}' returned a null node."); + } + + return new ComponentNodeActivation(node); + } + public void WithDisplay( string? displayName = null, string? category = null, @@ -39,45 +96,6 @@ public void WithDisplay( this.suggestedEditorWidth = suggestedEditorWidth; } - public void AddInput( - string name, - string? displayName, - string? group = null, - int order = 0, - string? summary = null, - bool isPrimary = false, - ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) - { - base.AddInput(name, linkCardinality); - DescribePort(name, PortDirection.Input, displayName, group, order, summary, isPrimary); - } - - public void AddSignalInput( - string name, - string? displayName, - string? group = null, - int order = 0, - string? summary = null, - bool isPrimary = false, - ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) - { - base.AddSignalInput(name, linkCardinality); - DescribePort(name, PortDirection.Input, displayName, group, order, summary, isPrimary); - } - - public void AddOutput( - string name, - string? displayName, - string? group = null, - int order = 0, - string? summary = null, - bool isPrimary = false, - ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) - { - base.AddOutput(name, linkCardinality); - DescribePort(name, PortDirection.Output, displayName, group, order, summary, isPrimary); - } - public void AddOption( string name, OptionValueKind kind, @@ -228,6 +246,9 @@ internal ComponentDesignMetadata CreateMetadata() return ComponentDesignMetadataFinalizer.Finalize(metadata); } + internal ComponentDesignDeclaration CreateDeclaration() + => new(CreateDescriptor(), CreateMetadata()); + internal void CopyRuntimeTo(RuntimeComponentRegistrationBuilder target) => CopyRuntimeConfigurationTo(target); @@ -292,7 +313,7 @@ private PortDesignMetadata CreatePort(ComponentPortMetadata port, PortDirection : new Dictionary() }; - private void DescribePort( + internal void DescribePort( string name, PortDirection direction, string? displayName, diff --git a/src/FluxFlow.Components.Designer/ComponentRegistrationExtensions.cs b/src/FluxFlow.Components.Designer/ComponentRegistrationExtensions.cs index db626db4..cb56d952 100644 --- a/src/FluxFlow.Components.Designer/ComponentRegistrationExtensions.cs +++ b/src/FluxFlow.Components.Designer/ComponentRegistrationExtensions.cs @@ -1,5 +1,6 @@ using FluxFlow.Components.Designer.Contracts; using FluxFlow.Composition; +using FluxFlow.Composition.Authoring; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System.Text.Json; @@ -8,6 +9,24 @@ namespace FluxFlow.Components.Designer; public static class ComponentRegistrationExtensions { + public static FluxFlowRegistrationBuilder AddDesignedComponent( + this FluxFlowRegistrationBuilder builder, + ComponentContract component) + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(component); + if (component is not IDesignedComponentContract designed) + { + throw new ArgumentException( + $"Component contract '{component.Type}' does not contain design metadata.", + nameof(component)); + } + + FluxFlowRegistrationExtensions.AddComponent(builder, component); + RegisterDesignMetadata(builder, component.Descriptor, designed.Metadata); + return builder; + } + public static FluxFlowRegistrationBuilder AddComponent( this FluxFlowRegistrationBuilder builder, string type, @@ -20,7 +39,24 @@ public static FluxFlowRegistrationBuilder AddComponent( var component = new ComponentRegistrationBuilder(type); configure(component); var metadata = component.CreateMetadata(); + builder.Advanced.AddDynamicComponent(type, component.CopyRuntimeTo); + var descriptor = builder.Services + .Where(static registration => registration.ServiceType == typeof(ComponentDescriptor)) + .Select(static registration => registration.ImplementationInstance) + .OfType() + .Single(candidate => string.Equals( + candidate.Type, + metadata.Type.Value, + StringComparison.Ordinal)); + RegisterDesignMetadata(builder, descriptor, metadata); + return builder; + } + private static void RegisterDesignMetadata( + FluxFlowRegistrationBuilder builder, + ComponentDescriptor descriptor, + ComponentDesignMetadata metadata) + { var existingDeclaration = GetDeclarations(builder.Services) .SingleOrDefault(declaration => string.Equals( declaration.Descriptor.Type, @@ -33,22 +69,10 @@ public static FluxFlowRegistrationBuilder AddComponent( $"Component type '{metadata.Type}' has a conflicting design registration."); } - builder.AddRuntimeComponent(type, component.CopyRuntimeTo); - var descriptor = builder.Services - .Where(static registration => registration.ServiceType == typeof(ComponentDescriptor)) - .Select(static registration => registration.ImplementationInstance) - .OfType() - .Single(candidate => string.Equals( - candidate.Type, - metadata.Type.Value, - StringComparison.Ordinal)); - if (existingDeclaration is null) builder.Services.AddSingleton(new ComponentDesignDeclaration(descriptor, metadata)); EnsureDesignMetadataCatalog(builder.Services); - - return builder; } private static void EnsureDesignMetadataCatalog(IServiceCollection services) diff --git a/src/FluxFlow.Components.Designer/DesignedComponentBindingBuilder.cs b/src/FluxFlow.Components.Designer/DesignedComponentBindingBuilder.cs new file mode 100644 index 00000000..e79ac2da --- /dev/null +++ b/src/FluxFlow.Components.Designer/DesignedComponentBindingBuilder.cs @@ -0,0 +1,151 @@ +using System.Threading.Tasks.Dataflow; +using FluxFlow.Components.Designer.Contracts; +using FluxFlow.Composition; +using FluxFlow.Nodes; + +namespace FluxFlow.Components.Designer; + +public sealed class DesignedComponentBindingBuilder + where TNode : IFlowNode +{ + private readonly ComponentRegistrationBuilder _component; + private readonly RuntimeComponentBindingBuilder _runtime; + + internal DesignedComponentBindingBuilder( + ComponentRegistrationBuilder component, + RuntimeComponentBindingBuilder runtime) + { + _component = component ?? throw new ArgumentNullException(nameof(component)); + _runtime = runtime ?? throw new ArgumentNullException(nameof(runtime)); + } + + public DesignedComponentBindingBuilder HasInput( + string name, + Func>> selector, + string? displayName = null, + string? group = null, + int? order = null, + string? summary = null, + bool isPrimary = false, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _runtime.HasInput(name, selector, linkCardinality); + _component.DescribePort(name, PortDirection.Input, displayName, group, order, summary, isPrimary); + return this; + } + + public DesignedComponentBindingBuilder HasSignalInput( + string name, + Func selector, + string? displayName = null, + string? group = null, + int? order = null, + string? summary = null, + bool isPrimary = false, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _runtime.HasSignalInput(name, selector, linkCardinality); + _component.DescribePort(name, PortDirection.Input, displayName, group, order, summary, isPrimary); + return this; + } + + public DesignedComponentBindingBuilder HasOutput( + string name, + Func>> selector, + string? displayName = null, + string? group = null, + int? order = null, + string? summary = null, + bool isPrimary = false, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _runtime.HasOutput(name, selector, linkCardinality); + _component.DescribePort(name, PortDirection.Output, displayName, group, order, summary, isPrimary); + return this; + } + + public DesignedComponentBindingBuilder HasEvents( + string name, + Func> selector, + string? displayName = null, + string? group = null, + int? order = null, + string? summary = null, + bool isPrimary = false, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _runtime.HasEvents(name, selector, linkCardinality); + _component.DescribePort(name, PortDirection.Output, displayName, group, order, summary, isPrimary); + return this; + } +} + +public sealed class DesignedComponentInstanceBindingBuilder +{ + private readonly ComponentRegistrationBuilder _component; + private readonly RuntimeComponentInstanceBindingBuilder _runtime; + + internal DesignedComponentInstanceBindingBuilder( + ComponentRegistrationBuilder component, + RuntimeComponentInstanceBindingBuilder runtime) + { + _component = component ?? throw new ArgumentNullException(nameof(component)); + _runtime = runtime ?? throw new ArgumentNullException(nameof(runtime)); + } + + public DesignedComponentInstanceBindingBuilder HasInput( + string name, + string? displayName = null, + string? group = null, + int? order = null, + string? summary = null, + bool isPrimary = false, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _runtime.HasInput(name, linkCardinality); + _component.DescribePort(name, PortDirection.Input, displayName, group, order, summary, isPrimary); + return this; + } + + public DesignedComponentInstanceBindingBuilder HasSignalInput( + string name, + string? displayName = null, + string? group = null, + int? order = null, + string? summary = null, + bool isPrimary = false, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _runtime.HasSignalInput(name, linkCardinality); + _component.DescribePort(name, PortDirection.Input, displayName, group, order, summary, isPrimary); + return this; + } + + public DesignedComponentInstanceBindingBuilder HasOutput( + string name, + string? displayName = null, + string? group = null, + int? order = null, + string? summary = null, + bool isPrimary = false, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _runtime.HasOutput(name, linkCardinality); + _component.DescribePort(name, PortDirection.Output, displayName, group, order, summary, isPrimary); + return this; + } + + public DesignedComponentInstanceBindingBuilder HasEvents( + string name, + string? displayName = null, + string? group = null, + int? order = null, + string? summary = null, + bool isPrimary = false, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _runtime.HasEvents(name, linkCardinality); + _component.DescribePort(name, PortDirection.Output, displayName, group, order, summary, isPrimary); + return this; + } +} diff --git a/src/FluxFlow.Components.Designer/DesignedComponentContract.cs b/src/FluxFlow.Components.Designer/DesignedComponentContract.cs new file mode 100644 index 00000000..57c8c85d --- /dev/null +++ b/src/FluxFlow.Components.Designer/DesignedComponentContract.cs @@ -0,0 +1,85 @@ +using FluxFlow.Components.Designer.Contracts; +using FluxFlow.Composition; +using FluxFlow.Composition.Authoring; + +namespace FluxFlow.Components.Designer; + +public static class DesignedComponentContract +{ + public static ComponentContract Create( + string type, + Action configure, + Func createHandle) + where THandle : AuthoredComponentHandle + { + var declaration = CreateDeclaration(type, configure); + return new DesignedContract( + declaration, + createHandle); + } + + public static ComponentContract Create( + string type, + Action configure, + Func createOptions, + Action apply, + Func createHandle) + where TOptions : class + where THandle : AuthoredComponentHandle + { + var declaration = CreateDeclaration(type, configure); + return new DesignedContract( + declaration, + createOptions, + apply, + createHandle); + } + + private static ComponentDesignDeclaration CreateDeclaration( + string type, + Action configure) + { + ArgumentException.ThrowIfNullOrWhiteSpace(type); + ArgumentNullException.ThrowIfNull(configure); + + var component = new ComponentRegistrationBuilder(type); + configure(component); + return component.CreateDeclaration(); + } + + private sealed class DesignedContract : + ComponentContract, + IDesignedComponentContract + where THandle : AuthoredComponentHandle + { + internal DesignedContract( + ComponentDesignDeclaration declaration, + Func createHandle) + : base(declaration.Descriptor, createHandle) + => Metadata = declaration.Metadata; + + public ComponentDesignMetadata Metadata { get; } + } + + private sealed class DesignedContract : + ComponentContract, + IDesignedComponentContract + where TOptions : class + where THandle : AuthoredComponentHandle + { + internal DesignedContract( + ComponentDesignDeclaration declaration, + Func createOptions, + Action apply, + Func createHandle) + : base(declaration.Descriptor, createOptions, apply, createHandle) + => Metadata = declaration.Metadata; + + public ComponentDesignMetadata Metadata { get; } + } +} + +internal interface IDesignedComponentContract +{ + ComponentDesignMetadata Metadata { get; } +} diff --git a/src/FluxFlow.Components.Designer/README.md b/src/FluxFlow.Components.Designer/README.md index 9f1b2582..0791cf93 100644 --- a/src/FluxFlow.Components.Designer/README.md +++ b/src/FluxFlow.Components.Designer/README.md @@ -24,15 +24,39 @@ var runtimeCatalog = provider.GetRequiredService(); var designCatalog = provider.GetRequiredService(); ``` -`ComponentCatalog` remains owned by Composition. Every designed -`AddComponent(...)` registration automatically contributes to the immutable -`ComponentDesignMetadataCatalog`; there is no terminal catalog-registration -call and no second component registry. A chain containing only -`AddRuntimeComponent(...)` registers only the runtime catalog. +`ComponentCatalog` remains owned by Composition. Every designed registration +automatically contributes to the immutable `ComponentDesignMetadataCatalog`; +there is no terminal catalog-registration call and no second component +registry. A chain containing only +`Advanced.AddDynamicComponent(...)` registers only the runtime catalog. -## Flat Designed Components +## Complete Designed Contracts -`AddComponent(...)` creates the runtime descriptor and presentation metadata +Official packages create complete `ComponentContract` values through +`DesignedComponentContract.Create(...)`. One flat declaration produces the +exact runtime descriptor, typed authoring handle, and presentation metadata. +Family registration passes that same contract to `AddDesignedComponent(...)`; +metadata inspection never activates the node factory. + +```csharp +public static ComponentContract Transform { get; } = + DesignedComponentContract.Create( + "sample.transform", + ConfigureTransform, + static component => new TransformHandle(component)); + +services.AddFluxFlowComponents() + .AddDesignedComponent(Transform); +``` + +Code-first application builders carry the contract's runtime descriptor in the +built definition. JSON hosts use the family extension or the explicit designed +registration above because JSON contains no executable descriptor. + +## Low-Level Designed Components + +The retained low-level `AddComponent(type, callback)` path creates the runtime +descriptor and presentation metadata from one authoritative, flat callback. The type appears once, the callback runs immediately, and no `Build`, `Commit`, nested builder, reflection, or scanning is involved. @@ -45,7 +69,6 @@ immutable metadata records directly and passes them to ```csharp builder.AddComponent("sample.transform", component => { - component.UseFactory(CreateTransformAsync); component.UseProcessing(CompositionProcessingCapabilities.Sequential); component.WithDisplay( @@ -56,21 +79,30 @@ builder.AddComponent("sample.transform", component => preferredNodeName: "transform", suggestedEditorWidth: 420); - component.AddInput( - "Input", - displayName: "Input", - group: "Values", - order: 0, - summary: "Value to transform.", - isPrimary: true); - - component.AddOutput( - "Output", - displayName: "Output", - group: "Results", - order: 0, - summary: "Transformed value.", - isPrimary: true); + component + .UseFactory(CreateTransform) + .HasInput( + "Input", + static node => node.Input, + displayName: "Input", + group: "Values", + order: 0, + summary: "Value to transform.", + isPrimary: true) + .HasOutput( + "Output", + static node => node.Output, + displayName: "Output", + group: "Results", + order: 0, + summary: "Transformed value.", + isPrimary: true) + .HasEvents( + "Diagnostics", + static node => node.Events, + displayName: "Diagnostics", + group: "Diagnostics", + order: 1); component.AddOption( "expression", @@ -107,15 +139,18 @@ builder.AddComponent("sample.transform", component => Root-level methods cover display information, ports, options, resources, choices, and attributes. References to unknown options, ports, or resources fail during registration. Duplicate names, invalid ranges, missing -factories, reserved `Events` outputs, and invalid metadata also fail immediately. +factories, duplicate output/event names, and invalid metadata also fail immediately. +Event ports are explicit and may use any valid output name. They select a +`FlowEvent` source and publish `ComponentEvent` values; no event metadata is +injected implicitly and `Events` is not reserved. Equivalent repeated built-in family registration is idempotent. A semantically different runtime descriptor or design registration for an existing type throws a clear conflict exception; registration never uses last-write-wins behavior. -Runtime-only components belong to `FluxFlow.Composition` and use the distinct -`AddRuntimeComponent(...)` API, so Composition-only consumers do not need this -package. +Runtime-only dynamic components belong to `FluxFlow.Composition` and use the +distinct `Advanced.AddDynamicComponent(...)` API, so Composition-only consumers +do not need this package. ## Metadata Contracts @@ -195,10 +230,12 @@ public static FluxFlowRegistrationBuilder AddSampleTransforms( this FluxFlowRegistrationBuilder builder) => builder.AddComponent("sample.transform", component => { - component.UseFactory(CreateTransformAsync); component.WithDisplay(displayName: "Sample Transform", category: "Samples"); - component.AddInput("Input", displayName: "Input"); - component.AddOutput("Output", displayName: "Output"); + component + .UseFactory(CreateTransform) + .HasInput("Input", static node => node.Input, displayName: "Input") + .HasOutput("Output", static node => node.Output, displayName: "Output") + .HasEvents("Events", static node => node.Events, displayName: "Events"); }); ``` diff --git a/src/FluxFlow.Components.Expectations.Composition/ExpectationsAuthoringExtensions.cs b/src/FluxFlow.Components.Expectations.Composition/ExpectationsAuthoringExtensions.cs index 37244b4f..0cc941a5 100644 --- a/src/FluxFlow.Components.Expectations.Composition/ExpectationsAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Expectations.Composition/ExpectationsAuthoringExtensions.cs @@ -1,26 +1,32 @@ using FluxFlow.Components.Expectations.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Components.Expectations.Nodes; using FluxFlow.Components.Projections.Contracts; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Expectations.Composition; +public static class ExpectationsComponents +{ + public static ComponentContract> EventExpectation { get; } = + DesignedComponentContract.Create( + ExpectationsComponentDefinition.Types.EventExpectation, + ExpectationsServiceCollectionExtensions.ConfigureEventExpectation, + static () => new EventExpectationComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, ExpectationsComponentDefinition.Ports.Input, ExpectationsComponentDefinition.Ports.Output, ExpectationsComponentDefinition.Ports.Events)); +} + public static class ExpectationsAuthoringExtensions { public static InputOutputComponentHandle AddEventExpectation( this WorkflowDefinitionBuilder workflow, string name, Action? configure = null) - { - ArgumentNullException.ThrowIfNull(workflow); - var component = workflow.AddComponent(name, ExpectationsComponentDefinition.Types.EventExpectation, definition => - { - var builder = new EventExpectationComponentBuilder(); - configure?.Invoke(builder); - builder.Apply(definition); - }); - return new(component, ExpectationsComponentDefinition.Ports.Input, ExpectationsComponentDefinition.Ports.Output); - } + => workflow.AddComponent( + name, + ExpectationsComponents.EventExpectation, + configure ?? (static _ => { })); public static WorkflowDefinitionBuilder AddEventExpectation( this WorkflowDefinitionBuilder workflow, diff --git a/src/FluxFlow.Components.Expectations.Composition/ExpectationsComponentDefinition.cs b/src/FluxFlow.Components.Expectations.Composition/ExpectationsComponentDefinition.cs index 99d6cfc6..78a130da 100644 --- a/src/FluxFlow.Components.Expectations.Composition/ExpectationsComponentDefinition.cs +++ b/src/FluxFlow.Components.Expectations.Composition/ExpectationsComponentDefinition.cs @@ -14,6 +14,6 @@ public static class Options } public static class Types { public const string EventExpectation = "event.expect"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Clock = "clock"; } } diff --git a/src/FluxFlow.Components.Expectations.Composition/ExpectationsServiceCollectionExtensions.cs b/src/FluxFlow.Components.Expectations.Composition/ExpectationsServiceCollectionExtensions.cs index f46d8536..03177ac9 100644 --- a/src/FluxFlow.Components.Expectations.Composition/ExpectationsServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Expectations.Composition/ExpectationsServiceCollectionExtensions.cs @@ -14,16 +14,18 @@ public static class ExpectationsServiceCollectionExtensions public static FluxFlowRegistrationBuilder AddExpectations(this FluxFlowRegistrationBuilder builder) { ArgumentNullException.ThrowIfNull(builder); - return builder.AddComponent(ExpectationsComponentDefinition.Types.EventExpectation, ConfigureEventExpectation); + return builder.AddDesignedComponent(ExpectationsComponents.EventExpectation); } - private static void ConfigureEventExpectation(ComponentRegistrationBuilder component) + internal static void ConfigureEventExpectation(ComponentRegistrationBuilder component) { var defaults = new EventExpectationOptions(); - component.UseFactory(CreateEventExpectationNode); component.WithDisplay("Event Expectation", "Expectations", "Resolves projection-event rules, timeout, completion, and evaluation failures through one result output.", "badge-check", "expectEvent", 460); - component.AddInput(ExpectationsComponentDefinition.Ports.Input, "Input", "Messages", 0, "Projection event observed by the expectation.", true); - component.AddOutput(ExpectationsComponentDefinition.Ports.Output, "Output", "Results", 1, "Normal matched, unmet, timeout, completion, or evaluation-failure result.", true); + component + .UseFactory(CreateEventExpectationNode) + .HasInput(ExpectationsComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Projection event observed by the expectation.", true) + .HasOutput(ExpectationsComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Normal matched, unmet, timeout, completion, or evaluation-failure result.", true) + .HasEvents(ExpectationsComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort expectation diagnostics."); component.AddOption(ExpectationsComponentDefinition.Options.Kind, OptionValueKind.Enum, "Kind", "Expectation behavior: expect a match or guard against one.", defaultValue: defaults.Kind.ToString(), section: "Expectation", importance: OptionDesignMetadataAttributeValues.Primary); component.AddOptionChoice(ExpectationsComponentDefinition.Options.Kind, EventExpectationNodeKind.Expect.ToString(), "Expect", "Satisfied when a matching event arrives."); component.AddOptionChoice(ExpectationsComponentDefinition.Options.Kind, EventExpectationNodeKind.Guard.ToString(), "Guard", "Satisfied when no matching event arrives."); @@ -36,28 +38,12 @@ private static void ConfigureEventExpectation(ComponentRegistrationBuilder compo component.AddResource(ExpectationsComponentDefinition.Resources.Clock, "Clock", 0, "Optional keyed clock for deterministic expectation timeouts, results, and diagnostics.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "Resources.{name}"); } - private static ValueTask CreateEventExpectationNode( + private static EventExpectationNode CreateEventExpectationNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource( ExpectationsComponentDefinition.Resources.Clock); - var node = new EventExpectationNode(options, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - ExpectationsComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - ExpectationsComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new EventExpectationNode(options, clock); } } diff --git a/src/FluxFlow.Components.Expectations.Composition/README.md b/src/FluxFlow.Components.Expectations.Composition/README.md index 33edff14..3dff9839 100644 --- a/src/FluxFlow.Components.Expectations.Composition/README.md +++ b/src/FluxFlow.Components.Expectations.Composition/README.md @@ -19,3 +19,13 @@ services.AddFluxFlowComponents().AddExpectations(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`ExpectationsComponents.EventExpectation` is the typed contract used by both generic `AddComponent` and `AddEventExpectation`. Its handle exposes named `Input`, `Output`, and `Events` ports. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from this contract retains its executable descriptor. Normal +code-first hosting therefore calls only `AddFluxFlow(definition)` and does not +repeat the family registration above. Use that service registration for +JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contract. diff --git a/src/FluxFlow.Components.FileSystem.Composition/FileSystemAuthoringExtensions.cs b/src/FluxFlow.Components.FileSystem.Composition/FileSystemAuthoringExtensions.cs index fa90481c..8240dd2b 100644 --- a/src/FluxFlow.Components.FileSystem.Composition/FileSystemAuthoringExtensions.cs +++ b/src/FluxFlow.Components.FileSystem.Composition/FileSystemAuthoringExtensions.cs @@ -1,16 +1,51 @@ using FluxFlow.Components.FileSystem.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.FileSystem.Composition; +public static class FileSystemComponents +{ + public static ComponentContract> FileRead { get; } = + DesignedComponentContract.Create( + FileSystemComponentDefinition.Types.Read, + FileSystemServiceCollectionExtensions.ConfigureRead, + static () => new FileReadComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, FileSystemComponentDefinition.Ports.Input, FileSystemComponentDefinition.Ports.Output, FileSystemComponentDefinition.Ports.Events)); + + public static ComponentContract> FileWrite { get; } = + DesignedComponentContract.Create( + FileSystemComponentDefinition.Types.Write, + FileSystemServiceCollectionExtensions.ConfigureWrite, + static () => new FileWriteComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, FileSystemComponentDefinition.Ports.Input, FileSystemComponentDefinition.Ports.Output, FileSystemComponentDefinition.Ports.Events)); + + public static ComponentContract> DirectoryEnumerate { get; } = + DesignedComponentContract.Create( + FileSystemComponentDefinition.Types.DirectoryEnumerate, + FileSystemServiceCollectionExtensions.ConfigureDirectoryEnumerate, + static () => new DirectoryEnumerateComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new OutputComponentHandle(component, FileSystemComponentDefinition.Ports.Output, FileSystemComponentDefinition.Ports.Events)); + + public static ComponentContract> FileWatch { get; } = + DesignedComponentContract.Create( + FileSystemComponentDefinition.Types.Watch, + FileSystemServiceCollectionExtensions.ConfigureWatch, + static () => new FileWatchComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new OutputComponentHandle(component, FileSystemComponentDefinition.Ports.Output, FileSystemComponentDefinition.Ports.Events)); +} + public static class FileSystemAuthoringExtensions { public static InputOutputComponentHandle AddFileRead( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => AddTransform( - workflow, name, FileSystemComponentDefinition.Types.Read, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, FileSystemComponents.FileRead, configure); public static WorkflowDefinitionBuilder AddFileRead( this WorkflowDefinitionBuilder workflow, @@ -26,8 +61,7 @@ public static InputOutputComponentHandle configure) - => AddTransform( - workflow, name, FileSystemComponentDefinition.Types.Write, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, FileSystemComponents.FileWrite, configure); public static WorkflowDefinitionBuilder AddFileWrite( this WorkflowDefinitionBuilder workflow, @@ -43,8 +77,7 @@ public static OutputComponentHandle AddDirectoryEnumerate( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => AddSource( - workflow, name, FileSystemComponentDefinition.Types.DirectoryEnumerate, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, FileSystemComponents.DirectoryEnumerate, configure); public static WorkflowDefinitionBuilder AddDirectoryEnumerate( this WorkflowDefinitionBuilder workflow, @@ -60,8 +93,7 @@ public static OutputComponentHandle AddFileWatch( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => AddSource( - workflow, name, FileSystemComponentDefinition.Types.Watch, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, FileSystemComponents.FileWatch, configure); public static WorkflowDefinitionBuilder AddFileWatch( this WorkflowDefinitionBuilder workflow, @@ -73,43 +105,6 @@ public static WorkflowDefinitionBuilder AddFileWatch( return workflow; } - private static InputOutputComponentHandle AddTransform( - WorkflowDefinitionBuilder workflow, - string name, - string type, - Action configure, - Action apply) - where TBuilder : FileSystemComponentBuilder, new() - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, type, definition => - { - var builder = new TBuilder(); - configure(builder); - apply(builder, definition); - }); - return new(component, FileSystemComponentDefinition.Ports.Input, FileSystemComponentDefinition.Ports.Output); - } - - private static OutputComponentHandle AddSource( - WorkflowDefinitionBuilder workflow, - string name, - string type, - Action configure, - Action apply) - where TBuilder : FileSystemComponentBuilder, new() - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, type, definition => - { - var builder = new TBuilder(); - configure(builder); - apply(builder, definition); - }); - return new(component, FileSystemComponentDefinition.Ports.Output); - } } public abstract class FileSystemComponentBuilder diff --git a/src/FluxFlow.Components.FileSystem.Composition/FileSystemComponentDefinition.cs b/src/FluxFlow.Components.FileSystem.Composition/FileSystemComponentDefinition.cs index a50f59f2..0ae58e87 100644 --- a/src/FluxFlow.Components.FileSystem.Composition/FileSystemComponentDefinition.cs +++ b/src/FluxFlow.Components.FileSystem.Composition/FileSystemComponentDefinition.cs @@ -27,6 +27,6 @@ public static class Types public const string Watch = "file.watch"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Clock = "clock"; } } diff --git a/src/FluxFlow.Components.FileSystem.Composition/FileSystemServiceCollectionExtensions.cs b/src/FluxFlow.Components.FileSystem.Composition/FileSystemServiceCollectionExtensions.cs index b880c0fb..18aab487 100644 --- a/src/FluxFlow.Components.FileSystem.Composition/FileSystemServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.FileSystem.Composition/FileSystemServiceCollectionExtensions.cs @@ -13,42 +13,48 @@ public static FluxFlowRegistrationBuilder AddFileSystem(this FluxFlowRegistratio { ArgumentNullException.ThrowIfNull(builder); return builder - .AddComponent(FileSystemComponentDefinition.Types.Read, ConfigureRead) - .AddComponent(FileSystemComponentDefinition.Types.Write, ConfigureWrite) - .AddComponent(FileSystemComponentDefinition.Types.DirectoryEnumerate, ConfigureDirectoryEnumerate) - .AddComponent(FileSystemComponentDefinition.Types.Watch, ConfigureWatch); + .AddDesignedComponent(FileSystemComponents.FileRead) + .AddDesignedComponent(FileSystemComponents.FileWrite) + .AddDesignedComponent(FileSystemComponents.DirectoryEnumerate) + .AddDesignedComponent(FileSystemComponents.FileWatch); } - private static void ConfigureRead(ComponentRegistrationBuilder component) + internal static void ConfigureRead(ComponentRegistrationBuilder component) { var defaults = new FileReadOptions(); - ConfigureCommon(component, CreateFileReadNode, "File Read", "Reads text or bytes from a file path using configured path policy.", "file-input", "readFile"); + ConfigureCommon(component, "File Read", "Reads text or bytes from a file path using configured path policy.", "file-input", "readFile"); AddCapacity(component, defaults.BoundedCapacity); AddBaseDirectory(component, OptionDesignMetadataAttributeValues.Primary); AddAllowAbsolutePaths(component, defaults.AllowAbsolutePaths); component.AddOption(FileSystemComponentDefinition.Options.DefaultEncoding, OptionValueKind.Text, "Default Encoding", "Encoding name used when a request does not specify one.", defaultValue: defaults.DefaultEncoding, section: "Encoding", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); component.AddOption(FileSystemComponentDefinition.Options.MaxBytes, OptionValueKind.Number, "Max Bytes", "Optional maximum file size to read. Leave empty for unlimited reads.", defaultValue: defaults.MaxBytes, min: 1, section: "Limits", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Number); - component.AddInput(FileSystemComponentDefinition.Ports.Input, "Input", "Messages", 0, "File read request.", true); - component.AddOutput(FileSystemComponentDefinition.Ports.Output, "Output", "Results", 1, "File content; read failures use the message error case.", true); + component + .UseFactory(CreateFileReadNode) + .HasInput(FileSystemComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "File read request.", true) + .HasOutput(FileSystemComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "File content; read failures use the message error case.", true) + .HasEvents(FileSystemComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort file-read diagnostics."); } - private static void ConfigureWrite(ComponentRegistrationBuilder component) + internal static void ConfigureWrite(ComponentRegistrationBuilder component) { var defaults = new FileWriteOptions(); - ConfigureCommon(component, CreateFileWriteNode, "File Write", "Writes text or bytes to a file path using configured path policy.", "file-output", "writeFile"); + ConfigureCommon(component, "File Write", "Writes text or bytes to a file path using configured path policy.", "file-output", "writeFile"); AddCapacity(component, defaults.BoundedCapacity); AddBaseDirectory(component, OptionDesignMetadataAttributeValues.Primary); AddAllowAbsolutePaths(component, defaults.AllowAbsolutePaths); component.AddAttribute("omittedOptions", FileSystemComponentDefinition.Options.DefaultEncoding); component.AddAttribute("omittedOptionsReason", "Canonical file.write writes exact FlowContent bytes and does not encode text."); - component.AddInput(FileSystemComponentDefinition.Ports.Input, "Input", "Messages", 0, "File content write request.", true); - component.AddOutput(FileSystemComponentDefinition.Ports.Output, "Output", "Results", 1, "File write receipt; write failures use the message error case.", true); + component + .UseFactory(CreateFileWriteNode) + .HasInput(FileSystemComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "File content write request.", true) + .HasOutput(FileSystemComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "File write receipt; write failures use the message error case.", true) + .HasEvents(FileSystemComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort file-write diagnostics."); } - private static void ConfigureDirectoryEnumerate(ComponentRegistrationBuilder component) + internal static void ConfigureDirectoryEnumerate(ComponentRegistrationBuilder component) { var defaults = new DirectoryEnumerateOptions(); - ConfigureCommon(component, CreateDirectoryEnumerateNode, "Directory Enumerate", "Enumerates matching files and directories from a configured directory.", "folder-search", "enumerateDirectory"); + ConfigureCommon(component, "Directory Enumerate", "Enumerates matching files and directories from a configured directory.", "folder-search", "enumerateDirectory"); AddCapacity(component, defaults.BoundedCapacity); AddDirectory(component, defaults.Directory); AddFilter(component, defaults.Filter); @@ -58,13 +64,16 @@ private static void ConfigureDirectoryEnumerate(ComponentRegistrationBuilder com AddBaseDirectory(component, OptionDesignMetadataAttributeValues.Advanced); AddAllowAbsolutePaths(component, defaults.AllowAbsolutePaths); component.AddOption(FileSystemComponentDefinition.Options.MaxEntries, OptionValueKind.Number, "Max Entries", "Optional maximum number of entries to emit.", min: 1, section: "Limits", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); - component.AddOutput(FileSystemComponentDefinition.Ports.Output, "Output", "Messages", 0, "Directory entry.", true); + component + .UseFactory(CreateDirectoryEnumerateNode) + .HasOutput(FileSystemComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 0, "Directory entry.", true) + .HasEvents(FileSystemComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 1, "Best-effort directory-enumeration diagnostics."); } - private static void ConfigureWatch(ComponentRegistrationBuilder component) + internal static void ConfigureWatch(ComponentRegistrationBuilder component) { var defaults = new FileWatchOptions(); - ConfigureCommon(component, CreateFileWatchNode, "File Watch", "Watches a configured directory and emits file change events.", "folder-sync", "watchFiles"); + ConfigureCommon(component, "File Watch", "Watches a configured directory and emits file change events.", "folder-sync", "watchFiles"); AddCapacity(component, defaults.BoundedCapacity); AddDirectory(component, defaults.Directory); AddBaseDirectory(component, OptionDesignMetadataAttributeValues.Advanced); @@ -73,12 +82,14 @@ private static void ConfigureWatch(ComponentRegistrationBuilder component) component.AddOption(FileSystemComponentDefinition.Options.IncludeSubdirectories, OptionValueKind.Boolean, "Include Subdirectories", "Watch child directories.", defaultValue: defaults.IncludeSubdirectories, section: "Traversal", importance: OptionDesignMetadataAttributeValues.Advanced); component.AddOption(FileSystemComponentDefinition.Options.NotifyFilters, OptionValueKind.Json, "Notify Filters", "Optional array of FileSystemWatcher notify filter names.", defaultValue: defaults.NotifyFilters, section: "Watching", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Json); component.AddOption(FileSystemComponentDefinition.Options.InternalBufferSize, OptionValueKind.Number, "Internal Buffer Size", "Optional watcher buffer size in bytes.", min: 4096, max: 65536, section: "Watching", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); - component.AddOutput(FileSystemComponentDefinition.Ports.Output, "Output", "Messages", 0, "File change event.", true); + component + .UseFactory(CreateFileWatchNode) + .HasOutput(FileSystemComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 0, "File change event.", true) + .HasEvents(FileSystemComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 1, "Best-effort file-watch diagnostics."); } - private static void ConfigureCommon(ComponentRegistrationBuilder component, ComponentFactory factory, string displayName, string summary, string iconKey, string preferredNodeName) + private static void ConfigureCommon(ComponentRegistrationBuilder component, string displayName, string summary, string iconKey, string preferredNodeName) { - component.UseFactory(factory); component.WithDisplay(displayName, "FileSystem", summary, iconKey, preferredNodeName, 460); component.AddResource(FileSystemComponentDefinition.Resources.Clock, "Clock", 0, "Optional keyed clock for deterministic file-system diagnostics and timestamps.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "clock:{name}"); } @@ -98,91 +109,39 @@ private static void AddDirectory(ComponentRegistrationBuilder component, string private static void AddFilter(ComponentRegistrationBuilder component, string defaultValue) => component.AddOption(FileSystemComponentDefinition.Options.Filter, OptionValueKind.Text, "Filter", "File-system wildcard filter.", true, defaultValue, section: "Paths", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Text); - private static ValueTask CreateFileReadNode( + private static FileReadNode CreateFileReadNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource( FileSystemComponentDefinition.Resources.Clock); - var node = new FileReadNode(options, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - FileSystemComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - FileSystemComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new FileReadNode(options, clock); } - private static ValueTask CreateFileWriteNode( + private static FileWriteNode CreateFileWriteNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource( FileSystemComponentDefinition.Resources.Clock); - var node = new FileWriteNode(options, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - FileSystemComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - FileSystemComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new FileWriteNode(options, clock); } - private static ValueTask CreateDirectoryEnumerateNode( + private static DirectoryEnumerateNode CreateDirectoryEnumerateNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource( FileSystemComponentDefinition.Resources.Clock); - var node = new DirectoryEnumerateNode(options, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - outputs: - [ - ComponentPorts.Output( - FileSystemComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new DirectoryEnumerateNode(options, clock); } - private static ValueTask CreateFileWatchNode( + private static FileWatchNode CreateFileWatchNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource( FileSystemComponentDefinition.Resources.Clock); - var node = new FileWatchNode(options, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - outputs: - [ - ComponentPorts.Output( - FileSystemComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new FileWatchNode(options, clock); } } diff --git a/src/FluxFlow.Components.FileSystem.Composition/README.md b/src/FluxFlow.Components.FileSystem.Composition/README.md index 3c86fb4b..d4f1745b 100644 --- a/src/FluxFlow.Components.FileSystem.Composition/README.md +++ b/src/FluxFlow.Components.FileSystem.Composition/README.md @@ -24,3 +24,13 @@ services.AddFluxFlowComponents().AddFileSystem(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`FileSystemComponents` exposes `FileRead`, `FileWrite`, `DirectoryEnumerate`, and `FileWatch` typed contracts. The retained `AddX` methods use those same contracts, and every handle exposes `Events`. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from these contracts retains its executable descriptors. +Normal code-first hosting therefore calls only `AddFluxFlow(definition)` and +does not repeat the family registration above. Use that service registration +for JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contracts. diff --git a/src/FluxFlow.Components.Http.Composition/HttpAuthoringExtensions.cs b/src/FluxFlow.Components.Http.Composition/HttpAuthoringExtensions.cs index 9e293dcc..32ad6dac 100644 --- a/src/FluxFlow.Components.Http.Composition/HttpAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Http.Composition/HttpAuthoringExtensions.cs @@ -1,28 +1,27 @@ using FluxFlow.Components.Http.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Http.Composition; +public static class HttpComponents +{ + public static ComponentContract> HttpRequest { get; } = + DesignedComponentContract.Create( + HttpComponentDefinition.Types.Client, + HttpServiceCollectionExtensions.ConfigureClient, + static () => new HttpRequestComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, HttpComponentDefinition.Ports.Input, HttpComponentDefinition.Ports.Output, HttpComponentDefinition.Ports.Events)); +} + public static class HttpAuthoringExtensions { public static InputOutputComponentHandle AddHttpRequest( this WorkflowDefinitionBuilder workflow, string name, Action configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent( - name, - HttpComponentDefinition.Types.Client, - definition => - { - var builder = new HttpRequestComponentBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new(component, HttpComponentDefinition.Ports.Input, HttpComponentDefinition.Ports.Output); - } + => workflow.AddComponent(name, HttpComponents.HttpRequest, configure); public static WorkflowDefinitionBuilder AddHttpRequest( this WorkflowDefinitionBuilder workflow, diff --git a/src/FluxFlow.Components.Http.Composition/HttpComponentDefinition.cs b/src/FluxFlow.Components.Http.Composition/HttpComponentDefinition.cs index 4ac17f98..b2fbcbd2 100644 --- a/src/FluxFlow.Components.Http.Composition/HttpComponentDefinition.cs +++ b/src/FluxFlow.Components.Http.Composition/HttpComponentDefinition.cs @@ -20,6 +20,7 @@ public static class Ports { public const string Input = "Input"; public const string Output = "Output"; + public const string Events = "Events"; } public static class Resources diff --git a/src/FluxFlow.Components.Http.Composition/HttpServiceCollectionExtensions.cs b/src/FluxFlow.Components.Http.Composition/HttpServiceCollectionExtensions.cs index 0dfb59a6..4e9c0ce9 100644 --- a/src/FluxFlow.Components.Http.Composition/HttpServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Http.Composition/HttpServiceCollectionExtensions.cs @@ -13,13 +13,12 @@ public static FluxFlowRegistrationBuilder AddHttp( this FluxFlowRegistrationBuilder builder) { ArgumentNullException.ThrowIfNull(builder); - return builder.AddComponent(HttpComponentDefinition.Types.Client, ConfigureClient); + return builder.AddDesignedComponent(HttpComponents.HttpRequest); } - private static void ConfigureClient(ComponentRegistrationBuilder component) + internal static void ConfigureClient(ComponentRegistrationBuilder component) { var defaults = HttpClientNodeOptions.Default; - component.UseFactory(CreateClientNode); component.UseProcessing(CompositionProcessingCapabilities.ParallelRelaxedOrder); component.WithDisplay( displayName: "HTTP Client", @@ -28,8 +27,11 @@ private static void ConfigureClient(ComponentRegistrationBuilder component) iconKey: "send", preferredNodeName: "httpClient", suggestedEditorWidth: 420); - component.AddInput(HttpComponentDefinition.Ports.Input, "Input", "Messages", 0, "HTTP request message.", true); - component.AddOutput(HttpComponentDefinition.Ports.Output, "Output", "Results", 1, "HTTP response or error result.", true); + component + .UseFactory(CreateClientNode) + .HasInput(HttpComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "HTTP request message.", true) + .HasOutput(HttpComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "HTTP response or error result.", true) + .HasEvents(HttpComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort HTTP diagnostics."); AddNumberOption(component, HttpComponentDefinition.Options.BoundedCapacity, "Bounded Capacity", "Capacity used for bounded processing and reliable normal-data output.", defaults.BoundedCapacity, 1, "Runtime", OptionDesignMetadataAttributeValues.Advanced); AddNumberOption(component, HttpComponentDefinition.Options.MaxResponseBodyBytes, "Max Response Body Bytes", "Maximum response body bytes read before truncating.", defaults.MaxResponseBodyBytes, 1, "Limits", OptionDesignMetadataAttributeValues.Primary); component.AddOption( @@ -91,7 +93,7 @@ private static void AddNumberOption( importance: importance, editor: OptionDesignMetadataAttributeValues.Number); - private static ValueTask CreateClientNode( + private static HttpClientNode CreateClientNode( ComponentActivationContext context) { var client = context.GetRequiredResource( @@ -99,22 +101,6 @@ private static ValueTask CreateClientNode( var options = context.BindConfiguration(); var clock = context.GetResource( HttpComponentDefinition.Resources.Clock); - var node = new HttpClientNode(client, options, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - HttpComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - HttpComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new HttpClientNode(client, options, clock); } } diff --git a/src/FluxFlow.Components.Http.Composition/README.md b/src/FluxFlow.Components.Http.Composition/README.md index 09bb0727..1e652fb9 100644 --- a/src/FluxFlow.Components.Http.Composition/README.md +++ b/src/FluxFlow.Components.Http.Composition/README.md @@ -104,3 +104,13 @@ services.AddFluxFlowComponents().AddHttp(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`HttpComponents.HttpRequest` is the typed contract used by both generic `AddComponent` and `AddHttpRequest`. Its handle exposes named `Input`, `Output`, and `Events` ports. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from this contract retains its executable descriptor. Normal +code-first hosting therefore calls only `AddFluxFlow(definition)` and does not +repeat the family registration above. Use that service registration for +JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contract. diff --git a/src/FluxFlow.Components.Mapping.Composition/MappingAuthoringExtensions.cs b/src/FluxFlow.Components.Mapping.Composition/MappingAuthoringExtensions.cs index 3171e105..7a808e0c 100644 --- a/src/FluxFlow.Components.Mapping.Composition/MappingAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Mapping.Composition/MappingAuthoringExtensions.cs @@ -1,30 +1,29 @@ using System.Text.Json; using FluxFlow.Components.Mapping.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; using FluxFlow.Mapping; namespace FluxFlow.Components.Mapping.Composition; +public static class MappingComponents +{ + public static ComponentContract> Mapper { get; } = + DesignedComponentContract.Create( + MappingComponentDefinition.Types.Mapper, + MappingServiceCollectionExtensions.ConfigureMapper, + static () => new MapperComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, MappingComponentDefinition.Ports.Input, MappingComponentDefinition.Ports.Output, MappingComponentDefinition.Ports.Events)); +} + public static class MappingAuthoringExtensions { public static InputOutputComponentHandle AddMapper( this WorkflowDefinitionBuilder workflow, string name, Action configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent( - name, - MappingComponentDefinition.Types.Mapper, - definition => - { - var builder = new MapperComponentBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new(component, MappingComponentDefinition.Ports.Input, MappingComponentDefinition.Ports.Output); - } + => workflow.AddComponent(name, MappingComponents.Mapper, configure); public static WorkflowDefinitionBuilder AddMapper( this WorkflowDefinitionBuilder workflow, diff --git a/src/FluxFlow.Components.Mapping.Composition/MappingComponentDefinition.cs b/src/FluxFlow.Components.Mapping.Composition/MappingComponentDefinition.cs index 3ea8ffce..ddbd0aa0 100644 --- a/src/FluxFlow.Components.Mapping.Composition/MappingComponentDefinition.cs +++ b/src/FluxFlow.Components.Mapping.Composition/MappingComponentDefinition.cs @@ -22,6 +22,7 @@ public static class Ports public const string Input = "Input"; public const string Output = "Output"; + public const string Events = "Events"; } public static class Resources diff --git a/src/FluxFlow.Components.Mapping.Composition/MappingServiceCollectionExtensions.cs b/src/FluxFlow.Components.Mapping.Composition/MappingServiceCollectionExtensions.cs index 4c9e22f4..fc39208e 100644 --- a/src/FluxFlow.Components.Mapping.Composition/MappingServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Mapping.Composition/MappingServiceCollectionExtensions.cs @@ -15,14 +15,11 @@ public static FluxFlowRegistrationBuilder AddMapping( this FluxFlowRegistrationBuilder builder) { ArgumentNullException.ThrowIfNull(builder); - return builder.AddComponent( - MappingComponentDefinition.Types.Mapper, - ConfigureMapper); + return builder.AddDesignedComponent(MappingComponents.Mapper); } - private static void ConfigureMapper(ComponentRegistrationBuilder component) + internal static void ConfigureMapper(ComponentRegistrationBuilder component) { - component.UseFactory(CreateJsonMapperNode); component.UseProcessing(CompositionProcessingCapabilities.Sequential); component.WithDisplay( displayName: "Mapper", @@ -32,20 +29,31 @@ private static void ConfigureMapper(ComponentRegistrationBuilder component) preferredNodeName: "map", suggestedEditorWidth: 420); - component.AddInput( - MappingComponentDefinition.Ports.Input, - displayName: MappingComponentDefinition.Ports.Input, - group: "Values", - order: 0, - summary: "Immutable value to map.", - isPrimary: true); - component.AddOutput( - MappingComponentDefinition.Ports.Output, - displayName: MappingComponentDefinition.Ports.Output, - group: "Results", - order: 1, - summary: "Mapped JSON value; mapping failures use the message error case.", - isPrimary: true); + component + .UseFactory(CreateJsonMapperNode) + .HasInput( + MappingComponentDefinition.Ports.Input, + static node => node.Input, + displayName: MappingComponentDefinition.Ports.Input, + group: "Values", + order: 0, + summary: "Immutable value to map.", + isPrimary: true) + .HasOutput( + MappingComponentDefinition.Ports.Output, + static node => node.Output, + displayName: MappingComponentDefinition.Ports.Output, + group: "Results", + order: 1, + summary: "Mapped JSON value; mapping failures use the message error case.", + isPrimary: true) + .HasEvents( + MappingComponentDefinition.Ports.Events, + static node => node.Events, + displayName: "Events", + group: "Diagnostics", + order: 2, + summary: "Best-effort mapping diagnostics."); component.AddOption( MappingComponentDefinition.Options.Expression, @@ -133,7 +141,7 @@ private static void ConfigureMapper(ComponentRegistrationBuilder component) keyPattern: "Resources.{name}"); } - private static ValueTask CreateJsonMapperNode( + private static JsonMapperNode CreateJsonMapperNode( ComponentActivationContext context) { var options = context.BindConfiguration(); @@ -143,27 +151,11 @@ private static ValueTask CreateJsonMapperNode( MappingComponentDefinition.Resources.ContextFactory); var clock = context.GetResource( MappingComponentDefinition.Resources.Clock); - var node = new JsonMapperNode( + return new JsonMapperNode( options, expressionEngine, contextFactory, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - MappingComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - MappingComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); } } diff --git a/src/FluxFlow.Components.Mapping.Composition/README.md b/src/FluxFlow.Components.Mapping.Composition/README.md index 3834f831..01928416 100644 --- a/src/FluxFlow.Components.Mapping.Composition/README.md +++ b/src/FluxFlow.Components.Mapping.Composition/README.md @@ -23,3 +23,13 @@ services.AddFluxFlowComponents().AddMapping(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`MappingComponents.Mapper` is the typed contract used by both generic `AddComponent` and `AddMapper`. Its handle exposes named `Input`, `Output`, and `Events` ports. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from this contract retains its executable descriptor. Normal +code-first hosting therefore calls only `AddFluxFlow(definition)` and does not +repeat the family registration above. Use that service registration for +JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contract. diff --git a/src/FluxFlow.Components.Metrics.Composition/MetricsAuthoringExtensions.cs b/src/FluxFlow.Components.Metrics.Composition/MetricsAuthoringExtensions.cs index 2e43bfc3..0fa34ae1 100644 --- a/src/FluxFlow.Components.Metrics.Composition/MetricsAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Metrics.Composition/MetricsAuthoringExtensions.cs @@ -1,24 +1,30 @@ using FluxFlow.Components.Metrics.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Metrics.Composition; +public static class MetricsComponents +{ + public static ComponentContract> MetricAggregation { get; } = + DesignedComponentContract.Create( + MetricsComponentDefinition.Types.Aggregate, + MetricsServiceCollectionExtensions.ConfigureAggregate, + static () => new MetricAggregationComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, MetricsComponentDefinition.Ports.Input, MetricsComponentDefinition.Ports.Output, MetricsComponentDefinition.Ports.Events)); +} + public static class MetricsAuthoringExtensions { public static InputOutputComponentHandle AddMetricAggregation( this WorkflowDefinitionBuilder workflow, string name, Action? configure = null) - { - ArgumentNullException.ThrowIfNull(workflow); - var component = workflow.AddComponent(name, MetricsComponentDefinition.Types.Aggregate, definition => - { - var builder = new MetricAggregationComponentBuilder(); - configure?.Invoke(builder); - builder.Apply(definition); - }); - return new(component, MetricsComponentDefinition.Ports.Input, MetricsComponentDefinition.Ports.Output); - } + => workflow.AddComponent( + name, + MetricsComponents.MetricAggregation, + configure ?? (static _ => { })); public static WorkflowDefinitionBuilder AddMetricAggregation( this WorkflowDefinitionBuilder workflow, diff --git a/src/FluxFlow.Components.Metrics.Composition/MetricsComponentDefinition.cs b/src/FluxFlow.Components.Metrics.Composition/MetricsComponentDefinition.cs index 0aac9f97..6a9facaf 100644 --- a/src/FluxFlow.Components.Metrics.Composition/MetricsComponentDefinition.cs +++ b/src/FluxFlow.Components.Metrics.Composition/MetricsComponentDefinition.cs @@ -16,6 +16,6 @@ public static class Options } public static class Types { public const string Aggregate = "metric.aggregate"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Clock = "clock"; } } diff --git a/src/FluxFlow.Components.Metrics.Composition/MetricsServiceCollectionExtensions.cs b/src/FluxFlow.Components.Metrics.Composition/MetricsServiceCollectionExtensions.cs index 37935da2..137ee96b 100644 --- a/src/FluxFlow.Components.Metrics.Composition/MetricsServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Metrics.Composition/MetricsServiceCollectionExtensions.cs @@ -13,16 +13,18 @@ public static class MetricsServiceCollectionExtensions public static FluxFlowRegistrationBuilder AddMetrics(this FluxFlowRegistrationBuilder builder) { ArgumentNullException.ThrowIfNull(builder); - return builder.AddComponent(MetricsComponentDefinition.Types.Aggregate, ConfigureAggregate); + return builder.AddDesignedComponent(MetricsComponents.MetricAggregation); } - private static void ConfigureAggregate(ComponentRegistrationBuilder component) + internal static void ConfigureAggregate(ComponentRegistrationBuilder component) { var defaults = new MetricsAggregateOptions(); - component.UseFactory(CreateMetricsAggregateNode); component.WithDisplay("Metrics Aggregate", "Metrics", "Folds metric samples into rolling count, value, rate, size, and group snapshots.", "chart-no-axes-combined", "aggregateMetrics", 460); - component.AddInput(MetricsComponentDefinition.Ports.Input, "Input", "Messages", 0, "Metric sample to aggregate.", true); - component.AddOutput(MetricsComponentDefinition.Ports.Output, "Output", "Results", 1, "Metric aggregate snapshot or expected aggregation failure.", true); + component + .UseFactory(CreateMetricsAggregateNode) + .HasInput(MetricsComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Metric sample to aggregate.", true) + .HasOutput(MetricsComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Metric aggregate snapshot or expected aggregation failure.", true) + .HasEvents(MetricsComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort metrics diagnostics."); component.AddOption(MetricsComponentDefinition.Options.RateWindowSeconds, OptionValueKind.Number, "Rate Window Seconds", "Rolling window in seconds for current-rate calculations.", defaultValue: defaults.RateWindowSeconds, min: 0.000001, section: "Rate", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Number); AddNumber(component, MetricsComponentDefinition.Options.BoundedCapacity, "Bounded Capacity", "Capacity used for bounded processing and reliable normal-data output.", defaults.BoundedCapacity, 1, "Runtime"); AddNumber(component, MetricsComponentDefinition.Options.MaxGroups, "Max Groups", "Maximum number of per-group snapshots to track.", defaults.MaxGroups, 0, "Grouping"); @@ -41,28 +43,12 @@ private static void AddNumber(ComponentRegistrationBuilder component, string nam private static void AddBoolean(ComponentRegistrationBuilder component, string name, string displayName, string helperText, bool defaultValue, string section) => component.AddOption(name, OptionValueKind.Boolean, displayName, helperText, defaultValue: defaultValue, section: section, importance: OptionDesignMetadataAttributeValues.Advanced); - private static ValueTask CreateMetricsAggregateNode( + private static MetricsAggregateNode CreateMetricsAggregateNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource( MetricsComponentDefinition.Resources.Clock); - var node = new MetricsAggregateNode(options, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - MetricsComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - MetricsComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new MetricsAggregateNode(options, clock); } } diff --git a/src/FluxFlow.Components.Metrics.Composition/README.md b/src/FluxFlow.Components.Metrics.Composition/README.md index 0934ee6b..1b19ca0b 100644 --- a/src/FluxFlow.Components.Metrics.Composition/README.md +++ b/src/FluxFlow.Components.Metrics.Composition/README.md @@ -19,3 +19,13 @@ services.AddFluxFlowComponents().AddMetrics(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`MetricsComponents.MetricAggregation` is the typed contract used by both generic `AddComponent` and `AddMetricAggregation`. Its handle exposes named `Input`, `Output`, and `Events` ports. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from this contract retains its executable descriptor. Normal +code-first hosting therefore calls only `AddFluxFlow(definition)` and does not +repeat the family registration above. Use that service registration for +JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contract. diff --git a/src/FluxFlow.Components.Observability.Composition/ObservabilityAuthoringExtensions.cs b/src/FluxFlow.Components.Observability.Composition/ObservabilityAuthoringExtensions.cs index 5100a9aa..cd437ecd 100644 --- a/src/FluxFlow.Components.Observability.Composition/ObservabilityAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Observability.Composition/ObservabilityAuthoringExtensions.cs @@ -1,18 +1,45 @@ using System.Text.Json; using FluxFlow.Components.Observability.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; using FluxFlow.Mapping; namespace FluxFlow.Components.Observability.Composition; +public static class ObservabilityComponents +{ + public static ComponentContract> Counter { get; } = + DesignedComponentContract.Create( + ObservabilityComponentDefinition.Types.Counter, + ObservabilityServiceCollectionExtensions.ConfigureCounter, + static () => new CounterComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, ObservabilityComponentDefinition.Ports.Input, ObservabilityComponentDefinition.Ports.Output, ObservabilityComponentDefinition.Ports.Events)); + + public static ComponentContract>> Logger { get; } = + DesignedComponentContract.Create( + ObservabilityComponentDefinition.Types.Logger, + ObservabilityServiceCollectionExtensions.ConfigureLogger, + static () => new LoggerComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle>(component, ObservabilityComponentDefinition.Ports.Input, ObservabilityComponentDefinition.Ports.Output, ObservabilityComponentDefinition.Ports.Events)); + + public static ComponentContract> Metrics { get; } = + DesignedComponentContract.Create( + ObservabilityComponentDefinition.Types.Metrics, + ObservabilityServiceCollectionExtensions.ConfigureMetrics, + static () => new MetricsComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, ObservabilityComponentDefinition.Ports.Input, ObservabilityComponentDefinition.Ports.Output, ObservabilityComponentDefinition.Ports.Events)); +} + public static class ObservabilityAuthoringExtensions { public static InputOutputComponentHandle AddCounter( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => Add( - workflow, name, ObservabilityComponentDefinition.Types.Counter, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, ObservabilityComponents.Counter, configure); public static WorkflowDefinitionBuilder AddCounter( this WorkflowDefinitionBuilder workflow, @@ -28,8 +55,7 @@ public static InputOutputComponentHandle> this WorkflowDefinitionBuilder workflow, string name, Action configure) - => Add, LoggerComponentBuilder>( - workflow, name, ObservabilityComponentDefinition.Types.Logger, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, ObservabilityComponents.Logger, configure); public static WorkflowDefinitionBuilder AddLogger( this WorkflowDefinitionBuilder workflow, @@ -45,8 +71,7 @@ public static InputOutputComponentHandle AddMet this WorkflowDefinitionBuilder workflow, string name, Action configure) - => Add( - workflow, name, ObservabilityComponentDefinition.Types.Metrics, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, ObservabilityComponents.Metrics, configure); public static WorkflowDefinitionBuilder AddMetrics( this WorkflowDefinitionBuilder workflow, @@ -58,24 +83,6 @@ public static WorkflowDefinitionBuilder AddMetrics( return workflow; } - private static InputOutputComponentHandle Add( - WorkflowDefinitionBuilder workflow, - string name, - string type, - Action configure, - Action apply) - where TBuilder : ObservabilityComponentBuilder, new() - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, type, definition => - { - var builder = new TBuilder(); - configure(builder); - apply(builder, definition); - }); - return new(component, ObservabilityComponentDefinition.Ports.Input, ObservabilityComponentDefinition.Ports.Output); - } } public abstract class ObservabilityComponentBuilder diff --git a/src/FluxFlow.Components.Observability.Composition/ObservabilityComponentDefinition.cs b/src/FluxFlow.Components.Observability.Composition/ObservabilityComponentDefinition.cs index 794abf87..725e0813 100644 --- a/src/FluxFlow.Components.Observability.Composition/ObservabilityComponentDefinition.cs +++ b/src/FluxFlow.Components.Observability.Composition/ObservabilityComponentDefinition.cs @@ -16,7 +16,7 @@ public static class Options } public static class Types { public const string Counter = "metric.count"; public const string Logger = "log.write"; public const string Metrics = "metric.measure"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Clock = "clock"; diff --git a/src/FluxFlow.Components.Observability.Composition/ObservabilityServiceCollectionExtensions.cs b/src/FluxFlow.Components.Observability.Composition/ObservabilityServiceCollectionExtensions.cs index 31adadcb..21b67a27 100644 --- a/src/FluxFlow.Components.Observability.Composition/ObservabilityServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Observability.Composition/ObservabilityServiceCollectionExtensions.cs @@ -15,15 +15,20 @@ public static FluxFlowRegistrationBuilder AddObservability(this FluxFlowRegistra { ArgumentNullException.ThrowIfNull(builder); return builder - .AddComponent(ObservabilityComponentDefinition.Types.Counter, ConfigureCounter) - .AddComponent(ObservabilityComponentDefinition.Types.Logger, ConfigureLogger) - .AddComponent(ObservabilityComponentDefinition.Types.Metrics, ConfigureMetrics); + .AddDesignedComponent(ObservabilityComponents.Counter) + .AddDesignedComponent(ObservabilityComponents.Logger) + .AddDesignedComponent(ObservabilityComponents.Metrics); } - private static void ConfigureCounter(ComponentRegistrationBuilder component) + internal static void ConfigureCounter(ComponentRegistrationBuilder component) { var defaults = new FlowCounterOptions(); - ConfigureCommon(component, CreateCounterNode, "Counter", "Counts accepted input messages and emits counter snapshots.", "hash", "count", "JSON value to count.", "Current counter snapshot or workflow error."); + ConfigureCommon(component, "Counter", "Counts accepted input messages and emits counter snapshots.", "hash", "count"); + component + .UseFactory(CreateCounterNode) + .HasInput(ObservabilityComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "JSON value to count.", true) + .HasOutput(ObservabilityComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Current counter snapshot or workflow error.", true) + .HasEvents(ObservabilityComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort counter diagnostics."); component.AddOption(ObservabilityComponentDefinition.Options.Name, OptionValueKind.Text, "Name", "Optional counter name included in snapshots and diagnostics.", section: "Counter", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); component.AddOption(ObservabilityComponentDefinition.Options.Predicate, OptionValueKind.Expression, "Predicate", "Optional boolean expression used to accept or reject inputs.", section: "Filtering", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Expression, syntax: OptionDesignMetadataAttributeValues.Expression, relatedResource: ObservabilityComponentDefinition.Resources.Engine); component.AddOption(ObservabilityComponentDefinition.Options.ExpressionId, OptionValueKind.Text, "Expression ID", "Optional diagnostic identifier emitted with counter diagnostics.", section: "Diagnostics", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); @@ -34,10 +39,15 @@ private static void ConfigureCounter(ComponentRegistrationBuilder component) component.AddResource(ObservabilityComponentDefinition.Resources.Clock, "Clock", 2, "Optional keyed clock for deterministic observability timestamps and diagnostics.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "clock:{name}"); } - private static void ConfigureLogger(ComponentRegistrationBuilder component) + internal static void ConfigureLogger(ComponentRegistrationBuilder component) { var defaults = new FlowLoggerOptions(); - ConfigureCommon>(component, CreateLoggerNode, "Logger", "Renders structured log entries from input messages.", "list", "log", "JSON value to log.", "Structured log entry or workflow error."); + ConfigureCommon(component, "Logger", "Renders structured log entries from input messages.", "list", "log"); + component + .UseFactory(CreateLoggerNode) + .HasInput(ObservabilityComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "JSON value to log.", true) + .HasOutput(ObservabilityComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Structured log entry or workflow error.", true) + .HasEvents(ObservabilityComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort logger diagnostics."); component.AddOption(ObservabilityComponentDefinition.Options.Level, OptionValueKind.Enum, "Level", "Log level applied to emitted entries.", defaultValue: defaults.Level, section: "Logging", importance: OptionDesignMetadataAttributeValues.Advanced); foreach (var level in Enum.GetValues()) component.AddOptionChoice(ObservabilityComponentDefinition.Options.Level, level.ToString(), level.ToString()); @@ -49,28 +59,30 @@ private static void ConfigureLogger(ComponentRegistrationBuilder component) component.AddResource>(ObservabilityComponentDefinition.Resources.AttributeSelectorPrefix + "{name}", "Attribute Selector", 1, "Required keyed selector pattern for each configured attributeSelectors entry.", designValueType: "IObservabilityValueSelector", ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Selector, keyPattern: ObservabilityComponentDefinition.Resources.AttributeSelectorPrefix + "{name}", option: ObservabilityComponentDefinition.Options.AttributeSelectors); } - private static void ConfigureMetrics(ComponentRegistrationBuilder component) + internal static void ConfigureMetrics(ComponentRegistrationBuilder component) { var defaults = new FlowMetricsOptions(); - ConfigureCommon(component, CreateMetricsNode, "Metrics", "Tracks count, rate, timestamp, and optional size snapshots for inputs.", "activity", "observeMetrics", "JSON value to observe.", "Metric snapshot or workflow error."); + ConfigureCommon(component, "Metrics", "Tracks count, rate, timestamp, and optional size snapshots for inputs.", "activity", "observeMetrics"); + component + .UseFactory(CreateMetricsNode) + .HasInput(ObservabilityComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "JSON value to observe.", true) + .HasOutput(ObservabilityComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Metric snapshot or workflow error.", true) + .HasEvents(ObservabilityComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort metrics diagnostics."); component.AddOption(ObservabilityComponentDefinition.Options.Name, OptionValueKind.Text, "Name", "Optional metric name included in snapshots and diagnostics.", section: "Metrics", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); AddCapacity(component, defaults.BoundedCapacity); component.AddResource>(ObservabilityComponentDefinition.Resources.SizeSelector, "Size Selector", 0, "Optional keyed selector used to calculate message size metrics.", designValueType: "IObservabilityValueSelector", ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Selector, keyPattern: "selector:{name}"); component.AddResource(ObservabilityComponentDefinition.Resources.Clock, "Clock", 1, "Optional keyed clock for deterministic observability timestamps and diagnostics.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "clock:{name}"); } - private static void ConfigureCommon(ComponentRegistrationBuilder component, ComponentFactory factory, string displayName, string summary, string iconKey, string preferredNodeName, string inputSummary, string outputSummary) + private static void ConfigureCommon(ComponentRegistrationBuilder component, string displayName, string summary, string iconKey, string preferredNodeName) { - component.UseFactory(factory); component.WithDisplay(displayName, "Observability", summary, iconKey, preferredNodeName, 460); - component.AddInput(ObservabilityComponentDefinition.Ports.Input, "Input", "Messages", 0, inputSummary, true); - component.AddOutput(ObservabilityComponentDefinition.Ports.Output, "Output", "Results", 1, outputSummary, true); } private static void AddCapacity(ComponentRegistrationBuilder component, int defaultValue) => component.AddOption(ObservabilityComponentDefinition.Options.BoundedCapacity, OptionValueKind.Number, "Bounded Capacity", "Capacity used for bounded processing and reliable normal-data output.", defaultValue: defaultValue, min: 1, section: "Runtime", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); - private static ValueTask CreateCounterNode( + private static FlowCounterNode CreateCounterNode( ComponentActivationContext context) { if (context.Component.Properties.Keys.Any(static name => @@ -89,56 +101,24 @@ private static ValueTask CreateCounterNode( ObservabilityComponentDefinition.Resources.ContextFactory); var clock = context.GetResource( ObservabilityComponentDefinition.Resources.Clock); - var node = new FlowCounterNode( + return new FlowCounterNode( options, expressionEngine, contextFactory, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - ObservabilityComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - ObservabilityComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); } - private static ValueTask CreateLoggerNode( + private static FlowLoggerNode CreateLoggerNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var attributeSelectors = ResolveAttributeSelectors(context, options); var clock = context.GetResource( ObservabilityComponentDefinition.Resources.Clock); - var node = new FlowLoggerNode(options, attributeSelectors, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - ObservabilityComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output>( - ObservabilityComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new FlowLoggerNode(options, attributeSelectors, clock); } - private static ValueTask CreateMetricsNode( + private static FlowMetricsNode CreateMetricsNode( ComponentActivationContext context) { var options = context.BindConfiguration(); @@ -146,23 +126,7 @@ private static ValueTask CreateMetricsNode( ObservabilityComponentDefinition.Resources.SizeSelector); var clock = context.GetResource( ObservabilityComponentDefinition.Resources.Clock); - var node = new FlowMetricsNode(options, sizeSelector, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - ObservabilityComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - ObservabilityComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new FlowMetricsNode(options, sizeSelector, clock); } private static IReadOnlyDictionary> diff --git a/src/FluxFlow.Components.Observability.Composition/README.md b/src/FluxFlow.Components.Observability.Composition/README.md index f439b8f0..41a3f380 100644 --- a/src/FluxFlow.Components.Observability.Composition/README.md +++ b/src/FluxFlow.Components.Observability.Composition/README.md @@ -24,3 +24,13 @@ services.AddFluxFlowComponents().AddObservability(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`ObservabilityComponents` exposes `Counter`, `Logger`, and `Metrics` typed contracts. The retained `AddX` methods use those same contracts, and every handle exposes `Events`. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from these contracts retains its executable descriptors. +Normal code-first hosting therefore calls only `AddFluxFlow(definition)` and +does not repeat the family registration above. Use that service registration +for JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contracts. diff --git a/src/FluxFlow.Components.Payloads.Composition/PayloadsAuthoringExtensions.cs b/src/FluxFlow.Components.Payloads.Composition/PayloadsAuthoringExtensions.cs index 95d2c9e4..d2947407 100644 --- a/src/FluxFlow.Components.Payloads.Composition/PayloadsAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Payloads.Composition/PayloadsAuthoringExtensions.cs @@ -1,28 +1,31 @@ using FluxFlow.Components.Payloads.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; using FluxFlow.Data; namespace FluxFlow.Components.Payloads.Composition; +public static class PayloadsComponents +{ + public static ComponentContract> PayloadInspection { get; } = + DesignedComponentContract.Create( + PayloadsComponentDefinition.Types.Inspect, + PayloadsServiceCollectionExtensions.ConfigureInspect, + static () => new PayloadInspectionComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, PayloadsComponentDefinition.Ports.Input, PayloadsComponentDefinition.Ports.Output, PayloadsComponentDefinition.Ports.Events)); +} + public static class PayloadsAuthoringExtensions { public static InputOutputComponentHandle AddPayloadInspection( this WorkflowDefinitionBuilder workflow, string name, Action? configure = null) - { - ArgumentNullException.ThrowIfNull(workflow); - var component = workflow.AddComponent( + => workflow.AddComponent( name, - PayloadsComponentDefinition.Types.Inspect, - definition => - { - var builder = new PayloadInspectionComponentBuilder(); - configure?.Invoke(builder); - builder.Apply(definition); - }); - return new(component, PayloadsComponentDefinition.Ports.Input, PayloadsComponentDefinition.Ports.Output); - } + PayloadsComponents.PayloadInspection, + configure ?? (static _ => { })); public static WorkflowDefinitionBuilder AddPayloadInspection( this WorkflowDefinitionBuilder workflow, diff --git a/src/FluxFlow.Components.Payloads.Composition/PayloadsComponentDefinition.cs b/src/FluxFlow.Components.Payloads.Composition/PayloadsComponentDefinition.cs index 4bd05936..d71947e8 100644 --- a/src/FluxFlow.Components.Payloads.Composition/PayloadsComponentDefinition.cs +++ b/src/FluxFlow.Components.Payloads.Composition/PayloadsComponentDefinition.cs @@ -19,6 +19,7 @@ public static class Ports { public const string Input = "Input"; public const string Output = "Output"; + public const string Events = "Events"; } public static class Resources { public const string Clock = "clock"; } diff --git a/src/FluxFlow.Components.Payloads.Composition/PayloadsServiceCollectionExtensions.cs b/src/FluxFlow.Components.Payloads.Composition/PayloadsServiceCollectionExtensions.cs index fda41cbf..9a3a7fe9 100644 --- a/src/FluxFlow.Components.Payloads.Composition/PayloadsServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Payloads.Composition/PayloadsServiceCollectionExtensions.cs @@ -14,13 +14,12 @@ public static FluxFlowRegistrationBuilder AddPayloads( this FluxFlowRegistrationBuilder builder) { ArgumentNullException.ThrowIfNull(builder); - return builder.AddComponent(PayloadsComponentDefinition.Types.Inspect, ConfigureInspect); + return builder.AddDesignedComponent(PayloadsComponents.PayloadInspection); } - private static void ConfigureInspect(ComponentRegistrationBuilder component) + internal static void ConfigureInspect(ComponentRegistrationBuilder component) { var defaults = PayloadInspectOptions.Default; - component.UseFactory(CreatePayloadInspectNode); component.WithDisplay( "Payload Inspect", "Payloads", @@ -28,8 +27,11 @@ private static void ConfigureInspect(ComponentRegistrationBuilder component) "scan-search", "inspect", 420); - component.AddInput(PayloadsComponentDefinition.Ports.Input, "Input", "Messages", 0, "Canonical content to inspect.", true); - component.AddOutput(PayloadsComponentDefinition.Ports.Output, "Output", "Results", 1, "Inspection result; content failures use the message error case.", true); + component + .UseFactory(CreatePayloadInspectNode) + .HasInput(PayloadsComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Canonical content to inspect.", true) + .HasOutput(PayloadsComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Inspection result; content failures use the message error case.", true) + .HasEvents(PayloadsComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort payload diagnostics."); AddNumber(component, PayloadsComponentDefinition.Options.MaxInputBytes, "Max Input Bytes", "Maximum input payload size to inspect.", defaults.MaxInputBytes, "Limits", OptionDesignMetadataAttributeValues.Primary); AddNumber(component, PayloadsComponentDefinition.Options.MaxPreviewBytes, "Max Preview Bytes", "Maximum text preview size in bytes.", defaults.MaxPreviewBytes, "Preview", OptionDesignMetadataAttributeValues.Primary); AddNumber(component, PayloadsComponentDefinition.Options.MaxFormattedChars, "Max Formatted Chars", "Maximum formatted preview size in characters.", defaults.MaxFormattedChars, "Preview", OptionDesignMetadataAttributeValues.Advanced); @@ -54,28 +56,12 @@ private static void AddNumber(ComponentRegistrationBuilder component, string nam private static void AddBoolean(ComponentRegistrationBuilder component, string name, string displayName, string helperText, bool defaultValue, string section) => component.AddOption(name, OptionValueKind.Boolean, displayName, helperText, defaultValue: defaultValue, section: section, importance: OptionDesignMetadataAttributeValues.Advanced); - private static ValueTask CreatePayloadInspectNode( + private static PayloadInspectNode CreatePayloadInspectNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource( PayloadsComponentDefinition.Resources.Clock); - var node = new PayloadInspectNode(options, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - PayloadsComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - PayloadsComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new PayloadInspectNode(options, clock); } } diff --git a/src/FluxFlow.Components.Payloads.Composition/README.md b/src/FluxFlow.Components.Payloads.Composition/README.md index d2ec03f9..e4ced917 100644 --- a/src/FluxFlow.Components.Payloads.Composition/README.md +++ b/src/FluxFlow.Components.Payloads.Composition/README.md @@ -22,3 +22,13 @@ services.AddFluxFlowComponents().AddPayloads(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`PayloadsComponents.PayloadInspection` is the typed contract used by both generic `AddComponent` and `AddPayloadInspection`. Its handle exposes named `Input`, `Output`, and `Events` ports. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from this contract retains its executable descriptor. Normal +code-first hosting therefore calls only `AddFluxFlow(definition)` and does not +repeat the family registration above. Use that service registration for +JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contract. diff --git a/src/FluxFlow.Components.Projections.Composition/ProjectionsAuthoringExtensions.cs b/src/FluxFlow.Components.Projections.Composition/ProjectionsAuthoringExtensions.cs index 1b25760e..d850f9f6 100644 --- a/src/FluxFlow.Components.Projections.Composition/ProjectionsAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Projections.Composition/ProjectionsAuthoringExtensions.cs @@ -1,24 +1,30 @@ using FluxFlow.Components.Projections.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Projections.Composition; +public static class ProjectionsComponents +{ + public static ComponentContract> EventProjection { get; } = + DesignedComponentContract.Create( + ProjectionsComponentDefinition.Types.EventProjection, + ProjectionsServiceCollectionExtensions.ConfigureProjection, + static () => new EventProjectionComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, ProjectionsComponentDefinition.Ports.Input, ProjectionsComponentDefinition.Ports.Output, ProjectionsComponentDefinition.Ports.Events)); +} + public static class ProjectionsAuthoringExtensions { public static InputOutputComponentHandle AddEventProjection( this WorkflowDefinitionBuilder workflow, string name, Action? configure = null) - { - ArgumentNullException.ThrowIfNull(workflow); - var component = workflow.AddComponent(name, ProjectionsComponentDefinition.Types.EventProjection, definition => - { - var builder = new EventProjectionComponentBuilder(); - configure?.Invoke(builder); - builder.Apply(definition); - }); - return new(component, ProjectionsComponentDefinition.Ports.Input, ProjectionsComponentDefinition.Ports.Output); - } + => workflow.AddComponent( + name, + ProjectionsComponents.EventProjection, + configure ?? (static _ => { })); public static WorkflowDefinitionBuilder AddEventProjection( this WorkflowDefinitionBuilder workflow, diff --git a/src/FluxFlow.Components.Projections.Composition/ProjectionsComponentDefinition.cs b/src/FluxFlow.Components.Projections.Composition/ProjectionsComponentDefinition.cs index b08fe33b..d9c2ae1c 100644 --- a/src/FluxFlow.Components.Projections.Composition/ProjectionsComponentDefinition.cs +++ b/src/FluxFlow.Components.Projections.Composition/ProjectionsComponentDefinition.cs @@ -14,6 +14,6 @@ public static class Options } public static class Types { public const string EventProjection = "event.project"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Clock = "clock"; } } diff --git a/src/FluxFlow.Components.Projections.Composition/ProjectionsServiceCollectionExtensions.cs b/src/FluxFlow.Components.Projections.Composition/ProjectionsServiceCollectionExtensions.cs index 3c53a161..efd35e7b 100644 --- a/src/FluxFlow.Components.Projections.Composition/ProjectionsServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Projections.Composition/ProjectionsServiceCollectionExtensions.cs @@ -13,16 +13,18 @@ public static class ProjectionsServiceCollectionExtensions public static FluxFlowRegistrationBuilder AddProjections(this FluxFlowRegistrationBuilder builder) { ArgumentNullException.ThrowIfNull(builder); - return builder.AddComponent(ProjectionsComponentDefinition.Types.EventProjection, ConfigureProjection); + return builder.AddDesignedComponent(ProjectionsComponents.EventProjection); } - private static void ConfigureProjection(ComponentRegistrationBuilder component) + internal static void ConfigureProjection(ComponentRegistrationBuilder component) { var defaults = new EventProjectionOptions(); - component.UseFactory(CreateEventProjectionNode); component.WithDisplay("Event Projection", "Projections", "Folds matching projection events into count, latest-event, and rolling-rate snapshots.", "activity", "projectEvents", 460); - component.AddInput(ProjectionsComponentDefinition.Ports.Input, "Input", "Messages", 0, "Projection event to fold into the running snapshot.", true); - component.AddOutput(ProjectionsComponentDefinition.Ports.Output, "Output", "Results", 1, "Event projection snapshot.", true); + component + .UseFactory(CreateEventProjectionNode) + .HasInput(ProjectionsComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Projection event to fold into the running snapshot.", true) + .HasOutput(ProjectionsComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Event projection snapshot.", true) + .HasEvents(ProjectionsComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort projection diagnostics."); component.AddOption(ProjectionsComponentDefinition.Options.Name, OptionValueKind.Text, "Name", "Optional snapshot name included in emitted projection snapshots.", section: "Diagnostics", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); component.AddOption(ProjectionsComponentDefinition.Options.Filter, OptionValueKind.Json, "Filter", "Event filter object for matching projection events.", defaultValue: defaults.Filter, section: "Filtering", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Json); component.AddOption(ProjectionsComponentDefinition.Options.RateWindowSeconds, OptionValueKind.Number, "Rate Window Seconds", "Rolling rate window in seconds; must be greater than zero.", defaultValue: defaults.RateWindowSeconds, min: 0.000001, section: "Rate", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Number); @@ -36,28 +38,12 @@ private static void ConfigureProjection(ComponentRegistrationBuilder component) private static void AddBoolean(ComponentRegistrationBuilder component, string name, string displayName, string helperText, bool defaultValue) => component.AddOption(name, OptionValueKind.Boolean, displayName, helperText, defaultValue: defaultValue, section: "Emission", importance: OptionDesignMetadataAttributeValues.Advanced); - private static ValueTask CreateEventProjectionNode( + private static EventProjectionNode CreateEventProjectionNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource( ProjectionsComponentDefinition.Resources.Clock); - var node = new EventProjectionNode(options, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - ProjectionsComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - ProjectionsComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new EventProjectionNode(options, clock); } } diff --git a/src/FluxFlow.Components.Projections.Composition/README.md b/src/FluxFlow.Components.Projections.Composition/README.md index fe39a061..f2697be4 100644 --- a/src/FluxFlow.Components.Projections.Composition/README.md +++ b/src/FluxFlow.Components.Projections.Composition/README.md @@ -19,3 +19,13 @@ services.AddFluxFlowComponents().AddProjections(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`ProjectionsComponents.EventProjection` is the typed contract used by both generic `AddComponent` and `AddEventProjection`. Its handle exposes named `Input`, `Output`, and `Events` ports. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from this contract retains its executable descriptor. Normal +code-first hosting therefore calls only `AddFluxFlow(definition)` and does not +repeat the family registration above. Use that service registration for +JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contract. diff --git a/src/FluxFlow.Components.Resilience.Composition/README.md b/src/FluxFlow.Components.Resilience.Composition/README.md index 04be1f62..61089a4f 100644 --- a/src/FluxFlow.Components.Resilience.Composition/README.md +++ b/src/FluxFlow.Components.Resilience.Composition/README.md @@ -24,3 +24,13 @@ services.AddFluxFlowComponents().AddResilience(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`ResilienceComponents.FlowRetry` is the typed contract used by both generic `AddComponent` and `AddFlowRetry`. Its handle exposes `Input`, `Ack`, `Nak`, `Cancel`, `Output`, and `Events`. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from this contract retains its executable descriptor. Normal +code-first hosting therefore calls only `AddFluxFlow(definition)` and does not +repeat the family registration above. Use that service registration for +JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contract. diff --git a/src/FluxFlow.Components.Resilience.Composition/ResilienceAuthoringExtensions.cs b/src/FluxFlow.Components.Resilience.Composition/ResilienceAuthoringExtensions.cs index e7459271..888e6004 100644 --- a/src/FluxFlow.Components.Resilience.Composition/ResilienceAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Resilience.Composition/ResilienceAuthoringExtensions.cs @@ -1,28 +1,30 @@ using System.Text.Json; using FluxFlow.Components.Resilience.Contracts; -using FluxFlow.Composition.Addressing; +using FluxFlow.Components.Designer; +using FluxFlow.Composition; using FluxFlow.Composition.Authoring; using FluxFlow.Resilience; namespace FluxFlow.Components.Resilience.Composition; +public static class ResilienceComponents +{ + public static ComponentContract FlowRetry { get; } = + DesignedComponentContract.Create( + ResilienceComponentDefinition.Types.Retry, + ResilienceServiceCollectionExtensions.ConfigureRetry, + static () => new FlowRetryComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new FlowRetryComponentHandle(component)); +} + public static class ResilienceAuthoringExtensions { public static FlowRetryComponentHandle AddFlowRetry( this WorkflowDefinitionBuilder workflow, string name, Action configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, ResilienceComponentDefinition.Types.Retry, definition => - { - var builder = new FlowRetryComponentBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new(component); - } + => workflow.AddComponent(name, ResilienceComponents.FlowRetry, configure); public static WorkflowDefinitionBuilder AddFlowRetry( this WorkflowDefinitionBuilder workflow, @@ -76,23 +78,22 @@ private static void Set(ComponentDefinitionBuilder definition, string name, T } } -public sealed class FlowRetryComponentHandle +public sealed class FlowRetryComponentHandle : AuthoredComponentHandle { - internal FlowRetryComponentHandle(ComponentHandle definition) + internal FlowRetryComponentHandle(ComponentHandle definition) : base(definition) { - Definition = definition; Input = definition.Input(ResilienceComponentDefinition.Ports.Input); Ack = definition.SignalInput(ResilienceComponentDefinition.Ports.Ack); Nak = definition.SignalInput(ResilienceComponentDefinition.Ports.Nak); Cancel = definition.SignalInput(ResilienceComponentDefinition.Ports.Cancel); Output = definition.Output>(ResilienceComponentDefinition.Ports.Output); + Events = definition.Output(ResilienceComponentDefinition.Ports.Events); } - public ComponentHandle Definition { get; } - public ApplicationAddress Address => Definition.Address; public InputPortHandle Input { get; } public SignalInputPortHandle Ack { get; } public SignalInputPortHandle Nak { get; } public SignalInputPortHandle Cancel { get; } public OutputPortHandle> Output { get; } + public OutputPortHandle Events { get; } } diff --git a/src/FluxFlow.Components.Resilience.Composition/ResilienceComponentDefinition.cs b/src/FluxFlow.Components.Resilience.Composition/ResilienceComponentDefinition.cs index 9cc9fe45..eddb4f5a 100644 --- a/src/FluxFlow.Components.Resilience.Composition/ResilienceComponentDefinition.cs +++ b/src/FluxFlow.Components.Resilience.Composition/ResilienceComponentDefinition.cs @@ -24,6 +24,7 @@ public static class Ports public const string Nak = "Nak"; public const string Cancel = "Cancel"; public const string Output = "Output"; + public const string Events = "Events"; } public static class Resources { public const string Clock = "Clock"; public const string Jitter = "Jitter"; } } diff --git a/src/FluxFlow.Components.Resilience.Composition/ResilienceServiceCollectionExtensions.cs b/src/FluxFlow.Components.Resilience.Composition/ResilienceServiceCollectionExtensions.cs index d46bed37..4ef5b717 100644 --- a/src/FluxFlow.Components.Resilience.Composition/ResilienceServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Resilience.Composition/ResilienceServiceCollectionExtensions.cs @@ -14,19 +14,21 @@ public static class ResilienceServiceCollectionExtensions public static FluxFlowRegistrationBuilder AddResilience(this FluxFlowRegistrationBuilder builder) { ArgumentNullException.ThrowIfNull(builder); - return builder.AddComponent(ResilienceComponentDefinition.Types.Retry, ConfigureRetry); + return builder.AddDesignedComponent(ResilienceComponents.FlowRetry); } - private static void ConfigureRetry(ComponentRegistrationBuilder component) + internal static void ConfigureRetry(ComponentRegistrationBuilder component) { var defaults = new FlowRetryOptions(); - component.UseFactory(CreateFlowRetryNode); component.WithDisplay("Flow Retry", "Resilience", "Coordinates acknowledged workflow attempts with retry, timeout, cancellation, and exhaustion results.", "refresh-cw", "retry", 460); - component.AddInput(ResilienceComponentDefinition.Ports.Input, "Input", "Messages", 0, "Value that begins a retry-controlled logical operation.", true); - component.AddSignalInput(ResilienceComponentDefinition.Ports.Ack, "Ack", "Signals", 1, "Completes the matching attempt successfully."); - component.AddSignalInput(ResilienceComponentDefinition.Ports.Nak, "Nak", "Signals", 2, "Fails the matching attempt and applies retry policy."); - component.AddSignalInput(ResilienceComponentDefinition.Ports.Cancel, "Cancel", "Signals", 3, "Cancels the matching logical operation."); - component.AddOutput>(ResilienceComponentDefinition.Ports.Output, "Output", "Results", 4, "Attempt, scheduled retry, completion, exhaustion, cancellation, or rejection result.", true); + component + .UseFactory(CreateFlowRetryNode) + .HasInput(ResilienceComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Value that begins a retry-controlled logical operation.", true) + .HasSignalInput(ResilienceComponentDefinition.Ports.Ack, static node => node.Ack, "Ack", "Signals", 1, "Completes the matching attempt successfully.") + .HasSignalInput(ResilienceComponentDefinition.Ports.Nak, static node => node.Nak, "Nak", "Signals", 2, "Fails the matching attempt and applies retry policy.") + .HasSignalInput(ResilienceComponentDefinition.Ports.Cancel, static node => node.Cancel, "Cancel", "Signals", 3, "Cancels the matching logical operation.") + .HasOutput(ResilienceComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 4, "Attempt, scheduled retry, completion, exhaustion, cancellation, or rejection result.", true) + .HasEvents(ResilienceComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 5, "Best-effort retry diagnostics."); component.AddOption(ResilienceComponentDefinition.Options.Name, OptionValueKind.Text, "Name", "Optional diagnostic name; composition defaults to the component address.", section: "Diagnostics", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); component.AddOption(ResilienceComponentDefinition.Options.Strategy, OptionValueKind.Enum, "Strategy", "Delay strategy applied after NAK or timeout.", defaultValue: defaults.Strategy.ToString(), section: "Retry", importance: OptionDesignMetadataAttributeValues.Primary); foreach (var strategy in Enum.GetValues()) @@ -46,7 +48,7 @@ private static void ConfigureRetry(ComponentRegistrationBuilder component) private static void AddNumber(ComponentRegistrationBuilder component, string name, string displayName, string helperText, object? defaultValue, string section, string importance, double min) => component.AddOption(name, OptionValueKind.Number, displayName, helperText, defaultValue: defaultValue, min: min, section: section, importance: importance, editor: OptionDesignMetadataAttributeValues.Number); - private static ValueTask CreateFlowRetryNode( + private static FlowRetryNode CreateFlowRetryNode( ComponentActivationContext context) { var options = context.BindConfiguration(); @@ -58,33 +60,9 @@ private static ValueTask CreateFlowRetryNode( }; } - var node = new FlowRetryNode( + return new FlowRetryNode( options, context.GetResource(ResilienceComponentDefinition.Resources.Clock), context.GetResource(ResilienceComponentDefinition.Resources.Jitter)); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - ResilienceComponentDefinition.Ports.Input, - node.Input), - ComponentPorts.SignalInput( - ResilienceComponentDefinition.Ports.Ack, - node.Ack), - ComponentPorts.SignalInput( - ResilienceComponentDefinition.Ports.Nak, - node.Nak), - ComponentPorts.SignalInput( - ResilienceComponentDefinition.Ports.Cancel, - node.Cancel) - ], - outputs: - [ - ComponentPorts.Output>( - ResilienceComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); } } diff --git a/src/FluxFlow.Components.Routing.Composition/README.md b/src/FluxFlow.Components.Routing.Composition/README.md index 5a6806a8..82ce2c07 100644 --- a/src/FluxFlow.Components.Routing.Composition/README.md +++ b/src/FluxFlow.Components.Routing.Composition/README.md @@ -24,3 +24,13 @@ services.AddFluxFlowComponents().AddRouting(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`RoutingComponents` exposes `Window`, `Correlation`, and `Join` typed contracts. The retained `AddX` methods use those same contracts; named handles include branch inputs, output, and `Events`. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from these contracts retains its executable descriptors. +Normal code-first hosting therefore calls only `AddFluxFlow(definition)` and +does not repeat the family registration above. Use that service registration +for JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contracts. diff --git a/src/FluxFlow.Components.Routing.Composition/RoutingAuthoringExtensions.cs b/src/FluxFlow.Components.Routing.Composition/RoutingAuthoringExtensions.cs index c08f6959..b99f8de1 100644 --- a/src/FluxFlow.Components.Routing.Composition/RoutingAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Routing.Composition/RoutingAuthoringExtensions.cs @@ -1,26 +1,44 @@ using System.Text.Json; using FluxFlow.Components.Routing.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Routing.Composition; +public static class RoutingComponents +{ + public static ComponentContract>> Window { get; } = + DesignedComponentContract.Create( + RoutingComponentDefinition.Types.Window, + RoutingServiceCollectionExtensions.ConfigureWindow, + static () => new WindowComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle>(component, RoutingComponentDefinition.Ports.Input, RoutingComponentDefinition.Ports.Output, RoutingComponentDefinition.Ports.Events)); + + public static ComponentContract>> Correlation { get; } = + DesignedComponentContract.Create( + RoutingComponentDefinition.Types.Correlation, + RoutingServiceCollectionExtensions.ConfigureCorrelation, + static () => new CorrelationComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle>(component, RoutingComponentDefinition.Ports.Input, RoutingComponentDefinition.Ports.Output, RoutingComponentDefinition.Ports.Events)); + + public static ComponentContract>> Join { get; } = + DesignedComponentContract.Create( + RoutingComponentDefinition.Types.Join, + RoutingServiceCollectionExtensions.ConfigureJoin, + static () => new JoinComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new DualInputOutputComponentHandle>(component, RoutingComponentDefinition.Ports.Left, RoutingComponentDefinition.Ports.Right, RoutingComponentDefinition.Ports.Output, RoutingComponentDefinition.Ports.Events)); +} + public static class RoutingAuthoringExtensions { public static InputOutputComponentHandle> AddWindow( this WorkflowDefinitionBuilder workflow, string name, Action configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, RoutingComponentDefinition.Types.Window, definition => - { - var builder = new WindowComponentBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new(component, RoutingComponentDefinition.Ports.Input, RoutingComponentDefinition.Ports.Output); - } + => workflow.AddComponent(name, RoutingComponents.Window, configure); public static WorkflowDefinitionBuilder AddWindow( this WorkflowDefinitionBuilder workflow, @@ -36,17 +54,7 @@ public static InputOutputComponentHandle configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, RoutingComponentDefinition.Types.Correlation, definition => - { - var builder = new CorrelationComponentBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new(component, RoutingComponentDefinition.Ports.Input, RoutingComponentDefinition.Ports.Output); - } + => workflow.AddComponent(name, RoutingComponents.Correlation, configure); public static WorkflowDefinitionBuilder AddCorrelation( this WorkflowDefinitionBuilder workflow, @@ -62,17 +70,7 @@ public static DualInputOutputComponentHandle configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, RoutingComponentDefinition.Types.Join, definition => - { - var builder = new JoinComponentBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new(component, RoutingComponentDefinition.Ports.Left, RoutingComponentDefinition.Ports.Right, RoutingComponentDefinition.Ports.Output); - } + => workflow.AddComponent(name, RoutingComponents.Join, configure); public static WorkflowDefinitionBuilder AddJoin( this WorkflowDefinitionBuilder workflow, diff --git a/src/FluxFlow.Components.Routing.Composition/RoutingComponentDefinition.cs b/src/FluxFlow.Components.Routing.Composition/RoutingComponentDefinition.cs index 29830495..1bd52fc6 100644 --- a/src/FluxFlow.Components.Routing.Composition/RoutingComponentDefinition.cs +++ b/src/FluxFlow.Components.Routing.Composition/RoutingComponentDefinition.cs @@ -26,6 +26,6 @@ public static class Options } public static class Types { public const string Window = "flow.window"; public const string Correlation = "flow.correlate"; public const string Join = "flow.join"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Left = "Left"; public const string Right = "Right"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Left = "Left"; public const string Right = "Right"; public const string Events = "Events"; } public static class Resources { public const string Clock = "clock"; public const string KeySelector = "keySelector"; public const string SideSelector = "sideSelector"; public const string LeftKeySelector = "leftKeySelector"; public const string RightKeySelector = "rightKeySelector"; } } diff --git a/src/FluxFlow.Components.Routing.Composition/RoutingServiceCollectionExtensions.cs b/src/FluxFlow.Components.Routing.Composition/RoutingServiceCollectionExtensions.cs index a7c8519b..4e291a76 100644 --- a/src/FluxFlow.Components.Routing.Composition/RoutingServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Routing.Composition/RoutingServiceCollectionExtensions.cs @@ -14,27 +14,30 @@ public static FluxFlowRegistrationBuilder AddRouting(this FluxFlowRegistrationBu { ArgumentNullException.ThrowIfNull(builder); return builder - .AddComponent(RoutingComponentDefinition.Types.Window, ConfigureWindow) - .AddComponent(RoutingComponentDefinition.Types.Correlation, ConfigureCorrelation) - .AddComponent(RoutingComponentDefinition.Types.Join, ConfigureJoin); + .AddDesignedComponent(RoutingComponents.Window) + .AddDesignedComponent(RoutingComponents.Correlation) + .AddDesignedComponent(RoutingComponents.Join); } - private static void ConfigureWindow(ComponentRegistrationBuilder component) + internal static void ConfigureWindow(ComponentRegistrationBuilder component) { - ConfigureCommon(component, CreateJsonWindowNode, "Window", "Buffers input messages into count- or time-based windows.", "panel-top", "window", 420); + ConfigureCommon(component, "Window", "Buffers input messages into count- or time-based windows.", "panel-top", "window", 420); AddTypeName(component, RoutingComponentDefinition.Options.InputType, "Input Type"); component.AddOption(RoutingComponentDefinition.Options.MaxItems, OptionValueKind.Number, "Max Items", "Maximum buffered item count; set timeMilliseconds when zero.", defaultValue: 0, min: 0, section: "Windowing", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Number); component.AddOption(RoutingComponentDefinition.Options.TimeMilliseconds, OptionValueKind.Number, "Time Milliseconds", "Maximum window duration in milliseconds; set maxItems when zero.", defaultValue: 0, min: 0, section: "Windowing", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Number); component.AddOption(RoutingComponentDefinition.Options.EmitPartialOnCompletion, OptionValueKind.Boolean, "Emit Partial On Completion", "Emit a partial window when input completes.", defaultValue: true, section: "Windowing", importance: OptionDesignMetadataAttributeValues.Advanced); AddCapacity(component); component.AddResource(RoutingComponentDefinition.Resources.Clock, "Clock", 0, "Optional keyed clock for deterministic routing timing, timeouts, and diagnostics.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "clock:{name}"); - component.AddInput(RoutingComponentDefinition.Ports.Input, "Input", "Messages", 0, "Schema-less JSON value.", true); - component.AddOutput>(RoutingComponentDefinition.Ports.Output, "Output", "Messages", 1, "Count-, time-, or completion-based window; failures use the message error case.", true); + component + .UseFactory(CreateJsonWindowNode) + .HasInput(RoutingComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Schema-less JSON value.", true) + .HasOutput(RoutingComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 1, "Count-, time-, or completion-based window; failures use the message error case.", true) + .HasEvents(RoutingComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort window diagnostics."); } - private static void ConfigureCorrelation(ComponentRegistrationBuilder component) + internal static void ConfigureCorrelation(ComponentRegistrationBuilder component) { - ConfigureCommon(component, CreateJsonCorrelationNode, "Correlation", "Pairs related request and response messages by host-provided key and side selectors.", "link", "correlate", 460); + ConfigureCommon(component, "Correlation", "Pairs related request and response messages by host-provided key and side selectors.", "link", "correlate", 460); AddEngine(component); AddExpression(component, RoutingComponentDefinition.Options.KeyExpression, "Key Expression", "Diagnostic key expression metadata; key selection uses the keySelector resource.", RoutingComponentDefinition.Resources.KeySelector); AddExpression(component, RoutingComponentDefinition.Options.SideExpression, "Side Expression", "Diagnostic side expression metadata; side selection uses the sideSelector resource.", RoutingComponentDefinition.Resources.SideSelector); @@ -47,13 +50,16 @@ private static void ConfigureCorrelation(ComponentRegistrationBuilder component) component.AddResource>(RoutingComponentDefinition.Resources.SideSelector, "Side Selector", 1, "Required keyed delegate that selects request or response side labels.", true, "Func", ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Delegate, keyPattern: "delegate:{name}"); AddClock(component, 2); component.AddAttribute("requiredResources", $"{RoutingComponentDefinition.Resources.KeySelector},{RoutingComponentDefinition.Resources.SideSelector}"); - component.AddInput(RoutingComponentDefinition.Ports.Input, "Input", "Messages", 0, "Schema-less JSON request or response value.", true); - component.AddOutput>(RoutingComponentDefinition.Ports.Output, "Output", "Messages", 1, "Match or timeout outcome; failures use the message error case.", true); + component + .UseFactory(CreateJsonCorrelationNode) + .HasInput(RoutingComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Schema-less JSON request or response value.", true) + .HasOutput(RoutingComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 1, "Match or timeout outcome; failures use the message error case.", true) + .HasEvents(RoutingComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort correlation diagnostics."); } - private static void ConfigureJoin(ComponentRegistrationBuilder component) + internal static void ConfigureJoin(ComponentRegistrationBuilder component) { - ConfigureCommon(component, CreateJsonJoinNode, "Join", "Joins left and right messages by host-provided key selectors.", "combine", "join", 460); + ConfigureCommon(component, "Join", "Joins left and right messages by host-provided key selectors.", "combine", "join", 460); AddEngine(component); AddExpression(component, RoutingComponentDefinition.Options.LeftKeyExpression, "Left Key Expression", "Diagnostic left key expression metadata; left keys use the leftKeySelector resource.", RoutingComponentDefinition.Resources.LeftKeySelector); AddExpression(component, RoutingComponentDefinition.Options.RightKeyExpression, "Right Key Expression", "Diagnostic right key expression metadata; right keys use the rightKeySelector resource.", RoutingComponentDefinition.Resources.RightKeySelector); @@ -65,14 +71,16 @@ private static void ConfigureJoin(ComponentRegistrationBuilder component) component.AddResource>(RoutingComponentDefinition.Resources.RightKeySelector, "Right Key Selector", 1, "Required keyed delegate that selects the join key for right messages.", true, "Func", ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Delegate, keyPattern: "delegate:{name}"); AddClock(component, 2); component.AddAttribute("requiredResources", $"{RoutingComponentDefinition.Resources.LeftKeySelector},{RoutingComponentDefinition.Resources.RightKeySelector}"); - component.AddInput(RoutingComponentDefinition.Ports.Left, "Left", "Messages", 0, "Schema-less JSON left value.", true); - component.AddInput(RoutingComponentDefinition.Ports.Right, "Right", "Messages", 1, "Schema-less JSON right value."); - component.AddOutput>(RoutingComponentDefinition.Ports.Output, "Output", "Messages", 2, "Match or timeout outcome; failures use the message error case.", true); + component + .UseFactory(CreateJsonJoinNode) + .HasInput(RoutingComponentDefinition.Ports.Left, static node => node.Left, "Left", "Messages", 0, "Schema-less JSON left value.", true) + .HasInput(RoutingComponentDefinition.Ports.Right, static node => node.Right, "Right", "Messages", 1, "Schema-less JSON right value.") + .HasOutput(RoutingComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 2, "Match or timeout outcome; failures use the message error case.", true) + .HasEvents(RoutingComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 3, "Best-effort join diagnostics."); } - private static void ConfigureCommon(ComponentRegistrationBuilder component, ComponentFactory factory, string displayName, string summary, string iconKey, string preferredNodeName, int width) + private static void ConfigureCommon(ComponentRegistrationBuilder component, string displayName, string summary, string iconKey, string preferredNodeName, int width) { - component.UseFactory(factory); component.WithDisplay(displayName, "Routing", summary, iconKey, preferredNodeName, width); } @@ -108,32 +116,16 @@ private static void AddCapacity(ComponentRegistrationBuilder component) private static void AddClock(ComponentRegistrationBuilder component, int order) => component.AddResource(RoutingComponentDefinition.Resources.Clock, "Clock", order, "Optional keyed clock for deterministic routing timing, timeouts, and diagnostics.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "clock:{name}"); - private static ValueTask CreateJsonWindowNode( + private static JsonWindowNode CreateJsonWindowNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource( RoutingComponentDefinition.Resources.Clock); - var node = new JsonWindowNode(options, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - RoutingComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output>( - RoutingComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new JsonWindowNode(options, clock); } - private static ValueTask CreateJsonCorrelationNode( + private static JsonCorrelationNode CreateJsonCorrelationNode( ComponentActivationContext context) { var options = context.BindConfiguration(); @@ -143,31 +135,15 @@ private static ValueTask CreateJsonCorrelationNode( RoutingComponentDefinition.Resources.SideSelector); var clock = context.GetResource( RoutingComponentDefinition.Resources.Clock); - var node = new JsonCorrelationNode( + return new JsonCorrelationNode( options, keySelector, sideSelector, options.Engine, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - RoutingComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output>( - RoutingComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); } - private static ValueTask CreateJsonJoinNode( + private static JsonJoinNode CreateJsonJoinNode( ComponentActivationContext context) { var options = context.BindConfiguration(); @@ -177,31 +153,12 @@ private static ValueTask CreateJsonJoinNode( RoutingComponentDefinition.Resources.RightKeySelector); var clock = context.GetResource( RoutingComponentDefinition.Resources.Clock); - var node = new JsonJoinNode( + return new JsonJoinNode( options, leftSelector, rightSelector, options.Engine, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - RoutingComponentDefinition.Ports.Left, - node.Left), - ComponentPorts.Input( - RoutingComponentDefinition.Ports.Right, - node.Right) - ], - outputs: - [ - ComponentPorts.Output>( - RoutingComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); } } diff --git a/src/FluxFlow.Components.Serialization.Composition/README.md b/src/FluxFlow.Components.Serialization.Composition/README.md index dfa6ae9e..76285036 100644 --- a/src/FluxFlow.Components.Serialization.Composition/README.md +++ b/src/FluxFlow.Components.Serialization.Composition/README.md @@ -22,3 +22,13 @@ services.AddFluxFlowComponents().AddSerialization(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`SerializationComponents` exposes the six JSON, text, and Base64 typed contracts. The retained `AddX` methods use those same contracts, and every handle exposes `Events`. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from these contracts retains its executable descriptors. +Normal code-first hosting therefore calls only `AddFluxFlow(definition)` and +does not repeat the family registration above. Use that service registration +for JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contracts. diff --git a/src/FluxFlow.Components.Serialization.Composition/SerializationAuthoringExtensions.cs b/src/FluxFlow.Components.Serialization.Composition/SerializationAuthoringExtensions.cs index ebef4e1d..afadab06 100644 --- a/src/FluxFlow.Components.Serialization.Composition/SerializationAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Serialization.Composition/SerializationAuthoringExtensions.cs @@ -1,16 +1,48 @@ using System.Text.Json; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; using FluxFlow.Data; namespace FluxFlow.Components.Serialization.Composition; +public static class SerializationComponents +{ + public static ComponentContract> JsonParse { get; } = + Create(SerializationComponentDefinition.Types.JsonParse, SerializationServiceCollectionExtensions.ConfigureJsonParse); + + public static ComponentContract> JsonStringify { get; } = + Create(SerializationComponentDefinition.Types.JsonStringify, SerializationServiceCollectionExtensions.ConfigureJsonStringify); + + public static ComponentContract> TextEncode { get; } = + Create(SerializationComponentDefinition.Types.TextEncode, SerializationServiceCollectionExtensions.ConfigureTextEncode); + + public static ComponentContract> TextDecode { get; } = + Create(SerializationComponentDefinition.Types.TextDecode, SerializationServiceCollectionExtensions.ConfigureTextDecode); + + public static ComponentContract> Base64Encode { get; } = + Create(SerializationComponentDefinition.Types.Base64Encode, SerializationServiceCollectionExtensions.ConfigureBase64Encode); + + public static ComponentContract> Base64Decode { get; } = + Create(SerializationComponentDefinition.Types.Base64Decode, SerializationServiceCollectionExtensions.ConfigureBase64Decode); + + private static ComponentContract> Create( + string type, + Action configure) + => DesignedComponentContract.Create( + type, + configure, + static () => new SerializationComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, SerializationComponentDefinition.Ports.Input, SerializationComponentDefinition.Ports.Output, SerializationComponentDefinition.Ports.Events)); +} + public static class SerializationAuthoringExtensions { public static InputOutputComponentHandle AddJsonParse( this WorkflowDefinitionBuilder workflow, string name, Action? configure = null) - => Add(workflow, name, SerializationComponentDefinition.Types.JsonParse, configure); + => workflow.AddComponent(name, SerializationComponents.JsonParse, configure ?? (static _ => { })); public static WorkflowDefinitionBuilder AddJsonParse( this WorkflowDefinitionBuilder workflow, @@ -36,7 +68,7 @@ public static InputOutputComponentHandle AddJsonString this WorkflowDefinitionBuilder workflow, string name, Action? configure = null) - => Add(workflow, name, SerializationComponentDefinition.Types.JsonStringify, configure); + => workflow.AddComponent(name, SerializationComponents.JsonStringify, configure ?? (static _ => { })); public static WorkflowDefinitionBuilder AddJsonStringify( this WorkflowDefinitionBuilder workflow, @@ -62,7 +94,7 @@ public static InputOutputComponentHandle AddTextEncode( this WorkflowDefinitionBuilder workflow, string name, Action? configure = null) - => Add(workflow, name, SerializationComponentDefinition.Types.TextEncode, configure); + => workflow.AddComponent(name, SerializationComponents.TextEncode, configure ?? (static _ => { })); public static WorkflowDefinitionBuilder AddTextEncode( this WorkflowDefinitionBuilder workflow, @@ -88,7 +120,7 @@ public static InputOutputComponentHandle AddTextDecode( this WorkflowDefinitionBuilder workflow, string name, Action? configure = null) - => Add(workflow, name, SerializationComponentDefinition.Types.TextDecode, configure); + => workflow.AddComponent(name, SerializationComponents.TextDecode, configure ?? (static _ => { })); public static WorkflowDefinitionBuilder AddTextDecode( this WorkflowDefinitionBuilder workflow, @@ -114,7 +146,7 @@ public static InputOutputComponentHandle AddBase64Encode( this WorkflowDefinitionBuilder workflow, string name, Action? configure = null) - => Add(workflow, name, SerializationComponentDefinition.Types.Base64Encode, configure); + => workflow.AddComponent(name, SerializationComponents.Base64Encode, configure ?? (static _ => { })); public static WorkflowDefinitionBuilder AddBase64Encode( this WorkflowDefinitionBuilder workflow, @@ -140,7 +172,7 @@ public static InputOutputComponentHandle AddBase64Decode( this WorkflowDefinitionBuilder workflow, string name, Action? configure = null) - => Add(workflow, name, SerializationComponentDefinition.Types.Base64Decode, configure); + => workflow.AddComponent(name, SerializationComponents.Base64Decode, configure ?? (static _ => { })); public static WorkflowDefinitionBuilder AddBase64Decode( this WorkflowDefinitionBuilder workflow, @@ -162,21 +194,6 @@ public static WorkflowDefinitionBuilder AddBase64Decode( return workflow; } - private static InputOutputComponentHandle Add( - WorkflowDefinitionBuilder workflow, - string name, - string type, - Action? configure) - { - ArgumentNullException.ThrowIfNull(workflow); - var component = workflow.AddComponent(name, type, definition => - { - var builder = new SerializationComponentBuilder(); - configure?.Invoke(builder); - builder.Apply(definition); - }); - return new(component, SerializationComponentDefinition.Ports.Input, SerializationComponentDefinition.Ports.Output); - } } public sealed class SerializationComponentBuilder diff --git a/src/FluxFlow.Components.Serialization.Composition/SerializationComponentDefinition.cs b/src/FluxFlow.Components.Serialization.Composition/SerializationComponentDefinition.cs index d7fc86cd..74ce8051 100644 --- a/src/FluxFlow.Components.Serialization.Composition/SerializationComponentDefinition.cs +++ b/src/FluxFlow.Components.Serialization.Composition/SerializationComponentDefinition.cs @@ -23,6 +23,6 @@ public static class Types public const string Base64Decode = "base64.decode"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Clock = "clock"; } } diff --git a/src/FluxFlow.Components.Serialization.Composition/SerializationServiceCollectionExtensions.cs b/src/FluxFlow.Components.Serialization.Composition/SerializationServiceCollectionExtensions.cs index 88cf370c..a14c801d 100644 --- a/src/FluxFlow.Components.Serialization.Composition/SerializationServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Serialization.Composition/SerializationServiceCollectionExtensions.cs @@ -1,12 +1,10 @@ using System.Text.Json; -using System.Threading.Tasks.Dataflow; using FluxFlow.Components.Designer; using FluxFlow.Components.Designer.Contracts; using FluxFlow.Components.Serialization.Nodes; using FluxFlow.Components.Serialization.Options; using FluxFlow.Composition; using FluxFlow.Data; -using FluxFlow.Nodes; namespace FluxFlow.Components.Serialization.Composition; @@ -16,39 +14,72 @@ public static FluxFlowRegistrationBuilder AddSerialization(this FluxFlowRegistra { ArgumentNullException.ThrowIfNull(builder); return builder - .AddComponent(SerializationComponentDefinition.Types.JsonParse, ConfigureJsonParse) - .AddComponent(SerializationComponentDefinition.Types.JsonStringify, ConfigureJsonStringify) - .AddComponent(SerializationComponentDefinition.Types.TextEncode, ConfigureTextEncode) - .AddComponent(SerializationComponentDefinition.Types.TextDecode, ConfigureTextDecode) - .AddComponent(SerializationComponentDefinition.Types.Base64Encode, ConfigureBase64Encode) - .AddComponent(SerializationComponentDefinition.Types.Base64Decode, ConfigureBase64Decode); + .AddDesignedComponent(SerializationComponents.JsonParse) + .AddDesignedComponent(SerializationComponents.JsonStringify) + .AddDesignedComponent(SerializationComponents.TextEncode) + .AddDesignedComponent(SerializationComponents.TextDecode) + .AddDesignedComponent(SerializationComponents.Base64Encode) + .AddDesignedComponent(SerializationComponents.Base64Decode); } - private static void ConfigureJsonParse(ComponentRegistrationBuilder component) - => Configure(component, CreateJsonParseNode, "JSON Parse", "Parses JSON content into an independently owned JSON value.", "braces", "parse"); + internal static void ConfigureJsonParse(ComponentRegistrationBuilder component) + { + ConfigureCommon(component, "JSON Parse", "Parses JSON content into an independently owned JSON value.", "braces", "parse"); + component.UseFactory(CreateJsonParseNode) + .HasInput(SerializationComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Canonical conversion input.", true) + .HasOutput(SerializationComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Converted value; conversion failures use the message error case.", true) + .HasEvents(SerializationComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort serialization diagnostics."); + } - private static void ConfigureJsonStringify(ComponentRegistrationBuilder component) - => Configure(component, CreateJsonStringifyNode, "JSON Stringify", "Serializes a JSON value into exact JSON content.", "file-json", "stringify"); + internal static void ConfigureJsonStringify(ComponentRegistrationBuilder component) + { + ConfigureCommon(component, "JSON Stringify", "Serializes a JSON value into exact JSON content.", "file-json", "stringify"); + component.UseFactory(CreateJsonStringifyNode) + .HasInput(SerializationComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Canonical conversion input.", true) + .HasOutput(SerializationComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Converted value; conversion failures use the message error case.", true) + .HasEvents(SerializationComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort serialization diagnostics."); + } - private static void ConfigureTextEncode(ComponentRegistrationBuilder component) - => Configure(component, CreateTextEncodeNode, "Text Encode", "Encodes a string into exact text content.", "binary", "encode"); + internal static void ConfigureTextEncode(ComponentRegistrationBuilder component) + { + ConfigureCommon(component, "Text Encode", "Encodes a string into exact text content.", "binary", "encode"); + component.UseFactory(CreateTextEncodeNode) + .HasInput(SerializationComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Canonical conversion input.", true) + .HasOutput(SerializationComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Converted value; conversion failures use the message error case.", true) + .HasEvents(SerializationComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort serialization diagnostics."); + } - private static void ConfigureTextDecode(ComponentRegistrationBuilder component) - => Configure(component, CreateTextDecodeNode, "Text Decode", "Decodes text content into a string.", "letter-text", "decode"); + internal static void ConfigureTextDecode(ComponentRegistrationBuilder component) + { + ConfigureCommon(component, "Text Decode", "Decodes text content into a string.", "letter-text", "decode"); + component.UseFactory(CreateTextDecodeNode) + .HasInput(SerializationComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Canonical conversion input.", true) + .HasOutput(SerializationComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Converted value; conversion failures use the message error case.", true) + .HasEvents(SerializationComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort serialization diagnostics."); + } - private static void ConfigureBase64Encode(ComponentRegistrationBuilder component) - => Configure(component, CreateBase64EncodeNode, "Base64 Encode", "Encodes exact content bytes into a Base64 string value.", "file-up", "base64Encode"); + internal static void ConfigureBase64Encode(ComponentRegistrationBuilder component) + { + ConfigureCommon(component, "Base64 Encode", "Encodes exact content bytes into a Base64 string value.", "file-up", "base64Encode"); + component.UseFactory(CreateBase64EncodeNode) + .HasInput(SerializationComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Canonical conversion input.", true) + .HasOutput(SerializationComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Converted value; conversion failures use the message error case.", true) + .HasEvents(SerializationComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort serialization diagnostics."); + } - private static void ConfigureBase64Decode(ComponentRegistrationBuilder component) - => Configure(component, CreateBase64DecodeNode, "Base64 Decode", "Decodes a Base64 string value into binary content.", "file-down", "base64Decode"); + internal static void ConfigureBase64Decode(ComponentRegistrationBuilder component) + { + ConfigureCommon(component, "Base64 Decode", "Decodes a Base64 string value into binary content.", "file-down", "base64Decode"); + component.UseFactory(CreateBase64DecodeNode) + .HasInput(SerializationComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Canonical conversion input.", true) + .HasOutput(SerializationComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Converted value; conversion failures use the message error case.", true) + .HasEvents(SerializationComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort serialization diagnostics."); + } - private static void Configure(ComponentRegistrationBuilder component, ComponentFactory factory, string displayName, string summary, string iconKey, string preferredNodeName) + private static void ConfigureCommon(ComponentRegistrationBuilder component, string displayName, string summary, string iconKey, string preferredNodeName) { var defaults = new SerializationNodeOptions(); - component.UseFactory(factory); component.WithDisplay(displayName, "Serialization", summary, iconKey, preferredNodeName, 420); - component.AddInput(SerializationComponentDefinition.Ports.Input, "Input", "Messages", 0, "Canonical conversion input.", true); - component.AddOutput(SerializationComponentDefinition.Ports.Output, "Output", "Results", 1, "Converted value; conversion failures use the message error case.", true); component.AddOption(SerializationComponentDefinition.Options.BoundedCapacity, OptionValueKind.Number, "Bounded Capacity", "Capacity used for bounded processing and reliable normal-data output.", defaultValue: defaults.BoundedCapacity, min: 1, section: "Runtime", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); component.AddOption(SerializationComponentDefinition.Options.DefaultEncoding, OptionValueKind.Text, "Default Encoding", "Encoding used when content does not declare one.", defaultValue: defaults.DefaultEncoding, section: "Encoding", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); component.AddOption(SerializationComponentDefinition.Options.MaxInputBytes, OptionValueKind.Number, "Max Input Bytes", "Maximum input payload size accepted by the node.", defaultValue: defaults.MaxInputBytes, min: 1, section: "Runtime", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); @@ -59,77 +90,49 @@ private static void Configure(ComponentRegistrationBuilder comp component.AddResource(SerializationComponentDefinition.Resources.Clock, "Clock", 0, "Optional keyed clock for deterministic serialization diagnostics.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "Resources.{name}"); } - private static ValueTask CreateJsonParseNode( + private static JsonParseNode CreateJsonParseNode( ComponentActivationContext context) { var options = context.BindConfiguration(); - var node = new JsonParseNode(options, GetClock(context)); - return Compose(node, node.Input, node.Output, node.Events); + return new JsonParseNode(options, GetClock(context)); } - private static ValueTask CreateJsonStringifyNode( + private static JsonStringifyNode CreateJsonStringifyNode( ComponentActivationContext context) { var options = context.BindConfiguration(); - var node = new JsonStringifyNode(options, GetClock(context)); - return Compose(node, node.Input, node.Output, node.Events); + return new JsonStringifyNode(options, GetClock(context)); } - private static ValueTask CreateTextEncodeNode( + private static TextEncodeNode CreateTextEncodeNode( ComponentActivationContext context) { var options = context.BindConfiguration(); - var node = new TextEncodeNode(options, GetClock(context)); - return Compose(node, node.Input, node.Output, node.Events); + return new TextEncodeNode(options, GetClock(context)); } - private static ValueTask CreateTextDecodeNode( + private static TextDecodeNode CreateTextDecodeNode( ComponentActivationContext context) { var options = context.BindConfiguration(); - var node = new TextDecodeNode(options, GetClock(context)); - return Compose(node, node.Input, node.Output, node.Events); + return new TextDecodeNode(options, GetClock(context)); } - private static ValueTask CreateBase64EncodeNode( + private static Base64EncodeNode CreateBase64EncodeNode( ComponentActivationContext context) { var options = context.BindConfiguration(); - var node = new Base64EncodeNode(options, GetClock(context)); - return Compose(node, node.Input, node.Output, node.Events); + return new Base64EncodeNode(options, GetClock(context)); } - private static ValueTask CreateBase64DecodeNode( + private static Base64DecodeNode CreateBase64DecodeNode( ComponentActivationContext context) { var options = context.BindConfiguration(); - var node = new Base64DecodeNode(options, GetClock(context)); - return Compose(node, node.Input, node.Output, node.Events); + return new Base64DecodeNode(options, GetClock(context)); } private static TimeProvider? GetClock(ComponentActivationContext context) => context.GetResource(SerializationComponentDefinition.Resources.Clock); - private static ValueTask Compose( - IFlowNode node, - ITargetBlock> input, - ISourceBlock> output, - ISourceBlock events) - { - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - SerializationComponentDefinition.Ports.Input, - input) - ], - outputs: - [ - ComponentPorts.Output( - SerializationComponentDefinition.Ports.Output, - output) - ], - events: events)); - } } diff --git a/src/FluxFlow.Components.Sessions.Composition/README.md b/src/FluxFlow.Components.Sessions.Composition/README.md index d17b6ec7..3038976e 100644 --- a/src/FluxFlow.Components.Sessions.Composition/README.md +++ b/src/FluxFlow.Components.Sessions.Composition/README.md @@ -22,3 +22,13 @@ services.AddFluxFlowComponents().AddSessions(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`SessionsComponents` exposes `SessionRecorder`, `SessionReplay`, and `SessionQuery` typed contracts. The retained `AddX` methods use those same contracts, and every handle exposes `Events`. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from these contracts retains its executable descriptors. +Normal code-first hosting therefore calls only `AddFluxFlow(definition)` and +does not repeat the family registration above. Use that service registration +for JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contracts. diff --git a/src/FluxFlow.Components.Sessions.Composition/SessionsAuthoringExtensions.cs b/src/FluxFlow.Components.Sessions.Composition/SessionsAuthoringExtensions.cs index 5e767f1b..e6ef4346 100644 --- a/src/FluxFlow.Components.Sessions.Composition/SessionsAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Sessions.Composition/SessionsAuthoringExtensions.cs @@ -1,16 +1,43 @@ using FluxFlow.Components.Sessions.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Sessions.Composition; +public static class SessionsComponents +{ + public static ComponentContract> SessionRecorder { get; } = + DesignedComponentContract.Create( + SessionsComponentDefinition.Types.Recorder, + SessionsServiceCollectionExtensions.ConfigureRecorder, + static () => new SessionRecorderComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, SessionsComponentDefinition.Ports.Input, SessionsComponentDefinition.Ports.Output, SessionsComponentDefinition.Ports.Events)); + + public static ComponentContract> SessionReplay { get; } = + DesignedComponentContract.Create( + SessionsComponentDefinition.Types.Replay, + SessionsServiceCollectionExtensions.ConfigureReplay, + static () => new SessionReplayComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new OutputComponentHandle(component, SessionsComponentDefinition.Ports.Output, SessionsComponentDefinition.Ports.Events)); + + public static ComponentContract> SessionQuery { get; } = + DesignedComponentContract.Create( + SessionsComponentDefinition.Types.Query, + SessionsServiceCollectionExtensions.ConfigureQuery, + static () => new SessionQueryComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, SessionsComponentDefinition.Ports.Input, SessionsComponentDefinition.Ports.Output, SessionsComponentDefinition.Ports.Events)); +} + public static class SessionsAuthoringExtensions { public static InputOutputComponentHandle AddSessionRecorder( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => Add( - workflow, name, SessionsComponentDefinition.Types.Recorder, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, SessionsComponents.SessionRecorder, configure); public static WorkflowDefinitionBuilder AddSessionRecorder( this WorkflowDefinitionBuilder workflow, @@ -26,17 +53,7 @@ public static OutputComponentHandle AddSessionReplay( this WorkflowDefinitionBuilder workflow, string name, Action configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, SessionsComponentDefinition.Types.Replay, definition => - { - var builder = new SessionReplayComponentBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new(component, SessionsComponentDefinition.Ports.Output); - } + => workflow.AddComponent(name, SessionsComponents.SessionReplay, configure); public static WorkflowDefinitionBuilder AddSessionReplay( this WorkflowDefinitionBuilder workflow, @@ -52,8 +69,7 @@ public static InputOutputComponentHandle configure) - => Add( - workflow, name, SessionsComponentDefinition.Types.Query, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, SessionsComponents.SessionQuery, configure); public static WorkflowDefinitionBuilder AddSessionQuery( this WorkflowDefinitionBuilder workflow, @@ -65,24 +81,6 @@ public static WorkflowDefinitionBuilder AddSessionQuery( return workflow; } - private static InputOutputComponentHandle Add( - WorkflowDefinitionBuilder workflow, - string name, - string type, - Action configure, - Action apply) - where TBuilder : SessionComponentBuilder, new() - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, type, definition => - { - var builder = new TBuilder(); - configure(builder); - apply(builder, definition); - }); - return new(component, SessionsComponentDefinition.Ports.Input, SessionsComponentDefinition.Ports.Output); - } } public abstract class SessionComponentBuilder diff --git a/src/FluxFlow.Components.Sessions.Composition/SessionsComponentDefinition.cs b/src/FluxFlow.Components.Sessions.Composition/SessionsComponentDefinition.cs index d65a1ad6..2c4e308f 100644 --- a/src/FluxFlow.Components.Sessions.Composition/SessionsComponentDefinition.cs +++ b/src/FluxFlow.Components.Sessions.Composition/SessionsComponentDefinition.cs @@ -22,6 +22,6 @@ public static class Options } public static class Types { public const string Recorder = "session.record"; public const string Replay = "session.replay"; public const string Query = "session.query"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Store = "store"; public const string Clock = "clock"; } } diff --git a/src/FluxFlow.Components.Sessions.Composition/SessionsServiceCollectionExtensions.cs b/src/FluxFlow.Components.Sessions.Composition/SessionsServiceCollectionExtensions.cs index ab71e033..6e8abb2c 100644 --- a/src/FluxFlow.Components.Sessions.Composition/SessionsServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Sessions.Composition/SessionsServiceCollectionExtensions.cs @@ -14,28 +14,31 @@ public static FluxFlowRegistrationBuilder AddSessions(this FluxFlowRegistrationB { ArgumentNullException.ThrowIfNull(builder); return builder - .AddComponent(SessionsComponentDefinition.Types.Recorder, ConfigureRecorder) - .AddComponent(SessionsComponentDefinition.Types.Replay, ConfigureReplay) - .AddComponent(SessionsComponentDefinition.Types.Query, ConfigureQuery); + .AddDesignedComponent(SessionsComponents.SessionRecorder) + .AddDesignedComponent(SessionsComponents.SessionReplay) + .AddDesignedComponent(SessionsComponents.SessionQuery); } - private static void ConfigureRecorder(ComponentRegistrationBuilder component) + internal static void ConfigureRecorder(ComponentRegistrationBuilder component) { var defaults = new SessionRecorderOptions(); - ConfigureCommon(component, CreateSessionRecorderNode, "Session Recorder", "Records incoming messages to a host-owned session store.", "history", "recordSession"); + ConfigureCommon(component, "Session Recorder", "Records incoming messages to a host-owned session store.", "history", "recordSession"); AddSessionId(component, false); component.AddOption(SessionsComponentDefinition.Options.SessionName, OptionValueKind.Text, "Session Name", "Optional session name stored with session metadata.", section: "Session", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Text); component.AddOption(SessionsComponentDefinition.Options.Notes, OptionValueKind.MultilineText, "Notes", "Optional session notes stored with session metadata.", section: "Session", importance: OptionDesignMetadataAttributeValues.Advanced); AddTags(component, "Metadata"); AddCapacity(component, defaults.BoundedCapacity); - component.AddInput(SessionsComponentDefinition.Ports.Input, "Input", "Messages", 0, "Exact-content session record input.", true); - component.AddOutput(SessionsComponentDefinition.Ports.Output, "Output", "Results", 1, "Stored or failed session record result.", true); + component + .UseFactory(CreateSessionRecorderNode) + .HasInput(SessionsComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Exact-content session record input.", true) + .HasOutput(SessionsComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Stored or failed session record result.", true) + .HasEvents(SessionsComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort session-recorder diagnostics."); } - private static void ConfigureReplay(ComponentRegistrationBuilder component) + internal static void ConfigureReplay(ComponentRegistrationBuilder component) { var defaults = new SessionReplayOptions(); - ConfigureCommon(component, CreateSessionReplayNode, "Session Replay", "Replays records from a host-owned session store as source messages.", "history-play", "replaySession"); + ConfigureCommon(component, "Session Replay", "Replays records from a host-owned session store as source messages.", "history-play", "replaySession"); AddSessionId(component, true); component.AddOption(SessionsComponentDefinition.Options.Mode, OptionValueKind.Enum, "Mode", "Timing mode used between replayed records.", defaultValue: defaults.Mode.ToString(), section: "Replay", importance: OptionDesignMetadataAttributeValues.Primary); component.AddOptionChoice(SessionsComponentDefinition.Options.Mode, SessionReplayMode.RealTime.ToString(), "Real Time", "Use timestamp deltas from stored records."); @@ -47,13 +50,16 @@ private static void ConfigureReplay(ComponentRegistrationBuilder component) component.AddOption(SessionsComponentDefinition.Options.MaxMessages, OptionValueKind.Number, "Max Messages", "Optional maximum number of messages to replay.", min: 1, section: "Replay", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); component.AddOption(SessionsComponentDefinition.Options.FixedIntervalMilliseconds, OptionValueKind.Number, "Fixed Interval Milliseconds", "Delay used by FixedInterval replay mode.", defaultValue: defaults.FixedIntervalMilliseconds, min: 0, section: "Timing", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); component.AddOption(SessionsComponentDefinition.Options.SpeedMultiplier, OptionValueKind.Number, "Speed Multiplier", "Multiplier used by Multiplier replay mode; must be greater than zero.", defaultValue: defaults.SpeedMultiplier, min: 0.000001, section: "Timing", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); - component.AddOutput(SessionsComponentDefinition.Ports.Output, "Output", "Messages", 0, "Replayed record or normal replay failure result.", true); + component + .UseFactory(CreateSessionReplayNode) + .HasOutput(SessionsComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 0, "Replayed record or normal replay failure result.", true) + .HasEvents(SessionsComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 1, "Best-effort session-replay diagnostics."); } - private static void ConfigureQuery(ComponentRegistrationBuilder component) + internal static void ConfigureQuery(ComponentRegistrationBuilder component) { var defaults = new SessionQueryOptions(); - ConfigureCommon(component, CreateSessionQueryNode, "Session Query", "Queries sessions and returns matching metadata in one normal result.", "history-search", "querySessions"); + ConfigureCommon(component, "Session Query", "Queries sessions and returns matching metadata in one normal result.", "history-search", "querySessions"); component.AddOption(SessionsComponentDefinition.Options.SessionName, OptionValueKind.Text, "Session Name", "Default exact session name filter.", section: "Filtering", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Text); component.AddOption(SessionsComponentDefinition.Options.NamePrefix, OptionValueKind.Text, "Name Prefix", "Default session name prefix filter.", section: "Filtering", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); AddTags(component, "Filtering"); @@ -62,13 +68,15 @@ private static void ConfigureQuery(ComponentRegistrationBuilder component) component.AddOption(SessionsComponentDefinition.Options.Limit, OptionValueKind.Number, "Limit", "Maximum number of sessions to return.", defaultValue: defaults.Limit, min: 1, section: "Results", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Number); component.AddOption(SessionsComponentDefinition.Options.EmitSessionsInResult, OptionValueKind.Boolean, "Emit Sessions In Result", "Include matching session metadata in the query result payload.", defaultValue: defaults.EmitSessionsInResult, section: "Results", importance: OptionDesignMetadataAttributeValues.Advanced); AddCapacity(component, defaults.BoundedCapacity); - component.AddInput(SessionsComponentDefinition.Ports.Input, "Input", "Messages", 0, "Session query request.", true); - component.AddOutput(SessionsComponentDefinition.Ports.Output, "Output", "Results", 1, "Completed or failed session query result.", true); + component + .UseFactory(CreateSessionQueryNode) + .HasInput(SessionsComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Session query request.", true) + .HasOutput(SessionsComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Completed or failed session query result.", true) + .HasEvents(SessionsComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort session-query diagnostics."); } - private static void ConfigureCommon(ComponentRegistrationBuilder component, ComponentFactory factory, string displayName, string summary, string iconKey, string preferredNodeName) + private static void ConfigureCommon(ComponentRegistrationBuilder component, string displayName, string summary, string iconKey, string preferredNodeName) { - component.UseFactory(factory); component.WithDisplay(displayName, "Sessions", summary, iconKey, preferredNodeName, 460); component.AddResource(SessionsComponentDefinition.Resources.Store, "Store", 0, "Required keyed session store or store factory used to record, replay, or query sessions.", true, "ISessionStore or ISessionStoreFactory", "ISessionStore or ISessionStoreFactory", ResourceDesignMetadataAttributeValues.HostOwned, ResourceDesignMetadataAttributeValues.Store, "Resources.{name}"); component.AddResource(SessionsComponentDefinition.Resources.Clock, "Clock", 1, "Optional keyed clock for deterministic session timestamps, replay pacing, and diagnostics.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "Resources.{name}"); @@ -83,7 +91,7 @@ private static void AddTags(ComponentRegistrationBuilder component, string secti private static void AddCapacity(ComponentRegistrationBuilder component, int defaultValue) => component.AddOption(SessionsComponentDefinition.Options.BoundedCapacity, OptionValueKind.Number, "Bounded Capacity", "Capacity used for bounded component work and reliable normal-data output.", defaultValue: defaultValue, min: 1, section: "Runtime", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); - private static async ValueTask CreateSessionRecorderNode( + private static async ValueTask> CreateSessionRecorderNode( ComponentActivationContext context) { var options = context.BindConfiguration(); @@ -94,21 +102,8 @@ private static async ValueTask CreateSessionRecorderNode( { var node = new SessionRecorderNode(options, store.Store, clock); - return ComponentInstance.Create( + return new ComponentNodeActivation( node, - inputs: - [ - ComponentPorts.Input( - SessionsComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - SessionsComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events, disposeAsync: store.DisposeAsync); } catch @@ -118,7 +113,7 @@ private static async ValueTask CreateSessionRecorderNode( } } - private static async ValueTask CreateSessionReplayNode( + private static async ValueTask> CreateSessionReplayNode( ComponentActivationContext context) { var options = context.BindConfiguration(); @@ -129,15 +124,8 @@ private static async ValueTask CreateSessionReplayNode( { var node = new SessionReplayNode(options, store.Store, clock); - return ComponentInstance.Create( + return new ComponentNodeActivation( node, - outputs: - [ - ComponentPorts.Output( - SessionsComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events, disposeAsync: store.DisposeAsync); } catch @@ -147,7 +135,7 @@ private static async ValueTask CreateSessionReplayNode( } } - private static async ValueTask CreateSessionQueryNode( + private static async ValueTask> CreateSessionQueryNode( ComponentActivationContext context) { var options = context.BindConfiguration(); @@ -158,21 +146,8 @@ private static async ValueTask CreateSessionQueryNode( { var node = new SessionQueryNode(options, store.Store, clock); - return ComponentInstance.Create( + return new ComponentNodeActivation( node, - inputs: - [ - ComponentPorts.Input( - SessionsComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - SessionsComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events, disposeAsync: store.DisposeAsync); } catch diff --git a/src/FluxFlow.Components.Sources.Composition/README.md b/src/FluxFlow.Components.Sources.Composition/README.md index ffc4de51..95c132c4 100644 --- a/src/FluxFlow.Components.Sources.Composition/README.md +++ b/src/FluxFlow.Components.Sources.Composition/README.md @@ -20,3 +20,13 @@ services.AddFluxFlowComponents().AddSources(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`SourcesComponents` exposes `GeneratedSource` and `SequenceSource` typed contracts. The retained `AddX` methods use those same contracts, and both handles expose `Output` and `Events`. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from these contracts retains its executable descriptors. +Normal code-first hosting therefore calls only `AddFluxFlow(definition)` and +does not repeat the family registration above. Use that service registration +for JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contracts. diff --git a/src/FluxFlow.Components.Sources.Composition/SourcesAuthoringExtensions.cs b/src/FluxFlow.Components.Sources.Composition/SourcesAuthoringExtensions.cs index cfff3a72..176d470b 100644 --- a/src/FluxFlow.Components.Sources.Composition/SourcesAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Sources.Composition/SourcesAuthoringExtensions.cs @@ -1,17 +1,36 @@ using System.Text.Json; using FluxFlow.Components.Sources.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Sources.Composition; +public static class SourcesComponents +{ + public static ComponentContract> GeneratedSource { get; } = + DesignedComponentContract.Create( + SourcesComponentDefinition.Types.Generated, + SourcesServiceCollectionExtensions.ConfigureGenerated, + static () => new GeneratedSourceComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new OutputComponentHandle(component, SourcesComponentDefinition.Ports.Output, SourcesComponentDefinition.Ports.Events)); + + public static ComponentContract> SequenceSource { get; } = + DesignedComponentContract.Create( + SourcesComponentDefinition.Types.Sequence, + SourcesServiceCollectionExtensions.ConfigureSequence, + static () => new SequenceSourceComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new OutputComponentHandle(component, SourcesComponentDefinition.Ports.Output, SourcesComponentDefinition.Ports.Events)); +} + public static class SourcesAuthoringExtensions { public static OutputComponentHandle AddGeneratedSource( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => Add( - workflow, name, SourcesComponentDefinition.Types.Generated, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, SourcesComponents.GeneratedSource, configure); public static WorkflowDefinitionBuilder AddGeneratedSource( this WorkflowDefinitionBuilder workflow, @@ -27,8 +46,7 @@ public static OutputComponentHandle AddSequenceSource( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => Add( - workflow, name, SourcesComponentDefinition.Types.Sequence, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, SourcesComponents.SequenceSource, configure); public static WorkflowDefinitionBuilder AddSequenceSource( this WorkflowDefinitionBuilder workflow, @@ -40,24 +58,6 @@ public static WorkflowDefinitionBuilder AddSequenceSource( return workflow; } - private static OutputComponentHandle Add( - WorkflowDefinitionBuilder workflow, - string name, - string type, - Action configure, - Action apply) - where TBuilder : SourceComponentBuilder, new() - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, type, definition => - { - var builder = new TBuilder(); - configure(builder); - apply(builder, definition); - }); - return new(component, SourcesComponentDefinition.Ports.Output); - } } public abstract class SourceComponentBuilder diff --git a/src/FluxFlow.Components.Sources.Composition/SourcesComponentDefinition.cs b/src/FluxFlow.Components.Sources.Composition/SourcesComponentDefinition.cs index a1b9b21d..93cd3646 100644 --- a/src/FluxFlow.Components.Sources.Composition/SourcesComponentDefinition.cs +++ b/src/FluxFlow.Components.Sources.Composition/SourcesComponentDefinition.cs @@ -17,6 +17,6 @@ public static class Options } public static class Types { public const string Generated = "source.items"; public const string Sequence = "source.sequence"; } - public static class Ports { public const string Output = "Output"; } + public static class Ports { public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Clock = "clock"; } } diff --git a/src/FluxFlow.Components.Sources.Composition/SourcesServiceCollectionExtensions.cs b/src/FluxFlow.Components.Sources.Composition/SourcesServiceCollectionExtensions.cs index 1aa18bd7..bc50562d 100644 --- a/src/FluxFlow.Components.Sources.Composition/SourcesServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Sources.Composition/SourcesServiceCollectionExtensions.cs @@ -16,13 +16,13 @@ public static FluxFlowRegistrationBuilder AddSources(this FluxFlowRegistrationBu { ArgumentNullException.ThrowIfNull(builder); return builder - .AddComponent(SourcesComponentDefinition.Types.Generated, ConfigureGenerated) - .AddComponent(SourcesComponentDefinition.Types.Sequence, ConfigureSequence); + .AddDesignedComponent(SourcesComponents.GeneratedSource) + .AddDesignedComponent(SourcesComponents.SequenceSource); } - private static void ConfigureGenerated(ComponentRegistrationBuilder component) + internal static void ConfigureGenerated(ComponentRegistrationBuilder component) { - ConfigureCommon(component, CreateGeneratedSourceNode, "Generated Source", "Emits inline configured JSON items as independently owned JSON values.", "list-plus", "generated", 440); + ConfigureCommon(component, "Generated Source", "Emits inline configured JSON items as independently owned JSON values.", "list-plus", "generated", 440); AddName(component, GeneratedSourceOptions.DefaultName); component.AddOption(SourcesComponentDefinition.Options.Items, OptionValueKind.Json, "Items", "One inline JSON value or an array of JSON values to emit.", section: "Items", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Json); component.AddOption(SourcesComponentDefinition.Options.Loop, OptionValueKind.Boolean, "Loop", "Repeat configured items until maxItems is reached.", defaultValue: false, section: "Emission", importance: OptionDesignMetadataAttributeValues.Advanced); @@ -30,12 +30,15 @@ private static void ConfigureGenerated(ComponentRegistrationBuilder component) AddTiming(component, SourcesComponentDefinition.Options.InitialDelayMilliseconds, "Initial Delay Milliseconds", "Delay before the first item is emitted."); AddTiming(component, SourcesComponentDefinition.Options.IntervalMilliseconds, "Interval Milliseconds", "Delay between emitted items."); AddCapacity(component); - component.AddOutput(SourcesComponentDefinition.Ports.Output, "Output", "Messages", 0, "Generated JSON value.", true); + component + .UseFactory(CreateGeneratedSourceNode) + .HasOutput(SourcesComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 0, "Generated JSON value.", true) + .HasEvents(SourcesComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 1, "Best-effort generated-source diagnostics."); } - private static void ConfigureSequence(ComponentRegistrationBuilder component) + internal static void ConfigureSequence(ComponentRegistrationBuilder component) { - ConfigureCommon(component, CreateSequenceSourceNode, "Sequence Source", "Emits typed numeric sequence items.", "list-ordered", "sequence", 420); + ConfigureCommon(component, "Sequence Source", "Emits typed numeric sequence items.", "list-ordered", "sequence", 420); AddName(component, SequenceSourceOptions.DefaultName); component.AddOption(SourcesComponentDefinition.Options.Start, OptionValueKind.Number, "Start", "First numeric value emitted.", defaultValue: 1, section: "Sequence", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); component.AddOption(SourcesComponentDefinition.Options.Step, OptionValueKind.Number, "Step", "Amount added for each item; cannot be zero.", defaultValue: 1, section: "Sequence", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); @@ -43,12 +46,14 @@ private static void ConfigureSequence(ComponentRegistrationBuilder component) AddTiming(component, SourcesComponentDefinition.Options.InitialDelayMilliseconds, "Initial Delay Milliseconds", "Delay before the first item is emitted."); AddTiming(component, SourcesComponentDefinition.Options.IntervalMilliseconds, "Interval Milliseconds", "Delay between emitted items."); AddCapacity(component); - component.AddOutput(SourcesComponentDefinition.Ports.Output, "Output", "Messages", 0, "Numeric sequence item.", true); + component + .UseFactory(CreateSequenceSourceNode) + .HasOutput(SourcesComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 0, "Numeric sequence item.", true) + .HasEvents(SourcesComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 1, "Best-effort sequence-source diagnostics."); } - private static void ConfigureCommon(ComponentRegistrationBuilder component, ComponentFactory factory, string displayName, string summary, string iconKey, string preferredNodeName, int width) + private static void ConfigureCommon(ComponentRegistrationBuilder component, string displayName, string summary, string iconKey, string preferredNodeName, int width) { - component.UseFactory(factory); component.WithDisplay(displayName, "Sources", summary, iconKey, preferredNodeName, width); component.AddResource(SourcesComponentDefinition.Resources.Clock, "Clock", 0, "Optional keyed clock for deterministic source timing and diagnostics.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "Resources.{name}"); } @@ -62,43 +67,23 @@ private static void AddTiming(ComponentRegistrationBuilder component, string nam private static void AddCapacity(ComponentRegistrationBuilder component) => component.AddOption(SourcesComponentDefinition.Options.BoundedCapacity, OptionValueKind.Number, "Bounded Capacity", "Capacity used for bounded source production and reliable normal-data output.", defaultValue: 128, min: 1, section: "Runtime", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); - private static ValueTask CreateGeneratedSourceNode( + private static GeneratedSourceNode CreateGeneratedSourceNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var items = DecodeGeneratedItems(context); var clock = context.GetResource( SourcesComponentDefinition.Resources.Clock); - var node = new GeneratedSourceNode(options, items, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - outputs: - [ - ComponentPorts.Output( - SourcesComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new GeneratedSourceNode(options, items, clock); } - private static ValueTask CreateSequenceSourceNode( + private static SequenceSourceNode CreateSequenceSourceNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource( SourcesComponentDefinition.Resources.Clock); - var node = new SequenceSourceNode(options, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - outputs: - [ - ComponentPorts.Output( - SourcesComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new SequenceSourceNode(options, clock); } private static IReadOnlyList DecodeGeneratedItems( diff --git a/src/FluxFlow.Components.State.Composition/README.md b/src/FluxFlow.Components.State.Composition/README.md index ce0d41f6..e8a3c1d9 100644 --- a/src/FluxFlow.Components.State.Composition/README.md +++ b/src/FluxFlow.Components.State.Composition/README.md @@ -23,3 +23,13 @@ services.AddFluxFlowComponents().AddState(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`StateComponents.StateReducer` is the typed contract used by both generic `AddComponent` and `AddStateReducer`. Its handle exposes named `Input`, `Output`, and `Events` ports. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from this contract retains its executable descriptor. Normal +code-first hosting therefore calls only `AddFluxFlow(definition)` and does not +repeat the family registration above. Use that service registration for +JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contract. diff --git a/src/FluxFlow.Components.State.Composition/StateAuthoringExtensions.cs b/src/FluxFlow.Components.State.Composition/StateAuthoringExtensions.cs index ccb72f0b..34b53d56 100644 --- a/src/FluxFlow.Components.State.Composition/StateAuthoringExtensions.cs +++ b/src/FluxFlow.Components.State.Composition/StateAuthoringExtensions.cs @@ -1,27 +1,29 @@ using System.Text.Json; using FluxFlow.Components.State.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; using FluxFlow.Mapping; namespace FluxFlow.Components.State.Composition; +public static class StateComponents +{ + public static ComponentContract, StateReducerResult>> StateReducer { get; } = + DesignedComponentContract.Create( + StateComponentDefinition.Types.Reducer, + StateServiceCollectionExtensions.ConfigureReducer, + static () => new StateReducerComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle, StateReducerResult>(component, StateComponentDefinition.Ports.Input, StateComponentDefinition.Ports.Output, StateComponentDefinition.Ports.Events)); +} + public static class StateAuthoringExtensions { public static InputOutputComponentHandle, StateReducerResult> AddStateReducer( this WorkflowDefinitionBuilder workflow, string name, Action configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, StateComponentDefinition.Types.Reducer, definition => - { - var builder = new StateReducerComponentBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new(component, StateComponentDefinition.Ports.Input, StateComponentDefinition.Ports.Output); - } + => workflow.AddComponent(name, StateComponents.StateReducer, configure); public static WorkflowDefinitionBuilder AddStateReducer( this WorkflowDefinitionBuilder workflow, diff --git a/src/FluxFlow.Components.State.Composition/StateComponentDefinition.cs b/src/FluxFlow.Components.State.Composition/StateComponentDefinition.cs index 0aecb279..e4d66603 100644 --- a/src/FluxFlow.Components.State.Composition/StateComponentDefinition.cs +++ b/src/FluxFlow.Components.State.Composition/StateComponentDefinition.cs @@ -14,6 +14,6 @@ public static class Options } public static class Types { public const string Reducer = "state.reduce"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Engine = "engine"; public const string Clock = "clock"; } } diff --git a/src/FluxFlow.Components.State.Composition/StateServiceCollectionExtensions.cs b/src/FluxFlow.Components.State.Composition/StateServiceCollectionExtensions.cs index ca50516f..08b54baa 100644 --- a/src/FluxFlow.Components.State.Composition/StateServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.State.Composition/StateServiceCollectionExtensions.cs @@ -14,15 +14,17 @@ public static class StateServiceCollectionExtensions public static FluxFlowRegistrationBuilder AddState(this FluxFlowRegistrationBuilder builder) { ArgumentNullException.ThrowIfNull(builder); - return builder.AddComponent(StateComponentDefinition.Types.Reducer, ConfigureReducer); + return builder.AddDesignedComponent(StateComponents.StateReducer); } - private static void ConfigureReducer(ComponentRegistrationBuilder component) + internal static void ConfigureReducer(ComponentRegistrationBuilder component) { - component.UseFactory(CreateStateReducerNode); component.WithDisplay("State Reducer", "State", "Maintains keyed state by applying a reducer expression to each input message.", "database-zap", "stateReducer", 460); - component.AddInput>(StateComponentDefinition.Ports.Input, "Input", "Messages", 0, "State reducer request.", true); - component.AddOutput>(StateComponentDefinition.Ports.Output, "Output", "Results", 1, "State reducer result.", true); + component + .UseFactory(CreateStateReducerNode) + .HasInput(StateComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "State reducer request.", true) + .HasOutput(StateComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "State reducer result.", true) + .HasEvents(StateComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort state diagnostics."); component.AddOption(StateComponentDefinition.Options.KeyExpression, OptionValueKind.Text, "Key Expression", "Optional expression used to resolve the state key from each input.", section: "State", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Expression, syntax: OptionDesignMetadataAttributeValues.Expression, relatedResource: StateComponentDefinition.Resources.Engine); component.AddOption(StateComponentDefinition.Options.Reducer, OptionValueKind.Text, "Reducer", "Expression evaluated once per reduce operation to produce the next state.", true, section: "State", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Expression, syntax: OptionDesignMetadataAttributeValues.Expression, relatedResource: StateComponentDefinition.Resources.Engine); component.AddOption(StateComponentDefinition.Options.ExpressionId, OptionValueKind.Text, "Expression ID", "Optional expression identifier emitted in diagnostics.", section: "Diagnostics", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); @@ -34,7 +36,7 @@ private static void ConfigureReducer(ComponentRegistrationBuilder component) component.AddResource(StateComponentDefinition.Resources.Clock, "Clock", 1, "Optional keyed clock for deterministic state reducer results and diagnostics.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "Resources.{name}"); } - private static ValueTask CreateStateReducerNode( + private static JsonStateReducerNode CreateStateReducerNode( ComponentActivationContext context) { var configuration = context.BindConfiguration(); @@ -52,23 +54,7 @@ private static ValueTask CreateStateReducerNode( StateComponentDefinition.Resources.Engine); var clock = context.GetResource( StateComponentDefinition.Resources.Clock); - var node = new JsonStateReducerNode(options, expressionEngine, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input>( - StateComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output>( - StateComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new JsonStateReducerNode(options, expressionEngine, clock); } private static JsonElement DecodeInitialState(JsonElement? value) diff --git a/src/FluxFlow.Components.Storage.Composition/README.md b/src/FluxFlow.Components.Storage.Composition/README.md index a1fb8aa4..83b3f826 100644 --- a/src/FluxFlow.Components.Storage.Composition/README.md +++ b/src/FluxFlow.Components.Storage.Composition/README.md @@ -19,3 +19,13 @@ services.AddFluxFlowComponents().AddStorage(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`StorageComponents` exposes `StoragePut`, `StorageGet`, `StorageQuery`, and `StorageDelete` typed contracts. The retained `AddX` methods use those same contracts, and every handle exposes `Events`. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from these contracts retains its executable descriptors. +Normal code-first hosting therefore calls only `AddFluxFlow(definition)` and +does not repeat the family registration above. Use that service registration +for JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contracts. diff --git a/src/FluxFlow.Components.Storage.Composition/StorageAuthoringExtensions.cs b/src/FluxFlow.Components.Storage.Composition/StorageAuthoringExtensions.cs index 202237c9..d12e136a 100644 --- a/src/FluxFlow.Components.Storage.Composition/StorageAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Storage.Composition/StorageAuthoringExtensions.cs @@ -1,16 +1,43 @@ using FluxFlow.Components.Storage.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Storage.Composition; +public static class StorageComponents +{ + public static ComponentContract> StoragePut { get; } = + Create(StorageComponentDefinition.Types.Put, StorageServiceCollectionExtensions.ConfigurePut, static (options, definition) => options.Apply(definition)); + + public static ComponentContract> StorageGet { get; } = + Create(StorageComponentDefinition.Types.Get, StorageServiceCollectionExtensions.ConfigureGet, static (options, definition) => options.Apply(definition)); + + public static ComponentContract> StorageQuery { get; } = + Create(StorageComponentDefinition.Types.Query, StorageServiceCollectionExtensions.ConfigureQuery, static (options, definition) => options.Apply(definition)); + + public static ComponentContract> StorageDelete { get; } = + Create(StorageComponentDefinition.Types.Delete, StorageServiceCollectionExtensions.ConfigureDelete, static (options, definition) => options.Apply(definition)); + + private static ComponentContract> Create( + string type, + Action configure, + Action apply) + where TOptions : class, new() + => DesignedComponentContract.Create( + type, + configure, + static () => new TOptions(), + apply, + static component => new InputOutputComponentHandle(component, StorageComponentDefinition.Ports.Input, StorageComponentDefinition.Ports.Output, StorageComponentDefinition.Ports.Events)); +} + public static class StorageAuthoringExtensions { public static InputOutputComponentHandle AddStoragePut( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => Add( - workflow, name, StorageComponentDefinition.Types.Put, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, StorageComponents.StoragePut, configure); public static WorkflowDefinitionBuilder AddStoragePut( this WorkflowDefinitionBuilder workflow, @@ -26,8 +53,7 @@ public static InputOutputComponentHandle A this WorkflowDefinitionBuilder workflow, string name, Action configure) - => Add( - workflow, name, StorageComponentDefinition.Types.Get, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, StorageComponents.StorageGet, configure); public static WorkflowDefinitionBuilder AddStorageGet( this WorkflowDefinitionBuilder workflow, @@ -43,8 +69,7 @@ public static InputOutputComponentHandle configure) - => Add( - workflow, name, StorageComponentDefinition.Types.Query, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, StorageComponents.StorageQuery, configure); public static WorkflowDefinitionBuilder AddStorageQuery( this WorkflowDefinitionBuilder workflow, @@ -60,8 +85,7 @@ public static InputOutputComponentHandle configure) - => Add( - workflow, name, StorageComponentDefinition.Types.Delete, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, StorageComponents.StorageDelete, configure); public static WorkflowDefinitionBuilder AddStorageDelete( this WorkflowDefinitionBuilder workflow, @@ -73,24 +97,6 @@ public static WorkflowDefinitionBuilder AddStorageDelete( return workflow; } - private static InputOutputComponentHandle Add( - WorkflowDefinitionBuilder workflow, - string name, - string type, - Action configure, - Action apply) - where TBuilder : StorageComponentBuilder, new() - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, type, definition => - { - var builder = new TBuilder(); - configure(builder); - apply(builder, definition); - }); - return new(component, StorageComponentDefinition.Ports.Input, StorageComponentDefinition.Ports.Output); - } } public abstract class StorageComponentBuilder diff --git a/src/FluxFlow.Components.Storage.Composition/StorageComponentDefinition.cs b/src/FluxFlow.Components.Storage.Composition/StorageComponentDefinition.cs index 4117a108..d62ebab6 100644 --- a/src/FluxFlow.Components.Storage.Composition/StorageComponentDefinition.cs +++ b/src/FluxFlow.Components.Storage.Composition/StorageComponentDefinition.cs @@ -15,6 +15,6 @@ public static class Options } public static class Types { public const string Put = "storage.put"; public const string Get = "storage.get"; public const string Query = "storage.query"; public const string Delete = "storage.delete"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Store = "store"; public const string Clock = "clock"; } } diff --git a/src/FluxFlow.Components.Storage.Composition/StorageCompositionStoreResolver.cs b/src/FluxFlow.Components.Storage.Composition/StorageCompositionStoreResolver.cs index a91aba97..96fcd6ed 100644 --- a/src/FluxFlow.Components.Storage.Composition/StorageCompositionStoreResolver.cs +++ b/src/FluxFlow.Components.Storage.Composition/StorageCompositionStoreResolver.cs @@ -1,5 +1,6 @@ using FluxFlow.Components.Storage.Contracts; using FluxFlow.Composition; +using FluxFlow.Nodes; using Microsoft.Extensions.DependencyInjection; namespace FluxFlow.Components.Storage.Composition; @@ -59,13 +60,16 @@ public static ResolvedStorageStore Leased(StorageStoreLease lease) return new ResolvedStorageStore(lease.Store, lease); } - internal async ValueTask CreateInstanceAsync( - Func, ComponentInstance> createInstance) + internal async ValueTask> CreateActivationAsync( + Func createNode) + where TNode : IFlowNode { - ArgumentNullException.ThrowIfNull(createInstance); + ArgumentNullException.ThrowIfNull(createNode); try { - return createInstance(Store, DisposeAsync); + return new ComponentNodeActivation( + createNode(Store), + disposeAsync: DisposeAsync); } catch { diff --git a/src/FluxFlow.Components.Storage.Composition/StorageServiceCollectionExtensions.cs b/src/FluxFlow.Components.Storage.Composition/StorageServiceCollectionExtensions.cs index b00231be..86b72e92 100644 --- a/src/FluxFlow.Components.Storage.Composition/StorageServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Storage.Composition/StorageServiceCollectionExtensions.cs @@ -14,16 +14,16 @@ public static FluxFlowRegistrationBuilder AddStorage(this FluxFlowRegistrationBu { ArgumentNullException.ThrowIfNull(builder); return builder - .AddComponent(StorageComponentDefinition.Types.Put, ConfigurePut) - .AddComponent(StorageComponentDefinition.Types.Get, ConfigureGet) - .AddComponent(StorageComponentDefinition.Types.Query, ConfigureQuery) - .AddComponent(StorageComponentDefinition.Types.Delete, ConfigureDelete); + .AddDesignedComponent(StorageComponents.StoragePut) + .AddDesignedComponent(StorageComponents.StorageGet) + .AddDesignedComponent(StorageComponents.StorageQuery) + .AddDesignedComponent(StorageComponents.StorageDelete); } - private static void ConfigurePut(ComponentRegistrationBuilder component) + internal static void ConfigurePut(ComponentRegistrationBuilder component) { var defaults = new StoragePutOptions(); - ConfigureCommon(component, CreateStoragePutNode, "Storage Put", "Stores exact content through a host-owned storage store.", "database-plus", "putRecord"); + ConfigureCommon(component, "Storage Put", "Stores exact content through a host-owned storage store.", "database-plus", "putRecord"); AddCollection(component); component.AddOption(StorageComponentDefinition.Options.Mode, OptionValueKind.Enum, "Mode", "Write behavior when a record already exists or is missing.", defaultValue: defaults.Mode.ToString(), section: "Write", importance: OptionDesignMetadataAttributeValues.Primary); component.AddOptionChoice(StorageComponentDefinition.Options.Mode, StorageWriteMode.Upsert.ToString(), "Upsert", "Create or replace the record."); @@ -31,44 +31,59 @@ private static void ConfigurePut(ComponentRegistrationBuilder component) component.AddOptionChoice(StorageComponentDefinition.Options.Mode, StorageWriteMode.Replace.ToString(), "Replace", "Fail when the record does not exist."); component.AddOption(StorageComponentDefinition.Options.EmitStoredRecord, OptionValueKind.Boolean, "Emit Stored Record", "Include the stored record in the output result.", defaultValue: defaults.EmitStoredRecord, section: "Results", importance: OptionDesignMetadataAttributeValues.Advanced); AddCapacity(component, defaults.BoundedCapacity); - AddPorts(component, "Exact-content storage put request.", "Stored or failed operation result."); + component + .UseFactory(CreateStoragePutNode) + .HasInput(StorageComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Exact-content storage put request.", true) + .HasOutput(StorageComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Stored or failed operation result.", true) + .HasEvents(StorageComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort storage-put diagnostics."); } - private static void ConfigureGet(ComponentRegistrationBuilder component) + internal static void ConfigureGet(ComponentRegistrationBuilder component) { var defaults = new StorageGetOptions(); - ConfigureCommon(component, CreateStorageGetNode, "Storage Get", "Reads exact content and returns found, missing, or failed results.", "database-search", "getRecord"); + ConfigureCommon(component, "Storage Get", "Reads exact content and returns found, missing, or failed results.", "database-search", "getRecord"); AddCollection(component); AddIncludeExpired(component, defaults.IncludeExpired); AddCapacity(component, defaults.BoundedCapacity); - AddPorts(component, "Storage get request.", "Found, missing, or failed operation result."); + component + .UseFactory(CreateStorageGetNode) + .HasInput(StorageComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Storage get request.", true) + .HasOutput(StorageComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Found, missing, or failed operation result.", true) + .HasEvents(StorageComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort storage-get diagnostics."); } - private static void ConfigureQuery(ComponentRegistrationBuilder component) + internal static void ConfigureQuery(ComponentRegistrationBuilder component) { var defaults = new StorageQueryOptions(); - ConfigureCommon(component, CreateStorageQueryNode, "Storage Query", "Queries exact-content records and returns one result.", "database", "queryRecords"); + ConfigureCommon(component, "Storage Query", "Queries exact-content records and returns one result.", "database", "queryRecords"); AddCollection(component); AddIncludeExpired(component, defaults.IncludeExpired); component.AddOption(StorageComponentDefinition.Options.Offset, OptionValueKind.Number, "Offset", "Number of matched records to skip.", defaultValue: defaults.Offset, min: 0, section: "Query", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); component.AddOption(StorageComponentDefinition.Options.Limit, OptionValueKind.Number, "Limit", "Maximum number of records to return.", defaultValue: defaults.Limit, min: 1, section: "Query", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); component.AddOption(StorageComponentDefinition.Options.EmitRecordsInResult, OptionValueKind.Boolean, "Emit Records In Result", "Include matched records in the query result payload.", defaultValue: defaults.EmitRecordsInResult, section: "Results", importance: OptionDesignMetadataAttributeValues.Advanced); AddCapacity(component, defaults.BoundedCapacity); - AddPorts(component, "Storage query request.", "Completed or failed storage query result."); + component + .UseFactory(CreateStorageQueryNode) + .HasInput(StorageComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Storage query request.", true) + .HasOutput(StorageComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Completed or failed storage query result.", true) + .HasEvents(StorageComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort storage-query diagnostics."); } - private static void ConfigureDelete(ComponentRegistrationBuilder component) + internal static void ConfigureDelete(ComponentRegistrationBuilder component) { var defaults = new StorageDeleteOptions(); - ConfigureCommon(component, CreateStorageDeleteNode, "Storage Delete", "Deletes a record through a host-owned storage store.", "database-x", "deleteRecord"); + ConfigureCommon(component, "Storage Delete", "Deletes a record through a host-owned storage store.", "database-x", "deleteRecord"); AddCollection(component); AddCapacity(component, defaults.BoundedCapacity); - AddPorts(component, "Storage delete request.", "Deleted, missing, or failed operation result."); + component + .UseFactory(CreateStorageDeleteNode) + .HasInput(StorageComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Storage delete request.", true) + .HasOutput(StorageComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Deleted, missing, or failed operation result.", true) + .HasEvents(StorageComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort storage-delete diagnostics."); } - private static void ConfigureCommon(ComponentRegistrationBuilder component, ComponentFactory factory, string displayName, string summary, string iconKey, string preferredNodeName) + private static void ConfigureCommon(ComponentRegistrationBuilder component, string displayName, string summary, string iconKey, string preferredNodeName) { - component.UseFactory(factory); component.WithDisplay(displayName, "Storage", summary, iconKey, preferredNodeName, 460); component.AddResource(StorageComponentDefinition.Resources.Store, "Store", 0, "Required keyed storage store or store factory used for put, get, query, and delete operations.", true, "IStorageStore or IStorageStoreFactory", "IStorageStore or IStorageStoreFactory", ResourceDesignMetadataAttributeValues.HostOwned, ResourceDesignMetadataAttributeValues.Store, "storage-store:{name}"); component.AddResource(StorageComponentDefinition.Resources.Clock, "Clock", 1, "Optional keyed clock for deterministic storage diagnostics and timestamps.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "clock:{name}"); @@ -83,126 +98,52 @@ private static void AddIncludeExpired(ComponentRegistrationBuilder component, bo private static void AddCapacity(ComponentRegistrationBuilder component, int defaultValue) => component.AddOption(StorageComponentDefinition.Options.BoundedCapacity, OptionValueKind.Number, "Bounded Capacity", "Capacity used for bounded processing and reliable normal-data output.", defaultValue: defaultValue, min: 1, section: "Runtime", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); - private static void AddPorts(ComponentRegistrationBuilder component, string inputSummary, string outputSummary) - { - component.AddInput(StorageComponentDefinition.Ports.Input, "Input", "Messages", 0, inputSummary, true); - component.AddOutput(StorageComponentDefinition.Ports.Output, "Output", "Results", 1, outputSummary, true); - } - - private static async ValueTask CreateStoragePutNode( + private static async ValueTask> CreateStoragePutNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource(StorageComponentDefinition.Resources.Clock); var store = await ResolveStoreAsync(context, options.Collection) .ConfigureAwait(false); - return await store.CreateInstanceAsync((storageStore, disposeAsync) => - { - var node = new StoragePutNode(storageStore, options, clock); - return ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - StorageComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - StorageComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events, - disposeAsync: disposeAsync); - }).ConfigureAwait(false); + return await store.CreateActivationAsync(storageStore => + new StoragePutNode(storageStore, options, clock)) + .ConfigureAwait(false); } - private static async ValueTask CreateStorageGetNode( + private static async ValueTask> CreateStorageGetNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource(StorageComponentDefinition.Resources.Clock); var store = await ResolveStoreAsync(context, options.Collection) .ConfigureAwait(false); - return await store.CreateInstanceAsync((storageStore, disposeAsync) => - { - var node = new StorageGetNode(storageStore, options, clock); - return ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - StorageComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - StorageComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events, - disposeAsync: disposeAsync); - }).ConfigureAwait(false); + return await store.CreateActivationAsync(storageStore => + new StorageGetNode(storageStore, options, clock)) + .ConfigureAwait(false); } - private static async ValueTask CreateStorageQueryNode( + private static async ValueTask> CreateStorageQueryNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource(StorageComponentDefinition.Resources.Clock); var store = await ResolveStoreAsync(context, options.Collection) .ConfigureAwait(false); - return await store.CreateInstanceAsync((storageStore, disposeAsync) => - { - var node = new StorageQueryNode(storageStore, options, clock); - return ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - StorageComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - StorageComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events, - disposeAsync: disposeAsync); - }).ConfigureAwait(false); + return await store.CreateActivationAsync(storageStore => + new StorageQueryNode(storageStore, options, clock)) + .ConfigureAwait(false); } - private static async ValueTask CreateStorageDeleteNode( + private static async ValueTask> CreateStorageDeleteNode( ComponentActivationContext context) { var options = context.BindConfiguration(); var clock = context.GetResource(StorageComponentDefinition.Resources.Clock); var store = await ResolveStoreAsync(context, options.Collection) .ConfigureAwait(false); - return await store.CreateInstanceAsync((storageStore, disposeAsync) => - { - var node = new StorageDeleteNode(storageStore, options, clock); - return ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - StorageComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - StorageComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events, - disposeAsync: disposeAsync); - }).ConfigureAwait(false); + return await store.CreateActivationAsync(storageStore => + new StorageDeleteNode(storageStore, options, clock)) + .ConfigureAwait(false); } private static ValueTask ResolveStoreAsync( diff --git a/src/FluxFlow.Components.Timers.Composition/README.md b/src/FluxFlow.Components.Timers.Composition/README.md index 9b9356b5..91e9acf9 100644 --- a/src/FluxFlow.Components.Timers.Composition/README.md +++ b/src/FluxFlow.Components.Timers.Composition/README.md @@ -22,3 +22,13 @@ services.AddFluxFlowComponents().AddTimers(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`TimersComponents` exposes `IntervalTimer`, `ScheduleTimer`, `Delay`, `Throttle`, and `Debounce` typed contracts. The retained `AddX` methods use those same contracts, and every handle exposes `Events`. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from these contracts retains its executable descriptors. +Normal code-first hosting therefore calls only `AddFluxFlow(definition)` and +does not repeat the family registration above. Use that service registration +for JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contracts. diff --git a/src/FluxFlow.Components.Timers.Composition/TimersAuthoringExtensions.cs b/src/FluxFlow.Components.Timers.Composition/TimersAuthoringExtensions.cs index 2ce487f2..746757c7 100644 --- a/src/FluxFlow.Components.Timers.Composition/TimersAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Timers.Composition/TimersAuthoringExtensions.cs @@ -1,17 +1,59 @@ using System.Text.Json; using FluxFlow.Components.Timers.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Timers.Composition; +public static class TimersComponents +{ + public static ComponentContract> IntervalTimer { get; } = + CreateSource(TimersComponentDefinition.Types.Interval, TimersServiceCollectionExtensions.ConfigureInterval, static (options, definition) => options.Apply(definition)); + + public static ComponentContract> ScheduleTimer { get; } = + CreateSource(TimersComponentDefinition.Types.Schedule, TimersServiceCollectionExtensions.ConfigureSchedule, static (options, definition) => options.Apply(definition)); + + public static ComponentContract> Delay { get; } = + CreateTransform(TimersComponentDefinition.Types.Delay, TimersServiceCollectionExtensions.ConfigureDelay, static (options, definition) => options.Apply(definition)); + + public static ComponentContract> Throttle { get; } = + CreateTransform(TimersComponentDefinition.Types.Throttle, TimersServiceCollectionExtensions.ConfigureThrottle, static (options, definition) => options.Apply(definition)); + + public static ComponentContract> Debounce { get; } = + CreateTransform(TimersComponentDefinition.Types.Debounce, TimersServiceCollectionExtensions.ConfigureDebounce, static (options, definition) => options.Apply(definition)); + + private static ComponentContract> CreateSource( + string type, + Action configure, + Action apply) + where TOptions : class, new() + => DesignedComponentContract.Create( + type, + configure, + static () => new TOptions(), + apply, + static component => new OutputComponentHandle(component, TimersComponentDefinition.Ports.Output, TimersComponentDefinition.Ports.Events)); + + private static ComponentContract> CreateTransform( + string type, + Action configure, + Action apply) + where TOptions : class, new() + => DesignedComponentContract.Create( + type, + configure, + static () => new TOptions(), + apply, + static component => new InputOutputComponentHandle(component, TimersComponentDefinition.Ports.Input, TimersComponentDefinition.Ports.Output, TimersComponentDefinition.Ports.Events)); +} + public static class TimersAuthoringExtensions { public static OutputComponentHandle AddIntervalTimer( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => AddSource( - workflow, name, TimersComponentDefinition.Types.Interval, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, TimersComponents.IntervalTimer, configure); public static WorkflowDefinitionBuilder AddIntervalTimer( this WorkflowDefinitionBuilder workflow, @@ -27,8 +69,7 @@ public static OutputComponentHandle AddScheduleTimer( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => AddSource( - workflow, name, TimersComponentDefinition.Types.Schedule, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, TimersComponents.ScheduleTimer, configure); public static WorkflowDefinitionBuilder AddScheduleTimer( this WorkflowDefinitionBuilder workflow, @@ -44,8 +85,7 @@ public static InputOutputComponentHandle AddDelay( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => AddTransform( - workflow, name, TimersComponentDefinition.Types.Delay, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, TimersComponents.Delay, configure); public static WorkflowDefinitionBuilder AddDelay( this WorkflowDefinitionBuilder workflow, @@ -61,8 +101,7 @@ public static InputOutputComponentHandle AddThrottle( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => AddTransform( - workflow, name, TimersComponentDefinition.Types.Throttle, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, TimersComponents.Throttle, configure); public static WorkflowDefinitionBuilder AddThrottle( this WorkflowDefinitionBuilder workflow, @@ -78,8 +117,7 @@ public static InputOutputComponentHandle AddDebounce( this WorkflowDefinitionBuilder workflow, string name, Action configure) - => AddTransform( - workflow, name, TimersComponentDefinition.Types.Debounce, configure, static (builder, definition) => builder.Apply(definition)); + => workflow.AddComponent(name, TimersComponents.Debounce, configure); public static WorkflowDefinitionBuilder AddDebounce( this WorkflowDefinitionBuilder workflow, @@ -91,43 +129,6 @@ public static WorkflowDefinitionBuilder AddDebounce( return workflow; } - private static OutputComponentHandle AddSource( - WorkflowDefinitionBuilder workflow, - string name, - string type, - Action configure, - Action apply) - where TBuilder : TimerComponentBuilder, new() - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, type, definition => - { - var builder = new TBuilder(); - configure(builder); - apply(builder, definition); - }); - return new(component, TimersComponentDefinition.Ports.Output); - } - - private static InputOutputComponentHandle AddTransform( - WorkflowDefinitionBuilder workflow, - string name, - string type, - Action configure, - Action apply) - where TBuilder : TimerComponentBuilder, new() - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var component = workflow.AddComponent(name, type, definition => - { - var builder = new TBuilder(); - configure(builder); - apply(builder, definition); - }); - return new(component, TimersComponentDefinition.Ports.Input, TimersComponentDefinition.Ports.Output); - } } public abstract class TimerComponentBuilder diff --git a/src/FluxFlow.Components.Timers.Composition/TimersComponentDefinition.cs b/src/FluxFlow.Components.Timers.Composition/TimersComponentDefinition.cs index 49d2de2f..59d7a087 100644 --- a/src/FluxFlow.Components.Timers.Composition/TimersComponentDefinition.cs +++ b/src/FluxFlow.Components.Timers.Composition/TimersComponentDefinition.cs @@ -25,6 +25,6 @@ public static class Types public const string Debounce = "timer.debounce"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Clock = "clock"; } } diff --git a/src/FluxFlow.Components.Timers.Composition/TimersServiceCollectionExtensions.cs b/src/FluxFlow.Components.Timers.Composition/TimersServiceCollectionExtensions.cs index adea8751..3a715c58 100644 --- a/src/FluxFlow.Components.Timers.Composition/TimersServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Timers.Composition/TimersServiceCollectionExtensions.cs @@ -14,68 +14,85 @@ public static FluxFlowRegistrationBuilder AddTimers(this FluxFlowRegistrationBui { ArgumentNullException.ThrowIfNull(builder); return builder - .AddComponent(TimersComponentDefinition.Types.Interval, ConfigureInterval) - .AddComponent(TimersComponentDefinition.Types.Schedule, ConfigureSchedule) - .AddComponent(TimersComponentDefinition.Types.Delay, ConfigureDelay) - .AddComponent(TimersComponentDefinition.Types.Throttle, ConfigureThrottle) - .AddComponent(TimersComponentDefinition.Types.Debounce, ConfigureDebounce); + .AddDesignedComponent(TimersComponents.IntervalTimer) + .AddDesignedComponent(TimersComponents.ScheduleTimer) + .AddDesignedComponent(TimersComponents.Delay) + .AddDesignedComponent(TimersComponents.Throttle) + .AddDesignedComponent(TimersComponents.Debounce); } - private static void ConfigureInterval(ComponentRegistrationBuilder component) + internal static void ConfigureInterval(ComponentRegistrationBuilder component) { - ConfigureCommon(component, CreateTimerIntervalNode, "Interval Timer", "Emits typed timer ticks on a fixed interval.", "timer", TimersComponentDefinition.Options.Interval); + ConfigureCommon(component, "Interval Timer", "Emits typed timer ticks on a fixed interval.", "timer", TimersComponentDefinition.Options.Interval); AddName(component, TimersComponentDefinition.Options.Interval); component.AddOption(TimersComponentDefinition.Options.Interval, OptionValueKind.Duration, "Interval", "Delay between ticks.", true, section: "Timing", importance: OptionDesignMetadataAttributeValues.Primary); component.AddOption(TimersComponentDefinition.Options.InitialDelay, OptionValueKind.Duration, "Initial Delay", "Optional delay before the first scheduled tick.", defaultValue: TimeSpan.Zero, section: "Timing", importance: OptionDesignMetadataAttributeValues.Advanced); component.AddOption(TimersComponentDefinition.Options.EmitImmediately, OptionValueKind.Boolean, "Emit Immediately", "Emit the first tick immediately when the source starts.", defaultValue: false, section: "Timing", importance: OptionDesignMetadataAttributeValues.Advanced); AddMaxTicks(component); AddCapacity(component); - component.AddOutput(TimersComponentDefinition.Ports.Output, "Output", "Messages", 1, "Interval timer tick.", true); + component + .UseFactory(CreateTimerIntervalNode) + .HasOutput(TimersComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 1, "Interval timer tick.", true) + .HasEvents(TimersComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort interval-timer diagnostics."); } - private static void ConfigureSchedule(ComponentRegistrationBuilder component) + internal static void ConfigureSchedule(ComponentRegistrationBuilder component) { - ConfigureCommon(component, CreateTimerScheduleNode, "Schedule Timer", "Emits typed timer ticks from a cron schedule.", "calendar-clock", "schedule"); + ConfigureCommon(component, "Schedule Timer", "Emits typed timer ticks from a cron schedule.", "calendar-clock", "schedule"); component.AddAttribute("omittedOptions", "timeZone"); component.AddAttribute("omittedOptionsReason", "TimerScheduleSettings.TimeZone requires typed configuration; this adapter does not add time-zone id conversion."); AddName(component, "schedule"); component.AddOption(TimersComponentDefinition.Options.Cron, OptionValueKind.Text, "Cron", "Five- or six-field cron expression. Schedule composition uses UTC unless the host provides a typed time-zone setting.", true, section: "Schedule", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Text); AddMaxTicks(component); AddCapacity(component); - component.AddOutput(TimersComponentDefinition.Ports.Output, "Output", "Messages", 1, "Scheduled timer tick.", true); + component + .UseFactory(CreateTimerScheduleNode) + .HasOutput(TimersComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 1, "Scheduled timer tick.", true) + .HasEvents(TimersComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort schedule-timer diagnostics."); } - private static void ConfigureDelay(ComponentRegistrationBuilder component) + internal static void ConfigureDelay(ComponentRegistrationBuilder component) { - ConfigureCommon(component, CreateTimerDelayNode, "Delay", "Emits a result for each workflow value after a configured delay.", TimersComponentDefinition.Resources.Clock, TimersComponentDefinition.Options.Delay); + ConfigureCommon(component, "Delay", "Emits a result for each workflow value after a configured delay.", TimersComponentDefinition.Resources.Clock, TimersComponentDefinition.Options.Delay); AddName(component, TimersComponentDefinition.Options.Delay); component.AddOption(TimersComponentDefinition.Options.Delay, OptionValueKind.Duration, "Delay", "Delay applied to each input message.", true, section: "Timing", importance: OptionDesignMetadataAttributeValues.Primary); AddCapacity(component); - AddTransformPorts(component); + component + .UseFactory(CreateTimerDelayNode) + .HasInput(TimersComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Schema-less JSON value.", true) + .HasOutput(TimersComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 1, "Delayed JSON value; failures use the message error case.", true) + .HasEvents(TimersComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort delay diagnostics."); } - private static void ConfigureThrottle(ComponentRegistrationBuilder component) + internal static void ConfigureThrottle(ComponentRegistrationBuilder component) { - ConfigureCommon(component, CreateTimerThrottleNode, "Throttle", "Rate-limits workflow values and emits ordered results.", "gauge", "throttle"); + ConfigureCommon(component, "Throttle", "Rate-limits workflow values and emits ordered results.", "gauge", "throttle"); AddName(component, "throttle"); component.AddOption(TimersComponentDefinition.Options.Interval, OptionValueKind.Duration, "Interval", "Minimum delay between emitted messages.", true, section: "Timing", importance: OptionDesignMetadataAttributeValues.Primary); component.AddOption(TimersComponentDefinition.Options.EmitFirstImmediately, OptionValueKind.Boolean, "Emit First Immediately", "Emit the first input immediately before applying the throttle interval.", defaultValue: true, section: "Timing", importance: OptionDesignMetadataAttributeValues.Advanced); AddCapacity(component); - AddTransformPorts(component); + component + .UseFactory(CreateTimerThrottleNode) + .HasInput(TimersComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Schema-less JSON value.", true) + .HasOutput(TimersComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 1, "Rate-limited JSON value; failures use the message error case.", true) + .HasEvents(TimersComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort throttle diagnostics."); } - private static void ConfigureDebounce(ComponentRegistrationBuilder component) + internal static void ConfigureDebounce(ComponentRegistrationBuilder component) { - ConfigureCommon(component, CreateTimerDebounceNode, "Debounce", "Emits a result for the latest workflow value after a quiet period.", "timer-reset", "debounce"); + ConfigureCommon(component, "Debounce", "Emits a result for the latest workflow value after a quiet period.", "timer-reset", "debounce"); AddName(component, "debounce"); component.AddOption(TimersComponentDefinition.Options.QuietPeriod, OptionValueKind.Duration, "Quiet Period", "Required quiet period before the latest input is emitted.", true, section: "Timing", importance: OptionDesignMetadataAttributeValues.Primary); AddCapacity(component); - AddTransformPorts(component); + component + .UseFactory(CreateTimerDebounceNode) + .HasInput(TimersComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Schema-less JSON value.", true) + .HasOutput(TimersComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 1, "Debounced JSON value; failures use the message error case.", true) + .HasEvents(TimersComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort debounce diagnostics."); } - private static void ConfigureCommon(ComponentRegistrationBuilder component, ComponentFactory factory, string displayName, string summary, string iconKey, string preferredNodeName) + private static void ConfigureCommon(ComponentRegistrationBuilder component, string displayName, string summary, string iconKey, string preferredNodeName) { - component.UseFactory(factory); component.WithDisplay(displayName, "Timers", summary, iconKey, preferredNodeName, 420); component.AddResource(TimersComponentDefinition.Resources.Clock, "Clock", 0, "Optional keyed clock for deterministic timer scheduling and diagnostics.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "Resources.{name}"); } @@ -89,123 +106,49 @@ private static void AddMaxTicks(ComponentRegistrationBuilder component) private static void AddCapacity(ComponentRegistrationBuilder component) => component.AddOption(TimersComponentDefinition.Options.BoundedCapacity, OptionValueKind.Number, "Bounded Capacity", "Capacity used for bounded timer work and reliable normal-data output.", defaultValue: 128, min: 1, section: "Runtime", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Number); - private static void AddTransformPorts(ComponentRegistrationBuilder component) - { - component.AddInput(TimersComponentDefinition.Ports.Input, "Input", "Messages", 0, "Schema-less JSON value.", true); - component.AddOutput(TimersComponentDefinition.Ports.Output, "Output", "Messages", 1, "Delayed or rate-limited JSON value; failures use the message error case.", true); - } - - private static ValueTask CreateTimerIntervalNode( + private static TimerIntervalNode CreateTimerIntervalNode( ComponentActivationContext context) { var settings = context.BindConfiguration(); var clock = context.GetResource( TimersComponentDefinition.Resources.Clock); - var node = new TimerIntervalNode(settings, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - outputs: - [ - ComponentPorts.Output( - TimersComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new TimerIntervalNode(settings, clock); } - private static ValueTask CreateTimerScheduleNode( + private static TimerScheduleNode CreateTimerScheduleNode( ComponentActivationContext context) { var settings = context.BindConfiguration(); var clock = context.GetResource( TimersComponentDefinition.Resources.Clock); - var node = new TimerScheduleNode(settings, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - outputs: - [ - ComponentPorts.Output( - TimersComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new TimerScheduleNode(settings, clock); } - private static ValueTask CreateTimerDelayNode( + private static TimerDelayNode CreateTimerDelayNode( ComponentActivationContext context) { var settings = context.BindConfiguration(); var clock = context.GetResource( TimersComponentDefinition.Resources.Clock); - var node = new TimerDelayNode(settings, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - TimersComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - TimersComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new TimerDelayNode(settings, clock); } - private static ValueTask CreateTimerThrottleNode( + private static TimerThrottleNode CreateTimerThrottleNode( ComponentActivationContext context) { var settings = context.BindConfiguration(); var clock = context.GetResource( TimersComponentDefinition.Resources.Clock); - var node = new TimerThrottleNode(settings, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - TimersComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - TimersComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new TimerThrottleNode(settings, clock); } - private static ValueTask CreateTimerDebounceNode( + private static TimerDebounceNode CreateTimerDebounceNode( ComponentActivationContext context) { var settings = context.BindConfiguration(); var clock = context.GetResource( TimersComponentDefinition.Resources.Clock); - var node = new TimerDebounceNode(settings, clock); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - TimersComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - TimersComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); + return new TimerDebounceNode(settings, clock); } } diff --git a/src/FluxFlow.Components.Validation.Composition/README.md b/src/FluxFlow.Components.Validation.Composition/README.md index 1ec20b58..56701057 100644 --- a/src/FluxFlow.Components.Validation.Composition/README.md +++ b/src/FluxFlow.Components.Validation.Composition/README.md @@ -23,3 +23,13 @@ services.AddFluxFlowComponents().AddValidation(); The resulting `ComponentCatalog` is built once from DI registrations. Standalone runtime nodes remain usable without this package, and referenced external resources remain host-owned. + +## Code-first authoring + +`ValidationComponents.JsonSchemaValidator` is the typed contract used by both generic `AddComponent` and `AddJsonSchemaValidator`. Its handle exposes named `Input`, `Output`, and `Events` ports. See [typed code-first authoring](../../docs/39-typed-code-first-authoring.md). + +A definition built from this contract retains its executable descriptor. Normal +code-first hosting therefore calls only `AddFluxFlow(definition)` and does not +repeat the family registration above. Use that service registration for +JSON/configuration, catalog, or dynamic definitions that do not carry the +complete contract. diff --git a/src/FluxFlow.Components.Validation.Composition/ValidationAuthoringExtensions.cs b/src/FluxFlow.Components.Validation.Composition/ValidationAuthoringExtensions.cs index a227b264..f24d04d9 100644 --- a/src/FluxFlow.Components.Validation.Composition/ValidationAuthoringExtensions.cs +++ b/src/FluxFlow.Components.Validation.Composition/ValidationAuthoringExtensions.cs @@ -1,28 +1,31 @@ using System.Text.Json; using FluxFlow.Components.Validation.Contracts; +using FluxFlow.Components.Designer; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Validation.Composition; +public static class ValidationComponents +{ + public static ComponentContract> JsonSchemaValidator { get; } = + DesignedComponentContract.Create( + ValidationComponentDefinition.Types.JsonSchemaValidator, + ValidationServiceCollectionExtensions.ConfigureJsonSchemaValidator, + static () => new JsonSchemaValidatorComponentBuilder(), + static (options, definition) => options.Apply(definition), + static component => new InputOutputComponentHandle(component, ValidationComponentDefinition.Ports.Input, ValidationComponentDefinition.Ports.Output, ValidationComponentDefinition.Ports.Events)); +} + public static class ValidationAuthoringExtensions { public static InputOutputComponentHandle AddJsonSchemaValidator( this WorkflowDefinitionBuilder workflow, string name, Action? configure = null) - { - ArgumentNullException.ThrowIfNull(workflow); - var component = workflow.AddComponent( + => workflow.AddComponent( name, - ValidationComponentDefinition.Types.JsonSchemaValidator, - definition => - { - var builder = new JsonSchemaValidatorComponentBuilder(); - configure?.Invoke(builder); - builder.Apply(definition); - }); - return new(component, ValidationComponentDefinition.Ports.Input, ValidationComponentDefinition.Ports.Output); - } + ValidationComponents.JsonSchemaValidator, + configure ?? (static _ => { })); public static WorkflowDefinitionBuilder AddJsonSchemaValidator( this WorkflowDefinitionBuilder workflow, diff --git a/src/FluxFlow.Components.Validation.Composition/ValidationComponentDefinition.cs b/src/FluxFlow.Components.Validation.Composition/ValidationComponentDefinition.cs index a6ecbf57..4a65a6da 100644 --- a/src/FluxFlow.Components.Validation.Composition/ValidationComponentDefinition.cs +++ b/src/FluxFlow.Components.Validation.Composition/ValidationComponentDefinition.cs @@ -13,6 +13,6 @@ public static class Options } public static class Types { public const string JsonSchemaValidator = "json.validate"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Events = "Events"; } public static class Resources { public const string Selector = "selector"; public const string Clock = "clock"; } } diff --git a/src/FluxFlow.Components.Validation.Composition/ValidationServiceCollectionExtensions.cs b/src/FluxFlow.Components.Validation.Composition/ValidationServiceCollectionExtensions.cs index fee5d402..68a0580b 100644 --- a/src/FluxFlow.Components.Validation.Composition/ValidationServiceCollectionExtensions.cs +++ b/src/FluxFlow.Components.Validation.Composition/ValidationServiceCollectionExtensions.cs @@ -13,15 +13,17 @@ public static class ValidationServiceCollectionExtensions public static FluxFlowRegistrationBuilder AddValidation(this FluxFlowRegistrationBuilder builder) { ArgumentNullException.ThrowIfNull(builder); - return builder.AddComponent(ValidationComponentDefinition.Types.JsonSchemaValidator, ConfigureJsonSchemaValidator); + return builder.AddDesignedComponent(ValidationComponents.JsonSchemaValidator); } - private static void ConfigureJsonSchemaValidator(ComponentRegistrationBuilder component) + internal static void ConfigureJsonSchemaValidator(ComponentRegistrationBuilder component) { - component.UseFactory(CreateJsonSchemaValidatorNode); component.WithDisplay("JSON Schema Validator", "Validation", "Validates schema-less JSON values against an inline or path-based JSON schema.", "shield-check", "validate", 460); - component.AddInput(ValidationComponentDefinition.Ports.Input, "Input", "Messages", 0, "Immutable workflow value to validate.", true); - component.AddOutput(ValidationComponentDefinition.Ports.Output, "Output", "Results", 1, "Normal valid, invalid, or processing-failure result.", true); + component + .UseFactory(CreateJsonSchemaValidatorNode) + .HasInput(ValidationComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Immutable workflow value to validate.", true) + .HasOutput(ValidationComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Normal valid, invalid, or processing-failure result.", true) + .HasEvents(ValidationComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort validation diagnostics."); component.AddOption(ValidationComponentDefinition.Options.Schema, OptionValueKind.Json, "Schema", "Inline JSON schema compiled during composition build.", section: "Schema", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Json); component.AddOption(ValidationComponentDefinition.Options.SchemaPath, OptionValueKind.Text, "Schema Path", "Path to a JSON schema file read during composition build.", section: "Schema", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); component.AddOption(ValidationComponentDefinition.Options.SchemaId, OptionValueKind.Text, "Schema ID", "Optional schema identifier used in results and diagnostics.", section: "Diagnostics", importance: OptionDesignMetadataAttributeValues.Advanced, editor: OptionDesignMetadataAttributeValues.Text); @@ -32,7 +34,7 @@ private static void ConfigureJsonSchemaValidator(ComponentRegistrationBuilder co component.AddResource(ValidationComponentDefinition.Resources.Clock, "Clock", 1, "Optional keyed clock for deterministic validation results and diagnostics.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "Resources.{name}"); } - private static ValueTask CreateJsonSchemaValidatorNode( + private static JsonSchemaValidatorNode CreateJsonSchemaValidatorNode( ComponentActivationContext context) { var options = context.BindConfiguration(); @@ -41,7 +43,7 @@ private static ValueTask CreateJsonSchemaValidatorNode( ValidationComponentDefinition.Resources.Selector); var clock = context.GetResource( ValidationComponentDefinition.Resources.Clock); - var node = new JsonSchemaValidatorNode( + return new JsonSchemaValidatorNode( schema, selector, options.EffectiveValueSelector, @@ -49,21 +51,5 @@ private static ValueTask CreateJsonSchemaValidatorNode( options.SchemaPath, clock, options); - - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - ValidationComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - ValidationComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events)); } } diff --git a/src/FluxFlow.Composition/ApplicationLinks/ApplicationLinkCompiler.cs b/src/FluxFlow.Composition/ApplicationLinks/ApplicationLinkCompiler.cs index a7679e7d..9ed4f505 100644 --- a/src/FluxFlow.Composition/ApplicationLinks/ApplicationLinkCompiler.cs +++ b/src/FluxFlow.Composition/ApplicationLinks/ApplicationLinkCompiler.cs @@ -26,7 +26,8 @@ public ApplicationLinkCompilationResult Compile(ApplicationDefinition definition ArgumentNullException.ThrowIfNull(definition); var diagnostics = new List(); - var components = IndexComponents(definition, diagnostics); + var catalog = _catalog.Merge(definition.ComponentDescriptors); + var components = IndexComponents(definition, catalog, diagnostics); var conditionCache = new Dictionary(StringComparer.Ordinal); var candidates = new List(); var declarations = new List(); @@ -37,6 +38,13 @@ public ApplicationLinkCompilationResult Compile(ApplicationDefinition definition candidates, declarations, diagnostics); + CollectCodeLinks( + definition.Links, + components, + conditionCache, + candidates, + declarations, + diagnostics); var normalized = RemoveDuplicates(candidates, diagnostics); ValidateExclusiveClaims(normalized, components, diagnostics); @@ -212,7 +220,9 @@ private void CollectDeclarations( target, sourceMetadata!.MessageType, declaration.Condition, - compiledCondition, + compiledCondition is null + ? null + : context => compiledCondition.Evaluate(context), side), context)); } @@ -223,8 +233,105 @@ private void CollectDeclarations( } } + private void CollectCodeLinks( + IReadOnlyList links, + IReadOnlyDictionary components, + Dictionary conditionCache, + List candidates, + List projections, + List diagnostics) + { + foreach (var link in links) + { + var context = CreateContext(link.Source); + var sourceValid = TryResolveMetadata( + link.Source, + output: true, + components, + _systemOutputs, + context, + diagnostics, + out var sourceMetadata); + var targetValid = TryResolveMetadata( + link.Target, + output: false, + components, + _systemOutputs, + context, + diagnostics, + out var targetMetadata); + + IFlowCompiledExpression? compiledExpression = null; + var conditionValid = link.ConditionExpression is null || + TryCompileCondition( + link.ConditionExpression, + context, + conditionCache, + diagnostics, + out compiledExpression); + + if (!sourceValid || !targetValid || !conditionValid) + continue; + + if (sourceMetadata!.MessageType != link.MessageType) + { + diagnostics.Add(CreateDiagnostic( + ApplicationLinkDiagnosticCode.PortTypeMismatch, + $"Link '{link.Source}' to '{link.Target}' declares '{link.MessageType}' but source port '{link.Source}' carries '{sourceMetadata.MessageType}'.", + context, + link.Source, + link.Target)); + continue; + } + + if (targetMetadata!.Kind != ComponentPortKind.Signal && + sourceMetadata.MessageType != targetMetadata.MessageType) + { + diagnostics.Add(CreateDiagnostic( + ApplicationLinkDiagnosticCode.PortTypeMismatch, + $"Link '{link.Source}' to '{link.Target}' connects '{sourceMetadata.MessageType}' to incompatible '{targetMetadata.MessageType}'.", + context, + link.Source, + link.Target)); + continue; + } + + Func? condition = link.CodeCondition; + if (condition is null && compiledExpression is not null) + condition = context => compiledExpression.Evaluate(context); + candidates.Add(new LinkCandidate( + new CompiledApplicationLink( + link.Source, + link.Target, + sourceMetadata.MessageType, + link.ConditionExpression, + condition, + link.DeclarationSide), + context)); + + if (link.CodeCondition is null && + ApplicationLinkDeclarationProjection.CanProject( + link.Source, + link.Target, + link.DeclarationSide)) + { + projections.Add(new ApplicationLinkDeclarationProjection( + link.Source, + link.Target, + link.ConditionExpression, + link.DeclarationSide)); + } + } + } + + private static DeclarationContext CreateContext(ApplicationAddress source) + => source.Kind == ApplicationAddressKind.WorkflowPort + ? new DeclarationContext(source.Segments[0], source.Segments[1], source.Segments[2]) + : new DeclarationContext(null, null, source.Value); + private Dictionary IndexComponents( ApplicationDefinition definition, + ComponentCatalog catalog, List diagnostics) { var components = new Dictionary(); @@ -234,7 +341,7 @@ private Dictionary IndexComponents( foreach (var component in workflow.Value.Components.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) { var key = new ComponentKey(workflow.Key, component.Key); - _catalog.TryGetDescriptor(component.Value.Type, out var descriptor); + catalog.TryGetDescriptor(component.Value.Type, out var descriptor); components.Add(key, new RegisteredComponent(component.Value, descriptor)); if (descriptor is null) diff --git a/src/FluxFlow.Composition/ApplicationLinks/ApplicationLinkDefinition.cs b/src/FluxFlow.Composition/ApplicationLinks/ApplicationLinkDefinition.cs new file mode 100644 index 00000000..828ed3df --- /dev/null +++ b/src/FluxFlow.Composition/ApplicationLinks/ApplicationLinkDefinition.cs @@ -0,0 +1,122 @@ +using System.Runtime.CompilerServices; +using FluxFlow.Composition.Addressing; +using FluxFlow.Mapping; +using FluxFlow.Nodes; + +namespace FluxFlow.Composition.Links; + +public sealed class ApplicationLinkDefinition : IEquatable +{ + private readonly object? _conditionIdentity; + + private ApplicationLinkDefinition( + ApplicationAddress source, + ApplicationAddress target, + Type messageType, + string? conditionExpression, + Func? codeCondition, + object? conditionIdentity, + ApplicationLinkDeclarationSide declarationSide) + { + Source = source; + Target = target; + MessageType = messageType; + ConditionExpression = conditionExpression; + CodeCondition = codeCondition; + _conditionIdentity = conditionIdentity; + DeclarationSide = declarationSide; + } + + public ApplicationAddress Source { get; } + + public ApplicationAddress Target { get; } + + public Type MessageType { get; } + + public string? ConditionExpression { get; } + + public bool IsConditional => ConditionExpression is not null || CodeCondition is not null; + + public ApplicationLinkDeclarationSide DeclarationSide { get; } + + internal Func? CodeCondition { get; } + + internal static ApplicationLinkDefinition Unconditional( + ApplicationAddress source, + ApplicationAddress target, + ApplicationLinkDeclarationSide declarationSide) + => new( + source, + target, + typeof(TMessage), + conditionExpression: null, + codeCondition: null, + conditionIdentity: null, + declarationSide); + + internal static ApplicationLinkDefinition Expression( + ApplicationAddress source, + ApplicationAddress target, + string condition, + ApplicationLinkDeclarationSide declarationSide) + => new( + source, + target, + typeof(TMessage), + condition, + codeCondition: null, + conditionIdentity: null, + declarationSide); + + internal static ApplicationLinkDefinition Predicate( + ApplicationAddress source, + ApplicationAddress target, + Func when, + ApplicationLinkDeclarationSide declarationSide) + { + ArgumentNullException.ThrowIfNull(when); + return new( + source, + target, + typeof(TMessage), + conditionExpression: null, + context => Match(context, when), + new object(), + declarationSide); + } + + public bool Equals(ApplicationLinkDefinition? other) + => other is not null && + Source == other.Source && + Target == other.Target && + MessageType == other.MessageType && + string.Equals(ConditionExpression, other.ConditionExpression, StringComparison.Ordinal) && + ReferenceEquals(_conditionIdentity, other._conditionIdentity) && + DeclarationSide == other.DeclarationSide; + + public override bool Equals(object? obj) => Equals(obj as ApplicationLinkDefinition); + + public override int GetHashCode() + { + var hash = new HashCode(); + hash.Add(Source); + hash.Add(Target); + hash.Add(MessageType); + hash.Add(ConditionExpression, StringComparer.Ordinal); + hash.Add(_conditionIdentity is null ? 0 : RuntimeHelpers.GetHashCode(_conditionIdentity)); + hash.Add(DeclarationSide); + return hash.ToHashCode(); + } + + private static bool Match(FlowMapContext context, Func when) + { + if (!context.Variables.TryGetValue("message", out var candidate) || + candidate is not FlowMessage message) + { + throw new InvalidOperationException( + $"Link condition expected a FlowMessage<{typeof(TMessage)}> context."); + } + + return !message.IsError && when(message.Value); + } +} diff --git a/src/FluxFlow.Composition/ApplicationLinks/CompiledApplicationLink.cs b/src/FluxFlow.Composition/ApplicationLinks/CompiledApplicationLink.cs index 579d9445..c5173509 100644 --- a/src/FluxFlow.Composition/ApplicationLinks/CompiledApplicationLink.cs +++ b/src/FluxFlow.Composition/ApplicationLinks/CompiledApplicationLink.cs @@ -5,21 +5,21 @@ namespace FluxFlow.Composition.Links; public sealed class CompiledApplicationLink { - private readonly IFlowCompiledExpression? _compiledCondition; + private readonly Func? _condition; internal CompiledApplicationLink( ApplicationAddress source, ApplicationAddress target, Type messageType, string? conditionExpression, - IFlowCompiledExpression? compiledCondition, + Func? condition, ApplicationLinkDeclarationSide declarationSide) { Source = source; Target = target; MessageType = messageType; ConditionExpression = conditionExpression; - _compiledCondition = compiledCondition; + _condition = condition; DeclarationSide = declarationSide; } @@ -31,14 +31,14 @@ internal CompiledApplicationLink( public string? ConditionExpression { get; } - public bool IsConditional => ConditionExpression is not null; + public bool IsConditional => _condition is not null; public ApplicationLinkDeclarationSide DeclarationSide { get; } public bool IsMatch(FlowMapContext context) { ArgumentNullException.ThrowIfNull(context); - return _compiledCondition?.Evaluate(context) ?? true; + return _condition?.Invoke(context) ?? true; } public bool TryMatch(FlowMapContext context, out Exception? exception) diff --git a/src/FluxFlow.Composition/ApplicationModel/ApplicationDefinition.cs b/src/FluxFlow.Composition/ApplicationModel/ApplicationDefinition.cs index 5bd9bf29..9cda2931 100644 --- a/src/FluxFlow.Composition/ApplicationModel/ApplicationDefinition.cs +++ b/src/FluxFlow.Composition/ApplicationModel/ApplicationDefinition.cs @@ -1,4 +1,6 @@ using System.Text.Json.Serialization; +using FluxFlow.Composition.Authoring; +using FluxFlow.Composition.Links; namespace FluxFlow.Composition.Model; @@ -8,6 +10,21 @@ public sealed class ApplicationDefinition public ApplicationDefinition( IEnumerable>? resources = null, IEnumerable>? workflows = null) + : this( + resources, + workflows, + links: null, + componentDescriptors: null, + applicationResourceContracts: null) + { + } + + internal ApplicationDefinition( + IEnumerable>? resources, + IEnumerable>? workflows, + IEnumerable? links, + IEnumerable? componentDescriptors, + IEnumerable? applicationResourceContracts) { Resources = DefinitionRules.CopyNamed( resources, @@ -17,9 +34,66 @@ public ApplicationDefinition( workflows, nameof(workflows), DefinitionRules.RequireWorkflowName); + Links = CopyLinks(links); + ComponentDescriptors = CopyComponentDescriptors(componentDescriptors); + ApplicationResourceContracts = CopyResourceContracts(applicationResourceContracts); } public IReadOnlyDictionary Resources { get; } public IReadOnlyDictionary Workflows { get; } + + public IReadOnlyList Links { get; } + + public IReadOnlyList ComponentDescriptors { get; } + + public IReadOnlyList ApplicationResourceContracts { get; } + + private static IReadOnlyList CopyLinks( + IEnumerable? links) + { + if (links is null) + return Array.Empty(); + + var values = links.ToArray(); + if (values.Any(static link => link is null)) + throw new ArgumentException("Application links cannot contain null values.", nameof(links)); + return Array.AsReadOnly(values); + } + + private static IReadOnlyList CopyComponentDescriptors( + IEnumerable? descriptors) + { + if (descriptors is null) + return Array.Empty(); + + return new ComponentCatalog(descriptors).Descriptors; + } + + private static IReadOnlyList CopyResourceContracts( + IEnumerable? contracts) + { + if (contracts is null) + return Array.Empty(); + + var values = contracts.ToArray(); + if (values.Any(static contract => contract is null)) + { + throw new ArgumentException( + "Application resource contracts cannot contain null values.", + nameof(contracts)); + } + + var duplicate = values + .GroupBy(static contract => contract.Type, StringComparer.Ordinal) + .FirstOrDefault(static group => group.Skip(1).Any()); + if (duplicate is not null) + { + throw new ArgumentException( + $"Application resource type '{duplicate.Key}' has more than one contract.", + nameof(contracts)); + } + + return Array.AsReadOnly(values); + } } diff --git a/src/FluxFlow.Composition/Authoring/ApplicationDefinitionBuilder.cs b/src/FluxFlow.Composition/Authoring/ApplicationDefinitionBuilder.cs index 97882458..2c6b11f4 100644 --- a/src/FluxFlow.Composition/Authoring/ApplicationDefinitionBuilder.cs +++ b/src/FluxFlow.Composition/Authoring/ApplicationDefinitionBuilder.cs @@ -5,13 +5,15 @@ namespace FluxFlow.Composition.Authoring; public sealed class ApplicationDefinitionBuilder : IResourceDefinitionContainerBuilder { private readonly AuthoringScope _owner = new(); + private readonly ComponentContractCollection _componentContracts = new(); + private readonly ApplicationResourceContractCollection _resourceContracts = new(); private readonly ResourceContainerState _resources; private readonly Dictionary _workflows = new(StringComparer.Ordinal); public ApplicationDefinitionBuilder() { - _resources = new ResourceContainerState(_owner, []); + _resources = new ResourceContainerState(_owner, _resourceContracts, []); } public ResourceGroupBuilder AddResourceGroup(string name) @@ -84,7 +86,7 @@ public WorkflowDefinitionBuilder AddWorkflow(string name) if (_workflows.ContainsKey(name)) throw new ArgumentException($"Application contains duplicate workflow '{name}'.", nameof(name)); - var workflow = new WorkflowDefinitionBuilder(_owner, name); + var workflow = new WorkflowDefinitionBuilder(_owner, _componentContracts, name); _workflows.Add(name, workflow); return workflow; } @@ -97,10 +99,58 @@ public ApplicationDefinitionBuilder AddWorkflow( return this; } + public ApplicationDefinitionBuilder Connect( + OutputPortHandle source, + InputPortHandle target) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(target); + EnsureSameOwner(source); + EnsureSameOwner(target); + source.Workflow.AddConnection(source, target, allowCrossWorkflow: true); + return this; + } + + public THandle AddResource( + string name, + ApplicationResourceContract resource) + where THandle : AuthoredResourceHandle + => _resources.AddResource(name, resource); + + public ApplicationDefinitionBuilder AddResource( + string name, + ApplicationResourceContract resource, + out THandle handle) + where THandle : AuthoredResourceHandle + { + handle = AddResource(name, resource); + return this; + } + + public THandle AddResource( + string name, + ApplicationResourceContract resource, + Action configure) + where TOptions : class + where THandle : AuthoredResourceHandle + => _resources.AddResource(name, resource, configure); + + public ApplicationDefinitionBuilder AddResource( + string name, + ApplicationResourceContract resource, + Action configure, + out THandle handle) + where TOptions : class + where THandle : AuthoredResourceHandle + { + handle = AddResource(name, resource, configure); + return this; + } + public ApplicationDefinitionBuilder Connect( OutputPortHandle source, InputPortHandle target, - string? condition = null) + string condition) { ArgumentNullException.ThrowIfNull(source); ArgumentNullException.ThrowIfNull(target); @@ -110,10 +160,35 @@ public ApplicationDefinitionBuilder Connect( return this; } + public ApplicationDefinitionBuilder Connect( + OutputPortHandle source, + InputPortHandle target, + Func when) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(target); + EnsureSameOwner(source); + EnsureSameOwner(target); + source.Workflow.AddConnection(source, target, when, allowCrossWorkflow: true); + return this; + } + + public ApplicationDefinitionBuilder Connect( + OutputPortHandle source, + SignalInputPortHandle target) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(target); + EnsureSameOwner(source); + EnsureSameOwner(target); + source.Workflow.AddConnection(source, target, allowCrossWorkflow: true); + return this; + } + public ApplicationDefinitionBuilder Connect( OutputPortHandle source, SignalInputPortHandle target, - string? condition = null) + string condition) { ArgumentNullException.ThrowIfNull(source); ArgumentNullException.ThrowIfNull(target); @@ -123,6 +198,19 @@ public ApplicationDefinitionBuilder Connect( return this; } + public ApplicationDefinitionBuilder Connect( + OutputPortHandle source, + SignalInputPortHandle target, + Func when) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(target); + EnsureSameOwner(source); + EnsureSameOwner(target); + source.Workflow.AddConnection(source, target, when, allowCrossWorkflow: true); + return this; + } + public ApplicationDefinition Build() { _owner.EnsureMutable(); @@ -132,7 +220,10 @@ public ApplicationDefinition Build() _workflows.Select(static workflow => new KeyValuePair( workflow.Key, - workflow.Value.Build()))); + workflow.Value.Build())), + _workflows.Values.SelectMany(static workflow => workflow.BuildLinks()), + _componentContracts.Build(), + _resourceContracts.Build()); _owner.Complete(); return definition; diff --git a/src/FluxFlow.Composition/Authoring/ApplicationResourceContract.cs b/src/FluxFlow.Composition/Authoring/ApplicationResourceContract.cs new file mode 100644 index 00000000..169fa193 --- /dev/null +++ b/src/FluxFlow.Composition/Authoring/ApplicationResourceContract.cs @@ -0,0 +1,93 @@ +using FluxFlow.Composition.Model; + +namespace FluxFlow.Composition.Authoring; + +public abstract class ApplicationResourceContract : IApplicationResourceRegistrar +{ + private protected ApplicationResourceContract( + string type, + IApplicationResourceRegistrar registrar) + { + Type = DefinitionRules.RequireType(type, nameof(type)); + Registrar = registrar ?? throw new ArgumentNullException(nameof(registrar)); + } + + public string Type { get; } + + private IApplicationResourceRegistrar Registrar { get; } + + IApplicationResourceRegistrar IApplicationResourceRegistrar.RegistrationIdentity + => Registrar.RegistrationIdentity; + + void IApplicationResourceRegistrar.Register(ApplicationResourceRegistrationContext context) + => Registrar.Register(context); + + public static ApplicationResourceContract Create( + string type, + IApplicationResourceRegistrar registrar, + Func createHandle) + where THandle : AuthoredResourceHandle + => new(type, registrar, createHandle); + + public static ApplicationResourceContract Create( + string type, + IApplicationResourceRegistrar registrar, + Func createOptions, + Action apply, + Func createHandle) + where TOptions : class + where THandle : AuthoredResourceHandle + => new(type, registrar, createOptions, apply, createHandle); +} + +public class ApplicationResourceContract : ApplicationResourceContract + where THandle : AuthoredResourceHandle +{ + private readonly Func _createHandle; + + protected internal ApplicationResourceContract( + string type, + IApplicationResourceRegistrar registrar, + Func createHandle) + : base(type, registrar) + { + _createHandle = createHandle ?? throw new ArgumentNullException(nameof(createHandle)); + } + + internal THandle CreateHandle(ResourceHandle resource) + => _createHandle(resource) ?? throw new InvalidOperationException( + $"Application resource contract '{Type}' returned no handle."); +} + +public class ApplicationResourceContract : ApplicationResourceContract + where TOptions : class + where THandle : AuthoredResourceHandle +{ + private readonly Func _createOptions; + private readonly Action _apply; + private readonly Func _createHandle; + + protected internal ApplicationResourceContract( + string type, + IApplicationResourceRegistrar registrar, + Func createOptions, + Action apply, + Func createHandle) + : base(type, registrar) + { + _createOptions = createOptions ?? throw new ArgumentNullException(nameof(createOptions)); + _apply = apply ?? throw new ArgumentNullException(nameof(apply)); + _createHandle = createHandle ?? throw new ArgumentNullException(nameof(createHandle)); + } + + internal TOptions CreateOptions() + => _createOptions() ?? throw new InvalidOperationException( + $"Application resource contract '{Type}' returned no options builder."); + + internal void Apply(TOptions options, ResourceDefinitionBuilder definition) + => _apply(options, definition); + + internal THandle CreateHandle(ResourceHandle resource) + => _createHandle(resource) ?? throw new InvalidOperationException( + $"Application resource contract '{Type}' returned no handle."); +} diff --git a/src/FluxFlow.Composition/Authoring/ApplicationResourceContractCollection.cs b/src/FluxFlow.Composition/Authoring/ApplicationResourceContractCollection.cs new file mode 100644 index 00000000..1edae80f --- /dev/null +++ b/src/FluxFlow.Composition/Authoring/ApplicationResourceContractCollection.cs @@ -0,0 +1,29 @@ +namespace FluxFlow.Composition.Authoring; + +internal sealed class ApplicationResourceContractCollection +{ + private readonly Dictionary _contracts = + new(StringComparer.Ordinal); + + internal void EnsureCanAdd(ApplicationResourceContract contract) + { + ArgumentNullException.ThrowIfNull(contract); + if (_contracts.TryGetValue(contract.Type, out var existing) && + !ReferenceEquals(existing, contract)) + { + throw new InvalidOperationException( + $"Application resource type '{contract.Type}' has conflicting contracts in the application definition."); + } + } + + internal void Add(ApplicationResourceContract contract) + { + EnsureCanAdd(contract); + _contracts.TryAdd(contract.Type, contract); + } + + internal IReadOnlyList Build() + => _contracts.Values + .OrderBy(static contract => contract.Type, StringComparer.Ordinal) + .ToArray(); +} diff --git a/src/FluxFlow.Composition/Authoring/AuthoringHandles.cs b/src/FluxFlow.Composition/Authoring/AuthoringHandles.cs index a29ea87b..d87bbadd 100644 --- a/src/FluxFlow.Composition/Authoring/AuthoringHandles.cs +++ b/src/FluxFlow.Composition/Authoring/AuthoringHandles.cs @@ -1,4 +1,5 @@ using FluxFlow.Composition.Addressing; +using FluxFlow.Nodes; namespace FluxFlow.Composition.Authoring; @@ -36,6 +37,24 @@ internal ResourceHandle( } } +public abstract class AuthoredResourceHandle +{ + protected AuthoredResourceHandle(ResourceHandle definition) + { + Definition = definition ?? throw new ArgumentNullException(nameof(definition)); + } + + public ResourceHandle Definition { get; } + + public ApplicationAddress Address => Definition.Address; + + public string Name => Definition.Name; + + public string Type => Definition.Type; + + public override string ToString() => Address.Value; +} + public class ComponentHandle { internal ComponentHandle( @@ -160,16 +179,60 @@ internal OutputPortHandle( : base(owner, workflow, address, linkCardinality) { } + + public OutputPortHandle ConnectTo(InputPortHandle target) + { + Workflow.AddConnection(this, target, allowCrossWorkflow: true); + return this; + } + + public OutputPortHandle ConnectTo( + InputPortHandle target, + string condition) + { + Workflow.AddConnection(this, target, condition, allowCrossWorkflow: true); + return this; + } + + public OutputPortHandle ConnectTo( + InputPortHandle target, + Func when) + { + Workflow.AddConnection(this, target, when, allowCrossWorkflow: true); + return this; + } + + public OutputPortHandle ConnectTo(SignalInputPortHandle target) + { + Workflow.AddConnection(this, target, allowCrossWorkflow: true); + return this; + } + + public OutputPortHandle ConnectTo( + SignalInputPortHandle target, + string condition) + { + Workflow.AddConnection(this, target, condition, allowCrossWorkflow: true); + return this; + } + + public OutputPortHandle ConnectTo( + SignalInputPortHandle target, + Func when) + { + Workflow.AddConnection(this, target, when, allowCrossWorkflow: true); + return this; + } } public abstract class AuthoredComponentHandle { - private protected AuthoredComponentHandle(ComponentHandle definition) + protected AuthoredComponentHandle(ComponentHandle definition) { Definition = definition ?? throw new ArgumentNullException(nameof(definition)); } - protected ComponentHandle Definition { get; } + public ComponentHandle Definition { get; } public ApplicationAddress Address => Definition.Address; @@ -185,38 +248,54 @@ public sealed class InputOutputComponentHandle : AuthoredCompon public InputOutputComponentHandle( ComponentHandle definition, string inputName, - string outputName) + string outputName, + string eventsName) : base(definition) { Input = definition.Input(inputName); Output = definition.Output(outputName); + Events = definition.Output(eventsName); } public InputPortHandle Input { get; } public OutputPortHandle Output { get; } + + public OutputPortHandle Events { get; } } public sealed class InputComponentHandle : AuthoredComponentHandle { - public InputComponentHandle(ComponentHandle definition, string inputName) + public InputComponentHandle( + ComponentHandle definition, + string inputName, + string eventsName) : base(definition) { Input = definition.Input(inputName); + Events = definition.Output(eventsName); } public InputPortHandle Input { get; } + + public OutputPortHandle Events { get; } } public sealed class OutputComponentHandle : AuthoredComponentHandle { - public OutputComponentHandle(ComponentHandle definition, string outputName) + public OutputComponentHandle( + ComponentHandle definition, + string outputName, + string eventsName) : base(definition) { Output = definition.Output(outputName); + Events = definition.Output(eventsName); } public OutputPortHandle Output { get; } + + public OutputPortHandle Events { get; } } public sealed class DualInputOutputComponentHandle : AuthoredComponentHandle @@ -225,12 +304,14 @@ public DualInputOutputComponentHandle( ComponentHandle definition, string leftName, string rightName, - string outputName) + string outputName, + string eventsName) : base(definition) { Left = definition.Input(leftName); Right = definition.Input(rightName); Output = definition.Output(outputName); + Events = definition.Output(eventsName); } public InputPortHandle Left { get; } @@ -238,4 +319,6 @@ public DualInputOutputComponentHandle( public InputPortHandle Right { get; } public OutputPortHandle Output { get; } + + public OutputPortHandle Events { get; } } diff --git a/src/FluxFlow.Composition/Authoring/ComponentContract.cs b/src/FluxFlow.Composition/Authoring/ComponentContract.cs new file mode 100644 index 00000000..aa7e4544 --- /dev/null +++ b/src/FluxFlow.Composition/Authoring/ComponentContract.cs @@ -0,0 +1,96 @@ +using FluxFlow.Composition.Model; + +namespace FluxFlow.Composition.Authoring; + +public abstract class ComponentContract +{ + private protected ComponentContract(ComponentDescriptor descriptor) + => Descriptor = descriptor ?? throw new ArgumentNullException(nameof(descriptor)); + + public string Type => Descriptor.Type; + + public ComponentDescriptor Descriptor { get; } + + public static ComponentContract Create( + string type, + Action configureRuntime, + Func createHandle) + where THandle : AuthoredComponentHandle + => new(CreateDescriptor(type, configureRuntime), createHandle); + + public static ComponentContract Create( + string type, + Action configureRuntime, + Func createOptions, + Action apply, + Func createHandle) + where TOptions : class + where THandle : AuthoredComponentHandle + => new( + CreateDescriptor(type, configureRuntime), + createOptions, + apply, + createHandle); + + private static ComponentDescriptor CreateDescriptor( + string type, + Action configureRuntime) + { + ArgumentException.ThrowIfNullOrWhiteSpace(type); + ArgumentNullException.ThrowIfNull(configureRuntime); + + var runtime = new RuntimeComponentRegistrationBuilder(type); + configureRuntime(runtime); + return runtime.CreateDescriptor(); + } +} + +public class ComponentContract : ComponentContract + where THandle : AuthoredComponentHandle +{ + private readonly Func _createHandle; + + protected internal ComponentContract( + ComponentDescriptor descriptor, + Func createHandle) + : base(descriptor) + { + _createHandle = createHandle ?? throw new ArgumentNullException(nameof(createHandle)); + } + + internal THandle CreateHandle(ComponentHandle component) + => _createHandle(component) ?? throw new InvalidOperationException( + $"Component contract '{Type}' returned no handle."); +} + +public class ComponentContract : ComponentContract + where TOptions : class + where THandle : AuthoredComponentHandle +{ + private readonly Func _createOptions; + private readonly Action _apply; + private readonly Func _createHandle; + + protected internal ComponentContract( + ComponentDescriptor descriptor, + Func createOptions, + Action apply, + Func createHandle) + : base(descriptor) + { + _createOptions = createOptions ?? throw new ArgumentNullException(nameof(createOptions)); + _apply = apply ?? throw new ArgumentNullException(nameof(apply)); + _createHandle = createHandle ?? throw new ArgumentNullException(nameof(createHandle)); + } + + internal TOptions CreateOptions() + => _createOptions() ?? throw new InvalidOperationException( + $"Component contract '{Type}' returned no options builder."); + + internal void Apply(TOptions options, ComponentDefinitionBuilder definition) + => _apply(options, definition); + + internal THandle CreateHandle(ComponentHandle component) + => _createHandle(component) ?? throw new InvalidOperationException( + $"Component contract '{Type}' returned no handle."); +} diff --git a/src/FluxFlow.Composition/Authoring/ComponentContractCollection.cs b/src/FluxFlow.Composition/Authoring/ComponentContractCollection.cs new file mode 100644 index 00000000..49c9f171 --- /dev/null +++ b/src/FluxFlow.Composition/Authoring/ComponentContractCollection.cs @@ -0,0 +1,29 @@ +namespace FluxFlow.Composition.Authoring; + +internal sealed class ComponentContractCollection +{ + private readonly Dictionary _descriptors = + new(StringComparer.Ordinal); + + internal void EnsureCanAdd(ComponentDescriptor descriptor) + { + ArgumentNullException.ThrowIfNull(descriptor); + if (_descriptors.TryGetValue(descriptor.Type, out var existing) && + !ReferenceEquals(existing, descriptor)) + { + throw new InvalidOperationException( + $"Component type '{descriptor.Type}' has conflicting contracts in the application definition."); + } + } + + internal void Add(ComponentDescriptor descriptor) + { + EnsureCanAdd(descriptor); + _descriptors.TryAdd(descriptor.Type, descriptor); + } + + internal IReadOnlyList Build() + => _descriptors.Values + .OrderBy(static descriptor => descriptor.Type, StringComparer.Ordinal) + .ToArray(); +} diff --git a/src/FluxFlow.Composition/Authoring/ResourceDefinitionContainerBuilder.cs b/src/FluxFlow.Composition/Authoring/ResourceDefinitionContainerBuilder.cs index 063e591e..4f6e59f8 100644 --- a/src/FluxFlow.Composition/Authoring/ResourceDefinitionContainerBuilder.cs +++ b/src/FluxFlow.Composition/Authoring/ResourceDefinitionContainerBuilder.cs @@ -16,6 +16,18 @@ ResourceHandle AddResource( string name, string type, Action? configure = null); + + THandle AddResource( + string name, + ApplicationResourceContract resource) + where THandle : AuthoredResourceHandle; + + THandle AddResource( + string name, + ApplicationResourceContract resource, + Action configure) + where TOptions : class + where THandle : AuthoredResourceHandle; } internal sealed record ResourceInstanceEntry( @@ -26,11 +38,16 @@ internal sealed class ResourceContainerState { private readonly Dictionary _entries = new(StringComparer.Ordinal); private readonly AuthoringScope _owner; + private readonly ApplicationResourceContractCollection _resourceContracts; private readonly string[] _path; - public ResourceContainerState(AuthoringScope owner, string[] path) + public ResourceContainerState( + AuthoringScope owner, + ApplicationResourceContractCollection resourceContracts, + string[] path) { _owner = owner; + _resourceContracts = resourceContracts; _path = path; } @@ -41,7 +58,7 @@ public ResourceGroupBuilder AddResourceGroup(string name) EnsureAvailable(name); string[] path = [.. _path, name]; - var state = new ResourceContainerState(_owner, path); + var state = new ResourceContainerState(_owner, _resourceContracts, path); var builder = new ResourceGroupBuilder(state); _entries.Add(name, builder); return builder; @@ -71,6 +88,37 @@ public ResourceHandle AddResource( committed.Entry.Type); } + public THandle AddResource( + string name, + ApplicationResourceContract resource) + where THandle : AuthoredResourceHandle + { + ArgumentNullException.ThrowIfNull(resource); + return AddContractResourceCore( + name, + resource, + configure: null, + resource.CreateHandle); + } + + public THandle AddResource( + string name, + ApplicationResourceContract resource, + Action configure) + where TOptions : class + where THandle : AuthoredResourceHandle + { + ArgumentNullException.ThrowIfNull(resource); + ArgumentNullException.ThrowIfNull(configure); + var options = resource.CreateOptions(); + configure(options); + return AddContractResourceCore( + name, + resource, + definition => resource.Apply(options, definition), + resource.CreateHandle); + } + public IReadOnlyDictionary Build() { var definitions = new Dictionary(StringComparer.Ordinal); @@ -109,6 +157,35 @@ public IReadOnlyDictionary Build() return (name, entry); } + private THandle AddContractResourceCore( + string name, + ApplicationResourceContract resource, + Action? configure, + Func createHandle) + where THandle : AuthoredResourceHandle + { + _owner.EnsureMutable(); + name = DefinitionRules.RequireResourceName(name, nameof(name)); + EnsureAvailable(name); + _resourceContracts.EnsureCanAdd(resource); + + var builder = new ResourceDefinitionBuilder(_owner); + configure?.Invoke(builder); + var entry = new ResourceInstanceEntry(resource.Type, builder.Commit()); + _ = new ResourceInstanceDefinition(entry.Type, entry.Properties); + + var definition = new UntypedResourceHandle( + _owner, + ApplicationAddress.Resource([.. _path, name]), + entry.Type); + var handle = createHandle(definition) ?? throw new InvalidOperationException( + $"Application resource '{definition.Address}' returned no authoring handle."); + + _resourceContracts.Add(resource); + _entries.Add(name, entry); + return handle; + } + private void EnsureAvailable(string name) { if (_entries.ContainsKey(name)) @@ -199,5 +276,41 @@ public ResourceGroupBuilder AddResource( return this; } + public THandle AddResource( + string name, + ApplicationResourceContract resource) + where THandle : AuthoredResourceHandle + => _state.AddResource(name, resource); + + public ResourceGroupBuilder AddResource( + string name, + ApplicationResourceContract resource, + out THandle handle) + where THandle : AuthoredResourceHandle + { + handle = AddResource(name, resource); + return this; + } + + public THandle AddResource( + string name, + ApplicationResourceContract resource, + Action configure) + where TOptions : class + where THandle : AuthoredResourceHandle + => _state.AddResource(name, resource, configure); + + public ResourceGroupBuilder AddResource( + string name, + ApplicationResourceContract resource, + Action configure, + out THandle handle) + where TOptions : class + where THandle : AuthoredResourceHandle + { + handle = AddResource(name, resource, configure); + return this; + } + internal IReadOnlyDictionary Build() => _state.Build(); } diff --git a/src/FluxFlow.Composition/Authoring/WorkflowDefinitionBuilder.cs b/src/FluxFlow.Composition/Authoring/WorkflowDefinitionBuilder.cs index 64376c27..fd715c9e 100644 --- a/src/FluxFlow.Composition/Authoring/WorkflowDefinitionBuilder.cs +++ b/src/FluxFlow.Composition/Authoring/WorkflowDefinitionBuilder.cs @@ -8,12 +8,17 @@ namespace FluxFlow.Composition.Authoring; public sealed class WorkflowDefinitionBuilder { private readonly Dictionary _components = new(StringComparer.Ordinal); - private readonly List _connections = []; + private readonly List _connections = []; + private readonly ComponentContractCollection _componentContracts; private readonly AuthoringScope _owner; - internal WorkflowDefinitionBuilder(AuthoringScope owner, string name) + internal WorkflowDefinitionBuilder( + AuthoringScope owner, + ComponentContractCollection componentContracts, + string name) { _owner = owner; + _componentContracts = componentContracts; Name = name; } @@ -24,12 +29,11 @@ public ComponentHandle AddComponent( string type, Action? configure = null) { - var committed = AddComponentCore(name, type, configure); - return new ComponentHandle( - _owner, - this, - ApplicationAddress.WorkflowComponent(Name, committed.Name), - committed.Entry.Type); + return AddComponentCore( + name, + type, + configure, + static component => component); } public WorkflowDefinitionBuilder AddComponent( @@ -57,12 +61,15 @@ public ComponentHandle AddComponent( string type, Action? configure = null) { - var committed = AddComponentCore(name, type, configure); - return new ComponentHandle( - _owner, - this, - ApplicationAddress.WorkflowComponent(Name, committed.Name), - committed.Entry.Type); + return AddComponentCore( + name, + type, + configure, + component => new ComponentHandle( + _owner, + this, + component.Address, + component.Type)); } public WorkflowDefinitionBuilder AddComponent( @@ -74,6 +81,57 @@ public WorkflowDefinitionBuilder AddComponent( return this; } + public THandle AddComponent( + string name, + ComponentContract component) + where THandle : AuthoredComponentHandle + { + ArgumentNullException.ThrowIfNull(component); + return AddComponentCore( + name, + component.Type, + configure: null, + component.CreateHandle, + component.Descriptor); + } + + public WorkflowDefinitionBuilder AddComponent( + string name, + ComponentContract component, + out THandle handle) + where THandle : AuthoredComponentHandle + { + handle = AddComponent(name, component); + return this; + } + + public THandle AddComponent( + string name, + ComponentContract component, + Action configure) + where TOptions : class + where THandle : AuthoredComponentHandle + { + ArgumentNullException.ThrowIfNull(component); + ArgumentNullException.ThrowIfNull(configure); + return AddConfiguredComponentCore( + name, + component, + configure); + } + + public WorkflowDefinitionBuilder AddComponent( + string name, + ComponentContract component, + Action configure, + out THandle handle) + where TOptions : class + where THandle : AuthoredComponentHandle + { + handle = AddComponent(name, component, configure); + return this; + } + public WorkflowDefinitionBuilder AddComponent( string name, string type, @@ -85,33 +143,60 @@ public WorkflowDefinitionBuilder AddComponent( return this; } + public WorkflowDefinitionBuilder Connect( + OutputPortHandle source, + InputPortHandle target) + { + AddConnection(source, target, allowCrossWorkflow: false); + return this; + } + public WorkflowDefinitionBuilder Connect( OutputPortHandle source, InputPortHandle target, - string? condition = null) + string condition) { AddConnection(source, target, condition, allowCrossWorkflow: false); return this; } + public WorkflowDefinitionBuilder Connect( + OutputPortHandle source, + InputPortHandle target, + Func when) + { + AddConnection(source, target, when, allowCrossWorkflow: false); + return this; + } + + public WorkflowDefinitionBuilder Connect( + OutputPortHandle source, + SignalInputPortHandle target) + { + AddConnection(source, target, allowCrossWorkflow: false); + return this; + } + public WorkflowDefinitionBuilder Connect( OutputPortHandle source, SignalInputPortHandle target, - string? condition = null) + string condition) { AddConnection(source, target, condition, allowCrossWorkflow: false); return this; } - internal WorkflowDefinition Build() + public WorkflowDefinitionBuilder Connect( + OutputPortHandle source, + SignalInputPortHandle target, + Func when) { - var linkProperties = _connections - .GroupBy(static connection => connection.DeclaredPort) - .ToDictionary( - static group => group.Key, - static group => ApplicationLinkCompiler.SerializeDeclarations(group), - ApplicationAddressEqualityComparer.Instance); + AddConnection(source, target, when, allowCrossWorkflow: false); + return this; + } + internal WorkflowDefinition Build() + { var definitions = new Dictionary(StringComparer.Ordinal); foreach (var (componentName, entry) in _components) { @@ -120,28 +205,68 @@ internal WorkflowDefinition Build() static property => property.Value.Clone(), StringComparer.Ordinal); - foreach (var (port, links) in linkProperties.Where(pair => - string.Equals(pair.Key.Segments[0], Name, StringComparison.Ordinal) && - string.Equals(pair.Key.Segments[1], componentName, StringComparison.Ordinal))) - { - var portName = port.Segments[2]; - if (!properties.TryAdd(portName, links)) - { - throw new InvalidOperationException( - $"Component '{Name}.{componentName}' configures port '{portName}' both as a raw property and through Connect()."); - } - } - definitions.Add(componentName, new ComponentDefinition(entry.Type, properties)); } return new WorkflowDefinition(definitions); } - internal void AddConnection( + internal IReadOnlyList BuildLinks() => _connections.ToArray(); + + internal void AddConnection( + OutputPortHandle source, + PortHandle target, + bool allowCrossWorkflow) + => AddConnectionCore( + source, + target, + ApplicationLinkDefinition.Unconditional( + source.Address, + target.Address, + ApplicationLinkDeclarationSide.Output), + allowCrossWorkflow); + + internal void AddConnection( + OutputPortHandle source, + PortHandle target, + string condition, + bool allowCrossWorkflow) + { + if (string.IsNullOrWhiteSpace(condition)) + throw new ArgumentException("Link condition cannot be empty or whitespace.", nameof(condition)); + AddConnectionCore( + source, + target, + ApplicationLinkDefinition.Expression( + source.Address, + target.Address, + condition, + ApplicationLinkDeclarationSide.Output), + allowCrossWorkflow); + } + + internal void AddConnection( + OutputPortHandle source, + PortHandle target, + Func when, + bool allowCrossWorkflow) + { + ArgumentNullException.ThrowIfNull(when); + AddConnectionCore( + source, + target, + ApplicationLinkDefinition.Predicate( + source.Address, + target.Address, + when, + ApplicationLinkDeclarationSide.Output), + allowCrossWorkflow); + } + + private void AddConnectionCore( PortHandle source, PortHandle target, - string? condition, + ApplicationLinkDefinition connection, bool allowCrossWorkflow) { _owner.EnsureMutable(); @@ -163,16 +288,8 @@ internal void AddConnection( "Use ApplicationDefinitionBuilder.Connect for cross-workflow connections."); } - var connection = new ApplicationLinkDeclarationProjection( - source.Address, - target.Address, - condition, - ApplicationLinkDeclarationSide.Output); - if (_connections.Any(existing => - existing.Source == connection.Source && - existing.Target == connection.Target && - string.Equals(existing.ConditionExpression, connection.ConditionExpression, StringComparison.Ordinal))) + existing.Equals(connection))) { throw new InvalidOperationException( $"Connection '{source.Address}' to '{target.Address}' is already declared."); @@ -195,24 +312,78 @@ internal void AddConnection( _connections.Add(connection); } - private (string Name, ComponentEntry Entry) AddComponentCore( + private THandle AddComponentCore( string name, string type, - Action? configure) + Action? configure, + Func createHandle, + ComponentDescriptor? descriptor = null) + where THandle : class + { + var component = PrepareComponent(name, type); + if (descriptor is not null) + _componentContracts.EnsureCanAdd(descriptor); + return CommitComponent( + component.Name, + component.Type, + configure, + createHandle, + descriptor); + } + + private THandle AddConfiguredComponentCore( + string name, + ComponentContract component, + Action configure) + where TOptions : class + where THandle : AuthoredComponentHandle + { + var prepared = PrepareComponent(name, component.Type); + _componentContracts.EnsureCanAdd(component.Descriptor); + var options = component.CreateOptions(); + configure(options); + return CommitComponent( + prepared.Name, + prepared.Type, + definition => component.Apply(options, definition), + component.CreateHandle, + component.Descriptor); + } + + private (string Name, string Type) PrepareComponent(string name, string type) { _owner.EnsureMutable(); name = DefinitionRules.RequireSegment(name, nameof(name), "Component name"); type = DefinitionRules.RequireType(type, nameof(type)); if (_components.ContainsKey(name)) throw new ArgumentException($"Workflow '{Name}' contains duplicate component '{name}'.", nameof(name)); + return (name, type); + } + private THandle CommitComponent( + string name, + string type, + Action? configure, + Func createHandle, + ComponentDescriptor? descriptor = null) + where THandle : class + { var builder = new ComponentDefinitionBuilder(_owner); configure?.Invoke(builder); var entry = new ComponentEntry(type, builder.Commit()); _ = new ComponentDefinition(entry.Type, entry.Properties); + var component = new ComponentHandle( + _owner, + this, + ApplicationAddress.WorkflowComponent(Name, name), + entry.Type); + var handle = createHandle(component) ?? throw new InvalidOperationException( + $"Component '{Name}.{name}' returned no authoring handle."); + if (descriptor is not null) + _componentContracts.Add(descriptor); _components.Add(name, entry); - return (name, entry); + return handle; } private void EnsureSameOwner(PortHandle port) @@ -228,12 +399,4 @@ private sealed record ComponentEntry( string Type, IReadOnlyDictionary Properties); - private sealed class ApplicationAddressEqualityComparer : IEqualityComparer - { - public static ApplicationAddressEqualityComparer Instance { get; } = new(); - - public bool Equals(ApplicationAddress? x, ApplicationAddress? y) => x == y; - - public int GetHashCode(ApplicationAddress obj) => obj.GetHashCode(); - } } diff --git a/src/FluxFlow.Composition/DependencyInjection/FluxFlowServiceCollectionExtensions.cs b/src/FluxFlow.Composition/DependencyInjection/FluxFlowServiceCollectionExtensions.cs index 563cbe92..eaabf975 100644 --- a/src/FluxFlow.Composition/DependencyInjection/FluxFlowServiceCollectionExtensions.cs +++ b/src/FluxFlow.Composition/DependencyInjection/FluxFlowServiceCollectionExtensions.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks.Dataflow; using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; using FluxFlow.Nodes; using Microsoft.Extensions.DependencyInjection; @@ -7,6 +8,16 @@ namespace FluxFlow.Composition.DependencyInjection; public static class FluxFlowServiceCollectionExtensions { + public static IServiceCollection AddFluxFlowResource( + this IServiceCollection services, + ResourceHandle resource, + Func factory) + where TService : class + { + ArgumentNullException.ThrowIfNull(resource); + return services.AddFluxFlowResource(resource.Address, factory); + } + public static IServiceCollection AddFluxFlowResource( this IServiceCollection services, ApplicationAddress address, @@ -22,6 +33,16 @@ public static IServiceCollection AddFluxFlowResource( return services; } + public static IServiceCollection AddExternalFluxFlowResource( + this IServiceCollection services, + ResourceHandle resource, + TService service) + where TService : class + { + ArgumentNullException.ThrowIfNull(resource); + return services.AddExternalFluxFlowResource(resource.Address, service); + } + public static IServiceCollection AddExternalFluxFlowResource( this IServiceCollection services, ApplicationAddress address, diff --git a/src/FluxFlow.Composition/Factories/ComponentCatalog.cs b/src/FluxFlow.Composition/Factories/ComponentCatalog.cs index c18e7ebd..1f4af2a7 100644 --- a/src/FluxFlow.Composition/Factories/ComponentCatalog.cs +++ b/src/FluxFlow.Composition/Factories/ComponentCatalog.cs @@ -45,4 +45,19 @@ public bool TryGetDescriptor(string type, out ComponentDescriptor descriptor) ArgumentException.ThrowIfNullOrWhiteSpace(type); return _components.TryGetValue(type.Trim(), out descriptor!); } + + public ComponentCatalog Merge(IEnumerable descriptors) + { + ArgumentNullException.ThrowIfNull(descriptors); + var additions = descriptors.ToArray(); + if (additions.All(descriptor => + descriptor is not null && + _components.TryGetValue(descriptor.Type, out var existing) && + ReferenceEquals(existing, descriptor))) + { + return this; + } + + return new ComponentCatalog(Descriptors.Concat(additions)); + } } diff --git a/src/FluxFlow.Composition/Factories/ComponentDescriptor.cs b/src/FluxFlow.Composition/Factories/ComponentDescriptor.cs index 274df6e3..8f349dab 100644 --- a/src/FluxFlow.Composition/Factories/ComponentDescriptor.cs +++ b/src/FluxFlow.Composition/Factories/ComponentDescriptor.cs @@ -13,9 +13,37 @@ public ComponentDescriptor( CompositionProcessingCapabilities.Sequential, IEnumerable? options = null, IEnumerable? resources = null) + : this( + type, + factory, + factory, + ComponentFactoryMode.Instance, + registrationBindings: [], + inputs, + outputs, + processingCapabilities, + options, + resources) + { + } + + internal ComponentDescriptor( + string type, + ComponentFactory factory, + Delegate registrationFactory, + ComponentFactoryMode factoryMode, + IReadOnlyList registrationBindings, + IEnumerable? inputs = null, + IEnumerable? outputs = null, + CompositionProcessingCapabilities processingCapabilities = + CompositionProcessingCapabilities.Sequential, + IEnumerable? options = null, + IEnumerable? resources = null) { ArgumentException.ThrowIfNullOrWhiteSpace(type); ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(registrationFactory); + ArgumentNullException.ThrowIfNull(registrationBindings); Type = type.Trim(); ProcessingCapabilities = processingCapabilities; @@ -24,26 +52,38 @@ public ComponentDescriptor( .ToFrozenDictionary(StringComparer.Ordinal); Resources = ToMetadataDictionary(resources, static resource => resource.Name, nameof(resources)) .ToFrozenDictionary(StringComparer.Ordinal); - var registeredOutputs = ToPortDictionary(outputs); - if (!registeredOutputs.TryAdd( - ComponentEvents.PortName, - ComponentPorts.Metadata( - ComponentEvents.PortName))) - { - throw new ArgumentException( - $"Output port '{ComponentEvents.PortName}' is reserved for component events.", - nameof(outputs)); - } - - Outputs = registeredOutputs.ToFrozenDictionary(StringComparer.Ordinal); - RegistrationFactory = factory; + Outputs = ToPortDictionary(outputs).ToFrozenDictionary(StringComparer.Ordinal); + RegistrationFactory = registrationFactory; + RegistrationFactoryMode = factoryMode; + RegistrationBindings = registrationBindings.ToArray(); Factory = async context => { context.ConfigureProcessing(ProcessingCapabilities); var component = await factory(context).ConfigureAwait(false); - if (component is not null) + if (component is null) + return null!; + + try + { component.AttachAddressableEvents(context.WorkflowName, context.ComponentName); - return component!; + return component; + } + catch (Exception activationFailure) + { + try + { + await component.DisposeAsync().ConfigureAwait(false); + } + catch (Exception cleanupFailure) + { + throw new AggregateException( + $"Component type '{Type}' event attachment and cleanup failed.", + activationFailure, + cleanupFailure); + } + + throw; + } }; } @@ -51,7 +91,11 @@ public ComponentDescriptor( public ComponentFactory Factory { get; } - internal ComponentFactory RegistrationFactory { get; } + internal Delegate RegistrationFactory { get; } + + internal ComponentFactoryMode RegistrationFactoryMode { get; } + + internal IReadOnlyList RegistrationBindings { get; } public IReadOnlyDictionary Inputs { get; } diff --git a/src/FluxFlow.Composition/Factories/ComponentNodeActivation.cs b/src/FluxFlow.Composition/Factories/ComponentNodeActivation.cs new file mode 100644 index 00000000..f8d4a48f --- /dev/null +++ b/src/FluxFlow.Composition/Factories/ComponentNodeActivation.cs @@ -0,0 +1,23 @@ +using FluxFlow.Nodes; + +namespace FluxFlow.Composition; + +public sealed record ComponentNodeActivation + where TNode : IFlowNode +{ + public ComponentNodeActivation( + TNode node, + Task? completion = null, + Func? disposeAsync = null) + { + Node = node ?? throw new ArgumentNullException(nameof(node)); + Completion = completion; + DisposeAsync = disposeAsync; + } + + public TNode Node { get; } + + public Task? Completion { get; } + + public Func? DisposeAsync { get; } +} diff --git a/src/FluxFlow.Composition/README.md b/src/FluxFlow.Composition/README.md index 685ea404..bcff0b27 100644 --- a/src/FluxFlow.Composition/README.md +++ b/src/FluxFlow.Composition/README.md @@ -29,36 +29,66 @@ Ordinary data-processing cycles are rejected. ## Code-First Authoring -The canonical builders support either direct handle capture or chain-first -capture without introducing another model: +JSON/configuration and compiled C# are independent authoring sources. They +converge at normalization, validation, link compilation, and runtime execution; +the C# builder does not serialize or round-trip through JSON. + +Create workflow scopes either by return value or by flat fluent capture: ```csharp var application = new ApplicationDefinitionBuilder() - .AddResourceGroup("Messaging", out var messaging) - .AddWorkflow("Orders", out var orders); - -messaging.AddResource("Client", "host.external", out var client); + .AddWorkflow("Orders", out var orders) + .AddWorkflow("Audit", out var audit); orders - .AddComponent("Source", "orders.source", out var source) - .AddComponent("Sink", "orders.sink", out var sink) - .Connect( - source.Output("Output"), - sink.Input("Input")); + .AddComponent("Source", OrderComponents.Source, out var source) + .AddComponent("Review", OrderComponents.Review, out var review) + .AddComponent("Priority", OrderComponents.Sink, out var priority) + .AddComponent("Standard", OrderComponents.Sink, out var standard); + +audit.AddComponent("Events", OrderComponents.EventCollector, out var events); + +source.Output.ConnectTo(review.Input); +review.Output + .ConnectTo(priority.Input, when: static order => order.Priority) + .ConnectTo(standard.Input, when: static order => !order.Priority); +review.Events.ConnectTo(events.Input); var definition = application.Build(); +services.AddFluxFlow(definition); ``` -Each fluent add delegates to the corresponding handle-returning method, -captures the committed typed handle, and returns the same parent builder. -Handles remain ordinary definition references. Component order does not imply -topology: links stay explicit, workflow links stay local, resource groups stay -resource-only, and `Build()` returns and freezes the same immutable -`ApplicationDefinition` used by JSON configuration. +`ComponentContract` and `ComponentContract` hold one +complete declaration: canonical type, runtime factory and bindings, typed +handle, and optional component-specific options factory/apply delegate. Contract +construction creates one immutable descriptor but performs no reflection, +scanning, service resolution, or runtime activation. Official packages expose +contracts through `Components` classes, and their retained `AddX` +methods delegate to the same core. Typed handles expose named ports, including +explicit `Events` outputs. + +`ConnectTo` returns the same output handle for fan-out. Workflow `Connect` is +local; application `Connect` and direct `ConnectTo` support same-owner +cross-workflow links. Conditions may be portable expression strings or +synchronous `Func` predicates. Predicates are definition/revision-owned, +require no expression engine, skip error messages, and isolate exceptions to +the affected route. + +`Build()` freezes the graph and returns a directly hostable in-memory +`ApplicationDefinition` that owns the exact runtime descriptors introduced by +its complete component contracts and the exact executable registrars introduced +by its application resource contracts. `services.AddFluxFlow(definition)` +therefore needs no duplicate component or resource-family registration. The +UI/designer remains JSON-only, and C# export or serialization is intentionally +not part of this API. See +`docs/39-typed-code-first-authoring.md` for custom contracts, condition and +revision semantics, and migration guidance. `ApplicationLinkCompiler` owns parsing, address resolution, validation, -normalization, and deterministic ordering. Its result exposes executable -`Links` plus resolved `Declarations` for persistence. Serialize edited +normalization, and deterministic ordering for both sources. Its result exposes +executable `Links` plus resolved portable `Declarations` for JSON persistence. +Code predicates remain executable in-memory links and are not persistence +projections. Serialize edited `ApplicationLinkDeclarationProjection` values with `ApplicationLinkCompiler.SerializeDeclarations(...)` so hosts and Designer use the same exact `Port` / `Condition` grammar. Composition grants no production @@ -66,27 +96,52 @@ friend access to Designer or Engine. `ComponentDescriptor` declares one canonical type, typed `FlowMessage` ports, link cardinality, processing capabilities, and an -activation delegate. Author runtime-only descriptors through the flat -`AddRuntimeComponent(...)` callback. -DI builds one immutable `ComponentCatalog`; application validation, link -compilation, Engine activation, and Designer metadata all consume that catalog. +activation delegate. For a JSON or low-level string definition, explicitly +register a reusable contract with `AddComponent(contract)`. Author a dynamic +runtime-only descriptor through the explicit +`AddFluxFlowComponents().Advanced.AddDynamicComponent(...)` escape hatch. +Engine builds one effective immutable `ComponentCatalog` per candidate from +host registrations plus definition-owned descriptors; application validation, +link compilation, activation, and Designer metadata consume the same descriptor +facts. Errors travel on normal outputs. Application revisions own component and link lifecycle but do not own external resources supplied by the host. ```csharp -services.AddFluxFlowComponents().AddRuntimeComponent( - "orders.handle", - component => +services.AddFluxFlowComponents() + .Advanced + .AddDynamicComponent("orders.handle", component => { - component.UseFactory(CreateHandlerAsync); - component.AddInput("Input"); - component.AddOutput("Output"); + component + .UseFactory(CreateHandler) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); }); ``` +This is the advanced/dynamic path, not an additional step after typed +`AddComponent(name, contract, ...)` authoring. `UseFactory` accepts synchronous +node factories and asynchronous `ValueTask` +node factories. Its typed builder makes each port declaration authoritative for +both descriptor metadata and the activated Dataflow binding. Selectors run only +after activation. `HasInput`, `HasSignalInput`, `HasOutput`, and `HasEvents` +describe existing node members; they do not create duplicate Dataflow ports. +`HasEvents(name, selector)` explicitly bridges the selected +`FlowEvent` source to a public `ComponentEvent` output; event ports are never +injected, and `Events` is not reserved. Advanced complete-instance factories +use `UseInstanceFactory`, while `ComponentNodeActivation` carries the +small optional completion/additional-cleanup case without duplicating ports. + Composition adapters that materialize application resources implement `IApplicationResourceRegistrar`. Its context exposes the complete definition, revision identity, host services, and revision-owned `IServiceCollection`. +`ApplicationResourceContract` and +`ApplicationResourceContract` pair one portable resource type, +typed handle, explicit options projection, and registrar. Contracts are kept in +`ApplicationDefinition.ApplicationResourceContracts` for compiled C# only and +are excluded from canonical JSON. Exact contract/registrar reuse deduplicates; +different contracts for one type fail atomically before activation. Canonical keyed DI helpers live in `FluxFlow.Composition.DependencyInjection`; Engine consumes these low-level contracts without making adapters depend on a hosting package. diff --git a/src/FluxFlow.Composition/Registration/FluxFlowRegistrationBuilder.cs b/src/FluxFlow.Composition/Registration/FluxFlowRegistrationBuilder.cs index 0e680c58..583486ab 100644 --- a/src/FluxFlow.Composition/Registration/FluxFlowRegistrationBuilder.cs +++ b/src/FluxFlow.Composition/Registration/FluxFlowRegistrationBuilder.cs @@ -10,4 +10,31 @@ internal FluxFlowRegistrationBuilder(IServiceCollection services) } public IServiceCollection Services { get; } + + public AdvancedFluxFlowRegistrationBuilder Advanced => new(Services); +} + +public sealed class AdvancedFluxFlowRegistrationBuilder +{ + internal AdvancedFluxFlowRegistrationBuilder(IServiceCollection services) + { + Services = services ?? throw new ArgumentNullException(nameof(services)); + } + + internal IServiceCollection Services { get; } + + public AdvancedFluxFlowRegistrationBuilder AddDynamicComponent( + string type, + Action configure) + { + ArgumentException.ThrowIfNullOrWhiteSpace(type); + ArgumentNullException.ThrowIfNull(configure); + + var component = new RuntimeComponentRegistrationBuilder(type); + configure(component); + FluxFlowRegistrationExtensions.RegisterDescriptor( + Services, + component.CreateDescriptor()); + return this; + } } diff --git a/src/FluxFlow.Composition/Registration/FluxFlowRegistrationExtensions.cs b/src/FluxFlow.Composition/Registration/FluxFlowRegistrationExtensions.cs index 6ad694cb..9d204144 100644 --- a/src/FluxFlow.Composition/Registration/FluxFlowRegistrationExtensions.cs +++ b/src/FluxFlow.Composition/Registration/FluxFlowRegistrationExtensions.cs @@ -1,3 +1,4 @@ +using FluxFlow.Composition.Authoring; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -13,24 +14,23 @@ public static FluxFlowRegistrationBuilder AddFluxFlowComponents( return new FluxFlowRegistrationBuilder(services); } - public static FluxFlowRegistrationBuilder AddRuntimeComponent( + public static FluxFlowRegistrationBuilder AddComponent( this FluxFlowRegistrationBuilder builder, - string type, - Action configure) + ComponentContract component) { ArgumentNullException.ThrowIfNull(builder); - ArgumentException.ThrowIfNullOrWhiteSpace(type); - ArgumentNullException.ThrowIfNull(configure); - - var component = new RuntimeComponentRegistrationBuilder(type); - configure(component); - RegisterDescriptor(builder.Services, component.CreateDescriptor()); + ArgumentNullException.ThrowIfNull(component); + RegisterDescriptor( + builder.Services, + component.Descriptor, + requireReferenceMatch: true); return builder; } internal static ComponentDescriptor RegisterDescriptor( IServiceCollection services, - ComponentDescriptor descriptor) + ComponentDescriptor descriptor, + bool requireReferenceMatch = false) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(descriptor); @@ -46,8 +46,11 @@ internal static ComponentDescriptor RegisterDescriptor( if (existing is not null) { - if (ComponentDescriptorsMatch(existing, descriptor)) + if (ReferenceEquals(existing, descriptor) || + (!requireReferenceMatch && ComponentDescriptorsMatch(existing, descriptor))) + { return existing; + } throw new InvalidOperationException( $"Component type '{descriptor.Type}' has a conflicting descriptor registration."); @@ -67,12 +70,36 @@ private static bool ComponentDescriptorsMatch( ComponentDescriptor right) => string.Equals(left.Type, right.Type, StringComparison.Ordinal) && Equals(left.RegistrationFactory, right.RegistrationFactory) && + left.RegistrationFactoryMode == right.RegistrationFactoryMode && + BindingsMatch(left.RegistrationBindings, right.RegistrationBindings) && left.ProcessingCapabilities == right.ProcessingCapabilities && DictionariesMatch(left.Inputs, right.Inputs, PortsMatch) && DictionariesMatch(left.Outputs, right.Outputs, PortsMatch) && DictionariesMatch(left.Options, right.Options, OptionsMatch) && DictionariesMatch(left.Resources, right.Resources, ResourcesMatch); + private static bool BindingsMatch( + IReadOnlyList left, + IReadOnlyList right) + { + if (left.Count != right.Count) + return false; + + for (var index = 0; index < left.Count; index++) + { + var leftBinding = left[index]; + var rightBinding = right[index]; + if (leftBinding.Role != rightBinding.Role || + !PortsMatch(leftBinding.Metadata, rightBinding.Metadata) || + !Equals(leftBinding.Selector, rightBinding.Selector)) + { + return false; + } + } + + return true; + } + private static bool DictionariesMatch( IReadOnlyDictionary left, IReadOnlyDictionary right, diff --git a/src/FluxFlow.Composition/Registration/RuntimeComponentBindingBuilder.cs b/src/FluxFlow.Composition/Registration/RuntimeComponentBindingBuilder.cs new file mode 100644 index 00000000..5be9aa36 --- /dev/null +++ b/src/FluxFlow.Composition/Registration/RuntimeComponentBindingBuilder.cs @@ -0,0 +1,197 @@ +using System.Threading.Tasks.Dataflow; +using FluxFlow.Nodes; + +namespace FluxFlow.Composition; + +public sealed class RuntimeComponentBindingBuilder + where TNode : IFlowNode +{ + private readonly RuntimeComponentRegistrationBuilder _component; + + internal RuntimeComponentBindingBuilder(RuntimeComponentRegistrationBuilder component) + => _component = component ?? throw new ArgumentNullException(nameof(component)); + + public RuntimeComponentBindingBuilder HasInput( + string name, + Func>> selector, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _component.AddInput(name, selector, linkCardinality); + return this; + } + + public RuntimeComponentBindingBuilder HasSignalInput( + string name, + Func selector, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _component.AddSignalInput(name, selector, linkCardinality); + return this; + } + + public RuntimeComponentBindingBuilder HasOutput( + string name, + Func>> selector, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _component.AddOutput(name, selector, linkCardinality); + return this; + } + + public RuntimeComponentBindingBuilder HasEvents( + string name, + Func> selector, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _component.AddEvents(name, selector, linkCardinality); + return this; + } +} + +public sealed class RuntimeComponentInstanceBindingBuilder +{ + private readonly RuntimeComponentRegistrationBuilder _component; + + internal RuntimeComponentInstanceBindingBuilder(RuntimeComponentRegistrationBuilder component) + => _component = component ?? throw new ArgumentNullException(nameof(component)); + + public RuntimeComponentInstanceBindingBuilder HasInput( + string name, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _component.AddInstanceInput(name, linkCardinality); + return this; + } + + public RuntimeComponentInstanceBindingBuilder HasSignalInput( + string name, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _component.AddInstanceSignalInput(name, linkCardinality); + return this; + } + + public RuntimeComponentInstanceBindingBuilder HasOutput( + string name, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _component.AddInstanceOutput(name, linkCardinality); + return this; + } + + public RuntimeComponentInstanceBindingBuilder HasEvents( + string name, + ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) + { + _component.AddInstanceEvents(name, linkCardinality); + return this; + } +} + +internal enum ComponentBindingRole +{ + Input, + SignalInput, + Output, + Events +} + +internal sealed record ComponentBindingIdentity( + ComponentBindingRole Role, + ComponentPortMetadata Metadata, + Delegate? Selector); + +internal abstract class ComponentBinding +{ + protected ComponentBinding(ComponentBindingIdentity identity) + => Identity = identity ?? throw new ArgumentNullException(nameof(identity)); + + internal ComponentBindingIdentity Identity { get; } + + internal abstract void Bind( + IFlowNode node, + string componentType, + ICollection inputs, + ICollection outputs, + ICollection events); + + protected static TBinding RequireBinding( + TBinding? binding, + string componentType, + string portName) + where TBinding : class + => binding ?? throw new InvalidOperationException( + $"Component type '{componentType}' selector for port '{portName}' returned null."); +} + +internal sealed class ComponentInputBinding( + ComponentBindingIdentity identity, + Func>> selector) + : ComponentBinding(identity) + where TNode : IFlowNode +{ + internal override void Bind( + IFlowNode node, + string componentType, + ICollection inputs, + ICollection outputs, + ICollection events) + { + var target = RequireBinding(selector((TNode)node), componentType, Identity.Metadata.Name); + inputs.Add(ComponentPorts.Input(Identity.Metadata.Name, target)); + } +} + +internal sealed class ComponentSignalInputBinding( + ComponentBindingIdentity identity, + Func selector) + : ComponentBinding(identity) + where TNode : IFlowNode +{ + internal override void Bind( + IFlowNode node, + string componentType, + ICollection inputs, + ICollection outputs, + ICollection events) + { + var target = RequireBinding(selector((TNode)node), componentType, Identity.Metadata.Name); + inputs.Add(ComponentPorts.SignalInput(Identity.Metadata.Name, target)); + } +} + +internal sealed class ComponentOutputBinding( + ComponentBindingIdentity identity, + Func>> selector) + : ComponentBinding(identity) + where TNode : IFlowNode +{ + internal override void Bind( + IFlowNode node, + string componentType, + ICollection inputs, + ICollection outputs, + ICollection events) + { + var source = RequireBinding(selector((TNode)node), componentType, Identity.Metadata.Name); + outputs.Add(ComponentPorts.Output(Identity.Metadata.Name, source)); + } +} + +internal sealed class ComponentEventsBinding( + ComponentBindingIdentity identity, + Func> selector) + : ComponentBinding(identity) + where TNode : IFlowNode +{ + internal override void Bind( + IFlowNode node, + string componentType, + ICollection inputs, + ICollection outputs, + ICollection events) + { + var source = RequireBinding(selector((TNode)node), componentType, Identity.Metadata.Name); + events.Add(ComponentPorts.Events(Identity.Metadata.Name, source)); + } +} diff --git a/src/FluxFlow.Composition/Registration/RuntimeComponentRegistrationBuilder.cs b/src/FluxFlow.Composition/Registration/RuntimeComponentRegistrationBuilder.cs index f06bfdc1..93545acf 100644 --- a/src/FluxFlow.Composition/Registration/RuntimeComponentRegistrationBuilder.cs +++ b/src/FluxFlow.Composition/Registration/RuntimeComponentRegistrationBuilder.cs @@ -1,12 +1,19 @@ +using System.Threading.Tasks.Dataflow; +using FluxFlow.Nodes; + namespace FluxFlow.Composition; public class RuntimeComponentRegistrationBuilder { - private readonly List inputs = []; - private readonly List outputs = []; - private readonly List options = []; - private readonly List resources = []; - private ComponentFactory? factory; + private readonly List _inputs = []; + private readonly List _outputs = []; + private readonly List _options = []; + private readonly List _resources = []; + private readonly List _bindings = []; + private readonly List _bindingIdentities = []; + private Func, ComponentFactory>? _createFactory; + private Delegate? _registrationFactory; + private ComponentFactoryMode _factoryMode; protected internal RuntimeComponentRegistrationBuilder(string type) { @@ -19,8 +26,47 @@ protected internal RuntimeComponentRegistrationBuilder(string type) protected CompositionProcessingCapabilities ProcessingCapabilities { get; private set; } = CompositionProcessingCapabilities.Sequential; - public void UseFactory(ComponentFactory value) - => factory = value ?? throw new ArgumentNullException(nameof(value)); + public RuntimeComponentBindingBuilder UseFactory( + Func value) + where TNode : IFlowNode + { + ArgumentNullException.ThrowIfNull(value); + return UseTypedFactory( + value, + context => ValueTask.FromResult(CreateNodeActivation(value(context)))); + } + + public RuntimeComponentBindingBuilder UseFactory( + Func> value) + where TNode : IFlowNode + { + ArgumentNullException.ThrowIfNull(value); + return UseTypedFactory(value, async context => + CreateNodeActivation(await value(context).ConfigureAwait(false))); + } + + public RuntimeComponentBindingBuilder UseFactory( + Func> value) + where TNode : IFlowNode + { + ArgumentNullException.ThrowIfNull(value); + return UseTypedFactory(value, context => ValueTask.FromResult(value(context))); + } + + public RuntimeComponentBindingBuilder UseFactory( + Func>> value) + where TNode : IFlowNode + { + ArgumentNullException.ThrowIfNull(value); + return UseTypedFactory(value, value); + } + + public RuntimeComponentInstanceBindingBuilder UseInstanceFactory(ComponentFactory value) + { + ArgumentNullException.ThrowIfNull(value); + SetFactory(value, ComponentFactoryMode.Instance, _ => value); + return new RuntimeComponentInstanceBindingBuilder(this); + } public void UseProcessing(CompositionProcessingCapabilities capabilities) { @@ -31,21 +77,6 @@ public void UseProcessing(CompositionProcessingCapabilities capabilities) OnProcessingChanged(capabilities); } - public void AddInput( - string name, - ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) - => AddInput(ComponentPortMetadata.Create(name, linkCardinality)); - - public void AddSignalInput( - string name, - ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) - => AddInput(ComponentPortMetadata.CreateSignal(name, linkCardinality)); - - public void AddOutput( - string name, - ComponentPortLinkCardinality linkCardinality = ComponentPortLinkCardinality.Multiple) - => AddOutput(ComponentPortMetadata.Create(name, linkCardinality)); - public void AddOption(string name, bool isRequired = false) => AddOption(ComponentOptions.Metadata(name, isRequired)); @@ -55,40 +86,58 @@ public void AddResource( string? valueTypeHint = null) => AddResource(ComponentResources.Metadata(name, isRequired, valueTypeHint)); + protected RuntimeComponentBindingBuilder UseTypedFactory( + Delegate registrationFactory, + Func>> activate) + where TNode : IFlowNode + { + ArgumentNullException.ThrowIfNull(registrationFactory); + ArgumentNullException.ThrowIfNull(activate); + SetFactory( + registrationFactory, + ComponentFactoryMode.Node, + bindings => context => ActivateAsync(Type, context, activate, bindings)); + return new RuntimeComponentBindingBuilder(this); + } + + protected RuntimeComponentInstanceBindingBuilder UseAdvancedFactory(ComponentFactory value) + => UseInstanceFactory(value); + protected internal ComponentDescriptor CreateDescriptor() { - if (factory is null) + if (_createFactory is null || _registrationFactory is null) { throw new InvalidOperationException( - $"Component type '{Type}' requires a factory. Call {nameof(UseFactory)} during registration."); + $"Component type '{Type}' requires a factory. Call {nameof(UseFactory)} or {nameof(UseInstanceFactory)} during registration."); } + var bindings = _bindings.ToArray(); return new ComponentDescriptor( Type, - factory, - inputs, - outputs, + _createFactory(bindings), + _registrationFactory, + _factoryMode, + _bindingIdentities.ToArray(), + _inputs, + _outputs, ProcessingCapabilities, - options, - resources); + _options, + _resources); } - protected internal void CopyRuntimeConfigurationTo( - RuntimeComponentRegistrationBuilder target) + protected internal void CopyRuntimeConfigurationTo(RuntimeComponentRegistrationBuilder target) { ArgumentNullException.ThrowIfNull(target); - if (factory is not null) - target.UseFactory(factory); - - target.UseProcessing(ProcessingCapabilities); - foreach (var input in inputs) - target.AddInput(input); - foreach (var output in outputs) - target.AddOutput(output); - foreach (var option in options) - target.AddOption(option); - foreach (var resource in resources) - target.AddResource(resource); + target._createFactory = _createFactory; + target._registrationFactory = _registrationFactory; + target._factoryMode = _factoryMode; + target.ProcessingCapabilities = ProcessingCapabilities; + target._inputs.AddRange(_inputs); + target._outputs.AddRange(_outputs); + target._options.AddRange(_options); + target._resources.AddRange(_resources); + target._bindings.AddRange(_bindings); + target._bindingIdentities.AddRange(_bindingIdentities); } protected virtual void OnProcessingChanged(CompositionProcessingCapabilities capabilities) @@ -111,45 +160,201 @@ protected virtual void OnResourceAdded(ComponentResourceMetadata resource) { } - private void AddInput(ComponentPortMetadata port) + internal void AddInput( + string name, + Func>> selector, + ComponentPortLinkCardinality linkCardinality) + where TNode : IFlowNode { - EnsureUnique(inputs, port.Name, "input port"); - inputs.Add(port); - OnInputAdded(port); + ArgumentNullException.ThrowIfNull(selector); + var metadata = ComponentPortMetadata.Create(name, linkCardinality); + AddInput(metadata); + var identity = new ComponentBindingIdentity(ComponentBindingRole.Input, metadata, selector); + _bindingIdentities.Add(identity); + _bindings.Add(new ComponentInputBinding(identity, selector)); } - private void AddOutput(ComponentPortMetadata port) + internal void AddSignalInput( + string name, + Func selector, + ComponentPortLinkCardinality linkCardinality) + where TNode : IFlowNode { - if (string.Equals(port.Name, ComponentEvents.PortName, StringComparison.Ordinal)) + ArgumentNullException.ThrowIfNull(selector); + var metadata = ComponentPortMetadata.CreateSignal(name, linkCardinality); + AddInput(metadata); + var identity = new ComponentBindingIdentity(ComponentBindingRole.SignalInput, metadata, selector); + _bindingIdentities.Add(identity); + _bindings.Add(new ComponentSignalInputBinding(identity, selector)); + } + + internal void AddOutput( + string name, + Func>> selector, + ComponentPortLinkCardinality linkCardinality) + where TNode : IFlowNode + { + ArgumentNullException.ThrowIfNull(selector); + var metadata = ComponentPortMetadata.Create(name, linkCardinality); + AddOutput(metadata); + var identity = new ComponentBindingIdentity(ComponentBindingRole.Output, metadata, selector); + _bindingIdentities.Add(identity); + _bindings.Add(new ComponentOutputBinding(identity, selector)); + } + + internal void AddEvents( + string name, + Func> selector, + ComponentPortLinkCardinality linkCardinality) + where TNode : IFlowNode + { + ArgumentNullException.ThrowIfNull(selector); + var metadata = ComponentPortMetadata.Create(name, linkCardinality); + AddOutput(metadata); + var identity = new ComponentBindingIdentity(ComponentBindingRole.Events, metadata, selector); + _bindingIdentities.Add(identity); + _bindings.Add(new ComponentEventsBinding(identity, selector)); + } + + internal void AddInstanceInput(string name, ComponentPortLinkCardinality linkCardinality) + => AddInstancePort(ComponentBindingRole.Input, ComponentPortMetadata.Create(name, linkCardinality), input: true); + + internal void AddInstanceSignalInput(string name, ComponentPortLinkCardinality linkCardinality) + => AddInstancePort(ComponentBindingRole.SignalInput, ComponentPortMetadata.CreateSignal(name, linkCardinality), input: true); + + internal void AddInstanceOutput(string name, ComponentPortLinkCardinality linkCardinality) + => AddInstancePort(ComponentBindingRole.Output, ComponentPortMetadata.Create(name, linkCardinality), input: false); + + internal void AddInstanceEvents(string name, ComponentPortLinkCardinality linkCardinality) + => AddInstancePort(ComponentBindingRole.Events, ComponentPortMetadata.Create(name, linkCardinality), input: false); + + private static async ValueTask ActivateAsync( + string componentType, + ComponentActivationContext context, + Func>> activate, + IReadOnlyList bindings) + where TNode : IFlowNode + { + var activation = await activate(context).ConfigureAwait(false) + ?? throw new InvalidOperationException($"Factory for component type '{componentType}' returned null."); + var node = activation.Node + ?? throw new InvalidOperationException($"Factory for component type '{componentType}' returned a null node."); + + try { - throw new ArgumentException( - $"Output port '{ComponentEvents.PortName}' is reserved for component events.", - nameof(port)); + var inputs = new List(); + var outputs = new List(); + var events = new List(); + Bind(ComponentBindingRole.Input); + Bind(ComponentBindingRole.SignalInput); + Bind(ComponentBindingRole.Output); + Bind(ComponentBindingRole.Events); + return ComponentInstance.Create( + node, + inputs, + outputs, + completion: activation.Completion, + disposeAsync: activation.DisposeAsync, + addressableEvents: events); + + void Bind(ComponentBindingRole role) + { + foreach (var binding in bindings) + { + if (binding.Identity.Role == role) + binding.Bind(node, componentType, inputs, outputs, events); + } + } } + catch (Exception activationFailure) + { + try + { + await ComponentInstance.Create( + node, + completion: activation.Completion, + disposeAsync: activation.DisposeAsync) + .DisposeAsync() + .ConfigureAwait(false); + } + catch (Exception cleanupFailure) + { + throw new AggregateException( + $"Component type '{componentType}' activation and cleanup failed.", + activationFailure, + cleanupFailure); + } - EnsureUnique(outputs, port.Name, "output port"); - outputs.Add(port); + throw; + } + } + + private void SetFactory( + Delegate registrationFactory, + ComponentFactoryMode mode, + Func, ComponentFactory> createFactory) + { + if (_createFactory is not null) + { + throw new InvalidOperationException( + $"Component type '{Type}' already has a factory. Configure exactly one factory mode."); + } + + _registrationFactory = registrationFactory; + _factoryMode = mode; + _createFactory = createFactory; + } + + private ComponentNodeActivation CreateNodeActivation(TNode node) + where TNode : IFlowNode + { + if (node is null) + { + throw new InvalidOperationException( + $"Factory for component type '{Type}' returned a null node."); + } + + return new ComponentNodeActivation(node); + } + + private void AddInstancePort(ComponentBindingRole role, ComponentPortMetadata metadata, bool input) + { + if (input) + AddInput(metadata); + else + AddOutput(metadata); + _bindingIdentities.Add(new ComponentBindingIdentity(role, metadata, Selector: null)); + } + + private void AddInput(ComponentPortMetadata port) + { + EnsureUnique(_inputs, port.Name, "input port"); + _inputs.Add(port); + OnInputAdded(port); + } + + private void AddOutput(ComponentPortMetadata port) + { + EnsureUnique(_outputs, port.Name, "output port"); + _outputs.Add(port); OnOutputAdded(port); } private void AddOption(ComponentOptionMetadata option) { - EnsureUnique(options, option.Name, "option"); - options.Add(option); + EnsureUnique(_options, option.Name, "option"); + _options.Add(option); OnOptionAdded(option); } private void AddResource(ComponentResourceMetadata resource) { - EnsureUnique(resources, resource.Name, "resource"); - resources.Add(resource); + EnsureUnique(_resources, resource.Name, "resource"); + _resources.Add(resource); OnResourceAdded(resource); } - private static void EnsureUnique( - IEnumerable items, - string name, - string kind) + private static void EnsureUnique(IEnumerable items, string name, string kind) { var existing = items.Any(item => string.Equals( item switch @@ -166,3 +371,9 @@ private static void EnsureUnique( throw new InvalidOperationException($"Component {kind} '{name}' is already registered."); } } + +internal enum ComponentFactoryMode +{ + Node, + Instance +} diff --git a/src/FluxFlow.Composition/Resources/IApplicationResourceRegistrar.cs b/src/FluxFlow.Composition/Resources/IApplicationResourceRegistrar.cs index 335e7405..f209c67a 100644 --- a/src/FluxFlow.Composition/Resources/IApplicationResourceRegistrar.cs +++ b/src/FluxFlow.Composition/Resources/IApplicationResourceRegistrar.cs @@ -2,5 +2,7 @@ namespace FluxFlow.Composition; public interface IApplicationResourceRegistrar { + IApplicationResourceRegistrar RegistrationIdentity => this; + void Register(ApplicationResourceRegistrationContext context); } diff --git a/src/FluxFlow.Composition/Runtime/ComponentEventSource.cs b/src/FluxFlow.Composition/Runtime/ComponentEventSource.cs new file mode 100644 index 00000000..986ccaa1 --- /dev/null +++ b/src/FluxFlow.Composition/Runtime/ComponentEventSource.cs @@ -0,0 +1,18 @@ +using System.Threading.Tasks.Dataflow; +using FluxFlow.Nodes; + +namespace FluxFlow.Composition; + +public sealed class ComponentEventSource +{ + public ComponentEventSource(string name, ISourceBlock source) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + Name = name.Trim(); + Source = source ?? throw new ArgumentNullException(nameof(source)); + } + + public string Name { get; } + + public ISourceBlock Source { get; } +} diff --git a/src/FluxFlow.Composition/Runtime/ComponentEvents.cs b/src/FluxFlow.Composition/Runtime/ComponentEvents.cs deleted file mode 100644 index 71ba5e64..00000000 --- a/src/FluxFlow.Composition/Runtime/ComponentEvents.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace FluxFlow.Composition; - -public static class ComponentEvents -{ - public const string PortName = "Events"; -} diff --git a/src/FluxFlow.Composition/Runtime/ComponentInstance.cs b/src/FluxFlow.Composition/Runtime/ComponentInstance.cs index 7b4f1ed0..e5c1d002 100644 --- a/src/FluxFlow.Composition/Runtime/ComponentInstance.cs +++ b/src/FluxFlow.Composition/Runtime/ComponentInstance.cs @@ -7,8 +7,10 @@ namespace FluxFlow.Composition; public sealed class ComponentInstance { private readonly Func? _disposeAsync; + private readonly IReadOnlyList _addressableEvents; private readonly Dictionary _outputs; - private ComponentEventBridge? _eventBridge; + private readonly List _eventBridges = []; + private bool _eventsAttached; public ComponentInstance( IFlowNode node, @@ -16,13 +18,15 @@ public ComponentInstance( IEnumerable? outputs = null, ISourceBlock? events = null, Task? completion = null, - Func? disposeAsync = null) + Func? disposeAsync = null, + IEnumerable? addressableEvents = null) { Node = node ?? throw new ArgumentNullException(nameof(node)); Inputs = ToInputDictionary(inputs); _outputs = ToOutputDictionary(outputs); Outputs = _outputs; Events = events; + _addressableEvents = ToEventSources(addressableEvents); Completion = completion ?? node.Completion; _disposeAsync = disposeAsync; } @@ -61,11 +65,11 @@ public async ValueTask DisposeAsync() } } - if (_eventBridge is not null) + foreach (var eventBridge in _eventBridges) { try { - await _eventBridge.DisposeAsync().ConfigureAwait(false); + await eventBridge.DisposeAsync().ConfigureAwait(false); } catch (Exception exception) { @@ -83,22 +87,26 @@ public async ValueTask DisposeAsync() internal void AttachAddressableEvents(string workflowName, string componentName) { - if (_eventBridge is not null) + if (_eventsAttached) throw new InvalidOperationException("Addressable component events are already attached."); - if (_outputs.ContainsKey(ComponentEvents.PortName)) + _eventsAttached = true; + + foreach (var eventSource in _addressableEvents) { - throw new InvalidOperationException( - $"Output port '{ComponentEvents.PortName}' is reserved for component events."); - } + if (_outputs.ContainsKey(eventSource.Name)) + { + throw new InvalidOperationException( + $"Output port '{eventSource.Name}' is already bound and cannot also be used for component events."); + } - _eventBridge = new ComponentEventBridge( - workflowName, - componentName, - Events, - Completion); - _outputs.Add( - ComponentEvents.PortName, - ComponentPorts.Output(ComponentEvents.PortName, _eventBridge.Output)); + var eventBridge = new ComponentEventBridge( + workflowName, + componentName, + eventSource.Source, + Completion); + _eventBridges.Add(eventBridge); + _outputs.Add(eventSource.Name, ComponentPorts.Output(eventSource.Name, eventBridge.Output)); + } } public static ComponentInstance Create( @@ -107,8 +115,9 @@ public static ComponentInstance Create( IEnumerable? outputs = null, ISourceBlock? events = null, Task? completion = null, - Func? disposeAsync = null) - => new(node, inputs, outputs, events, completion, disposeAsync); + Func? disposeAsync = null, + IEnumerable? addressableEvents = null) + => new(node, inputs, outputs, events, completion, disposeAsync, addressableEvents); private static IReadOnlyDictionary ToInputDictionary( IEnumerable? ports) @@ -141,4 +150,23 @@ private static Dictionary ToOutputDictionary( return result; } + + private static IReadOnlyList ToEventSources( + IEnumerable? sources) + { + if (sources is null) + return []; + + var result = new List(); + var names = new HashSet(StringComparer.Ordinal); + foreach (var source in sources) + { + ArgumentNullException.ThrowIfNull(source); + if (!names.Add(source.Name)) + throw new ArgumentException($"Duplicate event port name '{source.Name}'.", nameof(sources)); + result.Add(source); + } + + return result.ToArray(); + } } diff --git a/src/FluxFlow.Composition/Runtime/ComponentPorts.cs b/src/FluxFlow.Composition/Runtime/ComponentPorts.cs index 9d35a1d4..d8e311a1 100644 --- a/src/FluxFlow.Composition/Runtime/ComponentPorts.cs +++ b/src/FluxFlow.Composition/Runtime/ComponentPorts.cs @@ -20,6 +20,11 @@ public static ComponentOutputPort Output( ISourceBlock> source) => new(name, source); + public static ComponentEventSource Events( + string name, + ISourceBlock source) + => new(name, source); + public static ComponentPortMetadata Metadata(string name) => ComponentPortMetadata.Create(name); diff --git a/src/FluxFlow.Engine.DurableInput/DurableApplicationInputs.cs b/src/FluxFlow.Engine.DurableInput/DurableApplicationInputs.cs index b9e5727d..9aa9f99c 100644 --- a/src/FluxFlow.Engine.DurableInput/DurableApplicationInputs.cs +++ b/src/FluxFlow.Engine.DurableInput/DurableApplicationInputs.cs @@ -1,4 +1,5 @@ using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; using FluxFlow.Nodes; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -33,6 +34,15 @@ public ValueTask EnqueueAsync( CancellationToken cancellationToken = default) => EnqueueAsync(ApplicationAddress.Parse(input), message, cancellationToken); + public ValueTask EnqueueAsync( + InputPortHandle input, + FlowMessage message, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + return EnqueueAsync(input.Address, message, cancellationToken); + } + public async ValueTask EnqueueAsync( ApplicationAddress input, FlowMessage message, diff --git a/src/FluxFlow.Engine.DurableOutput/DurableOutputRegistration.cs b/src/FluxFlow.Engine.DurableOutput/DurableOutputRegistration.cs index ef070a94..17ec022c 100644 --- a/src/FluxFlow.Engine.DurableOutput/DurableOutputRegistration.cs +++ b/src/FluxFlow.Engine.DurableOutput/DurableOutputRegistration.cs @@ -1,5 +1,6 @@ using System.Text.Json.Serialization.Metadata; using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; namespace FluxFlow.Engine.DurableOutput; @@ -14,6 +15,15 @@ public DurableOutputRegistrationBuilder Capture( JsonTypeInfo jsonTypeInfo) => Capture(ApplicationAddress.Parse(output), contractName, jsonTypeInfo); + public DurableOutputRegistrationBuilder Capture( + OutputPortHandle output, + string contractName, + JsonTypeInfo jsonTypeInfo) + { + ArgumentNullException.ThrowIfNull(output); + return Capture(output.Address, contractName, jsonTypeInfo); + } + public DurableOutputRegistrationBuilder Capture( ApplicationAddress output, string contractName, diff --git a/src/FluxFlow.Engine.HealthChecks/FluxFlow.Engine.HealthChecks.csproj b/src/FluxFlow.Engine.HealthChecks/FluxFlow.Engine.HealthChecks.csproj new file mode 100644 index 00000000..e9550c90 --- /dev/null +++ b/src/FluxFlow.Engine.HealthChecks/FluxFlow.Engine.HealthChecks.csproj @@ -0,0 +1,34 @@ + + + + net8.0;net10.0 + FluxFlow.Engine.HealthChecks + FluxFlow.Engine.HealthChecks + FluxFlow.Engine.HealthChecks + 1.0.0 + Optional standard .NET readiness health check for FluxFlow application lifecycle and revision state. + workflow;dataflow;health-checks;readiness;hosting;operations + README.md + Adds one idempotent standard readiness check over existing FluxFlow application state with bounded privacy-safe metadata. + https://github.com/araxis/FluxFlow + https://github.com/araxis/FluxFlow + true + + + + + + + + + + + + + + + + + + + diff --git a/src/FluxFlow.Engine.HealthChecks/FluxFlowApplicationHealthCheck.cs b/src/FluxFlow.Engine.HealthChecks/FluxFlowApplicationHealthCheck.cs new file mode 100644 index 00000000..ea068894 --- /dev/null +++ b/src/FluxFlow.Engine.HealthChecks/FluxFlowApplicationHealthCheck.cs @@ -0,0 +1,122 @@ +using Microsoft.Extensions.Diagnostics.HealthChecks; + +namespace FluxFlow.Engine.HealthChecks; + +internal sealed class FluxFlowApplicationHealthCheck(FluxFlowApplication? application) + : IHealthCheck +{ + private const string HealthyDescription = + "An active FluxFlow application revision is available."; + private const string DegradedDescription = + "The active FluxFlow application revision remains available after the latest update was rejected."; + private const string MissingDescription = + "FluxFlow application services are not registered."; + private const string UnavailableDescription = + "The FluxFlow application has no active ready revision."; + private const string StoppedDescription = + "The FluxFlow application is stopped and is not ready."; + + public Task CheckHealthAsync( + HealthCheckContext context, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (application is null) + { + return Task.FromResult(HealthCheckResult.Unhealthy( + MissingDescription, + exception: null, + new Dictionary(StringComparer.Ordinal) + { + ["applicationState"] = "Unavailable" + })); + } + + var stateBefore = application.State; + var currentBefore = application.Current; + var lastUpdateBefore = application.LastUpdate; + var lastUpdateAfter = application.LastUpdate; + var currentAfter = application.Current; + var stateAfter = application.State; + if (stateBefore != stateAfter || + !ReferenceEquals(currentBefore, currentAfter) || + !ReferenceEquals(lastUpdateBefore, lastUpdateAfter)) + { + return Task.FromResult(CreateResult( + stateAfter, + current: null, + lastUpdateAfter)); + } + + return Task.FromResult(CreateResult( + stateAfter, + currentAfter, + lastUpdateAfter)); + } + + internal static HealthCheckResult CreateResult( + ApplicationState state, + ApplicationSnapshot? current, + ApplicationUpdateResult? lastUpdate) + { + var data = CreateData(state, current, lastUpdate); + if (state is ApplicationState.Stopping or ApplicationState.Stopped) + { + return HealthCheckResult.Unhealthy( + StoppedDescription, + exception: null, + data); + } + + if (current is null || + state is not (ApplicationState.Running or ApplicationState.Reloading)) + { + return HealthCheckResult.Unhealthy( + UnavailableDescription, + exception: null, + data); + } + + if (lastUpdate?.Status == ApplicationUpdateStatus.Rejected) + { + return HealthCheckResult.Degraded( + DegradedDescription, + exception: null, + data); + } + + return HealthCheckResult.Healthy(HealthyDescription, data); + } + + private static IReadOnlyDictionary CreateData( + ApplicationState state, + ApplicationSnapshot? current, + ApplicationUpdateResult? lastUpdate) + { + var data = new Dictionary(StringComparer.Ordinal) + { + ["applicationState"] = state.ToString() + }; + + if (current is not null) + { + data["activeRevisionId"] = current.RevisionId; + data["activeSequence"] = current.Sequence; + } + + if (lastUpdate is not null) + { + data["requestedRevisionId"] = lastUpdate.RequestedRevisionId; + data["lastUpdateStatus"] = lastUpdate.Status.ToString(); + var diagnostic = lastUpdate.Diagnostics.LastOrDefault(); + if (diagnostic is not null) + { + data["diagnosticStage"] = diagnostic.Stage.ToString(); + data["diagnosticCode"] = diagnostic.Error.Code; + } + } + + return data; + } +} diff --git a/src/FluxFlow.Engine.HealthChecks/FluxFlowHealthChecksBuilderExtensions.cs b/src/FluxFlow.Engine.HealthChecks/FluxFlowHealthChecksBuilderExtensions.cs new file mode 100644 index 00000000..252caf6e --- /dev/null +++ b/src/FluxFlow.Engine.HealthChecks/FluxFlowHealthChecksBuilderExtensions.cs @@ -0,0 +1,32 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; + +namespace FluxFlow.Engine.HealthChecks; + +public static class FluxFlowHealthChecksBuilderExtensions +{ + public static IHealthChecksBuilder AddFluxFlowApplication( + this IHealthChecksBuilder builder) + { + ArgumentNullException.ThrowIfNull(builder); + + if (builder.Services.Any(static descriptor => + descriptor.ServiceType == + typeof(FluxFlowApplicationHealthCheckRegistrationMarker))) + { + return builder; + } + + builder.Services.AddSingleton( + new FluxFlowApplicationHealthCheckRegistrationMarker()); + builder.Add(new HealthCheckRegistration( + "fluxflow.application", + static provider => new FluxFlowApplicationHealthCheck( + provider.GetService()), + HealthStatus.Unhealthy, + ["fluxflow", "ready"])); + return builder; + } + + private sealed class FluxFlowApplicationHealthCheckRegistrationMarker; +} diff --git a/src/FluxFlow.Engine.HealthChecks/README.md b/src/FluxFlow.Engine.HealthChecks/README.md new file mode 100644 index 00000000..e510faf7 --- /dev/null +++ b/src/FluxFlow.Engine.HealthChecks/README.md @@ -0,0 +1,44 @@ +# FluxFlow.Engine.HealthChecks + +Optional standard .NET readiness integration for a canonical +`FluxFlowApplication`. + +```sh +dotnet add package FluxFlow.Engine.HealthChecks +``` + +```csharp +using FluxFlow.Engine; +using FluxFlow.Engine.HealthChecks; + +services.AddFluxFlow(definition); + +services.AddHealthChecks() + .AddFluxFlowApplication(); +``` + +The idempotent registration adds one check named `fluxflow.application` with +the tags `fluxflow` and `ready`. + +- `Healthy`: a revision is active and usable. +- `Degraded`: the latest update was rejected, but rollback preserved the active + revision. +- `Unhealthy`: FluxFlow is missing, has no active revision, or is stopped. + +The check reads existing in-memory application state only. It adds no worker, +polling, timer, storage query, ASP.NET Core middleware, or endpoint. Result data +is bounded to lifecycle state, revision identity/sequence, update status, and +the final diagnostic stage/code. It never includes payloads, definitions, +addresses, diagnostic messages/details, exceptions, paths, connections, or +secrets. + +ASP.NET Core hosts may expose the standard result using host-owned endpoint +wiring: + +```csharp +app.MapHealthChecks("/health/ready"); +``` + +This package reports application readiness only. Process liveness, durable +backlog thresholds, and external dependency health remain separate operational +decisions. diff --git a/src/FluxFlow.Engine/ApplicationPorts.cs b/src/FluxFlow.Engine/ApplicationPorts.cs index c75ee02a..b0b7fa2d 100644 --- a/src/FluxFlow.Engine/ApplicationPorts.cs +++ b/src/FluxFlow.Engine/ApplicationPorts.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks.Dataflow; using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; using FluxFlow.Engine.Ports; using FluxFlow.Engine.Signals; using FluxFlow.Nodes; @@ -41,6 +42,24 @@ public ValueTask SendAsync( CancellationToken cancellationToken = default) => Runtime.SendAsync(input, message, cancellationToken); + public ValueTask SendAsync( + InputPortHandle input, + FlowMessage message, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + return SendAsync(input.Address, message, cancellationToken); + } + + public ValueTask SendAsync( + SignalInputPortHandle input, + FlowMessage message, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + return SendAsync(input.Address, message, cancellationToken); + } + public Task> ReceiveAsync( string output, TimeSpan? timeout = null, @@ -53,6 +72,15 @@ public Task> ReceiveAsync( CancellationToken cancellationToken = default) => Runtime.ReceiveAsync(output, timeout, cancellationToken); + public Task> ReceiveAsync( + OutputPortHandle output, + TimeSpan? timeout = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(output); + return ReceiveAsync(output.Address, timeout, cancellationToken); + } + public ValueTask> ObserveAsync( string output, int capacity = 128, @@ -65,6 +93,15 @@ public ValueTask> ObserveAsync( CancellationToken cancellationToken = default) => Runtime.ObserveAsync(output, capacity, cancellationToken); + public ValueTask> ObserveAsync( + OutputPortHandle output, + int capacity = 128, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(output); + return ObserveAsync(output.Address, capacity, cancellationToken); + } + public Task> SendAndReceiveAsync( string input, string output, @@ -91,5 +128,22 @@ public Task> SendAndReceiveAsync> SendAndReceiveAsync( + InputPortHandle input, + OutputPortHandle output, + FlowMessage request, + TimeSpan? timeout = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(output); + return SendAndReceiveAsync( + input.Address, + output.Address, + request, + timeout, + cancellationToken); + } + private ApplicationPortRuntime Runtime => _getRuntime(); } diff --git a/src/FluxFlow.Engine/FluxFlowApplication.cs b/src/FluxFlow.Engine/FluxFlowApplication.cs index b606d16a..9efceb9c 100644 --- a/src/FluxFlow.Engine/FluxFlowApplication.cs +++ b/src/FluxFlow.Engine/FluxFlowApplication.cs @@ -452,7 +452,13 @@ await PublishPhaseAsync( private ApplicationUpdateResult Record(ApplicationUpdateResult result) { - Volatile.Write(ref _lastUpdate, result); + var retainedResult = result.Status == ApplicationUpdateStatus.Applied + && result.PreviousRevision is not null + && !ReferenceEquals(result.PreviousRevision, result.ActiveRevision) + ? result with { PreviousRevision = null } + : result; + + Volatile.Write(ref _lastUpdate, retainedResult); if (result.Status != ApplicationUpdateStatus.Rejected) _hasActiveApplication = true; _state = _hasActiveApplication ? ApplicationState.Running : ApplicationState.Degraded; diff --git a/src/FluxFlow.Engine/Hosting/ApplicationRuntimeAssembler.cs b/src/FluxFlow.Engine/Hosting/ApplicationRuntimeAssembler.cs index e85d5ce6..7392e953 100644 --- a/src/FluxFlow.Engine/Hosting/ApplicationRuntimeAssembler.cs +++ b/src/FluxFlow.Engine/Hosting/ApplicationRuntimeAssembler.cs @@ -36,7 +36,6 @@ public ApplicationRuntimeAssembler( throw new ArgumentOutOfRangeException(nameof(options), "Output capacity must be greater than zero."); var portSurfaces = new ApplicationRuntimePortSurfaceFactory( - catalog, runtimeOptions, logger, outputCaptures); @@ -46,7 +45,7 @@ public ApplicationRuntimeAssembler( new ApplicationRuntimeResourceSnapshotFactory( hostServices, resourceRegistrars.ToArray()), - new ApplicationRuntimeComponentActivator(catalog)); + new ApplicationRuntimeComponentActivator()); } internal ApplicationPortRuntime? Ports => Volatile.Read(ref _ports); diff --git a/src/FluxFlow.Engine/Hosting/ApplicationRuntimeComponentActivator.cs b/src/FluxFlow.Engine/Hosting/ApplicationRuntimeComponentActivator.cs index 8959c258..10f92f0f 100644 --- a/src/FluxFlow.Engine/Hosting/ApplicationRuntimeComponentActivator.cs +++ b/src/FluxFlow.Engine/Hosting/ApplicationRuntimeComponentActivator.cs @@ -3,14 +3,16 @@ namespace FluxFlow.Engine.Hosting; -internal sealed class ApplicationRuntimeComponentActivator(ComponentCatalog catalog) +internal sealed class ApplicationRuntimeComponentActivator { internal async ValueTask PopulateAsync( ApplicationDefinition definition, + ComponentCatalog catalog, IServiceProvider services, IDictionary components, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(catalog); foreach (var (workflowName, workflow) in definition.Workflows) { foreach (var (componentName, component) in workflow.Components) diff --git a/src/FluxFlow.Engine/Hosting/ApplicationRuntimeDrainPlan.cs b/src/FluxFlow.Engine/Hosting/ApplicationRuntimeDrainPlan.cs new file mode 100644 index 00000000..49699643 --- /dev/null +++ b/src/FluxFlow.Engine/Hosting/ApplicationRuntimeDrainPlan.cs @@ -0,0 +1,116 @@ +using FluxFlow.Composition; +using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Model; +using FluxFlow.Engine.Ports; + +namespace FluxFlow.Engine.Hosting; + +internal sealed class ApplicationRuntimeDrainPlan( + IReadOnlyList stages) +{ + internal static ApplicationRuntimeDrainPlan? TryCreate( + ApplicationDefinition definition, + IReadOnlyDictionary components) + { + var upstreams = components.Keys.ToDictionary( + static key => key, + static _ => new HashSet()); + var downstreams = components.Keys.ToDictionary( + static key => key, + static _ => new HashSet()); + + foreach (var link in definition.Links) + { + var source = ComponentKey(link.Source); + var target = ComponentKey(link.Target); + if (source == target || !components.ContainsKey(source) || !components.ContainsKey(target)) + continue; + + upstreams[target].Add(source); + downstreams[source].Add(target); + } + + var remaining = upstreams.ToDictionary( + static item => item.Key, + static item => item.Value.Count); + var ready = remaining + .Where(static item => item.Value == 0) + .Select(static item => item.Key) + .OrderBy(static key => key.WorkflowName, StringComparer.Ordinal) + .ThenBy(static key => key.ComponentName, StringComparer.Ordinal) + .ToArray(); + var planned = new List(); + var visited = 0; + + while (ready.Length > 0) + { + planned.Add(CreateStage(ready, components)); + visited += ready.Length; + var next = new HashSet(); + foreach (var source in ready) + { + foreach (var target in downstreams[source]) + { + if (--remaining[target] == 0) + next.Add(target); + } + } + + ready = next + .OrderBy(static key => key.WorkflowName, StringComparer.Ordinal) + .ThenBy(static key => key.ComponentName, StringComparer.Ordinal) + .ToArray(); + } + + return visited == components.Count + ? new ApplicationRuntimeDrainPlan(planned) + : null; + } + + internal async ValueTask DrainAsync( + ApplicationRuntime runtime, + ApplicationPortRevisionLease ports, + CancellationToken cancellationToken) + { + foreach (var stage in stages) + { + await ports.DrainInputsAsync(stage.Inputs, cancellationToken).ConfigureAwait(false); + foreach (var component in stage.Components) + { + cancellationToken.ThrowIfCancellationRequested(); + component.Node.Complete(); + } + + await Task.WhenAll(stage.Components.Select(static component => component.Completion)) + .WaitAsync(cancellationToken) + .ConfigureAwait(false); + await ports.DrainOutputsAsync(stage.Outputs, cancellationToken).ConfigureAwait(false); + } + + await runtime.Completion.WaitAsync(cancellationToken).ConfigureAwait(false); + } + + private static ApplicationRuntimeComponentKey ComponentKey(ApplicationAddress port) + => new(port.Segments[0], port.Segments[1]); + + private static ApplicationRuntimeDrainStage CreateStage( + IReadOnlyList keys, + IReadOnlyDictionary components) + { + var instances = keys.Select(key => components[key].Instance).ToArray(); + var inputs = keys + .SelectMany(key => components[key].Instance.Inputs.Keys.Select(port => + ApplicationAddress.WorkflowPort(key.WorkflowName, key.ComponentName, port))) + .ToHashSet(); + var outputs = keys + .SelectMany(key => components[key].Instance.Outputs.Keys.Select(port => + ApplicationAddress.WorkflowPort(key.WorkflowName, key.ComponentName, port))) + .ToHashSet(); + return new ApplicationRuntimeDrainStage(instances, inputs, outputs); + } +} + +internal sealed record ApplicationRuntimeDrainStage( + IReadOnlyList Components, + IReadOnlySet Inputs, + IReadOnlySet Outputs); diff --git a/src/FluxFlow.Engine/Hosting/ApplicationRuntimePlanFactory.cs b/src/FluxFlow.Engine/Hosting/ApplicationRuntimePlanFactory.cs index 720a0f99..94cbe47c 100644 --- a/src/FluxFlow.Engine/Hosting/ApplicationRuntimePlanFactory.cs +++ b/src/FluxFlow.Engine/Hosting/ApplicationRuntimePlanFactory.cs @@ -8,14 +8,26 @@ namespace FluxFlow.Engine.Hosting; internal sealed class ApplicationRuntimePlanFactory( - ComponentCatalog registry, + ComponentCatalog hostCatalog, IServiceProvider hostServices, ApplicationRuntimePortSurfaceFactory portSurfaces) { internal ApplicationRuntimePlan Create(ApplicationDefinition definition) { + ComponentCatalog catalog; + try + { + catalog = hostCatalog.Merge(definition.ComponentDescriptors); + } + catch (InvalidOperationException exception) + { + throw new ApplicationRuntimeAssemblerException( + $"Application component catalog is invalid: {exception.Message}", + exception); + } + var compilation = new ApplicationLinkCompiler( - registry, + catalog, hostServices.GetService(), ApplicationPortRuntimeBuilder.SystemOutputs) .Compile(definition); @@ -23,11 +35,13 @@ internal ApplicationRuntimePlan Create(ApplicationDefinition definition) throw new ApplicationRuntimeAssemblerException(compilation.Diagnostics); return new ApplicationRuntimePlan( + catalog, compilation.Links, - portSurfaces.Describe(definition)); + portSurfaces.Describe(definition, catalog)); } } internal sealed record ApplicationRuntimePlan( + ComponentCatalog Catalog, IReadOnlyList Links, IReadOnlyList Surface); diff --git a/src/FluxFlow.Engine/Hosting/ApplicationRuntimePortSurface.cs b/src/FluxFlow.Engine/Hosting/ApplicationRuntimePortSurface.cs index 7f5e073d..ed3f7ff9 100644 --- a/src/FluxFlow.Engine/Hosting/ApplicationRuntimePortSurface.cs +++ b/src/FluxFlow.Engine/Hosting/ApplicationRuntimePortSurface.cs @@ -7,14 +7,15 @@ namespace FluxFlow.Engine.Hosting; internal sealed class ApplicationRuntimePortSurfaceFactory( - ComponentCatalog catalog, ApplicationRuntimeAssemblerOptions options, ILogger? logger, IApplicationOutputCaptureResolver? outputCaptures) { internal IReadOnlyList Describe( - ApplicationDefinition definition) + ApplicationDefinition definition, + ComponentCatalog catalog) { + ArgumentNullException.ThrowIfNull(catalog); var entries = new List(); foreach (var (workflowName, workflow) in definition.Workflows) { diff --git a/src/FluxFlow.Engine/Hosting/ApplicationRuntimePreparation.cs b/src/FluxFlow.Engine/Hosting/ApplicationRuntimePreparation.cs index d432419e..889540e9 100644 --- a/src/FluxFlow.Engine/Hosting/ApplicationRuntimePreparation.cs +++ b/src/FluxFlow.Engine/Hosting/ApplicationRuntimePreparation.cs @@ -36,6 +36,7 @@ internal async ValueTask PrepareAsync( await componentActivator.PopulateAsync( definition, + plan.Catalog, resourceSnapshot.Services, components, cancellationToken) @@ -51,6 +52,7 @@ await componentActivator.PopulateAsync( .Select(static value => value.Instance) .ToArray(); runtime = ApplicationRuntime.Create(descriptors, [], descriptors); + var drainPlan = ApplicationRuntimeDrainPlan.TryCreate(definition, components); generation = currentGeneration is not null && ApplicationRuntimePortSurfaceFactory.IsSame(currentGeneration.Surface, plan.Surface) @@ -71,6 +73,7 @@ await componentActivator.PopulateAsync( runtime, portRevision, snapshots, + drainPlan, generation.ReleaseAsync, ReferenceEquals(generation, currentGeneration) ? null @@ -139,4 +142,5 @@ await ApplicationRuntimeCleanup.DisposeComponentsAsync( cleanupFailures); } } + } diff --git a/src/FluxFlow.Engine/Hosting/ApplicationRuntimeResourceSnapshotFactory.cs b/src/FluxFlow.Engine/Hosting/ApplicationRuntimeResourceSnapshotFactory.cs index 9ea2011c..296151ad 100644 --- a/src/FluxFlow.Engine/Hosting/ApplicationRuntimeResourceSnapshotFactory.cs +++ b/src/FluxFlow.Engine/Hosting/ApplicationRuntimeResourceSnapshotFactory.cs @@ -30,17 +30,24 @@ internal CompositionServiceProviderSnapshot Create( context.RevisionId, hostServices, candidateServices); - foreach (var registrar in registrars) + var registered = new HashSet( + ReferenceEqualityComparer.Instance); + foreach (var registrar in registrars.Concat( + definition.ApplicationResourceContracts.Select( + static contract => (IApplicationResourceRegistrar)contract))) { cancellationToken.ThrowIfCancellationRequested(); - registrar.Register(registrationContext); + var identity = registrar.RegistrationIdentity; + if (registered.Add(identity)) + registrar.Register(registrationContext); } return new CompositionServiceProviderSnapshotBuilder() .AddServices(candidateServices) .Build( CompositionProviderBoundary.ResourceRevision, - $"resources:{context.RevisionId}"); + $"resources:{context.RevisionId}", + fallbackProvider: hostServices); } private static void RegisterProcessingProfiles( diff --git a/src/FluxFlow.Engine/Hosting/ApplicationRuntimeRevisionCandidate.cs b/src/FluxFlow.Engine/Hosting/ApplicationRuntimeRevisionCandidate.cs index 85705194..05fc45c1 100644 --- a/src/FluxFlow.Engine/Hosting/ApplicationRuntimeRevisionCandidate.cs +++ b/src/FluxFlow.Engine/Hosting/ApplicationRuntimeRevisionCandidate.cs @@ -10,6 +10,7 @@ internal sealed class ApplicationRuntimeRevisionCandidate : IApplicationRevision private readonly ApplicationRuntime _runtime; private readonly ApplicationPortRevision _portRevision; private readonly IReadOnlyList _snapshots; + private readonly ApplicationRuntimeDrainPlan? _drainPlan; private readonly Func _releasePorts; private readonly bool _releasePortsAfterActivation; private readonly Func? _adoptPorts; @@ -25,11 +26,13 @@ public ApplicationRuntimeRevisionCandidate( ApplicationPortRuntime ports, IReadOnlyList snapshots, bool ownsPorts, - Func? adoptPorts) + Func? adoptPorts, + ApplicationRuntimeDrainPlan? drainPlan = null) { _runtime = runtime; _portRevision = portRevision; _snapshots = snapshots; + _drainPlan = drainPlan; _releasePorts = ownsPorts ? ports.DisposeAsync : NoopReleaseAsync; _releasePortsAfterActivation = false; _adoptPorts = adoptPorts; @@ -40,12 +43,14 @@ internal ApplicationRuntimeRevisionCandidate( ApplicationRuntime runtime, ApplicationPortRevision portRevision, IReadOnlyList snapshots, + ApplicationRuntimeDrainPlan? drainPlan, Func releasePorts, Func? adoptPorts) { _runtime = runtime; _portRevision = portRevision; _snapshots = snapshots; + _drainPlan = drainPlan; _releasePorts = releasePorts; _releasePortsAfterActivation = true; _adoptPorts = adoptPorts; @@ -70,9 +75,17 @@ public async ValueTask DrainAsync(CancellationToken cancellationToken = default) { if (Interlocked.Exchange(ref _drained, 1) != 0) return; - if (_portLease is not null) - await _portLease.DrainInputsAsync(cancellationToken).ConfigureAwait(false); - await _runtime.StopAsync(cancellationToken).ConfigureAwait(false); + if (_drainPlan is not null && _portLease is not null) + { + await _drainPlan.DrainAsync(_runtime, _portLease, cancellationToken) + .ConfigureAwait(false); + } + else + { + if (_portLease is not null) + await _portLease.DrainInputsAsync(cancellationToken).ConfigureAwait(false); + await _runtime.StopAsync(cancellationToken).ConfigureAwait(false); + } if (_portLease is not null) await _portLease.DrainOutputsAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/FluxFlow.Engine/Internal/Revisions/ApplicationRevisionPlanner.cs b/src/FluxFlow.Engine/Internal/Revisions/ApplicationRevisionPlanner.cs index 0c28f47a..206a597d 100644 --- a/src/FluxFlow.Engine/Internal/Revisions/ApplicationRevisionPlanner.cs +++ b/src/FluxFlow.Engine/Internal/Revisions/ApplicationRevisionPlanner.cs @@ -1,5 +1,6 @@ using System.Text.Json; using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Links; using FluxFlow.Composition.Model; using ApplicationWorkflowDefinition = FluxFlow.Composition.Model.WorkflowDefinition; @@ -16,8 +17,12 @@ public ApplicationRevisionPlan Plan( var currentResources = FlattenResources(current); var nextResources = FlattenResources(next); - var resourceChanges = CompareResources(currentResources, nextResources); - var workflowChanges = CompareWorkflows(current.Workflows, next.Workflows); + var resourceChanges = CompareResources( + currentResources, + nextResources, + current, + next); + var workflowChanges = CompareWorkflows(current, next); var diagnostics = new List(); var resourceDependencies = ReadResourceDependencies(nextResources, diagnostics); var workflowDependencies = ReadWorkflowDependencies(next.Workflows, nextResources, diagnostics); @@ -86,7 +91,9 @@ private static void AddResource( private static IReadOnlyList CompareResources( IReadOnlyDictionary current, - IReadOnlyDictionary next) + IReadOnlyDictionary next, + ApplicationDefinition currentDefinition, + ApplicationDefinition nextDefinition) { var addresses = current.Keys .Concat(next.Keys) @@ -99,7 +106,11 @@ private static IReadOnlyList CompareResources var hasCurrent = current.TryGetValue(address, out var currentResource); var hasNext = next.TryGetValue(address, out var nextResource); var kind = hasCurrent && hasNext - ? ResourceEquals(currentResource!, nextResource!) + ? ResourceEquals(currentResource!, nextResource!) && + ResourceContractEquals( + currentResource!.Type, + currentDefinition, + nextDefinition) ? (ApplicationRevisionChangeKind?)null : ApplicationRevisionChangeKind.Updated : hasNext @@ -120,21 +131,23 @@ private static IReadOnlyList CompareResources } private static IReadOnlyList CompareWorkflows( - IReadOnlyDictionary current, - IReadOnlyDictionary next) + ApplicationDefinition current, + ApplicationDefinition next) { - var names = current.Keys - .Concat(next.Keys) + var names = current.Workflows.Keys + .Concat(next.Workflows.Keys) .Distinct(StringComparer.Ordinal) .OrderBy(static name => name, StringComparer.Ordinal); var changes = new List(); foreach (var name in names) { - var hasCurrent = current.TryGetValue(name, out var currentWorkflow); - var hasNext = next.TryGetValue(name, out var nextWorkflow); + var hasCurrent = current.Workflows.TryGetValue(name, out var currentWorkflow); + var hasNext = next.Workflows.TryGetValue(name, out var nextWorkflow); var kind = hasCurrent && hasNext - ? WorkflowEquals(currentWorkflow!, nextWorkflow!) + ? WorkflowEquals(currentWorkflow!, nextWorkflow!) && + WorkflowLinksEqual(name, current.Links, next.Links) && + WorkflowComponentContractsEqual(currentWorkflow!, current, next) ? (ApplicationRevisionChangeKind?)null : ApplicationRevisionChangeKind.Updated : hasNext @@ -154,6 +167,68 @@ private static IReadOnlyList CompareWorkflows return changes; } + private static bool ResourceContractEquals( + string resourceType, + ApplicationDefinition current, + ApplicationDefinition next) + { + var currentContract = current.ApplicationResourceContracts + .SingleOrDefault(contract => string.Equals( + contract.Type, + resourceType, + StringComparison.Ordinal)); + var nextContract = next.ApplicationResourceContracts + .SingleOrDefault(contract => string.Equals( + contract.Type, + resourceType, + StringComparison.Ordinal)); + return ReferenceEquals(currentContract, nextContract); + } + + private static bool WorkflowLinksEqual( + string workflow, + IReadOnlyList current, + IReadOnlyList next) + => current.Where(link => BelongsToWorkflow(link, workflow)) + .SequenceEqual(next.Where(link => BelongsToWorkflow(link, workflow))); + + private static bool WorkflowComponentContractsEqual( + ApplicationWorkflowDefinition workflow, + ApplicationDefinition current, + ApplicationDefinition next) + { + var currentDescriptors = current.ComponentDescriptors.ToDictionary( + static descriptor => descriptor.Type, + StringComparer.Ordinal); + var nextDescriptors = next.ComponentDescriptors.ToDictionary( + static descriptor => descriptor.Type, + StringComparer.Ordinal); + + foreach (var type in workflow.Components.Values + .Select(static component => component.Type) + .Distinct(StringComparer.Ordinal)) + { + var hasCurrent = currentDescriptors.TryGetValue(type, out var currentDescriptor); + var hasNext = nextDescriptors.TryGetValue(type, out var nextDescriptor); + if (hasCurrent != hasNext || + hasCurrent && !ReferenceEquals(currentDescriptor, nextDescriptor)) + { + return false; + } + } + + return true; + } + + private static bool BelongsToWorkflow( + ApplicationLinkDefinition link, + string workflow) + => IsWorkflow(link.Source, workflow) || IsWorkflow(link.Target, workflow); + + private static bool IsWorkflow(ApplicationAddress address, string workflow) + => address.Kind == ApplicationAddressKind.WorkflowPort && + string.Equals(address.Segments[0], workflow, StringComparison.Ordinal); + private static IReadOnlyDictionary> ReadResourceDependencies( IReadOnlyDictionary resources, ICollection diagnostics) diff --git a/src/FluxFlow.Engine/Internal/Snapshots/CompositionServiceProviderSnapshot.cs b/src/FluxFlow.Engine/Internal/Snapshots/CompositionServiceProviderSnapshot.cs index b19a8b58..d26948f8 100644 --- a/src/FluxFlow.Engine/Internal/Snapshots/CompositionServiceProviderSnapshot.cs +++ b/src/FluxFlow.Engine/Internal/Snapshots/CompositionServiceProviderSnapshot.cs @@ -9,6 +9,7 @@ internal sealed class CompositionServiceProviderSnapshot : IAsyncDisposable { private IServiceProvider? _provider; + private readonly IServiceProvider? _fallbackProvider; private readonly bool _ownsProvider; internal CompositionServiceProviderSnapshot( @@ -16,9 +17,11 @@ internal CompositionServiceProviderSnapshot( CompositionProviderBoundary boundary, IServiceProvider provider, bool ownsProvider, - int? serviceCount) + int? serviceCount, + IServiceProvider? fallbackProvider = null) { _provider = provider ?? throw new ArgumentNullException(nameof(provider)); + _fallbackProvider = fallbackProvider; _ownsProvider = ownsProvider; Info = new CompositionProviderSnapshotInfo { @@ -57,19 +60,23 @@ public static CompositionServiceProviderSnapshot CreateExternalHost( public object? GetService(Type serviceType) { ArgumentNullException.ThrowIfNull(serviceType); - return GetProvider().GetService(serviceType); + return GetProvider().GetService(serviceType) + ?? _fallbackProvider?.GetService(serviceType); } public object? GetKeyedService(Type serviceType, object? serviceKey) { ArgumentNullException.ThrowIfNull(serviceType); - return GetKeyedProvider().GetKeyedService(serviceType, serviceKey); + return GetKeyedProvider(GetProvider()).GetKeyedService(serviceType, serviceKey) + ?? GetFallbackKeyedProvider()?.GetKeyedService(serviceType, serviceKey); } public object GetRequiredKeyedService(Type serviceType, object? serviceKey) { ArgumentNullException.ThrowIfNull(serviceType); - return GetKeyedProvider().GetRequiredKeyedService(serviceType, serviceKey); + return GetKeyedService(serviceType, serviceKey) + ?? throw new InvalidOperationException( + $"No service for type '{serviceType}' and key '{serviceKey}' has been registered."); } public void Dispose() @@ -102,11 +109,14 @@ private IServiceProvider GetProvider() => Volatile.Read(ref _provider) ?? throw new ObjectDisposedException(nameof(CompositionServiceProviderSnapshot)); - private IKeyedServiceProvider GetKeyedProvider() - => GetProvider() as IKeyedServiceProvider + private static IKeyedServiceProvider GetKeyedProvider(IServiceProvider provider) + => provider as IKeyedServiceProvider ?? throw new InvalidOperationException( "The underlying provider does not support keyed services."); + private IKeyedServiceProvider? GetFallbackKeyedProvider() + => _fallbackProvider as IKeyedServiceProvider; + internal static string ValidateName(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); diff --git a/src/FluxFlow.Engine/Internal/Snapshots/CompositionServiceProviderSnapshotBuilder.cs b/src/FluxFlow.Engine/Internal/Snapshots/CompositionServiceProviderSnapshotBuilder.cs index ebf5a7d7..eca24389 100644 --- a/src/FluxFlow.Engine/Internal/Snapshots/CompositionServiceProviderSnapshotBuilder.cs +++ b/src/FluxFlow.Engine/Internal/Snapshots/CompositionServiceProviderSnapshotBuilder.cs @@ -69,7 +69,8 @@ public CompositionServiceProviderSnapshotBuilder BridgeExternalResource BeginRevisionAsync( PayloadType, "Input port", target => new ApplicationInputAttachmentLifetime( + Address, _core.CommitRevision(target), _core.DrainAsync, _core.DetachAsync), diff --git a/src/FluxFlow.Engine/Ports/ApplicationInputRevisionLifetime.cs b/src/FluxFlow.Engine/Ports/ApplicationInputRevisionLifetime.cs index 8f1c0a0a..7c9c6182 100644 --- a/src/FluxFlow.Engine/Ports/ApplicationInputRevisionLifetime.cs +++ b/src/FluxFlow.Engine/Ports/ApplicationInputRevisionLifetime.cs @@ -3,12 +3,15 @@ namespace FluxFlow.Engine.Ports; internal sealed class ApplicationInputAttachmentLifetime( + ApplicationAddress address, long generation, Func drain, Func detach) : IApplicationInputAttachment { private int _disposed; + public ApplicationAddress Address { get; } = address; + ValueTask IApplicationInputAttachment.DrainAsync(CancellationToken cancellationToken) => drain(generation, cancellationToken); diff --git a/src/FluxFlow.Engine/Ports/ApplicationOutputPort.cs b/src/FluxFlow.Engine/Ports/ApplicationOutputPort.cs index f2f965f9..c6dc8bf6 100644 --- a/src/FluxFlow.Engine/Ports/ApplicationOutputPort.cs +++ b/src/FluxFlow.Engine/Ports/ApplicationOutputPort.cs @@ -559,36 +559,8 @@ internal void TryDeliver( CompiledApplicationLink link, FlowMessage message) { - object? input = message.IsError ? message.Error : message.Value; - var context = new FlowMapContext - { - Variables = new Dictionary(StringComparer.Ordinal) - { - ["input"] = input, - ["message"] = message, - ["payload"] = input - } - }; - - if (!link.TryMatch(context, out var exception)) - { - if (exception is not null) - { - _report(new ApplicationPortRejection - { - Timestamp = DateTimeOffset.UtcNow, - Port = Address, - RelatedPort = target.Address, - CorrelationId = message.CorrelationId, - TraceId = message.TraceId, - MessageId = message.MessageId, - Reason = ApplicationPortRejectionReason.ConditionFailed, - Exception = exception - }); - } - + if (!TryMatch(link, message, target.Address)) return; - } target.TrySend(message, Address); } @@ -598,6 +570,20 @@ internal void TryDeliver( CompiledApplicationLink link, FlowMessage message) { + if (!TryMatch(link, message, target.Address)) + return; + + target.TrySend(message, Address); + } + + private bool TryMatch( + CompiledApplicationLink link, + FlowMessage message, + ApplicationAddress target) + { + if (!link.IsConditional) + return true; + object? input = message.IsError ? message.Error : message.Value; var context = new FlowMapContext { @@ -617,7 +603,7 @@ internal void TryDeliver( { Timestamp = DateTimeOffset.UtcNow, Port = Address, - RelatedPort = target.Address, + RelatedPort = target, CorrelationId = message.CorrelationId, TraceId = message.TraceId, MessageId = message.MessageId, @@ -626,9 +612,9 @@ internal void TryDeliver( }); } - return; + return false; } - target.TrySend(message, Address); + return true; } } diff --git a/src/FluxFlow.Engine/Ports/ApplicationPortEventPublisher.cs b/src/FluxFlow.Engine/Ports/ApplicationPortEventPublisher.cs index 13b266dd..f09f5b24 100644 --- a/src/FluxFlow.Engine/Ports/ApplicationPortEventPublisher.cs +++ b/src/FluxFlow.Engine/Ports/ApplicationPortEventPublisher.cs @@ -194,20 +194,44 @@ private static FlowMessage CreateSignalMessage( traceId is { IsEmpty: false } ? traceId : null, causationId: causationId); - private static IReadOnlyDictionary CreateAttributes( - params (string Name, string? Value)[] values) - => values - .Where(static value => value.Value is not null) - .ToDictionary( - value => value.Name, - value => value.Value!, - StringComparer.Ordinal); - - private static JsonElement CreateDetails(params (string Name, string? Value)[] values) - => JsonSerializer.SerializeToElement(values - .Where(static value => value.Value is not null) - .ToDictionary( - value => value.Name, - value => value.Value!, - StringComparer.Ordinal)); + private static Dictionary CreateAttributes( + (string Name, string? Value) first, + (string Name, string? Value) second) + { + var attributes = new Dictionary(2, StringComparer.Ordinal); + AddAttribute(attributes, first); + AddAttribute(attributes, second); + return attributes; + } + + private static Dictionary CreateAttributes( + (string Name, string? Value) first, + (string Name, string? Value) second, + (string Name, string? Value) third) + { + var attributes = new Dictionary(3, StringComparer.Ordinal); + AddAttribute(attributes, first); + AddAttribute(attributes, second); + AddAttribute(attributes, third); + return attributes; + } + + private static JsonElement CreateDetails( + (string Name, string? Value) first, + (string Name, string? Value) second) + => JsonSerializer.SerializeToElement(CreateAttributes(first, second)); + + private static JsonElement CreateDetails( + (string Name, string? Value) first, + (string Name, string? Value) second, + (string Name, string? Value) third) + => JsonSerializer.SerializeToElement(CreateAttributes(first, second, third)); + + private static void AddAttribute( + Dictionary attributes, + (string Name, string? Value) attribute) + { + if (attribute.Value is not null) + attributes.Add(attribute.Name, attribute.Value); + } } diff --git a/src/FluxFlow.Engine/Ports/ApplicationPortRevision.cs b/src/FluxFlow.Engine/Ports/ApplicationPortRevision.cs index 2887f96e..dfc9842f 100644 --- a/src/FluxFlow.Engine/Ports/ApplicationPortRevision.cs +++ b/src/FluxFlow.Engine/Ports/ApplicationPortRevision.cs @@ -261,8 +261,21 @@ internal ApplicationPortRevisionLease( public ApplicationPortRevisionInfo Info { get; } internal async ValueTask DrainInputsAsync(CancellationToken cancellationToken) + => await DrainInputsAsync(_inputAttachments, cancellationToken).ConfigureAwait(false); + + internal async ValueTask DrainInputsAsync( + IReadOnlySet addresses, + CancellationToken cancellationToken) + => await DrainInputsAsync( + _inputAttachments.Where(input => addresses.Contains(input.Address)), + cancellationToken) + .ConfigureAwait(false); + + private static async ValueTask DrainInputsAsync( + IEnumerable inputs, + CancellationToken cancellationToken) { - var drains = _inputAttachments + var drains = inputs .Select(attachment => attachment.DrainAsync(cancellationToken).AsTask()) .ToArray(); if (drains.Length > 0) @@ -270,9 +283,22 @@ internal async ValueTask DrainInputsAsync(CancellationToken cancellationToken) } internal async ValueTask DrainOutputsAsync(CancellationToken cancellationToken) + => await DrainOutputsAsync(_outputAttachments, cancellationToken).ConfigureAwait(false); + + internal async ValueTask DrainOutputsAsync( + IReadOnlySet addresses, + CancellationToken cancellationToken) + => await DrainOutputsAsync( + _outputAttachments.Where(output => addresses.Contains(output.Address)), + cancellationToken) + .ConfigureAwait(false); + + private static async ValueTask DrainOutputsAsync( + IEnumerable outputs, + CancellationToken cancellationToken) { List? failures = null; - foreach (var output in _outputAttachments) + foreach (var output in outputs) { try { diff --git a/src/FluxFlow.Engine/Ports/ApplicationPortRuntime.cs b/src/FluxFlow.Engine/Ports/ApplicationPortRuntime.cs index 311ae4a3..7a2d13aa 100644 --- a/src/FluxFlow.Engine/Ports/ApplicationPortRuntime.cs +++ b/src/FluxFlow.Engine/Ports/ApplicationPortRuntime.cs @@ -2,6 +2,7 @@ using System.Runtime.ExceptionServices; using System.Text.Json; using System.Threading.Tasks.Dataflow; +using FluxFlow.Composition.Authoring; using FluxFlow.Data; using FluxFlow.Composition.Addressing; using FluxFlow.Composition.Links; @@ -176,6 +177,24 @@ public ApplicationPortRevisionBuilder CreateRevision(string revisionId) return new ApplicationPortRevisionBuilder(this, revisionId); } + public ValueTask SendAsync( + InputPortHandle input, + FlowMessage message, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + return SendAsync(input.Address, message, cancellationToken); + } + + public ValueTask SendAsync( + SignalInputPortHandle input, + FlowMessage message, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + return SendAsync(input.Address, message, cancellationToken); + } + public ValueTask SendAsync( ApplicationAddress input, FlowMessage message, @@ -224,6 +243,15 @@ public async Task> ReceiveAsync( .ConfigureAwait(false); } + public Task> ReceiveAsync( + OutputPortHandle output, + TimeSpan? timeout = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(output); + return ReceiveAsync(output.Address, timeout, cancellationToken); + } + public ValueTask> ObserveAsync( ApplicationAddress output, int capacity = 128, @@ -233,6 +261,15 @@ public ValueTask> ObserveAsync( return ValueTask.FromResult(GetOutput(output).Observe(capacity)); } + public ValueTask> ObserveAsync( + OutputPortHandle output, + int capacity = 128, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(output); + return ObserveAsync(output.Address, capacity, cancellationToken); + } + public async Task> SendAndReceiveAsync( ApplicationAddress input, ApplicationAddress output, @@ -308,6 +345,32 @@ public async Task> SendAndReceiveAsync> SendAndReceiveAsync( + InputPortHandle input, + OutputPortHandle output, + FlowMessage request, + TimeSpan? timeout = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(output); + return SendAndReceiveAsync( + input.Address, + output.Address, + request, + timeout, + cancellationToken); + } + + public ValueTask AttachInputAsync( + InputPortHandle input, + ITargetBlock> target, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + return AttachInputAsync(input.Address, target, cancellationToken); + } + public ValueTask AttachInputAsync( ApplicationAddress input, ITargetBlock> target, @@ -317,6 +380,15 @@ public ValueTask AttachInputAsync( return GetInput(input).AttachAsync(target, cancellationToken); } + public ValueTask AttachSignalInputAsync( + SignalInputPortHandle input, + IFlowSignalTarget target, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + return AttachSignalInputAsync(input.Address, target, cancellationToken); + } + public ValueTask AttachSignalInputAsync( ApplicationAddress input, IFlowSignalTarget target, @@ -333,6 +405,20 @@ public IFlowSignalTarget GetSignalTarget(ApplicationAddress input) return GetSignalInput(input); } + public IFlowSignalTarget GetSignalTarget(SignalInputPortHandle input) + { + ArgumentNullException.ThrowIfNull(input); + return GetSignalTarget(input.Address); + } + + public IDisposable AttachOutput( + OutputPortHandle output, + ISourceBlock> source) + { + ArgumentNullException.ThrowIfNull(output); + return AttachOutput(output.Address, source); + } + public IDisposable AttachOutput( ApplicationAddress output, ISourceBlock> source) diff --git a/src/FluxFlow.Engine/Ports/ApplicationSignalInputPort.cs b/src/FluxFlow.Engine/Ports/ApplicationSignalInputPort.cs index 56c758fd..31539ff6 100644 --- a/src/FluxFlow.Engine/Ports/ApplicationSignalInputPort.cs +++ b/src/FluxFlow.Engine/Ports/ApplicationSignalInputPort.cs @@ -101,6 +101,7 @@ public async ValueTask BeginRevisionAsync( PayloadType, "Signal input port", target => new ApplicationInputAttachmentLifetime( + Address, _core.CommitRevision(target), _core.DrainAsync, _core.DetachAsync), diff --git a/src/FluxFlow.Engine/README.md b/src/FluxFlow.Engine/README.md index e1279be6..66f862ec 100644 --- a/src/FluxFlow.Engine/README.md +++ b/src/FluxFlow.Engine/README.md @@ -46,6 +46,22 @@ services.AddFluxFlow(options => }); ``` +A compiled C# definition built from complete `ComponentContract` values carries +its own executable descriptors. Register it directly; do not repeat those +components in the service-registration chain: + +```csharp +var definition = applicationBuilder.Build(); + +services.AddSingleton(orderStore); +services.AddFluxFlow(definition); +``` + +JSON and low-level string definitions intentionally carry no executable C#. +Register their required family extensions or individual complete contracts on +the host. Dynamic/plugin descriptors use the visibly advanced +`AddFluxFlowComponents().Advanced.AddDynamicComponent(...)` escape hatch. + The registered hosted service resolves the same singleton `FluxFlowApplication` that direct callers resolve. Set `StartWithHost` to `false` when the application will be started explicitly. @@ -82,28 +98,33 @@ switches stable ports atomically, then drains and disposes the old revision. Revision-owned providers and candidates are disposed exactly once. `State`, `Current`, `CurrentDefinition`, and `LastUpdate` expose the current -host view. A rejected reload may leave the application `Degraded` while the -previous revision continues serving work; a later successful update restores -`Running`. A stopped application cannot be restarted. +host view. A rejected reload keeps the application `Running` while the previous +revision continues serving work and records a rejected `LastUpdate`; a later +successful update replaces that result. A failed initial start with no active +revision is `Degraded`. The result returned by a successful replacement reports its +`PreviousRevision`; the retained `LastUpdate` copy omits that retired snapshot +so application state does not keep executable definitions and captured +predicates alive. A stopped application cannot be restarted. ## Stable Ports -`ApplicationPorts` is a stable facade over the active runtime generation. Use -canonical strings or `ApplicationAddress` values for send, receive, observe, -and request/reply operations: +`ApplicationPorts` is a stable facade over the active runtime generation. A +compiled-C# caller should retain component handles and use their typed ports; +canonical strings and `ApplicationAddress` remain available for JSON, +operations, and dynamic selection: ```csharp +var receive = application.Ports.ReceiveAsync( + finalResult.Output, + TimeSpan.FromSeconds(10)); + var send = await application.Ports.SendAsync( - "OrderProcessing.ValidateOrder.Input", + validateOrder.Input, FlowMessage.Create(order)); -var receive = await application.Ports.ReceiveAsync( - "OrderProcessing.FinalResult.Output", - TimeSpan.FromSeconds(10)); - -var reply = await application.Ports.SendAndReceiveAsync( - "OrderProcessing.ValidateOrder.Input", - "OrderProcessing.FinalResult.Output", +var reply = await application.Ports.SendAndReceiveAsync( + validateOrder.Input, + finalResult.Output, FlowMessage.Create(order), TimeSpan.FromSeconds(10)); ``` @@ -163,15 +184,39 @@ definitions. Composition adapters implement `IApplicationResourceRegistrar` from `FluxFlow.Composition`. Registrars receive a revision-owned service collection -and register keyed resources in deterministic order. Engine builds isolated -resource and workflow providers, activates components from the immutable -`ComponentCatalog`, and owns only revision-scoped services it creates. -Externally bridged host singletons keep host ownership. +and register keyed resources in deterministic order. For compiled C#, the +resource contract that authored the definition carries that registrar into the +candidate revision; JSON/configuration definitions intentionally carry none and +still require explicit package registration. Engine merges exact host and +definition registrar identities idempotently, builds isolated resource and +workflow providers, resolves one effective catalog from host and +definition-owned descriptors, and owns only revision-scoped services it +creates. During activation, revision-owned services and keyed resources take +precedence; ordinary host services remain available as an explicit fallback and +keep host ownership. Runtime generations, provider snapshots, revision candidates, binders, leases, and port builders are implementation details. Normal consumers construct and control only `FluxFlowApplication` through DI. +## Optional Readiness Health Check + +Hosts that use standard .NET health checks can reference the separate +`FluxFlow.Engine.HealthChecks` package and register one application readiness +check: + +```csharp +using FluxFlow.Engine.HealthChecks; + +services.AddHealthChecks() + .AddFluxFlowApplication(); +``` + +The adapter observes existing in-memory application state only. It adds no +Engine dependency in the reverse direction, worker, polling, storage access, +or endpoint. See `docs/42-application-health-readiness.md` for the exact status +and bounded-data contract. + ## Public Surface The primary host-level contracts are: diff --git a/src/FluxFlow.Fluent.Hosting/README.md b/src/FluxFlow.Fluent.Hosting/README.md index 64a3b9a1..3ac3cbdd 100644 --- a/src/FluxFlow.Fluent.Hosting/README.md +++ b/src/FluxFlow.Fluent.Hosting/README.md @@ -35,7 +35,8 @@ runs as its own hosted service. `AddFlowGraph` registration and a hosted service that builds the graph (once), starts it, stops it on host stop, and disposes it on shutdown. -It does not own node construction, the DSL, or the runtime — the graph comes from -`FluxFlow.Fluent` (`Flow.From(...)...Build()`), and you construct nodes inside the -factory (optionally from DI). For composing nodes without hosting, use +It does not own node construction, the DSL, or another runtime. The graph comes +from `FluxFlow.Fluent` (`Flow.From(...)...Build()`), already wraps the canonical +definition and `FluxFlowApplication`, and constructs nodes inside the factory +(optionally from DI). For composing nodes without Generic Host integration, use `FluxFlow.Fluent` directly. diff --git a/src/FluxFlow.Fluent/Flow.cs b/src/FluxFlow.Fluent/Flow.cs index 69fc0882..35c2817b 100644 --- a/src/FluxFlow.Fluent/Flow.cs +++ b/src/FluxFlow.Fluent/Flow.cs @@ -1,4 +1,3 @@ -using FluxFlow.Composition; using FluxFlow.Nodes; namespace FluxFlow.Fluent; @@ -27,7 +26,6 @@ public static FlowBuilder From(FlowSource source) ArgumentNullException.ThrowIfNull(source); var graph = new FlowGraphBuilder(); - graph.Register(ComponentInstance.Create(source, events: source.Events), isEntry: true); - return new FlowBuilder(graph, source.Output); + return new FlowBuilder(graph, graph.RegisterSource(source).Output); } } diff --git a/src/FluxFlow.Fluent/FlowBuilder.cs b/src/FluxFlow.Fluent/FlowBuilder.cs index fc9d06bb..3acfb01c 100644 --- a/src/FluxFlow.Fluent/FlowBuilder.cs +++ b/src/FluxFlow.Fluent/FlowBuilder.cs @@ -1,5 +1,5 @@ using System.Threading.Tasks.Dataflow; -using FluxFlow.Composition; +using FluxFlow.Composition.Authoring; using FluxFlow.Nodes; namespace FluxFlow.Fluent; @@ -13,9 +13,9 @@ namespace FluxFlow.Fluent; public sealed class FlowBuilder { private readonly FlowGraphBuilder _graph; - private readonly ISourceBlock> _output; + private readonly OutputPortHandle _output; - internal FlowBuilder(FlowGraphBuilder graph, ISourceBlock> output) + internal FlowBuilder(FlowGraphBuilder graph, OutputPortHandle output) { _graph = graph; _output = output; @@ -29,9 +29,9 @@ public FlowBuilder Then(FlowNode node) { ArgumentNullException.ThrowIfNull(node); - _graph.Register(ComponentInstance.Create(node, events: node.Events), isEntry: false); - _graph.Link(_output, node, node.Input); - return new FlowBuilder(_graph, node.Output); + var registered = _graph.RegisterNode(node); + _graph.Connect(_output, registered.Input); + return new FlowBuilder(_graph, registered.Output); } /// @@ -43,8 +43,8 @@ public FlowBuilder Tap(FlowNode node) { ArgumentNullException.ThrowIfNull(node); - _graph.Register(ComponentInstance.Create(node, events: node.Events), isEntry: false); - _graph.Link(_output, node, node.Input); + var registered = _graph.RegisterNode(node); + _graph.Connect(_output, registered.Input); return this; } @@ -62,7 +62,9 @@ public FlowBuilder Branch( ArgumentNullException.ThrowIfNull(port); ArgumentNullException.ThrowIfNull(build); - build(new FlowBuilder(_graph, port)); + var branch = _graph.RegisterBranch(port); + _graph.Connect(_output, branch.Dependency); + build(new FlowBuilder(_graph, branch.Output)); return this; } @@ -87,8 +89,8 @@ public FlowTerminal To(FlowNode node) { ArgumentNullException.ThrowIfNull(node); - _graph.Register(ComponentInstance.Create(node, events: node.Events), isEntry: false); - _graph.Link(_output, node, node.Input); + var registered = _graph.RegisterNode(node); + _graph.Connect(_output, registered.Input); return new FlowTerminal(_graph); } diff --git a/src/FluxFlow.Fluent/FlowGraph.cs b/src/FluxFlow.Fluent/FlowGraph.cs index b252dfb5..d11cd431 100644 --- a/src/FluxFlow.Fluent/FlowGraph.cs +++ b/src/FluxFlow.Fluent/FlowGraph.cs @@ -1,72 +1,176 @@ using System.Threading.Tasks.Dataflow; -using FluxFlow.Composition; +using FluxFlow.Composition.Model; +using FluxFlow.Engine; using FluxFlow.Nodes; +using Microsoft.Extensions.DependencyInjection; namespace FluxFlow.Fluent; /// -/// A built, runnable flow. Wraps a : call -/// to start the sources, await , observe the aggregated -/// stream, and dispose to tear the graph down in order. +/// A fluent facade over the canonical immutable definition and +/// host. The fluent DSL does not own a second workflow runtime. /// public sealed class FlowGraph : IAsyncDisposable { - private readonly ApplicationRuntime _runtime; - private readonly List _subscriptions = new(); + private readonly IServiceProvider _services; + private readonly BroadcastBlock _events = + new(static flowEvent => flowEvent); + private readonly List _subscriptions = []; + private readonly Task _sourceCompletion; + private readonly object _lifecycleGate = new(); + private Task? _stopTask; + private readonly TaskCompletionSource _completion = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _started; + private int _disposed; - internal FlowGraph(ApplicationRuntime runtime) => _runtime = runtime; + internal FlowGraph( + ApplicationDefinition definition, + IReadOnlyList> eventSources, + IReadOnlyList sourceCompletions) + { + Definition = definition ?? throw new ArgumentNullException(nameof(definition)); + ArgumentNullException.ThrowIfNull(eventSources); + ArgumentNullException.ThrowIfNull(sourceCompletions); + _sourceCompletion = Task.WhenAll(sourceCompletions); + + var services = new ServiceCollection(); + services.AddFluxFlow( + definition, + options => options.StartWithHost = false); + _services = services.BuildServiceProvider(new ServiceProviderOptions + { + ValidateOnBuild = true, + ValidateScopes = true + }); + Application = _services.GetRequiredService(); + + foreach (var source in eventSources) + _subscriptions.Add(source.LinkTo(_events)); + _ = CompleteEventsAsync(eventSources); + } + + public ApplicationDefinition Definition { get; } - /// The underlying composition runtime, for advanced hosting scenarios. - public ApplicationRuntime Runtime => _runtime; + public FluxFlowApplication Application { get; } - /// Completes when every node has completed; faults if any node faults. - public Task Completion => _runtime.Completion; + public Task Completion => _completion.Task; - /// Aggregated event stream across all nodes in the flow. - public ISourceBlock Events => _runtime.Events; + public ISourceBlock Events => _events; - /// - /// Observe every event the flow's nodes raise. A throwing handler is isolated so it cannot - /// break observation. - /// public IDisposable OnEvent(Action handler) { ArgumentNullException.ThrowIfNull(handler); - return Subscribe(_runtime.Events, handler); + return Subscribe(_events, handler); } - /// Start every source node so the flow begins producing. - public ValueTask StartAsync(CancellationToken cancellationToken = default) - => _runtime.StartAsync(cancellationToken); + public async ValueTask StartAsync(CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + if (Interlocked.Exchange(ref _started, 1) != 0) + return; - /// Complete the entry nodes and await the flow draining to completion. - public ValueTask StopAsync(CancellationToken cancellationToken = default) - => _runtime.StopAsync(cancellationToken); + var result = await Application.StartAsync(cancellationToken).ConfigureAwait(false); + if (result.IsRejected) + { + var message = string.Join( + Environment.NewLine, + result.Diagnostics.Select(static diagnostic => diagnostic.Error.Message)); + _completion.TrySetException(new InvalidOperationException(message)); + throw new InvalidOperationException(message); + } + + _ = StopWhenSourcesCompleteAsync(); + } + + public async ValueTask StopAsync(CancellationToken cancellationToken = default) + { + if (Volatile.Read(ref _started) == 0) + return; + + await EnsureStoppedAsync().WaitAsync(cancellationToken).ConfigureAwait(false); + _completion.TrySetResult(); + } - /// Dispose every node and link in order, and tear down error/event subscriptions. public async ValueTask DisposeAsync() { - // Dispose the runtime first: it completes the nodes and the aggregated event stream, - // which completes the subscription sinks (they are linked with completion propagation). - await _runtime.DisposeAsync().ConfigureAwait(false); + if (Interlocked.Exchange(ref _disposed, 1) != 0) + return; - foreach (var subscription in _subscriptions) - subscription.Dispose(); + try + { + if (Volatile.Read(ref _started) != 0) + await EnsureStoppedAsync().ConfigureAwait(false); + await Application.DisposeAsync().ConfigureAwait(false); + } + finally + { + if (Volatile.Read(ref _started) == 0) + _completion.TrySetResult(); + + foreach (var subscription in _subscriptions) + subscription.Dispose(); + _events.Complete(); + if (_services is IAsyncDisposable asyncDisposable) + await asyncDisposable.DisposeAsync().ConfigureAwait(false); + else if (_services is IDisposable disposable) + disposable.Dispose(); + } + } + + private async Task StopWhenSourcesCompleteAsync() + { + try + { + await _sourceCompletion.ConfigureAwait(false); + await EnsureStoppedAsync().ConfigureAwait(false); + _completion.TrySetResult(); + } + catch (Exception exception) + { + try + { + await EnsureStoppedAsync().ConfigureAwait(false); + } + catch + { + // The source failure remains the authoritative graph failure. + } + _completion.TrySetException(exception); + } + } + + private Task EnsureStoppedAsync() + { + lock (_lifecycleGate) + return _stopTask ??= Application.StopAsync(CancellationToken.None).AsTask(); + } + + private async Task CompleteEventsAsync(IReadOnlyList> sources) + { + try + { + await Task.WhenAll(sources.Select(static source => source.Completion)) + .ConfigureAwait(false); + _events.Complete(); + } + catch (Exception exception) + { + ((IDataflowBlock)_events).Fault(exception); + } } private IDisposable Subscribe(ISourceBlock source, Action handler) { var sink = new ActionBlock(item => { - // An observer must not be able to break the subscription or fault the shared stream, - // so a handler bug is isolated here rather than tearing observation down. try { handler(item); } catch { - // Intentionally swallowed: OnError/OnEvent are diagnostic sinks. + // Diagnostic observers cannot break the workflow. } }); diff --git a/src/FluxFlow.Fluent/FlowGraphBuilder.cs b/src/FluxFlow.Fluent/FlowGraphBuilder.cs index 24cb9589..75f3cf72 100644 --- a/src/FluxFlow.Fluent/FlowGraphBuilder.cs +++ b/src/FluxFlow.Fluent/FlowGraphBuilder.cs @@ -1,92 +1,199 @@ using System.Threading.Tasks.Dataflow; using FluxFlow.Composition; +using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; +using FluxFlow.Composition.Model; using FluxFlow.Nodes; namespace FluxFlow.Fluent; /// -/// Mutable accumulator shared by every in one fluent chain: it -/// collects the composed nodes (de-duplicated by reference so the same node can be a fan-in -/// target of several branches), the links wiring them, and which nodes are entry (source) nodes. -/// wires completion and hands everything to -/// . +/// Collects the fluent chain into the same immutable application definition and component +/// contracts used by the general code-first authoring API. /// -/// -/// Links are created without TPL Dataflow's PropagateCompletion. Instead, each node is -/// completed once all of its upstream sources finish (). Propagating -/// completion per-link would let the first upstream of a fan-in node complete it prematurely and -/// drop the other branches' messages; waiting for every upstream is correct for linear, fan-out, -/// and fan-in graphs alike, and faults propagate the same way. -/// internal sealed class FlowGraphBuilder { - private readonly List _nodes = new(); - private readonly HashSet _registered = new(ReferenceEqualityComparer.Instance); - private readonly List _entryNodes = new(); - private readonly List _links = new(); - private readonly Dictionary> _upstreamCompletions = + private const string InputPort = "Input"; + private const string OutputPort = "Output"; + private const string EventsPort = "Events"; + + private readonly ApplicationDefinitionBuilder _application = new(); + private readonly WorkflowDefinitionBuilder _workflow; + private readonly Dictionary _nodes = + new(ReferenceEqualityComparer.Instance); + private readonly Dictionary _branches = new(ReferenceEqualityComparer.Instance); - private readonly List> _eventHandlers = new(); + private readonly List> _eventSources = []; + private readonly List> _eventHandlers = []; + private int _nextComponent; + + internal FlowGraphBuilder() + { + _workflow = _application.AddWorkflow("main"); + } - /// Register a node once (by reference). Repeated registrations of the same node — as - /// happens when several branches fan into one sink — are ignored. - public void Register(ComponentInstance node, bool isEntry) + internal FluentSourceHandle RegisterSource(FlowSource source) { - if (!_registered.Add(node.Node)) - return; + ArgumentNullException.ThrowIfNull(source); + if (_nodes.TryGetValue(source, out var existing)) + return (FluentSourceHandle)existing; - _nodes.Add(node); - if (isEntry) - _entryNodes.Add(node); + var identity = NextIdentity(); + var contract = ComponentContract.Create>( + identity.Type, + runtime => runtime + .UseFactory(_ => source) + .HasOutput(OutputPort, static node => node.Output) + .HasEvents(EventsPort, static node => node.Events), + static component => new FluentSourceHandle(component)); + var handle = _workflow.AddComponent(identity.Name, contract); + _nodes.Add(source, handle); + _eventSources.Add(source.Events); + return handle; } - /// Link a typed source port to a target node's input and record the completion edge. - public void Link( - ISourceBlock> source, - IFlowNode targetNode, - ITargetBlock> targetInput) + internal FluentNodeHandle RegisterNode( + FlowNode node) { - _links.Add(source.LinkTo(targetInput)); + ArgumentNullException.ThrowIfNull(node); + if (_nodes.TryGetValue(node, out var existing)) + return (FluentNodeHandle)existing; + + var identity = NextIdentity(); + var contract = ComponentContract.Create>( + identity.Type, + runtime => runtime + .UseFactory(_ => node) + .HasInput(InputPort, static value => value.Input) + .HasOutput(OutputPort, static value => value.Output) + .HasEvents(EventsPort, static value => value.Events), + static component => new FluentNodeHandle(component)); + var handle = _workflow.AddComponent(identity.Name, contract); + _nodes.Add(node, handle); + _eventSources.Add(node.Events); + return handle; + } - if (!_upstreamCompletions.TryGetValue(targetNode, out var completions)) - { - completions = new List(); - _upstreamCompletions[targetNode] = completions; - } + internal FluentBranchHandle RegisterBranch(ISourceBlock> source) + { + ArgumentNullException.ThrowIfNull(source); + if (_branches.TryGetValue(source, out var existing)) + return (FluentBranchHandle)existing; - completions.Add(source.Completion); + var adapter = new BorrowedOutputNode(source); + var identity = NextIdentity(); + var contract = ComponentContract.Create>( + identity.Type, + runtime => runtime + .UseFactory(_ => adapter) + .HasSignalInput("Dependency", static node => node) + .HasOutput(OutputPort, static node => node.Output), + static component => new FluentBranchHandle(component)); + var handle = _workflow.AddComponent(identity.Name, contract); + _branches.Add(source, handle); + return handle; } - public void OnEvent(Action handler) => _eventHandlers.Add(handler); + internal void Connect(OutputPortHandle source, InputPortHandle target) + => _workflow.Connect(source, target); - public FlowGraph Build() - { - if (_entryNodes.Count == 0) - throw new InvalidOperationException("A flow must start from at least one source (Flow.From)."); + internal void Connect(OutputPortHandle source, SignalInputPortHandle target) + => _workflow.Connect(source, target); - foreach (var (target, completions) in _upstreamCompletions) - _ = CompleteWhenUpstreamsFinishAsync(completions, target); + internal void OnEvent(Action handler) + { + ArgumentNullException.ThrowIfNull(handler); + _eventHandlers.Add(handler); + } - var graph = new FlowGraph(ApplicationRuntime.Create(_nodes, _links, _entryNodes)); + internal FlowGraph Build() + { + if (_nodes.Count == 0) + throw new InvalidOperationException("A flow must start from at least one source (Flow.From)."); - // Wire deferred handlers now that the runtime (and its aggregated streams) exist, before - // the caller starts the flow — so they observe from the first message. + var graph = new FlowGraph( + _application.Build(), + _eventSources, + _nodes.Keys + .OfType() + .Select(static source => source.Completion) + .ToArray()); foreach (var handler in _eventHandlers) graph.OnEvent(handler); - return graph; } - private static async Task CompleteWhenUpstreamsFinishAsync(List upstreams, IFlowNode target) + private (string Name, string Type) NextIdentity() + { + var id = ++_nextComponent; + return ($"node{id:D4}", $"fluent.node.{id:D4}"); + } + +} + +internal sealed class FluentSourceHandle : AuthoredComponentHandle +{ + internal FluentSourceHandle(ComponentHandle definition) : base(definition) + { + Output = definition.Output("Output"); + Events = definition.Output("Events"); + } + + internal OutputPortHandle Output { get; } + + internal OutputPortHandle Events { get; } +} + +internal sealed class FluentNodeHandle : AuthoredComponentHandle +{ + internal FluentNodeHandle(ComponentHandle definition) : base(definition) + { + Input = definition.Input("Input"); + Output = definition.Output("Output"); + Events = definition.Output("Events"); + } + + internal InputPortHandle Input { get; } + + internal OutputPortHandle Output { get; } + + internal OutputPortHandle Events { get; } +} + +internal sealed class FluentBranchHandle : AuthoredComponentHandle +{ + internal FluentBranchHandle(ComponentHandle definition) : base(definition) { - try - { - await Task.WhenAll(upstreams).ConfigureAwait(false); - target.Complete(); - } - catch (Exception exception) - { - target.Fault(exception); - } + Dependency = definition.SignalInput("Dependency"); + Output = definition.Output("Output"); } + + internal SignalInputPortHandle Dependency { get; } + + internal OutputPortHandle Output { get; } +} + +internal sealed class BorrowedOutputNode(ISourceBlock> output) : + IFlowNode, + IFlowSignalTarget +{ + internal ISourceBlock> Output { get; } = + output ?? throw new ArgumentNullException(nameof(output)); + + public Task Completion => Output.Completion; + + public void Complete() { } + + public void Fault(Exception exception) => ArgumentNullException.ThrowIfNull(exception); + + public ValueTask SendAsync( + FlowMessage signal, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(signal); + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(true); + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; } diff --git a/src/FluxFlow.Fluent/FluxFlow.Fluent.csproj b/src/FluxFlow.Fluent/FluxFlow.Fluent.csproj index 3244e9bb..5e723e92 100644 --- a/src/FluxFlow.Fluent/FluxFlow.Fluent.csproj +++ b/src/FluxFlow.Fluent/FluxFlow.Fluent.csproj @@ -16,9 +16,11 @@ + + diff --git a/src/FluxFlow.Fluent/README.md b/src/FluxFlow.Fluent/README.md index 49da068c..ab80e636 100644 --- a/src/FluxFlow.Fluent/README.md +++ b/src/FluxFlow.Fluent/README.md @@ -4,8 +4,9 @@ Type-safe, code-first fluent DSL for composing `FluxFlow.Nodes`. Use this package when you want to wire standalone nodes into a runnable graph in C# with the compiler checking every connection, instead of canonical string/JSON -application links. It reuses the `FluxFlow.Composition` runtime for -lifecycle, error/event aggregation, and disposal. +application links. The fluent builder produces the same canonical +`ApplicationDefinition` and runs it with an owned `FluxFlowApplication`; it is +a concise facade, not a second workflow runtime. ## Why @@ -22,11 +23,21 @@ work in payload types. - the fluent builder (`Flow`, `FlowBuilder`, `FlowTerminal`) - compile-time-checked linear chains, fan-out (`Tap`), branching (`Branch` from a typed output port), and fan-in (share one node instance across branches) -- the built `FlowGraph` (start, stop, completion, error/event streams, disposal) - -It does not own node implementations, the runtime, a component catalog, JSON/config -loading, or persistence — nodes come from `FluxFlow.Nodes` (and the component -packages), and the runtime comes from `FluxFlow.Composition`. +- explicit instance-backed component contracts and canonical typed links +- the built `FlowGraph` (definition, canonical application, start, stop, + completion, event stream, disposal) + +It does not own node implementations, a parallel runtime, JSON/configuration +loading, or persistence. Nodes come from `FluxFlow.Nodes` (and component +packages); lifecycle, stable routing, and staged graph draining come from +`FluxFlow.Engine`. + +`ApplicationDefinitionBuilder` remains the general code-first surface for named +resources, workflows, reusable package contracts, typed handles, conditions, +and host-managed revisions. `FluxFlow.Fluent` is the smaller instance-first +surface for `From`/`Then`/`Tap`/`Branch`/`Apply` chains. Both converge on the +same immutable definition and Engine lifecycle. Neither serializes constructed +node instances or C# behavior into JSON. ## Capacity configuration @@ -75,6 +86,9 @@ await using var flow = Flow await flow.StartAsync(); await flow.Completion; + +var definition = flow.Definition; +var application = flow.Application; ``` ## Fan-out, branching, and fan-in @@ -100,23 +114,23 @@ in more than one branch fans them into that node. Each node completes once all o its upstream sources finish, so fan-in drains correctly rather than being completed early by the first branch. -## Observing errors and events +## Observing events and failures ```csharp await using var flow = Flow .From(new WordSource(["alpha", "beta"])) .Then(new RiskyNode()) .To(new CollectSink(collector)) - .OnError(error => logger.LogError(error.Exception, "{Message}", error.Message)) .OnEvent(@event => logger.LogInformation("{Name}", @event.Name)) .Build(); ``` -`OnError`/`OnEvent` observe the flow's aggregated error/event streams. They are -also available on the built `FlowGraph` (returning an `IDisposable` you can -dispose to unsubscribe). Observation is best-effort (the underlying stream is a -latest-wins broadcast), a throwing handler is isolated so it cannot break -observation, and subscriptions are torn down with the graph. +`OnEvent` observes the nodes' aggregated event stream. It is also available on +the built `FlowGraph` and returns an `IDisposable` for explicit unsubscribe. +Observation is best-effort, a throwing handler is isolated so it cannot break +the workflow, and subscriptions are torn down with the graph. Expected node +processing failures remain ordinary error-valued `FlowMessage` data; +terminal source/node faults surface through `Completion`. ## Reusable named sub-flows diff --git a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttApplicationAuthoringExtensions.cs b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttApplicationAuthoringExtensions.cs index 8a5e67dc..a8800904 100644 --- a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttApplicationAuthoringExtensions.cs +++ b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttApplicationAuthoringExtensions.cs @@ -1,7 +1,82 @@ +using FluxFlow.Composition; using FluxFlow.Composition.Authoring; +using FluxFlow.Components.Designer; namespace FluxFlow.Components.Mqtt.Composition; +public static class MqttResources +{ + internal static IApplicationResourceRegistrar Registrar { get; } = + new MqttCompositionResourceRegistrar(); + + public static ApplicationResourceContract Broker { get; } = + ApplicationResourceContract.Create( + MqttComponentDefinition.ResourceTypes.Broker, + Registrar, + static () => new MqttBrokerResourceBuilder(), + static (options, definition) => options.Apply(definition), + static resource => new MqttBrokerResourceHandle(resource)); + + public static ApplicationResourceContract RetryPolicy { get; } = + ApplicationResourceContract.Create( + MqttComponentDefinition.ResourceTypes.Retry, + Registrar, + static () => new MqttRetryPolicyResourceBuilder(), + static (options, definition) => options.Apply(definition), + static resource => new MqttRetryPolicyResourceHandle(resource)); + + public static ApplicationResourceContract Subscription { get; } = + ApplicationResourceContract.Create( + MqttComponentDefinition.ResourceTypes.Subscription, + Registrar, + static () => new MqttSubscriptionResourceBuilder(), + static (options, definition) => options.Apply(definition), + static resource => new MqttSubscriptionResourceHandle(resource)); + + public static ApplicationResourceContract Client { get; } = + ApplicationResourceContract.Create( + MqttComponentDefinition.ResourceTypes.Client, + Registrar, + static () => new MqttClientResourceBuilder(), + static (options, definition) => options.Apply(definition), + static resource => new MqttClientResourceHandle(resource)); +} + +public static class MqttComponents +{ + public static ComponentContract MqttCommand { get; } = + DesignedComponentContract.Create( + MqttComponentDefinition.Types.Control, + MqttServiceCollectionExtensions.ConfigureControl, + static () => new MqttCommandBuilder(), + static (options, definition) => options.Apply(definition), + static component => new MqttCommandHandle(component)); + + public static ComponentContract MqttPublish { get; } = + DesignedComponentContract.Create( + MqttComponentDefinition.Types.Publish, + MqttServiceCollectionExtensions.ConfigurePublish, + static () => new MqttPublishBuilder(), + static (options, definition) => options.Apply(definition), + static component => new MqttPublishHandle(component)); + + public static ComponentContract MqttReceive { get; } = + DesignedComponentContract.Create( + MqttComponentDefinition.Types.Trigger, + MqttServiceCollectionExtensions.ConfigureTrigger, + static () => new MqttReceiveBuilder(), + static (options, definition) => options.Apply(definition), + static component => new MqttReceiveHandle(component)); + + public static ComponentContract MqttEvents { get; } = + DesignedComponentContract.Create( + MqttComponentDefinition.Types.Events, + MqttServiceCollectionExtensions.ConfigureEvents, + static () => new MqttEventsBuilder(), + static (options, definition) => options.Apply(definition), + static component => new MqttEventsHandle(component)); +} + public static class MqttApplicationAuthoringExtensions { public static MqttBrokerResourceHandle AddMqttBroker( @@ -11,16 +86,7 @@ public static MqttBrokerResourceHandle AddMqttBroker( { ArgumentNullException.ThrowIfNull(resources); ArgumentNullException.ThrowIfNull(configure); - var handle = resources.AddResource( - name, - MqttComponentDefinition.ResourceTypes.Broker, - definition => - { - var builder = new MqttBrokerResourceBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new MqttBrokerResourceHandle(handle); + return resources.AddResource(name, MqttResources.Broker, configure); } public static TResources AddMqttBroker( @@ -40,16 +106,10 @@ public static MqttRetryPolicyResourceHandle AddMqttRetryPolicy( Action? configure = null) { ArgumentNullException.ThrowIfNull(resources); - var handle = resources.AddResource( + return resources.AddResource( name, - MqttComponentDefinition.ResourceTypes.Retry, - definition => - { - var builder = new MqttRetryPolicyResourceBuilder(); - configure?.Invoke(builder); - builder.Apply(definition); - }); - return new MqttRetryPolicyResourceHandle(handle); + MqttResources.RetryPolicy, + configure ?? (static _ => { })); } public static TResources AddMqttRetryPolicy( @@ -81,16 +141,7 @@ public static MqttSubscriptionResourceHandle AddMqttSubscription( { ArgumentNullException.ThrowIfNull(resources); ArgumentNullException.ThrowIfNull(configure); - var handle = resources.AddResource( - name, - MqttComponentDefinition.ResourceTypes.Subscription, - definition => - { - var builder = new MqttSubscriptionResourceBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new MqttSubscriptionResourceHandle(handle); + return resources.AddResource(name, MqttResources.Subscription, configure); } public static TResources AddMqttSubscription( @@ -111,16 +162,7 @@ public static MqttClientResourceHandle AddMqttClient( { ArgumentNullException.ThrowIfNull(resources); ArgumentNullException.ThrowIfNull(configure); - var handle = resources.AddResource( - name, - MqttComponentDefinition.ResourceTypes.Client, - definition => - { - var builder = new MqttClientResourceBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new MqttClientResourceHandle(handle); + return resources.AddResource(name, MqttResources.Client, configure); } public static TResources AddMqttClient( @@ -138,20 +180,7 @@ public static MqttCommandHandle AddMqttCommand( this WorkflowDefinitionBuilder workflow, string name, Action configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var handle = workflow.AddComponent( - name, - MqttComponentDefinition.Types.Control, - definition => - { - var builder = new MqttCommandBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new MqttCommandHandle(handle); - } + => workflow.AddComponent(name, MqttComponents.MqttCommand, configure); public static WorkflowDefinitionBuilder AddMqttCommand( this WorkflowDefinitionBuilder workflow, @@ -167,20 +196,7 @@ public static MqttPublishHandle AddMqttPublish( this WorkflowDefinitionBuilder workflow, string name, Action configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var handle = workflow.AddComponent( - name, - MqttComponentDefinition.Types.Publish, - definition => - { - var builder = new MqttPublishBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new MqttPublishHandle(handle); - } + => workflow.AddComponent(name, MqttComponents.MqttPublish, configure); public static WorkflowDefinitionBuilder AddMqttPublish( this WorkflowDefinitionBuilder workflow, @@ -196,20 +212,7 @@ public static MqttReceiveHandle AddMqttReceive( this WorkflowDefinitionBuilder workflow, string name, Action configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var handle = workflow.AddComponent( - name, - MqttComponentDefinition.Types.Trigger, - definition => - { - var builder = new MqttReceiveBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new MqttReceiveHandle(handle); - } + => workflow.AddComponent(name, MqttComponents.MqttReceive, configure); public static WorkflowDefinitionBuilder AddMqttReceive( this WorkflowDefinitionBuilder workflow, @@ -225,20 +228,7 @@ public static MqttEventsHandle AddMqttEvents( this WorkflowDefinitionBuilder workflow, string name, Action configure) - { - ArgumentNullException.ThrowIfNull(workflow); - ArgumentNullException.ThrowIfNull(configure); - var handle = workflow.AddComponent( - name, - MqttComponentDefinition.Types.Events, - definition => - { - var builder = new MqttEventsBuilder(); - configure(builder); - builder.Apply(definition); - }); - return new MqttEventsHandle(handle); - } + => workflow.AddComponent(name, MqttComponents.MqttEvents, configure); public static WorkflowDefinitionBuilder AddMqttEvents( this WorkflowDefinitionBuilder workflow, diff --git a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttComponentAuthoring.cs b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttComponentAuthoring.cs index 95cd1c00..170da14c 100644 --- a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttComponentAuthoring.cs +++ b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttComponentAuthoring.cs @@ -4,7 +4,7 @@ using FluxFlow.Components.Mqtt.Events; using FluxFlow.Components.Mqtt.Options; using FluxFlow.Components.Mqtt.Subscriptions; -using FluxFlow.Composition.Addressing; +using FluxFlow.Composition; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Mqtt.Composition; @@ -130,20 +130,11 @@ internal void Apply(ComponentDefinitionBuilder definition) } } -public abstract class MqttComponentHandle +public abstract class MqttComponentHandle : AuthoredComponentHandle { - private protected MqttComponentHandle(ComponentHandle definition) + private protected MqttComponentHandle(ComponentHandle definition) : base(definition) { - Definition = definition; } - - protected ComponentHandle Definition { get; } - - public ApplicationAddress Address => Definition.Address; - - public string Name => Definition.Name; - - public override string ToString() => Address.Value; } public sealed class MqttCommandHandle : MqttComponentHandle @@ -152,10 +143,12 @@ internal MqttCommandHandle(ComponentHandle definition) : base(definition) { Input = definition.Input(MqttComponentDefinition.Ports.Input); Output = definition.Output(MqttComponentDefinition.Ports.Output); + Events = definition.Output(MqttComponentDefinition.Ports.Events); } public InputPortHandle Input { get; } public OutputPortHandle Output { get; } + public OutputPortHandle Events { get; } } public sealed class MqttPublishHandle : MqttComponentHandle @@ -164,10 +157,12 @@ internal MqttPublishHandle(ComponentHandle definition) : base(definition) { Input = definition.Input(MqttComponentDefinition.Ports.Input); Output = definition.Output(MqttComponentDefinition.Ports.Output); + Events = definition.Output(MqttComponentDefinition.Ports.Events); } public InputPortHandle Input { get; } public OutputPortHandle Output { get; } + public OutputPortHandle Events { get; } } public sealed class MqttReceiveHandle : MqttComponentHandle @@ -177,11 +172,13 @@ internal MqttReceiveHandle(ComponentHandle definition) : base(definition) Ack = definition.SignalInput(MqttComponentDefinition.Ports.Ack); Nak = definition.SignalInput(MqttComponentDefinition.Ports.Nak); Output = definition.Output(MqttComponentDefinition.Ports.Output); + Events = definition.Output(MqttComponentDefinition.Ports.Events); } public SignalInputPortHandle Ack { get; } public SignalInputPortHandle Nak { get; } public OutputPortHandle Output { get; } + public OutputPortHandle Events { get; } } public sealed class MqttEventsHandle : MqttComponentHandle @@ -189,7 +186,9 @@ public sealed class MqttEventsHandle : MqttComponentHandle internal MqttEventsHandle(ComponentHandle definition) : base(definition) { Output = definition.Output(MqttComponentDefinition.Ports.Output); + Events = definition.Output(MqttComponentDefinition.Ports.Events); } public OutputPortHandle Output { get; } + public OutputPortHandle Events { get; } } diff --git a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttResourceAuthoring.cs b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttResourceAuthoring.cs index 9caacd8c..a6c6ee36 100644 --- a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttResourceAuthoring.cs +++ b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttResourceAuthoring.cs @@ -1,25 +1,13 @@ using FluxFlow.Components.Mqtt.Configuration; using FluxFlow.Components.Mqtt.Contracts; using FluxFlow.Components.Mqtt.Subscriptions; -using FluxFlow.Composition.Addressing; using FluxFlow.Composition.Authoring; namespace FluxFlow.Components.Mqtt.Composition; -public abstract class MqttResourceHandle +public abstract class MqttResourceHandle : AuthoredResourceHandle { - private protected MqttResourceHandle(ResourceHandle definition) - { - Definition = definition; - } - - internal ResourceHandle Definition { get; } - - public ApplicationAddress Address => Definition.Address; - - public string Name => Definition.Name; - - public override string ToString() => Address.Value; + private protected MqttResourceHandle(ResourceHandle definition) : base(definition) { } } public sealed class MqttBrokerResourceHandle : MqttResourceHandle diff --git a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttComponentDefinition.cs b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttComponentDefinition.cs index 848af1e5..4be2b38b 100644 --- a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttComponentDefinition.cs +++ b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttComponentDefinition.cs @@ -17,7 +17,7 @@ public static class Options } public static class Types { public const string Control = "mqtt.command"; public const string Publish = "mqtt.publish"; public const string Trigger = "mqtt.receive"; public const string Events = "mqtt.events"; } - public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Ack = "Ack"; public const string Nak = "Nak"; } + public static class Ports { public const string Input = "Input"; public const string Output = "Output"; public const string Ack = "Ack"; public const string Nak = "Nak"; public const string Events = "Events"; } public static class Resources { public const string Client = "Client"; public const string Clock = "Clock"; } public static class ResourceTypes { public const string Broker = "mqtt.broker"; public const string Client = "mqtt.client"; public const string Subscription = "mqtt.subscription"; public const string Retry = "retry.policy"; } diff --git a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttCompositionNodeFactories.cs b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttCompositionNodeFactories.cs index 3bcd0790..bdf87c1d 100644 --- a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttCompositionNodeFactories.cs +++ b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttCompositionNodeFactories.cs @@ -18,91 +18,38 @@ internal static class MqttCompositionNodeFactories NumberHandling = JsonNumberHandling.AllowReadingFromString }; - internal static async ValueTask CreateControlNodeAsync( + internal static async ValueTask CreateControlNodeAsync( ComponentActivationContext context) { var controller = await GetStartedControllerAsync(context).ConfigureAwait(false); - var node = new MqttControlNode(controller, context.BindConfiguration()); - return ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - MqttComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - MqttComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events); + return new MqttControlNode(controller, context.BindConfiguration()); } - internal static async ValueTask CreatePublishNodeAsync( + internal static async ValueTask CreatePublishNodeAsync( ComponentActivationContext context) { var controller = await GetStartedControllerAsync(context).ConfigureAwait(false); var options = context.BindConfiguration(); - var node = new MqttPublishOperationNode(controller, options.MaximumPendingRequests); - return ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input( - MqttComponentDefinition.Ports.Input, - node.Input) - ], - outputs: - [ - ComponentPorts.Output( - MqttComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events); + return new MqttPublishOperationNode(controller, options.MaximumPendingRequests); } - internal static async ValueTask CreateTriggerNodeAsync( + internal static async ValueTask CreateTriggerNodeAsync( ComponentActivationContext context) { var controller = await GetStartedControllerAsync(context).ConfigureAwait(false); var options = context.BindConfiguration(); - var node = new MqttSubscriptionTriggerNode( + return new MqttSubscriptionTriggerNode( controller, BindTriggerOptions(context, options), context.GetResource(MqttComponentDefinition.Resources.Clock)); - return ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.SignalInput(MqttComponentDefinition.Ports.Ack, node.Ack), - ComponentPorts.SignalInput(MqttComponentDefinition.Ports.Nak, node.Nak) - ], - outputs: - [ - ComponentPorts.Output( - MqttComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events); } - internal static async ValueTask CreateEventsNodeAsync( + internal static async ValueTask CreateEventsNodeAsync( ComponentActivationContext context) { var controller = await GetStartedControllerAsync(context).ConfigureAwait(false); var options = context.BindConfiguration(); - var node = new MqttClientEventsNode(controller, options.MaximumPendingEvents); - return ComponentInstance.Create( - node, - outputs: - [ - ComponentPorts.Output( - MqttComponentDefinition.Ports.Output, - node.Output) - ], - events: node.Events); + return new MqttClientEventsNode(controller, options.MaximumPendingEvents); } private static async ValueTask GetStartedControllerAsync( diff --git a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttServiceCollectionExtensions.cs b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttServiceCollectionExtensions.cs index 63851891..b5035e26 100644 --- a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttServiceCollectionExtensions.cs +++ b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttServiceCollectionExtensions.cs @@ -15,39 +15,47 @@ public static class MqttServiceCollectionExtensions public static FluxFlowRegistrationBuilder AddMqtt(this FluxFlowRegistrationBuilder builder) { ArgumentNullException.ThrowIfNull(builder); - builder.Services.AddApplicationResourceRegistrar(); + builder.Services.AddApplicationResourceRegistrar(MqttResources.Registrar); return builder - .AddComponent(MqttComponentDefinition.Types.Control, ConfigureControl) - .AddComponent(MqttComponentDefinition.Types.Publish, ConfigurePublish) - .AddComponent(MqttComponentDefinition.Types.Trigger, ConfigureTrigger) - .AddComponent(MqttComponentDefinition.Types.Events, ConfigureEvents); + .AddDesignedComponent(MqttComponents.MqttCommand) + .AddDesignedComponent(MqttComponents.MqttPublish) + .AddDesignedComponent(MqttComponents.MqttReceive) + .AddDesignedComponent(MqttComponents.MqttEvents); } - private static void ConfigureControl(ComponentRegistrationBuilder component) + internal static void ConfigureControl(ComponentRegistrationBuilder component) { var defaults = new MqttControlOptions(); - ConfigureCommon(component, MqttCompositionNodeFactories.CreateControlNodeAsync, "MQTT Command", "Executes lifecycle, status, publish, and subscription requests for one logical client.", "sliders-horizontal", "mqttCommand", 460); + ConfigureCommon(component, "MQTT Command", "Executes lifecycle, status, publish, and subscription requests for one logical client.", "sliders-horizontal", "mqttCommand", 460); AddEnum(component, MqttComponentDefinition.Options.RequestProcessing, "Request Processing", "Processing", OptionDesignMetadataAttributeValues.Primary, defaults.RequestProcessing); AddEnum(component, MqttComponentDefinition.Options.ResultOrder, "Result Order", "Processing", OptionDesignMetadataAttributeValues.Advanced, defaults.ResultOrder); AddNumber(component, MqttComponentDefinition.Options.MaximumConcurrentRequests, "Maximum Concurrent Requests", "Maximum requests processed concurrently by the control component.", defaults.MaximumConcurrentRequests); AddNumber(component, MqttComponentDefinition.Options.MaximumPendingRequests, "Maximum Pending Requests", "Capacity used for queued requests and reliable normal-data result output.", defaults.MaximumPendingRequests); AddClient(component); - AddMessagePorts(component); + component + .UseFactory(MqttCompositionNodeFactories.CreateControlNodeAsync) + .HasInput(MqttComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Input message.", true) + .HasOutput(MqttComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Operation result.", true) + .HasEvents(MqttComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort MQTT command diagnostics."); } - private static void ConfigurePublish(ComponentRegistrationBuilder component) + internal static void ConfigurePublish(ComponentRegistrationBuilder component) { var defaults = new MqttPublishCompositionOptions(); - ConfigureCommon(component, MqttCompositionNodeFactories.CreatePublishNodeAsync, "MQTT Publish", "Publishes one exact-content MQTT message through a logical client.", "send", "publishMqtt", 420); + ConfigureCommon(component, "MQTT Publish", "Publishes one exact-content MQTT message through a logical client.", "send", "publishMqtt", 420); AddNumber(component, MqttComponentDefinition.Options.MaximumPendingRequests, "Maximum Pending Requests", "Capacity used for queued publish requests and reliable normal-data result output.", defaults.MaximumPendingRequests); AddClient(component); - AddMessagePorts(component); + component + .UseFactory(MqttCompositionNodeFactories.CreatePublishNodeAsync) + .HasInput(MqttComponentDefinition.Ports.Input, static node => node.Input, "Input", "Messages", 0, "Input message.", true) + .HasOutput(MqttComponentDefinition.Ports.Output, static node => node.Output, "Output", "Results", 1, "Operation result.", true) + .HasEvents(MqttComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 2, "Best-effort MQTT publish diagnostics."); } - private static void ConfigureTrigger(ComponentRegistrationBuilder component) + internal static void ConfigureTrigger(ComponentRegistrationBuilder component) { var defaults = new MqttSubscriptionTriggerOptions { TriggerId = "designer" }; - ConfigureCommon(component, MqttCompositionNodeFactories.CreateTriggerNodeAsync, "MQTT Receive", "Emits received messages for named or inline subscriptions and accepts Ack/Nak signals.", "radio-tower", "mqttReceive", 500); + ConfigureCommon(component, "MQTT Receive", "Emits received messages for named or inline subscriptions and accepts Ack/Nak signals.", "radio-tower", "mqttReceive", 500); component.AddOption(MqttComponentDefinition.Options.Subscription, OptionValueKind.Json, "Subscription", "One named subscription, one inline subscription, or a mixed array.", true, section: "Subscription", importance: OptionDesignMetadataAttributeValues.Primary, editor: OptionDesignMetadataAttributeValues.Json); AddEnum(component, MqttComponentDefinition.Options.WorkflowAcknowledgement, "Workflow Acknowledgement", "Delivery", OptionDesignMetadataAttributeValues.Primary, defaults.WorkflowAcknowledgement); AddEnum(component, MqttComponentDefinition.Options.BrokerAcknowledgement, "Broker Acknowledgement", "Delivery", OptionDesignMetadataAttributeValues.Advanced, defaults.BrokerAcknowledgement); @@ -55,35 +63,34 @@ private static void ConfigureTrigger(ComponentRegistrationBuilder component) AddNumber(component, MqttComponentDefinition.Options.MaximumPendingMessages, "Maximum Pending Messages", "Capacity used for pending broker messages and reliable normal-data trigger output.", defaults.MaximumPendingMessages); AddClient(component); component.AddResource(MqttComponentDefinition.Resources.Clock, "Clock", 1, "Optional deterministic trigger timeout clock.", designValueType: nameof(TimeProvider), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Clock, keyPattern: "Resources.{name}"); - component.AddSignalInput(MqttComponentDefinition.Ports.Ack, "Ack", "Signals", 0, "Acknowledges the pending delivery with the same trace identity.", true); - component.AddSignalInput(MqttComponentDefinition.Ports.Nak, "Nak", "Signals", 1, "Rejects the pending delivery with the same trace identity."); - component.AddOutput(MqttComponentDefinition.Ports.Output, "Output", "Messages", 2, "Received MQTT application message.", true); + component + .UseFactory(MqttCompositionNodeFactories.CreateTriggerNodeAsync) + .HasSignalInput(MqttComponentDefinition.Ports.Ack, static node => node.Ack, "Ack", "Signals", 0, "Acknowledges the pending delivery with the same trace identity.", true) + .HasSignalInput(MqttComponentDefinition.Ports.Nak, static node => node.Nak, "Nak", "Signals", 1, "Rejects the pending delivery with the same trace identity.") + .HasOutput(MqttComponentDefinition.Ports.Output, static node => node.Output, "Output", "Messages", 2, "Received MQTT application message.", true) + .HasEvents(MqttComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 3, "Best-effort MQTT receive diagnostics."); } - private static void ConfigureEvents(ComponentRegistrationBuilder component) + internal static void ConfigureEvents(ComponentRegistrationBuilder component) { var defaults = new MqttEventsCompositionOptions(); - ConfigureCommon(component, MqttCompositionNodeFactories.CreateEventsNodeAsync, "MQTT Events", "Emits reliable logical-client connection and subscription events.", "activity", "mqttEvents", 400); + ConfigureCommon(component, "MQTT Events", "Emits reliable logical-client connection and subscription events.", "activity", "mqttEvents", 400); AddNumber(component, MqttComponentDefinition.Options.MaximumPendingEvents, "Maximum Pending Events", "Capacity used for reliable normal-data logical-client event output.", defaults.MaximumPendingEvents); AddClient(component); - component.AddOutput(MqttComponentDefinition.Ports.Output, "Output", "Events", 0, "Logical MQTT client lifecycle event.", true); + component + .UseFactory(MqttCompositionNodeFactories.CreateEventsNodeAsync) + .HasOutput(MqttComponentDefinition.Ports.Output, static node => node.Output, "Output", "Events", 0, "Logical MQTT client lifecycle event.", true) + .HasEvents(MqttComponentDefinition.Ports.Events, static node => node.Events, "Events", "Diagnostics", 1, "Best-effort MQTT component diagnostics."); } - private static void ConfigureCommon(ComponentRegistrationBuilder component, ComponentFactory factory, string displayName, string summary, string iconKey, string preferredNodeName, int width) + private static void ConfigureCommon(ComponentRegistrationBuilder component, string displayName, string summary, string iconKey, string preferredNodeName, int width) { - component.UseFactory(factory); component.WithDisplay(displayName, "MQTT", summary, iconKey, preferredNodeName, width); } private static void AddClient(ComponentRegistrationBuilder component) => component.AddResource(MqttComponentDefinition.Resources.Client, "Client", 0, "Logical MQTT client controller resource.", true, nameof(IMqttClientController), ownership: ResourceDesignMetadataAttributeValues.HostOwned, pickerKind: ResourceDesignMetadataAttributeValues.Client, keyPattern: "Resources.{name}"); - private static void AddMessagePorts(ComponentRegistrationBuilder component) - { - component.AddInput(MqttComponentDefinition.Ports.Input, "Input", "Messages", 0, "Input message.", true); - component.AddOutput(MqttComponentDefinition.Ports.Output, "Output", "Results", 1, "Operation result.", true); - } - private static void AddNumber( ComponentRegistrationBuilder component, string name, diff --git a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/README.md b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/README.md index efcec06f..3419e2ca 100644 --- a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/README.md +++ b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/README.md @@ -22,16 +22,18 @@ Definitions use the exact canonical names above. Retired `resilience.retry`, before load. The host registers an `IMqttTransportFactory`, credentials, certificates, and -optional clocks. `AddMqtt()` adds the MQTT descriptors, Designer -provider, and `IApplicationResourceRegistrar`. During revision -preparation, that registrar validates MQTT resource references and registers +optional clocks. The four code-first resource contracts carry one shared MQTT +registrar into the built definition. `AddMqtt()` registers that exact registrar, +the official component contracts, and Designer metadata for JSON/configuration +hosts. During revision preparation, the effective registrar validates MQTT +resource references and registers broker, retry, subscription, client configuration, and one revision-owned controller per `mqtt.client` address. Host transports, credentials, certificates, clocks, and inline-secret policy are resolved explicitly from the host provider and are never transferred to revision ownership. It does not scan assemblies or choose a concrete MQTT provider. -## Registration +## JSON/configuration registration ```csharp using FluxFlow.Components.Mqtt.Composition; @@ -45,6 +47,10 @@ services .AddMqtt(); ``` +This explicit package registration is required when `definition` came from +JSON/configuration because portable JSON contains no CLR factory, registrar, or +contract delegates. + For different transports per client, register keyed factories under the full client resource address. A keyed factory takes precedence over the unkeyed host default. The same rule applies to an optional keyed `TimeProvider`. @@ -181,10 +187,26 @@ orders.AddMqttPublish( The direct form remains valid, for example `var client = messaging.AddMqttClient(...)`. Both forms call the same configuration and validation implementation and build the same canonical -resource properties. Capturing a component does not connect it: call +resource properties. Those calls also capture the exact executable application +resource contracts, so the compiled-C# host needs only: + +```csharp +services.AddSingleton(transportFactory); +services.AddFluxFlow(application.Build()); +``` + +Do not repeat `.AddMqtt()` for this code-first definition. Capturing a component +does not connect it: call `orders.Connect(...)` with real typed ports, or `application.Connect(...)` for an intentional cross-workflow link. +If an external host already owns a controller, bind it by the typed resource +handle instead of rebuilding its address: + +```csharp +services.AddExternalFluxFlowResource(client, controller); +``` + ## Node Contracts | Type | Input | Output | @@ -237,7 +259,7 @@ options, fixed ports, signal-port kind, and host-owned `Client`/`Clock` picker hints. The metadata is descriptive only; hosts still own resource catalogs, secret entry, rendering, persistence, and lifecycle policy. -## DI Registration +## JSON and dynamic-host registration This optional application-integration adapter registers its immutable `ComponentDescriptor` entries and explicit MqttComponentDefinition declarations through `IServiceCollection`: @@ -246,6 +268,17 @@ entries and explicit MqttComponentDefinition declarations through `IServiceColle services.AddFluxFlowComponents().AddMqtt(); ``` -The resulting `ComponentCatalog` is built once from DI registrations. Standalone -runtime nodes remain usable without this package, and referenced external resources -remain host-owned. +The resulting host registrations supply descriptors and the registrar for +definitions that did not originate from complete code-first contracts. +Standalone runtime nodes remain usable without this package, and referenced +external resources remain host-owned. + +## Code-first authoring + +`MqttComponents` exposes `MqttCommand`, `MqttPublish`, `MqttReceive`, and `MqttEvents` typed contracts. The retained `AddX` methods use those same contracts; named handles expose data or signal ports plus explicit `Events`. See [typed code-first authoring](../../../docs/39-typed-code-first-authoring.md). + +A definition built from these component and resource contracts retains its +executable descriptors and registrar. Normal code-first hosting therefore calls +only `AddFluxFlow(definition)` and does not repeat the family registration +above. Use that service registration for JSON/configuration, catalog, or dynamic +definitions that do not carry the complete contracts. diff --git a/tests/FluxFlow.Components.Assertions.Composition.Tests/AssertionsServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Assertions.Composition.Tests/AssertionsServiceCollectionExtensionsTests.cs index 88074371..9cca7dc5 100644 --- a/tests/FluxFlow.Components.Assertions.Composition.Tests/AssertionsServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Assertions.Composition.Tests/AssertionsServiceCollectionExtensionsTests.cs @@ -40,7 +40,7 @@ public void AddAssertions_registers_only_the_canonical_contract() assertion.Inputs.Keys.ShouldBe([AssertionsComponentDefinition.Ports.Input]); assertion.Outputs.Keys.ShouldBe([ AssertionsComponentDefinition.Ports.Output, - ComponentEvents.PortName + "Events" ], ignoreOrder: false); assertion.Inputs[AssertionsComponentDefinition.Ports.Input].MessageType.ShouldBe( typeof(JsonElement)); @@ -138,7 +138,7 @@ public void Design_declaration_describes_canonical_ports() port.ValueType?.Value)).ShouldBe([ (AssertionsComponentDefinition.Ports.Input, PortDirection.Input, 0, true, nameof(JsonElement)), (AssertionsComponentDefinition.Ports.Output, PortDirection.Output, 1, true, "AssertionResult"), - (ComponentEvents.PortName, PortDirection.Output, int.MaxValue, false, nameof(ComponentEvent)) + (AssertionsComponentDefinition.Ports.Events, PortDirection.Output, 2, false, nameof(ComponentEvent)) ]); } diff --git a/tests/FluxFlow.Components.Designer.Tests/ComponentDesignMetadataCatalogTests.cs b/tests/FluxFlow.Components.Designer.Tests/ComponentDesignMetadataCatalogTests.cs index 7ab01ac8..7690ac15 100644 --- a/tests/FluxFlow.Components.Designer.Tests/ComponentDesignMetadataCatalogTests.cs +++ b/tests/FluxFlow.Components.Designer.Tests/ComponentDesignMetadataCatalogTests.cs @@ -1,5 +1,7 @@ +using System.Threading.Tasks.Dataflow; using FluxFlow.Components.Designer.Contracts; using FluxFlow.Composition; +using FluxFlow.Nodes; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Xunit; @@ -35,7 +37,7 @@ public void Explicit_metadata_can_be_registered_in_catalog() catalog.TryGet(new ComponentType("sample.catalog"), out var found).ShouldBeTrue(); found.ShouldNotBeSameAs(metadata); - found.Ports.Select(port => port.Name.Value).ShouldBe(["Input", "Output", "Events"]); + found.Ports.Select(port => port.Name.Value).ShouldBe(["Input", "Output"]); } [Fact] @@ -50,7 +52,7 @@ public void Catalog_resolves_only_exact_component_types() } [Fact] - public void Catalog_adds_the_reserved_component_events_output() + public void Catalog_does_not_add_an_implicit_component_events_output() { var catalog = new ComponentDesignMetadataCatalog( [ @@ -71,13 +73,8 @@ public void Catalog_adds_the_reserved_component_events_output() ]); catalog.TryGet(new ComponentType("data.map"), out var metadata).ShouldBeTrue(); - var events = metadata.Ports.Single(port => port.Name.Value == "Events"); - events.Direction.ShouldBe(PortDirection.Output); - events.ValueType.ShouldNotBeNull(); - events.ValueType.Value.Value.ShouldBe("ComponentEvent"); - events.Group.ShouldNotBeNull(); - events.Group.Value.Value.ShouldBe("Diagnostics"); - events.IsPrimary.ShouldBeFalse(); + metadata.Ports.Select(static port => port.Name.Value).ShouldBe(["Output"]); + metadata.Ports.ShouldNotContain(port => port.Name.Value == "Events"); } [Fact] @@ -302,7 +299,7 @@ public void Add_registers_and_finds_metadata_by_component_type() catalog.TryGet(new ComponentType("sample.transform"), out var found).ShouldBeTrue(); found.ShouldNotBeSameAs(metadata); found.Options[0].Kind.ShouldBe(OptionValueKind.Expression); - found.Ports.Select(port => port.Name.Value).ShouldBe(["Input", "Output", "Events"]); + found.Ports.Select(port => port.Name.Value).ShouldBe(["Input", "Output"]); } [Fact] @@ -429,20 +426,29 @@ public void Registration_finalization_preserves_canonical_and_structural_metadat var services = new ServiceCollection(); services.AddFluxFlowComponents().AddComponent("sample.finalized", component => { - component.UseFactory(static _ => throw new NotSupportedException()); component.UseProcessing(CompositionProcessingCapabilities.ParallelPreservingOrder); component.WithDisplay(displayName: "Finalized component"); - component.AddInput>( - "Input", - displayName: "Input", - order: 4, - isPrimary: true, - linkCardinality: ComponentPortLinkCardinality.Single); + component + .UseFactory(static _ => new MetadataNode()) + .HasInput( + "Input", + static node => node.Input, + displayName: "Input", + order: 4, + isPrimary: true, + linkCardinality: ComponentPortLinkCardinality.Single) + .HasOutput( + "Output", + static node => node.Output, + displayName: "Output", + order: 2) + .HasEvents( + "Events", + static node => node.Events, + displayName: "Events", + group: "Diagnostics", + order: int.MaxValue); component.SetPortAttribute("Input", PortDirection.Input, "port-scope", "original"); - component.AddOutput>( - "Output", - displayName: "Output", - order: 2); component.AddOption("name", OptionValueKind.Text); component.AddOption("BoundedCapacity", OptionValueKind.Number); component.AddOption("MaxDegreeOfParallelism", OptionValueKind.Number); @@ -514,7 +520,7 @@ public void Registration_finalization_preserves_canonical_and_structural_metadat output.LinkCardinality.ShouldBe(ComponentPortLinkCardinality.Multiple); output.Order.ShouldBe(2); - var events = found.Ports.Single(port => port.Name.Value == ComponentEvents.PortName); + var events = found.Ports.Single(port => port.Name.Value == "Events"); events.Direction.ShouldBe(PortDirection.Output); events.MessageType.ShouldBe(typeof(ComponentEvent)); events.ValueType?.Value.ShouldBe(nameof(ComponentEvent)); @@ -626,7 +632,7 @@ public void Constructor_preserves_order_snapshot_isolation_and_cached_read_only_ } [Fact] - public void Catalog_rejects_invalid_reserved_component_events_presentation() + public void Catalog_accepts_an_input_named_Events_without_treating_it_as_diagnostics() { var metadata = CreateMetadata("sample.invalid.events") with { @@ -635,7 +641,7 @@ public void Catalog_rejects_invalid_reserved_component_events_presentation() .. CreateMetadata().Ports, new PortDesignMetadata { - Name = new ComponentPortName(ComponentEvents.PortName), + Name = new ComponentPortName("Events"), Direction = PortDirection.Input, Order = int.MaxValue, ValueType = new ComponentValueTypeHint(nameof(ComponentEvent)) @@ -643,10 +649,12 @@ .. CreateMetadata().Ports, ] }; - var act = () => new ComponentDesignMetadataCatalog([metadata]); + var catalog = new ComponentDesignMetadataCatalog([metadata]); - act.ShouldThrow() - .Message.ShouldContain("reserved for traced component events"); + catalog.TryGet(metadata.Type, out var found).ShouldBeTrue(); + var events = found.Ports.Single(port => port.Name.Value == "Events"); + events.Direction.ShouldBe(PortDirection.Input); + events.ValueType?.Value.ShouldBe(nameof(ComponentEvent)); } [Fact] @@ -1873,11 +1881,39 @@ private static ComponentDescriptor CreateDescriptor( private static FluxFlowRegistrationBuilder RegisterSampleService(IServiceCollection services) => services.AddFluxFlowComponents().AddComponent("sample.service", component => { - component.UseFactory(static _ => - throw new NotSupportedException("The metadata test component is not activated.")); + component.UseFactory(static _ => new MetadataNode()); component.WithDisplay(displayName: "Sample Service"); }); + private sealed class MetadataNode : IFlowNode + { + public BufferBlock>> Input { get; } = new(); + + public BufferBlock>> Output { get; } = new(); + + public BufferBlock Events { get; } = new(); + + public Task Completion { get; } = Task.CompletedTask; + + public void Complete() + { + Input.Complete(); + Output.Complete(); + Events.Complete(); + } + + public void Fault(Exception exception) + { + ArgumentNullException.ThrowIfNull(exception); + } + + public ValueTask DisposeAsync() + { + Complete(); + return ValueTask.CompletedTask; + } + } + private static ComponentAttributeName Attribute(string name) => new(name); private static string AttributeValue( diff --git a/tests/FluxFlow.Components.Designer.Tests/DesignedComponentBindingBuilderTests.cs b/tests/FluxFlow.Components.Designer.Tests/DesignedComponentBindingBuilderTests.cs new file mode 100644 index 00000000..44237631 --- /dev/null +++ b/tests/FluxFlow.Components.Designer.Tests/DesignedComponentBindingBuilderTests.cs @@ -0,0 +1,320 @@ +using System.Threading.Tasks.Dataflow; +using FluxFlow.Components.Designer.Contracts; +using FluxFlow.Composition; +using FluxFlow.Nodes; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; + +namespace FluxFlow.Components.Designer.Tests; + +public sealed class DesignedComponentBindingBuilderTests +{ + [Fact] + public void Designed_typed_ports_create_runtime_and_design_metadata_from_one_declaration() + { + var services = new ServiceCollection(); + services.AddFluxFlowComponents().AddComponent("test.designed", component => + { + component.WithDisplay( + displayName: "Designed test", + category: "Testing", + summary: "Typed design metadata"); + component + .UseFactory(CreateNode) + .HasInput( + "Input", + SelectInput, + displayName: "Incoming value", + group: "Data", + order: 3, + summary: "Value to process.", + isPrimary: true, + linkCardinality: ComponentPortLinkCardinality.Single) + .HasSignalInput( + "Signal", + SelectSignal, + displayName: "Control signal", + group: "Control", + order: 4, + summary: "Controls processing.") + .HasOutput( + "Output", + SelectOutput, + displayName: "Processed value", + group: "Data", + order: 5, + summary: "Processed result.", + isPrimary: true) + .HasEvents( + "Diagnostics", + SelectEvents, + displayName: "Diagnostic events", + group: "Observability", + order: 6, + summary: "Component diagnostics."); + component.SetPortAttribute("Input", PortDirection.Input, "shape", "value"); + component.SetPortAttribute("Diagnostics", PortDirection.Output, "delivery", "best-effort"); + }); + + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + var metadata = provider.GetRequiredService() + .All.ShouldHaveSingleItem(); + + descriptor.Inputs.Keys.ShouldBe(["Input", "Signal"]); + descriptor.Outputs.Keys.ShouldBe(["Output", "Diagnostics"]); + descriptor.Inputs["Input"].MessageType.ShouldBe(typeof(string)); + descriptor.Inputs["Input"].LinkCardinality.ShouldBe(ComponentPortLinkCardinality.Single); + descriptor.Inputs["Signal"].Kind.ShouldBe(ComponentPortKind.Signal); + descriptor.Outputs["Output"].MessageType.ShouldBe(typeof(int)); + descriptor.Outputs["Diagnostics"].MessageType.ShouldBe(typeof(ComponentEvent)); + + metadata.DisplayName?.Value.ShouldBe("Designed test"); + metadata.Category?.Value.ShouldBe("Testing"); + metadata.Summary?.Value.ShouldBe("Typed design metadata"); + metadata.Ports.Select(static port => port.Name.Value) + .ShouldBe(["Input", "Signal", "Output", "Diagnostics"]); + + var input = metadata.Ports.Single(port => port.Name.Value == "Input"); + input.Direction.ShouldBe(PortDirection.Input); + input.MessageType.ShouldBe(typeof(string)); + input.ValueType?.Value.ShouldBe(nameof(String)); + input.DisplayName?.Value.ShouldBe("Incoming value"); + input.Group?.Value.ShouldBe("Data"); + input.Order.ShouldBe(3); + input.Summary?.Value.ShouldBe("Value to process."); + input.IsPrimary.ShouldBeTrue(); + input.LinkCardinality.ShouldBe(ComponentPortLinkCardinality.Single); + AttributeValue(input.Attributes, "shape").ShouldBe("value"); + + var signal = metadata.Ports.Single(port => port.Name.Value == "Signal"); + signal.Direction.ShouldBe(PortDirection.Input); + signal.Kind.ShouldBe(ComponentPortKind.Signal); + signal.DisplayName?.Value.ShouldBe("Control signal"); + signal.Group?.Value.ShouldBe("Control"); + signal.Order.ShouldBe(4); + + var output = metadata.Ports.Single(port => port.Name.Value == "Output"); + output.Direction.ShouldBe(PortDirection.Output); + output.MessageType.ShouldBe(typeof(int)); + output.ValueType?.Value.ShouldBe(nameof(Int32)); + output.DisplayName?.Value.ShouldBe("Processed value"); + output.Group?.Value.ShouldBe("Data"); + output.Order.ShouldBe(5); + output.IsPrimary.ShouldBeTrue(); + + var events = metadata.Ports.Single(port => port.Name.Value == "Diagnostics"); + events.Direction.ShouldBe(PortDirection.Output); + events.MessageType.ShouldBe(typeof(ComponentEvent)); + events.ValueType?.Value.ShouldBe(nameof(ComponentEvent)); + events.DisplayName?.Value.ShouldBe("Diagnostic events"); + events.Group?.Value.ShouldBe("Observability"); + events.Order.ShouldBe(6); + events.Summary?.Value.ShouldBe("Component diagnostics."); + events.IsPrimary.ShouldBeFalse(); + AttributeValue(events.Attributes, "delivery").ShouldBe("best-effort"); + } + + [Fact] + public void Designed_component_binding_builders_expose_only_Has_port_methods() + { + AssertCanonicalPortMethods(typeof(DesignedComponentBindingBuilder<>)); + AssertCanonicalPortMethods(typeof(DesignedComponentInstanceBindingBuilder)); + } + + [Fact] + public void Designed_component_without_HasEvents_has_no_implicit_event_metadata() + { + var services = new ServiceCollection(); + services.AddFluxFlowComponents().AddComponent("test.no-events", component => + component + .UseFactory(CreateNode) + .HasOutput("Output", SelectOutput, displayName: "Output")); + + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + var metadata = provider.GetRequiredService() + .All.ShouldHaveSingleItem(); + + descriptor.Outputs.Keys.ShouldBe(["Output"]); + descriptor.Outputs.ContainsKey("Events").ShouldBeFalse(); + metadata.Ports.Select(static port => port.Name.Value).ShouldBe(["Output"]); + metadata.Ports.ShouldNotContain(port => port.Name.Value == "Events"); + } + + [Fact] + public void Designed_advanced_factory_declares_metadata_without_activating_instance() + { + var services = new ServiceCollection(); + var factoryCalls = 0; + services.AddFluxFlowComponents().AddComponent("test.advanced", component => + component + .UseInstanceFactory(_ => + { + factoryCalls++; + throw new InvalidOperationException("Metadata registration must not activate the factory."); + }) + .HasInput( + "Input", + displayName: "Input", + linkCardinality: ComponentPortLinkCardinality.Single) + .HasSignalInput("Signal", displayName: "Signal") + .HasOutput("Output", displayName: "Output") + .HasEvents("Diagnostics", displayName: "Diagnostics")); + + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + var metadata = provider.GetRequiredService() + .All.ShouldHaveSingleItem(); + + factoryCalls.ShouldBe(0); + descriptor.Inputs.Keys.ShouldBe(["Input", "Signal"]); + descriptor.Outputs.Keys.ShouldBe(["Output", "Diagnostics"]); + descriptor.Inputs["Input"].MessageType.ShouldBe(typeof(string)); + descriptor.Inputs["Input"].LinkCardinality.ShouldBe(ComponentPortLinkCardinality.Single); + descriptor.Inputs["Signal"].Kind.ShouldBe(ComponentPortKind.Signal); + descriptor.Outputs["Output"].MessageType.ShouldBe(typeof(int)); + descriptor.Outputs["Diagnostics"].MessageType.ShouldBe(typeof(ComponentEvent)); + metadata.Ports.Select(static port => + (port.Name.Value, port.Direction, port.Order, port.DisplayName?.Value)) + .ShouldBe( + [ + ("Input", PortDirection.Input, 0, "Input"), + ("Signal", PortDirection.Input, 1, "Signal"), + ("Output", PortDirection.Output, 0, "Output"), + ("Diagnostics", PortDirection.Output, 1, "Diagnostics") + ]); + } + + [Fact] + public void Equivalent_designed_typed_registration_is_idempotent_and_changed_selector_conflicts() + { + var services = new ServiceCollection(); + var builder = services.AddFluxFlowComponents() + .AddComponent("test.identity", ConfigureEquivalent) + .AddComponent("test.identity", ConfigureEquivalent); + + services.Count(registration => registration.ServiceType == typeof(ComponentDescriptor)) + .ShouldBe(1); + services.Count(registration => registration.ServiceType == typeof(ComponentDesignMetadataCatalog)) + .ShouldBe(1); + + var exception = Should.Throw(() => + builder.AddComponent("test.identity", ConfigureChangedSelector)); + + exception.Message.ShouldContain("test.identity"); + exception.Message.ShouldContain("conflicting descriptor registration"); + services.Count(registration => registration.ServiceType == typeof(ComponentDescriptor)) + .ShouldBe(1); + } + + private static void ConfigureEquivalent(ComponentRegistrationBuilder component) + => component + .UseFactory(CreateNode) + .HasInput("Input", SelectInput, displayName: "Input") + .HasOutput("Output", SelectOutput, displayName: "Output") + .HasEvents("Diagnostics", SelectEvents, displayName: "Diagnostics"); + + private static void ConfigureChangedSelector(ComponentRegistrationBuilder component) + => component + .UseFactory(CreateNode) + .HasInput("Input", SelectAlternateInput, displayName: "Input") + .HasOutput("Output", SelectOutput, displayName: "Output") + .HasEvents("Diagnostics", SelectEvents, displayName: "Diagnostics"); + + private static DesignedNode CreateNode(ComponentActivationContext _) => new(); + + private static ITargetBlock> SelectInput(DesignedNode node) => node.Input; + + private static ITargetBlock> SelectAlternateInput(DesignedNode node) + => node.AlternateInput; + + private static ISourceBlock> SelectOutput(DesignedNode node) => node.Output; + + private static ISourceBlock SelectEvents(DesignedNode node) => node.Events; + + private static IFlowSignalTarget SelectSignal(DesignedNode node) => node.Signal; + + private static string AttributeValue( + IReadOnlyDictionary attributes, + string name) + => attributes[new ComponentAttributeName(name)].Value; + + private static void AssertCanonicalPortMethods(Type builderType) + { + var methodNames = builderType + .GetMethods( + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.DeclaredOnly) + .Select(static method => method.Name) + .Order(StringComparer.Ordinal) + .ToArray(); + + methodNames.ShouldBe( + [ + "HasEvents", + "HasInput", + "HasOutput", + "HasSignalInput" + ], + $"{builderType.Name} must expose only the canonical Has port DSL."); + methodNames.ShouldNotContain( + static name => name.StartsWith("Add", StringComparison.Ordinal), + $"{builderType.Name} must not retain a public Add port alias."); + } + + private sealed class DesignedNode : IFlowNode + { + public BufferBlock> Input { get; } = new(); + + public BufferBlock> AlternateInput { get; } = new(); + + public BufferBlock> Output { get; } = new(); + + public BufferBlock Events { get; } = new(); + + public DesignedSignalTarget Signal { get; } = new(); + + public Task Completion { get; } = Task.CompletedTask; + + public void Complete() + { + Input.Complete(); + AlternateInput.Complete(); + Output.Complete(); + Events.Complete(); + Signal.Complete(); + } + + public void Fault(Exception exception) + { + ArgumentNullException.ThrowIfNull(exception); + } + + public ValueTask DisposeAsync() + { + Complete(); + return ValueTask.CompletedTask; + } + } + + private sealed class DesignedSignalTarget : IFlowSignalTarget + { + private readonly TaskCompletionSource _completion = new( + TaskCreationOptions.RunContinuationsAsynchronously); + + public Task Completion => _completion.Task; + + public ValueTask SendAsync( + FlowMessage signal, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(true); + } + + public void Complete() => _completion.TrySetResult(); + } +} diff --git a/tests/FluxFlow.Components.Designer.Tests/FluxFlowDesignedComponentRegistrationTests.cs b/tests/FluxFlow.Components.Designer.Tests/FluxFlowDesignedComponentRegistrationTests.cs index 2ac7328f..a7463f37 100644 --- a/tests/FluxFlow.Components.Designer.Tests/FluxFlowDesignedComponentRegistrationTests.cs +++ b/tests/FluxFlow.Components.Designer.Tests/FluxFlowDesignedComponentRegistrationTests.cs @@ -1,5 +1,8 @@ +using System.Threading.Tasks.Dataflow; using FluxFlow.Components.Designer.Contracts; using FluxFlow.Composition; +using FluxFlow.Composition.Authoring; +using FluxFlow.Nodes; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Xunit; @@ -130,11 +133,7 @@ public void Conflicting_runtime_registration_from_designed_path_preserves_origin var originalDeclaration = ReadDeclarations(services).ShouldHaveSingleItem(); var exception = Should.Throw(() => - builder.AddComponent("test.component", component => - { - ConfigureDesigned(component); - component.UseFactory(ConflictingFactory); - })); + builder.AddComponent("test.component", ConfigureDesignedWithConflictingFactory)); exception.Message.ShouldContain("test.component"); exception.Message.ShouldContain("conflicting descriptor registration"); @@ -147,8 +146,8 @@ public void Conflicting_runtime_registration_from_designed_path_preserves_origin public void Runtime_then_designed_registration_reuses_one_descriptor_owner() { var services = new ServiceCollection(); - var builder = services.AddFluxFlowComponents() - .AddRuntimeComponent("test.component", ConfigureRuntime); + var builder = services.AddFluxFlowComponents(); + builder.Advanced.AddDynamicComponent("test.component", ConfigureRuntime); builder.AddComponent("test.component", ConfigureDesigned) .ShouldBeSameAs(builder); @@ -169,9 +168,10 @@ public void Designed_then_runtime_registration_reuses_one_descriptor_owner() var services = new ServiceCollection(); var builder = services.AddFluxFlowComponents() .AddComponent("test.component", ConfigureDesigned); + var advanced = builder.Advanced; - builder.AddRuntimeComponent("test.component", ConfigureRuntime) - .ShouldBeSameAs(builder); + advanced.AddDynamicComponent("test.component", ConfigureRuntime) + .ShouldBeSameAs(advanced); ReadDescriptors(services).Length.ShouldBe(1); ReadDeclarations(services).Length.ShouldBe(1); @@ -184,14 +184,15 @@ public void Designed_then_runtime_registration_reuses_one_descriptor_owner() } [Fact] - public void AddRuntimeComponent_remains_runtime_only() + public void Advanced_dynamic_component_remains_runtime_only() { var services = new ServiceCollection(); var builder = services.AddFluxFlowComponents(); + var advanced = builder.Advanced; - var returned = builder.AddRuntimeComponent("test.component", ConfigureRuntime); + var returned = advanced.AddDynamicComponent("test.component", ConfigureRuntime); - returned.ShouldBeSameAs(builder); + returned.ShouldBeSameAs(advanced); services.Count(registration => registration.ServiceType == typeof(ComponentDescriptor)) .ShouldBe(1); services.Count(registration => registration.ServiceType == typeof(ComponentDesignDeclaration)) @@ -233,11 +234,12 @@ public void Resolved_designer_catalog_is_detached_from_retained_component_builde { var services = new ServiceCollection(); ComponentRegistrationBuilder? retained = null; + DesignedComponentBindingBuilder? retainedBindings = null; services.AddFluxFlowComponents() .AddComponent("test.component", component => { retained = component; - ConfigureMutableDesigned(component); + retainedBindings = ConfigureMutableDesigned(component); }); retained.ShouldNotBeNull(); @@ -246,7 +248,8 @@ public void Resolved_designer_catalog_is_detached_from_retained_component_builde retained.SetResourceAttribute("clock", "phase", "late"); retained.SetPortAttribute("Input", PortDirection.Input, "phase", "late"); retained.AddAttribute("late", "value"); - retained.AddOutput("Late", "Late"); + retainedBindings.ShouldNotBeNull() + .HasOutput("Late", static node => node.Late, displayName: "Late"); using var provider = services.BuildServiceProvider(); var declaration = provider.GetRequiredService(); @@ -283,7 +286,7 @@ public void Standalone_flat_designed_usage_compiles_without_Engine() FluxFlowRegistrationBuilder returned = registration .AddComponent("test.component", component => { - component.UseFactory(UnusedFactory); + component.UseFactory(CreateNode); component.WithDisplay(displayName: "Test"); }); @@ -297,27 +300,138 @@ public void Standalone_flat_designed_usage_compiles_without_Engine() private static void ConfigureRuntime(RuntimeComponentRegistrationBuilder component) { - component.UseFactory(UnusedFactory); component.UseProcessing(CompositionProcessingCapabilities.ParallelRelaxedOrder); - component.AddInput("Input"); - component.AddOutput("Output", ComponentPortLinkCardinality.Single); + component + .UseFactory(CreateNode) + .HasInput("Input", SelectInput) + .HasOutput( + "Output", + SelectOutput, + ComponentPortLinkCardinality.Single) + .HasEvents("Events", SelectEvents); component.AddOption("enabled", isRequired: true); component.AddResource("clock", isRequired: true); } + [Fact] + public void Complete_contract_registration_projects_design_metadata_without_activating_factory() + { + var activations = 0; + var contract = DesignedComponentContract.Create( + " test.component ", + component => + { + component.UseProcessing( + CompositionProcessingCapabilities.ParallelRelaxedOrder); + component.WithDisplay( + displayName: "Designed contract", + category: "Testing", + summary: "One complete declaration"); + component + .UseFactory(_ => + { + activations++; + return new RegistrationNode(); + }) + .HasInput( + "Input", + SelectInput, + displayName: "Input", + order: 7) + .HasOutput( + "Output", + SelectOutput, + displayName: "Output", + order: 11, + linkCardinality: ComponentPortLinkCardinality.Single) + .HasEvents( + "Events", + SelectEvents, + displayName: "Events", + order: 12); + component.AddOption( + "enabled", + OptionValueKind.Boolean, + displayName: "Enabled", + isRequired: true); + component.AddResource( + "clock", + "Clock", + isRequired: true); + }, + static component => new InputOutputComponentHandle( + component, + "Input", + "Output", + "Events")); + activations.ShouldBe(0); + var application = new ApplicationDefinitionBuilder(); + application.AddWorkflow("Main").AddComponent("Node", contract); + var definition = application.Build(); + definition.ComponentDescriptors.ShouldHaveSingleItem() + .ShouldBeSameAs(contract.Descriptor); + activations.ShouldBe(0); + var services = new ServiceCollection(); + var registration = services.AddFluxFlowComponents(); + + registration.AddDesignedComponent(contract).ShouldBeSameAs(registration); + activations.ShouldBe(0); + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + var declaration = provider.GetRequiredService(); + var metadata = provider.GetRequiredService() + .All.ShouldHaveSingleItem(); + + descriptor.ShouldBeSameAs(contract.Descriptor); + declaration.Descriptor.ShouldBeSameAs(contract.Descriptor); + metadata.Type.Value.ShouldBe("test.component"); + metadata.DisplayName?.Value.ShouldBe("Designed contract"); + metadata.Category?.Value.ShouldBe("Testing"); + metadata.Summary?.Value.ShouldBe("One complete declaration"); + metadata.ProcessingCapabilities.ShouldBe( + CompositionProcessingCapabilities.ParallelRelaxedOrder); + metadata.Ports.Single(port => + port.Name.Value == "Input" && port.Direction == PortDirection.Input) + .Order.ShouldBe(7); + metadata.Ports.Single(port => + port.Name.Value == "Output" && port.Direction == PortDirection.Output) + .Order.ShouldBe(11); + metadata.Ports.Single(port => + port.Name.Value == "Events" && port.Direction == PortDirection.Output) + .Order.ShouldBe(12); + metadata.Options.Single(option => option.Name.Value == "enabled") + .IsRequired.ShouldBeTrue(); + metadata.Resources.Single(resource => resource.Name.Value == "clock") + .IsRequired.ShouldBeTrue(); + provider.GetRequiredService().Descriptors + .ShouldHaveSingleItem().ShouldBeSameAs(contract.Descriptor); + activations.ShouldBe(0); + } + private static void ConfigureDesigned(ComponentRegistrationBuilder component) + => ConfigureDesigned(component, CreateNode); + + private static void ConfigureDesignedWithConflictingFactory(ComponentRegistrationBuilder component) + => ConfigureDesigned(component, CreateConflictingNode); + + private static void ConfigureDesigned( + ComponentRegistrationBuilder component, + Func factory) { - component.UseFactory(UnusedFactory); component.UseProcessing(CompositionProcessingCapabilities.ParallelRelaxedOrder); component.WithDisplay( displayName: "Test component", category: "Testing", summary: "Registration test component"); - component.AddInput("Input", "Input"); - component.AddOutput( - "Output", - "Output", - linkCardinality: ComponentPortLinkCardinality.Single); + component + .UseFactory(factory) + .HasInput("Input", SelectInput, displayName: "Input") + .HasOutput( + "Output", + SelectOutput, + displayName: "Output", + linkCardinality: ComponentPortLinkCardinality.Single) + .HasEvents("Events", SelectEvents, displayName: "Events"); component.AddOption( "enabled", OptionValueKind.Boolean, @@ -329,19 +443,22 @@ private static void ConfigureDesigned(ComponentRegistrationBuilder component) isRequired: true); } - private static void ConfigureMutableDesigned(ComponentRegistrationBuilder component) + private static DesignedComponentBindingBuilder ConfigureMutableDesigned( + ComponentRegistrationBuilder component) { - component.UseFactory(UnusedFactory); component.WithDisplay(displayName: "Mutable test component"); - component.AddInput("Input", "Input"); + var bindings = component + .UseFactory(CreateNode) + .HasInput("Input", static node => node.Input, displayName: "Input") + .HasOutput("Output", static node => node.Output, displayName: "Output"); component.SetPortAttribute("Input", PortDirection.Input, "phase", "initial"); - component.AddOutput("Output", "Output"); component.AddOption("mode", OptionValueKind.Enum, displayName: "Mode"); component.AddOptionChoice("mode", "initial"); component.SetOptionAttribute("mode", "phase", "initial"); component.AddResource("clock", "Clock"); component.SetResourceAttribute("clock", "phase", "initial"); component.AddAttribute("phase", "initial"); + return bindings; } private static ComponentDescriptor[] ReadDescriptors(IServiceCollection services) @@ -363,9 +480,45 @@ private static string AttributeValue( string name) => attributes[new ComponentAttributeName(name)].Value; - private static ValueTask UnusedFactory(ComponentActivationContext _) - => throw new InvalidOperationException("Factory should not run."); + private static RegistrationNode CreateNode(ComponentActivationContext _) => new(); + + private static RegistrationNode CreateConflictingNode(ComponentActivationContext _) => new(); + + private static ITargetBlock> SelectInput(RegistrationNode node) => node.Input; + + private static ISourceBlock> SelectOutput(RegistrationNode node) => node.Output; + + private static ISourceBlock SelectEvents(RegistrationNode node) => node.Events; + + private sealed class RegistrationNode : IFlowNode + { + public BufferBlock> Input { get; } = new(); - private static ValueTask ConflictingFactory(ComponentActivationContext _) - => throw new InvalidOperationException("Conflicting factory should not run."); + public BufferBlock> Output { get; } = new(); + + public BufferBlock> Late { get; } = new(); + + public BufferBlock Events { get; } = new(); + + public Task Completion { get; } = Task.CompletedTask; + + public void Complete() + { + Input.Complete(); + Output.Complete(); + Late.Complete(); + Events.Complete(); + } + + public void Fault(Exception exception) + { + ArgumentNullException.ThrowIfNull(exception); + } + + public ValueTask DisposeAsync() + { + Complete(); + return ValueTask.CompletedTask; + } + } } diff --git a/tests/FluxFlow.Components.Expectations.Composition.Tests/ExpectationsServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Expectations.Composition.Tests/ExpectationsServiceCollectionExtensionsTests.cs index 55a4d659..f371e933 100644 --- a/tests/FluxFlow.Components.Expectations.Composition.Tests/ExpectationsServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Expectations.Composition.Tests/ExpectationsServiceCollectionExtensionsTests.cs @@ -36,7 +36,7 @@ public sealed class ExpectationsServiceCollectionExtensionsTests private static readonly ApplicationAddress Events = ApplicationAddress.WorkflowPort( "main", "node", - ComponentEvents.PortName); + "Events"); [Fact] public void AddExpectations_registers_only_the_canonical_contract() @@ -49,7 +49,7 @@ public void AddExpectations_registers_only_the_canonical_contract() registration.Inputs.Keys.ShouldBe([ExpectationsComponentDefinition.Ports.Input]); registration.Outputs.Keys.ShouldBe([ ExpectationsComponentDefinition.Ports.Output, - ComponentEvents.PortName + "Events" ], ignoreOrder: false); registration.Inputs[ExpectationsComponentDefinition.Ports.Input].MessageType .ShouldBe(typeof(ProjectionEvent)); @@ -104,7 +104,7 @@ public void Design_metadata_provider_describes_expectation_ports() nameof(ProjectionEvent), true), (ExpectationsComponentDefinition.Ports.Output, PortDirection.Output, 1, "EventExpectationResult", true), - (ComponentEvents.PortName, PortDirection.Output, int.MaxValue, + (ExpectationsComponentDefinition.Ports.Events, PortDirection.Output, 2, nameof(ComponentEvent), false) ], ignoreOrder: false); } diff --git a/tests/FluxFlow.Components.FileSystem.Composition.Tests/FileSystemServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.FileSystem.Composition.Tests/FileSystemServiceCollectionExtensionsTests.cs index 4280e2c2..48bfb464 100644 --- a/tests/FluxFlow.Components.FileSystem.Composition.Tests/FileSystemServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.FileSystem.Composition.Tests/FileSystemServiceCollectionExtensionsTests.cs @@ -732,20 +732,10 @@ private static void RegisterRecorder( IServiceCollection services, string nodeType, MessageTracker tracker) - => services.AddFluxFlowComponents().AddRuntimeComponent(nodeType, component => - { - component.UseFactory(_ => - { - var node = new MessageRecordingNode(tracker); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input("Input", node.Input) - ])); - }); - component.AddInput("Input"); - }); + => services.AddFluxFlowComponents().Advanced.AddDynamicComponent(nodeType, component => + component + .UseFactory(_ => new MessageRecordingNode(tracker)) + .HasInput("Input", static node => node.Input)); private static Dictionary CopyProperties( IReadOnlyDictionary? properties) diff --git a/tests/FluxFlow.Components.Mapping.Composition.Tests/MappingServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Mapping.Composition.Tests/MappingServiceCollectionExtensionsTests.cs index 3637751b..918f8826 100644 --- a/tests/FluxFlow.Components.Mapping.Composition.Tests/MappingServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Mapping.Composition.Tests/MappingServiceCollectionExtensionsTests.cs @@ -29,7 +29,7 @@ public sealed class MappingServiceCollectionExtensionsTests private static readonly ApplicationAddress Output = ApplicationAddress.WorkflowPort("main", "node", MappingComponentDefinition.Ports.Output); private static readonly ApplicationAddress Events = - ApplicationAddress.WorkflowPort("main", "node", ComponentEvents.PortName); + ApplicationAddress.WorkflowPort("main", "node", "Events"); [Fact] public void AddMapping_registers_only_the_canonical_json_contract() @@ -41,7 +41,7 @@ public void AddMapping_registers_only_the_canonical_json_contract() mapper.Inputs.Keys.ShouldBe([MappingComponentDefinition.Ports.Input]); mapper.Outputs.Keys.ShouldBe([ MappingComponentDefinition.Ports.Output, - ComponentEvents.PortName + "Events" ], ignoreOrder: false); mapper.Inputs[MappingComponentDefinition.Ports.Input].MessageType.ShouldBe(typeof(JsonElement)); mapper.Outputs[MappingComponentDefinition.Ports.Output].MessageType.ShouldBe(typeof(JsonElement)); @@ -151,7 +151,7 @@ public void Design_metadata_provider_describes_only_canonical_mapper_ports() port.ValueType?.Value)).ShouldBe([ (MappingComponentDefinition.Ports.Input, PortDirection.Input, 0, true, nameof(JsonElement)), (MappingComponentDefinition.Ports.Output, PortDirection.Output, 1, true, nameof(JsonElement)), - ("Events", PortDirection.Output, int.MaxValue, false, nameof(ComponentEvent)) + (MappingComponentDefinition.Ports.Events, PortDirection.Output, 2, false, nameof(ComponentEvent)) ]); } diff --git a/tests/FluxFlow.Components.Metrics.Composition.Tests/MetricsServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Metrics.Composition.Tests/MetricsServiceCollectionExtensionsTests.cs index 287756f9..9dbc6a7c 100644 --- a/tests/FluxFlow.Components.Metrics.Composition.Tests/MetricsServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Metrics.Composition.Tests/MetricsServiceCollectionExtensionsTests.cs @@ -29,7 +29,7 @@ public sealed class MetricsServiceCollectionExtensionsTests private static readonly ApplicationAddress Output = ApplicationAddress.WorkflowPort("main", "node", MetricsComponentDefinition.Ports.Output); private static readonly ApplicationAddress Events = - ApplicationAddress.WorkflowPort("main", "node", ComponentEvents.PortName); + ApplicationAddress.WorkflowPort("main", "node", "Events"); [Fact] public void AddMetrics_registers_request_result_metadata() diff --git a/tests/FluxFlow.Components.Mqtt.Composition.Tests/MqttApplicationDefinitionAuthoringTests.cs b/tests/FluxFlow.Components.Mqtt.Composition.Tests/MqttApplicationDefinitionAuthoringTests.cs index 7b970739..1d629ea4 100644 --- a/tests/FluxFlow.Components.Mqtt.Composition.Tests/MqttApplicationDefinitionAuthoringTests.cs +++ b/tests/FluxFlow.Components.Mqtt.Composition.Tests/MqttApplicationDefinitionAuthoringTests.cs @@ -114,6 +114,18 @@ public void Typed_mqtt_authoring_projects_resources_components_options_and_ports retryCategories[0] = "Changed"; var definition = builder.Build(); + definition.ApplicationResourceContracts.ShouldBe([ + MqttResources.Broker, + MqttResources.Client, + MqttResources.Subscription, + MqttResources.RetryPolicy + ]); + definition.ComponentDescriptors.ShouldBe([ + MqttComponents.MqttCommand.Descriptor, + MqttComponents.MqttEvents.Descriptor, + MqttComponents.MqttPublish.Descriptor, + MqttComponents.MqttReceive.Descriptor + ]); broker.Address.Value.ShouldBe("Resources.Messaging.Broker"); broker.Name.ShouldBe("Broker"); broker.ToString().ShouldBe(broker.Address.Value); @@ -226,16 +238,31 @@ public void Typed_mqtt_authoring_projects_resources_components_options_and_ports subscriptions[1].GetProperty("Qos").GetString().ShouldBe("ExactlyOnce"); subscriptions[1].GetProperty("NoLocal").GetBoolean().ShouldBeTrue(); subscriptions[1].GetProperty("RetainHandling").GetString().ShouldBe("DoNotSend"); - receiveDefinition.Properties["Output"].GetString().ShouldBe("Handler.Input"); - components["Outcome"].Properties["Ack"].GetString().ShouldBe("Receive.Ack"); - components["Outcome"].Properties["Nak"].GetProperty("Port") - .GetString().ShouldBe("Receive.Nak"); - components["Outcome"].Properties["Nak"].GetProperty("Condition") - .GetString().ShouldBe("failed == true"); + receiveDefinition.Properties.ContainsKey("Output").ShouldBeFalse(); + components["Outcome"].Properties.ContainsKey("Ack").ShouldBeFalse(); + components["Outcome"].Properties.ContainsKey("Nak").ShouldBeFalse(); + + definition.Links.Count.ShouldBe(3); + definition.Links[0].Source.ShouldBe(receive.Output.Address); + definition.Links[0].Target.ShouldBe(handler.Input("Input").Address); + definition.Links[0].MessageType.ShouldBe(typeof(MqttReceivedApplicationMessage)); + definition.Links[0].IsConditional.ShouldBeFalse(); + definition.Links[1].Source.ShouldBe(outcome.Output("Ack").Address); + definition.Links[1].Target.ShouldBe(receive.Ack.Address); + definition.Links[1].MessageType.ShouldBe(typeof(string)); + definition.Links[1].IsConditional.ShouldBeFalse(); + definition.Links[2].Source.ShouldBe(outcome.Output("Nak").Address); + definition.Links[2].Target.ShouldBe(receive.Nak.Address); + definition.Links[2].MessageType.ShouldBe(typeof(string)); + definition.Links[2].ConditionExpression.ShouldBe("failed == true"); var json = ApplicationDefinitionJson.Serialize(definition); - ApplicationDefinitionJson.Serialize(ApplicationDefinitionJson.Deserialize(json)) - .ShouldBe(json); + json.ShouldNotContain(nameof(ApplicationDefinition.ApplicationResourceContracts)); + json.ShouldNotContain(nameof(ApplicationDefinition.ComponentDescriptors)); + var roundTripped = ApplicationDefinitionJson.Deserialize(json); + roundTripped.ApplicationResourceContracts.ShouldBeEmpty(); + roundTripped.ComponentDescriptors.ShouldBeEmpty(); + ApplicationDefinitionJson.Serialize(roundTripped).ShouldBe(json); } [Fact] diff --git a/tests/FluxFlow.Components.Mqtt.Composition.Tests/MqttServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Mqtt.Composition.Tests/MqttServiceCollectionExtensionsTests.cs index b01c5aac..8d6a68e6 100644 --- a/tests/FluxFlow.Components.Mqtt.Composition.Tests/MqttServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Mqtt.Composition.Tests/MqttServiceCollectionExtensionsTests.cs @@ -11,6 +11,7 @@ using FluxFlow.Components.Mqtt.Transport; using FluxFlow.Composition; using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; using FluxFlow.Composition.Model; using FluxFlow.Testing; using Microsoft.Extensions.DependencyInjection; @@ -320,6 +321,56 @@ public async Task Host_credentials_certificates_and_inline_policy_bridge_into_re .ShouldBeNull(); } + [Fact] + public async Task Code_first_definition_embeds_mqtt_components_and_resources_without_AddMqtt() + { + var builder = new ApplicationDefinitionBuilder(); + var broker = builder.AddMqttBroker( + "Broker", + mqtt => mqtt.Host = "code-first-broker.internal"); + var client = builder.AddMqttClient("Client", mqtt => + { + mqtt.ClientId = "code-first-client"; + mqtt.Broker = broker; + mqtt.AutoConnect = MqttAutoConnectMode.OnStart; + mqtt.DisableReconnect(); + }); + builder.AddWorkflow("Main").AddMqttCommand("Command", mqtt => + { + mqtt.Client = client; + mqtt.MaximumConcurrentRequests = 2; + }); + var definition = builder.Build(); + var transport = new RecordingTransportFactory(); + + await using var host = await CanonicalApplicationTestHost.StartAsync( + definition, + static _ => { }, + services => services.AddSingleton(transport)); + + host.StartResult.Succeeded.ShouldBeTrue(); + host.Application.CurrentDefinition.ShouldBeSameAs(definition); + definition.ComponentDescriptors.ShouldHaveSingleItem() + .Type.ShouldBe(MqttComponentDefinition.Types.Control); + definition.ApplicationResourceContracts.Select(static contract => contract.Type) + .ShouldBe([ + MqttComponentDefinition.ResourceTypes.Broker, + MqttComponentDefinition.ResourceTypes.Client + ], ignoreOrder: true); + var configuration = transport.Configurations.ShouldHaveSingleItem(); + configuration.Name.ShouldBe(client.Address.Value); + configuration.ClientId.ShouldBe("code-first-client"); + configuration.Broker.Host.ShouldBe("code-first-broker.internal"); + var session = transport.Sessions.ShouldHaveSingleItem(); + session.ConnectCalls.ShouldBe(1); + session.DisposeCalls.ShouldBe(0); + + await host.Application.StopAsync(); + + session.DisconnectCalls.ShouldBe(1); + session.DisposeCalls.ShouldBe(1); + } + [Fact] public async Task Engine_failure_replacement_and_stop_dispose_each_revision_controller_once() { diff --git a/tests/FluxFlow.Components.Observability.Composition.Tests/ObservabilityServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Observability.Composition.Tests/ObservabilityServiceCollectionExtensionsTests.cs index c2ccdc5e..cb58215a 100644 --- a/tests/FluxFlow.Components.Observability.Composition.Tests/ObservabilityServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Observability.Composition.Tests/ObservabilityServiceCollectionExtensionsTests.cs @@ -36,7 +36,7 @@ public sealed class ObservabilityServiceCollectionExtensionsTests private static readonly ApplicationAddress Events = ApplicationAddress.WorkflowPort( "main", "node", - ComponentEvents.PortName); + "Events"); [Fact] public void AddObservability_registers_canonical_metadata() diff --git a/tests/FluxFlow.Components.Payloads.Composition.Tests/PayloadsServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Payloads.Composition.Tests/PayloadsServiceCollectionExtensionsTests.cs index 4e7e8aaf..9adb2269 100644 --- a/tests/FluxFlow.Components.Payloads.Composition.Tests/PayloadsServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Payloads.Composition.Tests/PayloadsServiceCollectionExtensionsTests.cs @@ -29,7 +29,7 @@ public sealed class PayloadsServiceCollectionExtensionsTests private static readonly ApplicationAddress Output = ApplicationAddress.WorkflowPort("main", "node", PayloadsComponentDefinition.Ports.Output); private static readonly ApplicationAddress Events = - ApplicationAddress.WorkflowPort("main", "node", ComponentEvents.PortName); + ApplicationAddress.WorkflowPort("main", "node", "Events"); [Fact] public void AddPayloads_registers_canonical_content_result_metadata() diff --git a/tests/FluxFlow.Components.Projections.Composition.Tests/ProjectionsServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Projections.Composition.Tests/ProjectionsServiceCollectionExtensionsTests.cs index ce3e2c8c..9ecad3b1 100644 --- a/tests/FluxFlow.Components.Projections.Composition.Tests/ProjectionsServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Projections.Composition.Tests/ProjectionsServiceCollectionExtensionsTests.cs @@ -29,7 +29,7 @@ public sealed class ProjectionsServiceCollectionExtensionsTests private static readonly ApplicationAddress Output = ApplicationAddress.WorkflowPort("main", "node", ProjectionsComponentDefinition.Ports.Output); private static readonly ApplicationAddress Events = - ApplicationAddress.WorkflowPort("main", "node", ComponentEvents.PortName); + ApplicationAddress.WorkflowPort("main", "node", "Events"); [Fact] public void AddProjections_registers_request_result_metadata() diff --git a/tests/FluxFlow.Components.Routing.Composition.Tests/RoutingServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Routing.Composition.Tests/RoutingServiceCollectionExtensionsTests.cs index 97052c88..9b333700 100644 --- a/tests/FluxFlow.Components.Routing.Composition.Tests/RoutingServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Routing.Composition.Tests/RoutingServiceCollectionExtensionsTests.cs @@ -38,7 +38,7 @@ public void AddRouting_registers_canonical_json_metadata() registry.Components[RoutingComponentDefinition.Types.Correlation] .Outputs.Keys.ShouldBe([ RoutingComponentDefinition.Ports.Output, - ComponentEvents.PortName + "Events" ], ignoreOrder: false); registry.Components[RoutingComponentDefinition.Types.Join] .Inputs.Values.Select(input => input.MessageType).ShouldBe([ @@ -122,14 +122,14 @@ public void Design_metadata_provider_describes_static_routing_ports() [ (RoutingComponentDefinition.Ports.Input, PortDirection.Input, 0, true, nameof(JsonElement)), (RoutingComponentDefinition.Ports.Output, PortDirection.Output, 1, true, "FlowWindow"), - ("Events", PortDirection.Output, int.MaxValue, false, nameof(ComponentEvent)) + (RoutingComponentDefinition.Ports.Events, PortDirection.Output, 2, false, nameof(ComponentEvent)) ]); AssertPorts( metadata[RoutingComponentDefinition.Types.Correlation], [ (RoutingComponentDefinition.Ports.Input, PortDirection.Input, 0, true, nameof(JsonElement)), (RoutingComponentDefinition.Ports.Output, PortDirection.Output, 1, true, "FlowCorrelationOutcome"), - ("Events", PortDirection.Output, int.MaxValue, false, nameof(ComponentEvent)) + (RoutingComponentDefinition.Ports.Events, PortDirection.Output, 2, false, nameof(ComponentEvent)) ]); AssertPorts( metadata[RoutingComponentDefinition.Types.Join], @@ -137,7 +137,7 @@ public void Design_metadata_provider_describes_static_routing_ports() (RoutingComponentDefinition.Ports.Left, PortDirection.Input, 0, true, nameof(JsonElement)), (RoutingComponentDefinition.Ports.Right, PortDirection.Input, 1, false, nameof(JsonElement)), (RoutingComponentDefinition.Ports.Output, PortDirection.Output, 2, true, "FlowJoinOutcome"), - ("Events", PortDirection.Output, int.MaxValue, false, nameof(ComponentEvent)) + (RoutingComponentDefinition.Ports.Events, PortDirection.Output, 3, false, nameof(ComponentEvent)) ]); } @@ -397,7 +397,7 @@ public async Task Hosted_canonical_correlation_resolves_json_selectors() port.Address.Segments[1] == "node") .Select(port => port.Address.Segments[^1]) .ShouldBe([ - ComponentEvents.PortName, + "Events", RoutingComponentDefinition.Ports.Output ], ignoreOrder: false); var outputResult = ports.ReceiveAsync>( diff --git a/tests/FluxFlow.Components.Serialization.Composition.Tests/SerializationServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Serialization.Composition.Tests/SerializationServiceCollectionExtensionsTests.cs index e29c98cb..ce735867 100644 --- a/tests/FluxFlow.Components.Serialization.Composition.Tests/SerializationServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Serialization.Composition.Tests/SerializationServiceCollectionExtensionsTests.cs @@ -34,7 +34,7 @@ public sealed class SerializationServiceCollectionExtensionsTests private static readonly ApplicationAddress Events = ApplicationAddress.WorkflowPort( "main", "node", - ComponentEvents.PortName); + "Events"); [Fact] public void AddSerialization_registers_canonical_metadata() diff --git a/tests/FluxFlow.Components.Sessions.Composition.Tests/SessionsServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Sessions.Composition.Tests/SessionsServiceCollectionExtensionsTests.cs index 7b3ede6b..3592dfe6 100644 --- a/tests/FluxFlow.Components.Sessions.Composition.Tests/SessionsServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Sessions.Composition.Tests/SessionsServiceCollectionExtensionsTests.cs @@ -43,7 +43,7 @@ public sealed class SessionsServiceCollectionExtensionsTests private static readonly ApplicationAddress Events = ApplicationAddress.WorkflowPort( WorkflowName, ComponentName, - ComponentEvents.PortName); + "Events"); [Fact] public void AddSessions_registers_canonical_metadata() @@ -68,7 +68,7 @@ public void AddSessions_registers_canonical_metadata() .ShouldBe(typeof(SessionQueryOutcome)); query.Outputs.Keys.ShouldBe([ SessionsComponentDefinition.Ports.Output, - ComponentEvents.PortName + "Events" ], ignoreOrder: false); } @@ -761,17 +761,10 @@ private static ComponentDefinition Component( private static void RegisterRecorder( IServiceCollection services, MessageTracker tracker) - => services.AddFluxFlowComponents().AddRuntimeComponent(RecorderType, component => - { - component.UseFactory(_ => - { - var node = new MessageRecordingNode(tracker); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)])); - }); - component.AddInput("Input"); - }); + => services.AddFluxFlowComponents().Advanced.AddDynamicComponent(RecorderType, component => + component + .UseFactory(_ => new MessageRecordingNode(tracker)) + .HasInput("Input", static node => node.Input)); private static void AssertPreparationFailure( CanonicalApplicationTestHost host, diff --git a/tests/FluxFlow.Components.Sources.Composition.Tests/SourcesServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Sources.Composition.Tests/SourcesServiceCollectionExtensionsTests.cs index 450eb853..6b2f1b87 100644 --- a/tests/FluxFlow.Components.Sources.Composition.Tests/SourcesServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Sources.Composition.Tests/SourcesServiceCollectionExtensionsTests.cs @@ -34,7 +34,7 @@ public sealed class SourcesServiceCollectionExtensionsTests ApplicationAddress.WorkflowPort( "main", "source", - ComponentEvents.PortName); + "Events"); [Fact] public void AddSources_exposes_canonical_typed_metadata() @@ -436,7 +436,7 @@ private static void AssertSourcePorts(ComponentDesignMetadata metadata, string v port.IsPrimary, port.ValueType?.Value)).ShouldBe([ (SourcesComponentDefinition.Ports.Output, PortDirection.Output, 0, true, valueType), - ("Events", PortDirection.Output, int.MaxValue, false, nameof(ComponentEvent)) + (SourcesComponentDefinition.Ports.Events, PortDirection.Output, 1, false, nameof(ComponentEvent)) ]); } diff --git a/tests/FluxFlow.Components.State.Composition.Tests/StateServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.State.Composition.Tests/StateServiceCollectionExtensionsTests.cs index dd3acfaf..04c2c9c0 100644 --- a/tests/FluxFlow.Components.State.Composition.Tests/StateServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.State.Composition.Tests/StateServiceCollectionExtensionsTests.cs @@ -30,7 +30,7 @@ public sealed class StateServiceCollectionExtensionsTests private static readonly ApplicationAddress Output = ApplicationAddress.WorkflowPort("main", "node", StateComponentDefinition.Ports.Output); private static readonly ApplicationAddress Events = - ApplicationAddress.WorkflowPort("main", "node", ComponentEvents.PortName); + ApplicationAddress.WorkflowPort("main", "node", "Events"); [Fact] public void AddState_registers_only_the_canonical_contract() @@ -42,7 +42,7 @@ public void AddState_registers_only_the_canonical_contract() reducer.Inputs.Keys.ShouldBe([StateComponentDefinition.Ports.Input]); reducer.Outputs.Keys.ShouldBe([ StateComponentDefinition.Ports.Output, - ComponentEvents.PortName + "Events" ], ignoreOrder: false); reducer.Inputs[StateComponentDefinition.Ports.Input].MessageType .ShouldBe(typeof(StateReducerInput)); @@ -104,7 +104,7 @@ public void Design_metadata_provider_describes_canonical_state_ports() "StateReducerInput", true), (StateComponentDefinition.Ports.Output, PortDirection.Output, 1, "StateReducerResult", true), - ("Events", PortDirection.Output, int.MaxValue, + (StateComponentDefinition.Ports.Events, PortDirection.Output, 2, nameof(ComponentEvent), false) ], ignoreOrder: false); } diff --git a/tests/FluxFlow.Components.Storage.Composition.Tests/StorageServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Storage.Composition.Tests/StorageServiceCollectionExtensionsTests.cs index cf69602c..27b5251f 100644 --- a/tests/FluxFlow.Components.Storage.Composition.Tests/StorageServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Storage.Composition.Tests/StorageServiceCollectionExtensionsTests.cs @@ -32,7 +32,7 @@ public sealed class StorageServiceCollectionExtensionsTests private static readonly ApplicationAddress Output = ApplicationAddress.WorkflowPort("main", "node", StorageComponentDefinition.Ports.Output); private static readonly ApplicationAddress Events = - ApplicationAddress.WorkflowPort("main", "node", ComponentEvents.PortName); + ApplicationAddress.WorkflowPort("main", "node", "Events"); [Fact] public void AddStorage_registers_canonical_metadata() @@ -50,7 +50,7 @@ public void AddStorage_registers_canonical_metadata() .ShouldBe(typeof(StorageGetRequest)); get.Outputs.Keys.ShouldBe([ StorageComponentDefinition.Ports.Output, - ComponentEvents.PortName + "Events" ], ignoreOrder: false); get.Outputs[StorageComponentDefinition.Ports.Output].MessageType .ShouldBe(typeof(StorageGetOutcome)); @@ -60,7 +60,7 @@ public void AddStorage_registers_canonical_metadata() .ShouldBe(typeof(StorageQueryRequest)); query.Outputs.Keys.ShouldBe([ StorageComponentDefinition.Ports.Output, - ComponentEvents.PortName + "Events" ], ignoreOrder: false); query.Outputs[StorageComponentDefinition.Ports.Output].MessageType .ShouldBe(typeof(StorageQueryOutcome)); @@ -255,7 +255,7 @@ await WithNodeAsync( } [Fact] - public async Task Resolved_store_disposes_owned_lease_once_when_instance_creation_fails() + public async Task Resolved_store_disposes_owned_lease_once_when_node_creation_fails() { var store = new InMemoryStorageStore(); var resolved = ResolvedStorageStore.Leased(StorageStoreLease.Owned(store)); @@ -263,7 +263,7 @@ public async Task Resolved_store_disposes_owned_lease_once_when_instance_creatio IStorageStore? activatedStore = null; var actual = await Should.ThrowAsync(async () => - await resolved.CreateInstanceAsync((storageStore, _) => + await resolved.CreateActivationAsync(storageStore => { activatedStore = storageStore; throw expected; @@ -279,27 +279,28 @@ await resolved.CreateInstanceAsync((storageStore, _) => } [Fact] - public async Task Resolved_store_transfers_owned_lease_cleanup_to_component_instance() + public async Task Resolved_store_transfers_owned_lease_cleanup_to_node_activation() { var store = new InMemoryStorageStore(); var resolved = ResolvedStorageStore.Leased(StorageStoreLease.Owned(store)); IStorageStore? activatedStore = null; - await using var instance = await resolved.CreateInstanceAsync( - (storageStore, disposeAsync) => + var activation = await resolved.CreateActivationAsync( + storageStore => { activatedStore = storageStore; - var node = new StoragePutNode(storageStore); - return ComponentInstance.Create(node, disposeAsync: disposeAsync); + return new StoragePutNode(storageStore); }); activatedStore.ShouldBeSameAs(store); + var cleanup = activation.DisposeAsync.ShouldNotBeNull(); store.DisposeCount.ShouldBe(0); - await instance.DisposeAsync(); + await activation.Node.DisposeAsync(); + await cleanup(); store.DisposeCount.ShouldBe(1); - await instance.DisposeAsync(); + await cleanup(); store.DisposeCount.ShouldBe(1); } diff --git a/tests/FluxFlow.Components.Timers.Composition.Tests/TimersServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Timers.Composition.Tests/TimersServiceCollectionExtensionsTests.cs index 76f884fe..eeda14dc 100644 --- a/tests/FluxFlow.Components.Timers.Composition.Tests/TimersServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Timers.Composition.Tests/TimersServiceCollectionExtensionsTests.cs @@ -464,7 +464,7 @@ private static void AssertSourcePorts( port.IsPrimary, port.ValueType?.Value)).ShouldBe([ (TimersComponentDefinition.Ports.Output, PortDirection.Output, 1, true, outputType), - ("Events", PortDirection.Output, int.MaxValue, false, nameof(ComponentEvent)) + (TimersComponentDefinition.Ports.Events, PortDirection.Output, 2, false, nameof(ComponentEvent)) ]); } @@ -478,7 +478,7 @@ private static void AssertTransformPorts(ComponentDesignMetadata metadata) port.ValueType?.Value)).ShouldBe([ (TimersComponentDefinition.Ports.Input, PortDirection.Input, 0, true, nameof(JsonElement)), (TimersComponentDefinition.Ports.Output, PortDirection.Output, 1, true, nameof(JsonElement)), - ("Events", PortDirection.Output, int.MaxValue, false, nameof(ComponentEvent)) + (TimersComponentDefinition.Ports.Events, PortDirection.Output, 2, false, nameof(ComponentEvent)) ]); } diff --git a/tests/FluxFlow.Components.Validation.Composition.Tests/ValidationServiceCollectionExtensionsTests.cs b/tests/FluxFlow.Components.Validation.Composition.Tests/ValidationServiceCollectionExtensionsTests.cs index 86731b12..05dc088a 100644 --- a/tests/FluxFlow.Components.Validation.Composition.Tests/ValidationServiceCollectionExtensionsTests.cs +++ b/tests/FluxFlow.Components.Validation.Composition.Tests/ValidationServiceCollectionExtensionsTests.cs @@ -40,7 +40,7 @@ public void AddValidation_registers_only_the_canonical_contract() validator.Inputs.Keys.ShouldBe([ValidationComponentDefinition.Ports.Input]); validator.Outputs.Keys.ShouldBe([ ValidationComponentDefinition.Ports.Output, - ComponentEvents.PortName + "Events" ], ignoreOrder: false); validator.Inputs[ValidationComponentDefinition.Ports.Input].MessageType.ShouldBe( typeof(JsonElement)); @@ -110,7 +110,7 @@ public void Design_metadata_provider_describes_canonical_ports() port.ValueType?.Value)).ShouldBe([ (ValidationComponentDefinition.Ports.Input, PortDirection.Input, 0, true, nameof(JsonElement)), (ValidationComponentDefinition.Ports.Output, PortDirection.Output, 1, true, nameof(JsonSchemaValidationResult)), - ("Events", PortDirection.Output, int.MaxValue, false, nameof(ComponentEvent)) + (ValidationComponentDefinition.Ports.Events, PortDirection.Output, 2, false, nameof(ComponentEvent)) ]); } diff --git a/tests/FluxFlow.Composition.Tests/ApplicationDefinitionAuthoringTests.cs b/tests/FluxFlow.Composition.Tests/ApplicationDefinitionAuthoringTests.cs index 9033dde1..9606ae90 100644 --- a/tests/FluxFlow.Composition.Tests/ApplicationDefinitionAuthoringTests.cs +++ b/tests/FluxFlow.Composition.Tests/ApplicationDefinitionAuthoringTests.cs @@ -125,7 +125,7 @@ public void Build_projects_values_json_resources_and_typed_handle_addresses() } [Fact] - public void Connect_projects_local_cross_workflow_conditional_and_signal_links() + public void Connect_records_first_class_local_cross_workflow_conditional_and_signal_links() { var builder = new ApplicationDefinitionBuilder(); var orders = builder.AddWorkflow("Orders"); @@ -146,15 +146,23 @@ public void Connect_projects_local_cross_workflow_conditional_and_signal_links() var sourceProperties = definition.Workflows["Orders"].Components["Source"].Properties; sourceProperties["Mode"].GetString().ShouldBe("ordered"); - var declarations = sourceProperties["Output"].EnumerateArray().ToArray(); - declarations.Length.ShouldBe(3); - declarations[0].GetString().ShouldBe("Local.Input"); - declarations[1].GetProperty("Port").GetString().ShouldBe("Local.Cancel"); - declarations[1].GetProperty("Condition").GetString().ShouldBe("cancel == true"); - declarations[2].GetProperty("Port").GetString() - .ShouldBe("Shipping.Target.Input"); - declarations[2].GetProperty("Condition").GetString() - .ShouldBe("route == 'shipping'"); + sourceProperties.ContainsKey("Output").ShouldBeFalse(); + definition.Links.Count.ShouldBe(3); + definition.Links.Select(static link => link.Source.Value) + .ShouldAllBe(static source => source == "Orders.Source.Output"); + definition.Links.Select(static link => link.Target.Value).ShouldBe( + [ + "Orders.Local.Input", + "Orders.Local.Cancel", + "Shipping.Target.Input" + ]); + definition.Links.Select(static link => link.ConditionExpression).ShouldBe( + [ + null, + "cancel == true", + "route == 'shipping'" + ]); + definition.Links.ShouldAllBe(static link => link.MessageType == typeof(Envelope)); definition.Workflows["Orders"].Components["Local"].Properties.ShouldBeEmpty(); definition.Workflows["Shipping"].Components["Target"].Properties.ShouldBeEmpty(); } @@ -197,10 +205,14 @@ public void Connect_rejects_duplicates_invalid_conditions_and_single_cardinality var definition = builder.Build(); var firstProperties = definition.Workflows["Main"].Components["First"].Properties; - firstProperties["SingleOutput"].GetString().ShouldBe("Sink.FirstInput"); - firstProperties["MultipleOutput"].GetString().ShouldBe("Sink.SingleInput"); - firstProperties["DuplicateOutput"].GetString().ShouldBe("Sink.DuplicateInput"); - firstProperties.ContainsKey("InvalidCondition").ShouldBeFalse(); + firstProperties.ShouldBeEmpty(); + definition.Links.Select(static link => (link.Source.Value, link.Target.Value)).ShouldBe( + [ + ("Main.First.SingleOutput", "Main.Sink.FirstInput"), + ("Main.First.MultipleOutput", "Main.Sink.SingleInput"), + ("Main.First.DuplicateOutput", "Main.Sink.DuplicateInput") + ]); + definition.Links.ShouldAllBe(static link => !link.IsConditional); definition.Workflows["Main"].Components["Second"].Properties.ShouldBeEmpty(); } @@ -409,7 +421,7 @@ public void Build_freezes_root_and_all_retained_child_mutation_paths() } [Fact] - public void Failed_build_does_not_freeze_builder_when_raw_property_conflicts_with_connection() + public void First_class_connection_does_not_conflict_with_raw_component_property() { var builder = new ApplicationDefinitionBuilder(); var workflow = builder.AddWorkflow("Main"); @@ -422,38 +434,19 @@ public void Failed_build_does_not_freeze_builder_when_raw_property_conflicts_wit source.Output("Output"), sink.Input("Input")); - var error = Should.Throw(() => builder.Build()); + var definition = builder.Build(); - error.Message.ShouldContain("Main.Source"); - error.Message.ShouldContain("Output"); - builder.AddWorkflow("StillMutable").Name.ShouldBe("StillMutable"); + definition.Workflows["Main"].Components["Source"].Properties["Output"] + .GetString().ShouldBe("manual.reference"); + var link = definition.Links.ShouldHaveSingleItem(); + link.Source.Value.ShouldBe("Main.Source.Output"); + link.Target.Value.ShouldBe("Main.Sink.Input"); + Should.Throw(() => builder.AddWorkflow("Frozen")); } [Fact] - public void Built_definition_round_trips_through_exact_canonical_json() + public void Portable_json_round_trip_remains_canonical_and_never_creates_code_predicates() { - var builder = new ApplicationDefinitionBuilder(); - var resources = builder.AddResourceGroup("Data"); - var store = resources.AddResource( - "Store", - "sample.store", - resource => - { - resource.Set("Enabled", true); - resource.Set("Limits", new[] { 2, 4 }); - }); - var workflow = builder.AddWorkflow("Main"); - var source = workflow.AddComponent( - "Source", - "sample.source", - component => component.UseResource("Store", store)); - var sink = workflow.AddComponent("Sink", "sample.sink"); - workflow.Connect( - source.Output("Output"), - sink.Input("Input"), - "value > 0"); - - var definition = builder.Build(); const string expected = "{\"Resources\":{\"Data\":{\"Store\":{\"Type\":\"sample.store\"," + "\"Enabled\":true,\"Limits\":[2,4]}}},\"Workflows\":{\"Main\":{" + @@ -461,8 +454,10 @@ public void Built_definition_round_trips_through_exact_canonical_json() "\"Output\":{\"Condition\":\"value \\u003E 0\",\"Port\":\"Sink.Input\"}," + "\"Store\":\"Resources.Data.Store\"}}}}"; + var definition = ApplicationDefinitionJson.Deserialize(expected); var json = ApplicationDefinitionJson.Serialize(definition); + definition.Links.ShouldBeEmpty(); json.ShouldBe(expected); ApplicationDefinitionJson.Serialize( ApplicationDefinitionJson.Deserialize(json)).ShouldBe(expected); diff --git a/tests/FluxFlow.Composition.Tests/ApplicationDefinitionFluentCaptureTests.cs b/tests/FluxFlow.Composition.Tests/ApplicationDefinitionFluentCaptureTests.cs index 92895db1..3b24681b 100644 --- a/tests/FluxFlow.Composition.Tests/ApplicationDefinitionFluentCaptureTests.cs +++ b/tests/FluxFlow.Composition.Tests/ApplicationDefinitionFluentCaptureTests.cs @@ -7,6 +7,34 @@ namespace FluxFlow.Composition.Tests; public sealed class ApplicationDefinitionFluentCaptureTests { + [Fact] + public void Workflow_authoring_exposes_only_return_and_out_capture_shapes() + { + var methods = typeof(ApplicationDefinitionBuilder) + .GetMethods( + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.DeclaredOnly) + .Where(static method => method.Name == nameof(ApplicationDefinitionBuilder.AddWorkflow)) + .OrderBy(static method => method.GetParameters().Length) + .ToArray(); + + methods.Length.ShouldBe(2); + methods[0].ReturnType.ShouldBe(typeof(WorkflowDefinitionBuilder)); + methods[0].GetParameters().Select(static parameter => parameter.ParameterType) + .ShouldBe([typeof(string)]); + methods[1].ReturnType.ShouldBe(typeof(ApplicationDefinitionBuilder)); + var captureParameters = methods[1].GetParameters(); + captureParameters.Length.ShouldBe(2); + captureParameters[0].ParameterType.ShouldBe(typeof(string)); + captureParameters[1].IsOut.ShouldBeTrue(); + captureParameters[1].ParameterType.ShouldBe( + typeof(WorkflowDefinitionBuilder).MakeByRefType()); + methods.SelectMany(static method => method.GetParameters()) + .ShouldNotContain(static parameter => + typeof(Delegate).IsAssignableFrom(parameter.ParameterType)); + } + [Fact] public void Capture_overloads_return_exact_builders_and_assign_exact_handles() { @@ -108,14 +136,15 @@ public void Same_chain_out_variables_are_definitely_assigned_and_connect_fluentl recorder.Address.Value.ShouldBe("Audit.Recorder"); var definition = application.Build(); - var sourceOutput = definition.Workflows["Main"].Components["Source"].Properties["Output"]; - sourceOutput.GetProperty("Port").GetString().ShouldBe("Transform.Input"); - sourceOutput.GetProperty("Condition").GetString().ShouldBe("value > 0"); - definition.Workflows["Main"].Components["Transform"].Properties["Output"] - .GetString().ShouldBe("Sink.Input"); - var auditOutput = definition.Workflows["Main"].Components["Transform"].Properties["Audit"]; - auditOutput.GetProperty("Port").GetString().ShouldBe("Audit.Recorder.Input"); - auditOutput.GetProperty("Condition").GetString().ShouldBe("value != null"); + definition.Workflows["Main"].Components.Values + .ShouldAllBe(static component => component.Properties.Count == 0); + definition.Links.Select(static link => + (link.Source.Value, link.Target.Value, link.ConditionExpression)).ShouldBe( + [ + ("Main.Source.Output", "Main.Transform.Input", "value > 0"), + ("Main.Transform.Output", "Main.Sink.Input", null), + ("Main.Transform.Audit", "Audit.Recorder.Input", "value != null") + ]); } [Fact] @@ -174,18 +203,33 @@ public void Fluent_configuration_failures_are_atomic_and_allow_same_name_retry() } [Fact] - public void Fluent_capture_and_original_authoring_produce_identical_canonical_json() + public void Workflow_return_and_out_capture_shapes_build_equivalent_immutable_definitions() { var original = BuildWithOriginalReturns(); var fluent = BuildWithFluentCaptures(); - const string expected = - "{\"Resources\":{\"Infrastructure\":{\"Store\":{\"Type\":\"sample.store\"," + - "\"Enabled\":true}}},\"Workflows\":{\"Main\":{\"Sink\":{\"Type\":\"sample.sink\"}," + - "\"Source\":{\"Type\":\"sample.source\",\"Output\":{\"Condition\":\"value \\u003E 0\"," + - "\"Port\":\"Sink.Input\"},\"Store\":\"Resources.Infrastructure.Store\"}}}}"; - - ApplicationDefinitionJson.Serialize(original).ShouldBe(expected); - ApplicationDefinitionJson.Serialize(fluent).ShouldBe(expected); + + original.Resources.Keys.ShouldBe(fluent.Resources.Keys); + original.Workflows.Keys.ShouldBe(fluent.Workflows.Keys); + var originalWorkflow = original.Workflows["Main"]; + var fluentWorkflow = fluent.Workflows["Main"]; + originalWorkflow.Components.Keys.ShouldBe(fluentWorkflow.Components.Keys); + foreach (var componentName in originalWorkflow.Components.Keys) + { + var originalComponent = originalWorkflow.Components[componentName]; + var fluentComponent = fluentWorkflow.Components[componentName]; + fluentComponent.Type.ShouldBe(originalComponent.Type); + fluentComponent.Properties.Keys.ShouldBe(originalComponent.Properties.Keys); + foreach (var property in originalComponent.Properties) + { + fluentComponent.Properties[property.Key].GetRawText() + .ShouldBe(property.Value.GetRawText()); + } + } + + original.Links.Count.ShouldBe(1); + fluent.Links.Count.ShouldBe(1); + fluent.Links[0].ShouldBe(original.Links[0]); + fluent.Links[0].ConditionExpression.ShouldBe("value > 0"); } private static ApplicationDefinition BuildWithOriginalReturns() diff --git a/tests/FluxFlow.Composition.Tests/ApplicationDefinitionJsonTests.cs b/tests/FluxFlow.Composition.Tests/ApplicationDefinitionJsonTests.cs index 0ac5f690..a3687498 100644 --- a/tests/FluxFlow.Composition.Tests/ApplicationDefinitionJsonTests.cs +++ b/tests/FluxFlow.Composition.Tests/ApplicationDefinitionJsonTests.cs @@ -1,3 +1,4 @@ +using FluxFlow.Composition.Authoring; using FluxFlow.Composition.Model; using Shouldly; using System.Reflection; @@ -224,6 +225,83 @@ public void Omitted_component_defaults_remain_omitted_after_round_trip() ApplicationDefinitionJson.Serialize(definition).ShouldBe(json); } + [Fact] + public void Code_first_component_descriptors_are_omitted_from_json_and_deserialization_is_descriptor_free() + { + var activations = 0; + var contract = ComponentContract.Create( + "test.uppercase", + component => component + .UseFactory(_ => + { + activations++; + return new UppercaseNode(); + }) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events), + static component => new InputOutputComponentHandle( + component, + "Input", + "Output", + "Events")); + var builder = new ApplicationDefinitionBuilder(); + builder.AddWorkflow("Main").AddComponent("Upper", contract); + var definition = builder.Build(); + + definition.ComponentDescriptors.ShouldHaveSingleItem() + .ShouldBeSameAs(contract.Descriptor); + activations.ShouldBe(0); + + var json = ApplicationDefinitionJson.Serialize(definition); + + json.ShouldBe( + "{\"Resources\":{},\"Workflows\":{\"Main\":{\"Upper\":{\"Type\":\"test.uppercase\"}}}}"); + json.ShouldNotContain(nameof(ApplicationDefinition.ComponentDescriptors)); + json.ShouldNotContain("Descriptor"); + json.ShouldNotContain("Factory"); + activations.ShouldBe(0); + + var roundTripped = ApplicationDefinitionJson.Deserialize(json); + roundTripped.ComponentDescriptors.ShouldBeEmpty(); + roundTripped.Workflows["Main"].Components["Upper"].Type.ShouldBe("test.uppercase"); + activations.ShouldBe(0); + } + + [Fact] + public void Code_first_resource_contracts_are_omitted_from_json_and_deserialization_is_contract_free() + { + var registrar = new JsonResourceRegistrar(); + var contract = ApplicationResourceContract.Create( + "test.executable-resource", + registrar, + static definition => new JsonResourceHandle(definition)); + var builder = new ApplicationDefinitionBuilder(); + var handle = builder.AddResource("service", contract); + var definition = builder.Build(); + + handle.Address.Value.ShouldBe("Resources.service"); + definition.ApplicationResourceContracts.ShouldHaveSingleItem() + .ShouldBeSameAs(contract); + registrar.RegistrationCount.ShouldBe(0); + + var json = ApplicationDefinitionJson.Serialize(definition); + + json.ShouldBe( + "{\"Resources\":{\"service\":{\"Type\":\"test.executable-resource\"}},\"Workflows\":{}}"); + json.ShouldNotContain(nameof(ApplicationDefinition.ApplicationResourceContracts)); + json.ShouldNotContain(nameof(IApplicationResourceRegistrar)); + json.ShouldNotContain("Registrar"); + json.ShouldNotContain("Factory"); + registrar.RegistrationCount.ShouldBe(0); + + var roundTripped = ApplicationDefinitionJson.Deserialize(json); + roundTripped.ApplicationResourceContracts.ShouldBeEmpty(); + roundTripped.Resources["service"].ShouldBeOfType() + .Type.ShouldBe(contract.Type); + registrar.RegistrationCount.ShouldBe(0); + } + [Fact] public void PublicConstructorsRejectDuplicateAndReservedNames() { @@ -246,4 +324,18 @@ public void PublicConstructorsRejectDuplicateAndReservedNames() "sample", [new("configuration", document.RootElement)])); } + + private sealed class JsonResourceHandle(ResourceHandle definition) + : AuthoredResourceHandle(definition); + + private sealed class JsonResourceRegistrar : IApplicationResourceRegistrar + { + public int RegistrationCount { get; private set; } + + public void Register(ApplicationResourceRegistrationContext context) + { + ArgumentNullException.ThrowIfNull(context); + RegistrationCount++; + } + } } diff --git a/tests/FluxFlow.Composition.Tests/ApplicationLinkCompilerTests.cs b/tests/FluxFlow.Composition.Tests/ApplicationLinkCompilerTests.cs index cc307739..62cbabc8 100644 --- a/tests/FluxFlow.Composition.Tests/ApplicationLinkCompilerTests.cs +++ b/tests/FluxFlow.Composition.Tests/ApplicationLinkCompilerTests.cs @@ -802,7 +802,11 @@ private static ComponentCatalog CreateRegistry( new ComponentDescriptor( "source", UnusedFactory, - outputs: [ComponentPorts.Metadata("Output", sourceCardinality)]), + outputs: + [ + ComponentPorts.Metadata("Output", sourceCardinality), + ComponentPorts.Metadata("Events") + ]), new ComponentDescriptor( "int-source", UnusedFactory, diff --git a/tests/FluxFlow.Composition.Tests/ComponentDescriptorTests.cs b/tests/FluxFlow.Composition.Tests/ComponentDescriptorTests.cs index ccceec82..a430c9e5 100644 --- a/tests/FluxFlow.Composition.Tests/ComponentDescriptorTests.cs +++ b/tests/FluxFlow.Composition.Tests/ComponentDescriptorTests.cs @@ -6,7 +6,7 @@ namespace FluxFlow.Composition.Tests; public sealed class ComponentDescriptorTests { [Fact] - public void Descriptor_normalizes_type_and_port_names() + public void Descriptor_normalizes_type_and_port_names_without_injecting_events() { var descriptor = new ComponentDescriptor( " data.map ", @@ -16,8 +16,8 @@ public void Descriptor_normalizes_type_and_port_names() descriptor.Type.ShouldBe("data.map"); descriptor.Inputs.Keys.ShouldBe(["Input"]); - descriptor.Outputs.Keys.ShouldBe(["Output", "Events"]); - descriptor.Outputs["Events"].MessageType.ShouldBe(typeof(ComponentEvent)); + descriptor.Outputs.Keys.ShouldBe(["Output"]); + descriptor.Outputs.ContainsKey("Events").ShouldBeFalse(); } [Fact] diff --git a/tests/FluxFlow.Composition.Tests/ComponentEventTests.cs b/tests/FluxFlow.Composition.Tests/ComponentEventTests.cs index c5d9f099..7820f68f 100644 --- a/tests/FluxFlow.Composition.Tests/ComponentEventTests.cs +++ b/tests/FluxFlow.Composition.Tests/ComponentEventTests.cs @@ -2,6 +2,7 @@ using FluxFlow.Composition.Model; using FluxFlow.Data; using FluxFlow.Nodes; +using Microsoft.Extensions.DependencyInjection; using Shouldly; using Xunit; @@ -9,19 +10,14 @@ namespace FluxFlow.Composition.Tests; public sealed class ComponentEventTests { + private const string EventPortName = "Diagnostics"; + [Fact] public async Task Component_event_bridge_fans_out_every_event_in_order_to_two_subscribers() { var node = new EventNode(); - var registration = new ComponentDescriptor( - "sample.component", - _ => ValueTask.FromResult(ComponentInstance.Create(node, events: node.Events))); - var descriptor = await registration.Factory(new ComponentActivationContext( - EmptyServiceProvider.Instance, - "Orders", - "Validate", - new ComponentDefinition("sample.component"))); - var output = descriptor.Outputs[ComponentEvents.PortName] + var instance = await ActivateAsync(node); + var output = instance.Outputs[EventPortName] .ShouldBeOfType>(); var first = new BufferBlock>(); var second = new BufferBlock>(); @@ -66,23 +62,15 @@ await Task.WhenAll(first.Completion, second.Completion) secondMessages.Select(static message => message.MessageId) .ShouldBe(firstMessages.Select(static message => message.MessageId)); - await descriptor.DisposeAsync(); + await instance.DisposeAsync(); } [Fact] - public async Task Registered_factories_expose_traced_addressable_component_events() + public async Task HasEvents_uses_custom_name_and_preserves_component_event_envelope() { var node = new EventNode(); - var registration = new ComponentDescriptor( - "sample.component", - _ => ValueTask.FromResult(ComponentInstance.Create(node, events: node.Events))); - var context = new ComponentActivationContext( - EmptyServiceProvider.Instance, - "Orders", - "Validate", - new ComponentDefinition("sample.component")); - var descriptor = await registration.Factory(context); - var output = descriptor.Outputs[ComponentEvents.PortName] + var instance = await ActivateAsync(node); + var output = instance.Outputs[EventPortName] .ShouldBeOfType>(); var correlationId = CorrelationId.New(); var occurredAt = DateTimeOffset.UtcNow.AddSeconds(-1); @@ -93,10 +81,13 @@ public async Task Registered_factories_expose_traced_addressable_component_event Timestamp = occurredAt, CorrelationId = correlationId, Name = "validation.completed", + Level = FlowEventLevel.Warning, + Message = "Validation completed with warnings.", Attributes = new Dictionary { ["valid"] = true, - ["count"] = 2 + ["count"] = 2, + ["bytes"] = new byte[] { 1, 2, 3 } } }).ShouldBeTrue(); @@ -109,50 +100,39 @@ public async Task Registered_factories_expose_traced_addressable_component_event message.Value.ComponentAddress.ShouldBe("Orders.Validate"); message.Value.Timestamp.ShouldBe(occurredAt); message.Value.Name.ShouldBe("validation.completed"); + message.Value.Level.ShouldBe(FlowEventLevel.Warning); + message.Value.Message.ShouldBe("Validation completed with warnings."); message.Value.Attributes["valid"].ShouldBe("true"); message.Value.Attributes["count"].ShouldBe("2"); + message.Value.Attributes["bytes"].ShouldBe("AQID"); node.Complete(); await output.Source.Completion.WaitAsync(TimeSpan.FromSeconds(5)); - await descriptor.DisposeAsync(); + await instance.DisposeAsync(); } [Fact] public async Task Component_faults_remain_on_completion_and_do_not_fault_the_events_output() { var node = new EventNode(); - var registration = new ComponentDescriptor( - "sample.component", - _ => ValueTask.FromResult(ComponentInstance.Create(node, events: node.Events))); - var descriptor = await registration.Factory(new ComponentActivationContext( - EmptyServiceProvider.Instance, - "Orders", - "Validate", - new ComponentDefinition("sample.component"))); - var output = descriptor.Outputs[ComponentEvents.PortName] + var instance = await ActivateAsync(node); + var output = instance.Outputs[EventPortName] .ShouldBeOfType>(); node.Fault(new InvalidOperationException("component failed")); - await Should.ThrowAsync(async () => await descriptor.Completion); + await Should.ThrowAsync(async () => await instance.Completion); await output.Source.Completion.WaitAsync(TimeSpan.FromSeconds(5)); output.Source.Completion.IsCompletedSuccessfully.ShouldBeTrue(); - await descriptor.DisposeAsync(); + await instance.DisposeAsync(); } [Fact] public async Task Unconsumed_component_events_do_not_hold_completion_open() { var node = new EventNode(); - var registration = new ComponentDescriptor( - "sample.component", - _ => ValueTask.FromResult(ComponentInstance.Create(node, events: node.Events))); - var descriptor = await registration.Factory(new ComponentActivationContext( - EmptyServiceProvider.Instance, - "Orders", - "Validate", - new ComponentDefinition("sample.component"))); - var output = descriptor.Outputs[ComponentEvents.PortName] + var instance = await ActivateAsync(node); + var output = instance.Outputs[EventPortName] .ShouldBeOfType>(); node.Events.Post(new FlowEvent { @@ -163,7 +143,23 @@ public async Task Unconsumed_component_events_do_not_hold_completion_open() node.Complete(); await output.Source.Completion.WaitAsync(TimeSpan.FromSeconds(5)); - await descriptor.DisposeAsync(); + await instance.DisposeAsync(); + } + + private static async ValueTask ActivateAsync(EventNode node) + { + var services = new ServiceCollection(); + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("sample.component", component => + component + .UseFactory(_ => node) + .HasEvents(EventPortName, static activated => activated.Events)); + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + return await descriptor.Factory(new ComponentActivationContext( + provider, + "Orders", + "Validate", + new ComponentDefinition("sample.component"))); } private sealed class EventNode : IFlowNode @@ -194,10 +190,4 @@ public ValueTask DisposeAsync() } } - private sealed class EmptyServiceProvider : IServiceProvider - { - public static EmptyServiceProvider Instance { get; } = new(); - - public object? GetService(Type serviceType) => null; - } } diff --git a/tests/FluxFlow.Composition.Tests/FluxFlowRegistrationBuilderTests.cs b/tests/FluxFlow.Composition.Tests/FluxFlowRegistrationBuilderTests.cs index eb9d8f8c..100180c9 100644 --- a/tests/FluxFlow.Composition.Tests/FluxFlowRegistrationBuilderTests.cs +++ b/tests/FluxFlow.Composition.Tests/FluxFlowRegistrationBuilderTests.cs @@ -1,3 +1,6 @@ +using System.Threading.Tasks.Dataflow; +using FluxFlow.Composition.Authoring; +using FluxFlow.Nodes; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Xunit; @@ -31,30 +34,31 @@ public void AddFluxFlowComponents_rejects_null_services() } [Fact] - public void AddRuntimeComponent_returns_same_builder_and_invokes_configuration_once() + public void Advanced_dynamic_registration_returns_same_builder_and_invokes_configuration_once() { var builder = new ServiceCollection().AddFluxFlowComponents(); + var advanced = builder.Advanced; var invocationCount = 0; RuntimeComponentRegistrationBuilder? configured = null; - var returned = builder.AddRuntimeComponent("test.component", component => + var returned = advanced.AddDynamicComponent("test.component", component => { invocationCount++; configured = component; ConfigureRuntime(component); }); - returned.ShouldBeSameAs(builder); + returned.ShouldBeSameAs(advanced); invocationCount.ShouldBe(1); configured.ShouldNotBeNull(); } [Fact] - public void AddRuntimeComponent_registers_the_complete_runtime_descriptor() + public void Advanced_dynamic_registration_registers_the_complete_runtime_descriptor() { var services = new ServiceCollection(); services.AddFluxFlowComponents() - .AddRuntimeComponent(" test.component ", ConfigureRuntime); + .Advanced.AddDynamicComponent(" test.component ", ConfigureRuntime); using var provider = services.BuildServiceProvider(); var descriptor = provider.GetRequiredService(); @@ -85,10 +89,10 @@ public void Equivalent_runtime_registration_is_idempotent_across_flat_builders() var services = new ServiceCollection(); services.AddFluxFlowComponents() - .AddRuntimeComponent("test.component", ConfigureRuntime) - .AddRuntimeComponent("test.component", ConfigureRuntime); + .Advanced.AddDynamicComponent("test.component", ConfigureRuntime) + .AddDynamicComponent("test.component", ConfigureRuntime); services.AddFluxFlowComponents() - .AddRuntimeComponent("test.component", ConfigureRuntime); + .Advanced.AddDynamicComponent("test.component", ConfigureRuntime); services.Count(registration => registration.ServiceType == typeof(ComponentCatalog)) .ShouldBe(1); @@ -106,7 +110,7 @@ public void Conflicting_runtime_registration_fails_immediately_without_partial_s { var services = new ServiceCollection(); var builder = services.AddFluxFlowComponents() - .AddRuntimeComponent("test.component", ConfigureRuntime); + .Advanced.AddDynamicComponent("test.component", ConfigureRuntime); var original = services .Where(registration => registration.ServiceType == typeof(ComponentDescriptor)) .Select(registration => registration.ImplementationInstance) @@ -114,7 +118,7 @@ public void Conflicting_runtime_registration_fails_immediately_without_partial_s .ShouldHaveSingleItem(); var exception = Should.Throw(() => - builder.AddRuntimeComponent("test.component", component => + builder.AddDynamicComponent("test.component", component => { ConfigureRuntime(component); component.UseProcessing(CompositionProcessingCapabilities.Sequential); @@ -137,11 +141,11 @@ public void Conflicting_runtime_registration_fails_immediately_without_partial_s public void Runtime_registration_requires_factory_without_appending_partial_state() { var services = new ServiceCollection(); - var builder = services.AddFluxFlowComponents(); + var builder = services.AddFluxFlowComponents().Advanced; var exception = Should.Throw(() => - builder.AddRuntimeComponent("test.component", component => - component.AddInput("Input"))); + builder.AddDynamicComponent("test.component", component => + component.UseProcessing(CompositionProcessingCapabilities.Sequential))); exception.Message.ShouldContain("test.component"); exception.Message.ShouldContain(nameof(RuntimeComponentRegistrationBuilder.UseFactory)); @@ -155,19 +159,17 @@ public void Runtime_registration_requires_factory_without_appending_partial_stat [Fact] public void Runtime_registration_rejects_null_builder_type_and_configuration() { - var builder = new ServiceCollection().AddFluxFlowComponents(); + var builder = new ServiceCollection().AddFluxFlowComponents().Advanced; - Should.Throw(() => - FluxFlowRegistrationExtensions.AddRuntimeComponent( - null!, + Should.Throw(() => + ((AdvancedFluxFlowRegistrationBuilder)null!).AddDynamicComponent( "test.component", - ConfigureRuntime)) - .ParamName.ShouldBe("builder"); + ConfigureRuntime)); Should.Throw(() => - builder.AddRuntimeComponent(" ", ConfigureRuntime)) + builder.AddDynamicComponent(" ", ConfigureRuntime)) .ParamName.ShouldBe("type"); Should.Throw(() => - builder.AddRuntimeComponent("test.component", null!)) + builder.AddDynamicComponent("test.component", null!)) .ParamName.ShouldBe("configure"); } @@ -177,9 +179,9 @@ public void Separate_flat_builders_compose_into_one_ordinal_catalog() var services = new ServiceCollection(); services.AddFluxFlowComponents() - .AddRuntimeComponent("test.zulu", ConfigureMinimal); + .Advanced.AddDynamicComponent("test.zulu", ConfigureMinimal); services.AddFluxFlowComponents() - .AddRuntimeComponent("test.alpha", ConfigureMinimal); + .Advanced.AddDynamicComponent("test.alpha", ConfigureMinimal); services.Count(registration => registration.ServiceType == typeof(ComponentCatalog)) .ShouldBe(1); @@ -196,11 +198,12 @@ public void Standalone_flat_runtime_usage_compiles_without_Designer_or_Engine() IServiceCollection services = new ServiceCollection(); FluxFlowRegistrationBuilder registration = services.AddFluxFlowComponents(); - FluxFlowRegistrationBuilder returned = registration.AddRuntimeComponent( + AdvancedFluxFlowRegistrationBuilder advanced = registration.Advanced; + AdvancedFluxFlowRegistrationBuilder returned = advanced.AddDynamicComponent( "test.component", - component => component.UseFactory(UnusedFactory)); + component => component.UseFactory(CreateNode)); - returned.ShouldBeSameAs(registration); + returned.ShouldBeSameAs(advanced); using var provider = services.BuildServiceProvider(); provider.GetRequiredService().Components.Keys .ShouldBe(["test.component"]); @@ -208,18 +211,116 @@ public void Standalone_flat_runtime_usage_compiles_without_Designer_or_Engine() private static void ConfigureRuntime(RuntimeComponentRegistrationBuilder component) { - component.UseFactory(UnusedFactory); component.UseProcessing(CompositionProcessingCapabilities.ParallelRelaxedOrder); - component.AddInput("Input"); - component.AddSignalInput("Signal"); - component.AddOutput("Output", ComponentPortLinkCardinality.Single); + component + .UseFactory(CreateNode) + .HasInput("Input", static node => node.Input) + .HasSignalInput("Signal", static node => node.Signal) + .HasOutput( + "Output", + static node => node.Output, + ComponentPortLinkCardinality.Single) + .HasEvents("Events", static node => node.Events); component.AddOption("enabled", isRequired: true); component.AddResource("clock", isRequired: true); } + [Fact] + public void Exact_contract_registration_is_idempotent_and_reuses_the_owned_descriptor() + { + var contract = ComponentContract.Create( + " test.component ", + ConfigureRuntime, + static component => new OutputComponentHandle(component, "Output", "Events")); + var services = new ServiceCollection(); + var builder = services.AddFluxFlowComponents(); + + builder.AddComponent(contract).ShouldBeSameAs(builder); + builder.AddComponent(contract).ShouldBeSameAs(builder); + services.AddFluxFlowComponents().AddComponent(contract); + + services.Count(registration => registration.ServiceType == typeof(ComponentDescriptor)) + .ShouldBe(1); + services.Count(registration => registration.ServiceType == typeof(ComponentCatalog)) + .ShouldBe(1); + using var provider = services.BuildServiceProvider(); + provider.GetRequiredService().ShouldBeSameAs(contract.Descriptor); + provider.GetRequiredService().Descriptors + .ShouldHaveSingleItem().ShouldBeSameAs(contract.Descriptor); + contract.Type.ShouldBe("test.component"); + } + + [Fact] + public void Distinct_contract_registration_for_the_same_type_conflicts_without_partial_state() + { + var first = ComponentContract.Create( + "test.component", + ConfigureRuntime, + static component => new OutputComponentHandle(component, "Output", "Events")); + var second = ComponentContract.Create( + "test.component", + ConfigureRuntime, + static component => new OutputComponentHandle(component, "Output", "Events")); + second.Descriptor.ShouldNotBeSameAs(first.Descriptor); + var services = new ServiceCollection(); + var builder = services.AddFluxFlowComponents().AddComponent(first); + var originalRegistrations = services.ToArray(); + + var exception = Should.Throw(() => + builder.AddComponent(second)); + + exception.Message.ShouldContain("test.component"); + exception.Message.ShouldContain("conflicting descriptor registration"); + services.Count.ShouldBe(originalRegistrations.Length); + for (var index = 0; index < originalRegistrations.Length; index++) + services[index].ShouldBeSameAs(originalRegistrations[index]); + using var provider = services.BuildServiceProvider(); + provider.GetRequiredService().ShouldBeSameAs(first.Descriptor); + provider.GetRequiredService().Descriptors + .ShouldHaveSingleItem().ShouldBeSameAs(first.Descriptor); + } + private static void ConfigureMinimal(RuntimeComponentRegistrationBuilder component) - => component.UseFactory(UnusedFactory); + => component.UseFactory(CreateNode); + + private static RegistrationNode CreateNode(ComponentActivationContext _) => new(); + + private sealed class RegistrationNode : IFlowNode, IFlowSignalTarget + { + public BufferBlock> Input { get; } = new(); + + public BufferBlock> Output { get; } = new(); - private static ValueTask UnusedFactory(ComponentActivationContext _) - => throw new InvalidOperationException("Factory should not run."); + public BufferBlock Events { get; } = new(); + + public IFlowSignalTarget Signal => this; + + public Task Completion { get; } = Task.CompletedTask; + + public void Complete() + { + Input.Complete(); + Output.Complete(); + Events.Complete(); + } + + public void Fault(Exception exception) + { + ArgumentNullException.ThrowIfNull(exception); + } + + public ValueTask SendAsync( + FlowMessage signal, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(true); + } + + public ValueTask DisposeAsync() + { + Complete(); + return ValueTask.CompletedTask; + } + } } diff --git a/tests/FluxFlow.Composition.Tests/RuntimeComponentBindingBuilderTests.cs b/tests/FluxFlow.Composition.Tests/RuntimeComponentBindingBuilderTests.cs new file mode 100644 index 00000000..ac541d1d --- /dev/null +++ b/tests/FluxFlow.Composition.Tests/RuntimeComponentBindingBuilderTests.cs @@ -0,0 +1,555 @@ +using System.Threading.Tasks.Dataflow; +using FluxFlow.Composition.Model; +using FluxFlow.Nodes; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; + +namespace FluxFlow.Composition.Tests; + +public sealed class RuntimeComponentBindingBuilderTests +{ + [Fact] + public void Typed_factory_registration_declares_metadata_without_running_factory_or_selectors() + { + var services = new ServiceCollection(); + var configurationCalls = 0; + var factoryCalls = 0; + var selectorCalls = 0; + + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.typed", component => + { + configurationCalls++; + component + .UseFactory(_ => + { + factoryCalls++; + return new BindingNode(); + }) + .HasInput( + "Input", + node => + { + selectorCalls++; + return node.Input; + }, + ComponentPortLinkCardinality.Single) + .HasSignalInput( + "Signal", + node => + { + selectorCalls++; + return node.Signal; + }) + .HasOutput( + "Output", + node => + { + selectorCalls++; + return node.Output; + }) + .HasEvents( + "Diagnostics", + node => + { + selectorCalls++; + return node.Events; + }); + }); + + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + + configurationCalls.ShouldBe(1); + factoryCalls.ShouldBe(0); + selectorCalls.ShouldBe(0); + descriptor.Inputs.Keys.ShouldBe(["Input", "Signal"]); + descriptor.Inputs["Input"].MessageType.ShouldBe(typeof(string)); + descriptor.Inputs["Input"].LinkCardinality.ShouldBe(ComponentPortLinkCardinality.Single); + descriptor.Inputs["Signal"].Kind.ShouldBe(ComponentPortKind.Signal); + descriptor.Outputs.Keys.ShouldBe(["Output", "Diagnostics"]); + descriptor.Outputs["Output"].MessageType.ShouldBe(typeof(int)); + descriptor.Outputs["Diagnostics"].MessageType.ShouldBe(typeof(ComponentEvent)); + } + + [Fact] + public void Runtime_component_binding_builders_expose_only_Has_port_methods() + { + AssertCanonicalPortMethods(typeof(RuntimeComponentBindingBuilder<>)); + AssertCanonicalPortMethods(typeof(RuntimeComponentInstanceBindingBuilder)); + } + + [Fact] + public async Task Sync_factory_infers_ports_and_binds_exact_node_members_once_in_role_order() + { + var services = new ServiceCollection(); + var selectorOrder = new List(); + BindingNode? created = null; + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.typed", component => + component + .UseFactory(_ => created = new BindingNode()) + .HasOutput("Output", node => Record("output", node.Output)) + .HasInput("First", node => Record("first", node.Input)) + .HasEvents("Diagnostics", node => Record("events", node.Events)) + .HasSignalInput("Signal", node => Record("signal", node.Signal)) + .HasInput("Second", node => Record("second", node.AlternateInput))); + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + + var instance = await descriptor.Factory(Context(provider)); + + created.ShouldNotBeNull(); + selectorOrder.ShouldBe(["first", "second", "signal", "output", "events"]); + descriptor.Inputs.Keys.ShouldBe(["First", "Signal", "Second"]); + descriptor.Outputs.Keys.ShouldBe(["Output", "Diagnostics"]); + instance.Inputs["First"].ShouldBeOfType>() + .Target.ShouldBeSameAs(created.Input); + instance.Inputs["Second"].ShouldBeOfType>() + .Target.ShouldBeSameAs(created.AlternateInput); + instance.Inputs["Signal"].ShouldBeOfType() + .Target.ShouldBeSameAs(created.Signal); + instance.Outputs["Output"].ShouldBeOfType>() + .Source.ShouldBeSameAs(created.Output); + instance.Outputs["Diagnostics"].ShouldBeOfType>(); + + await instance.DisposeAsync(); + created.DisposeCount.ShouldBe(1); + + T Record(string name, T value) + { + selectorOrder.Add(name); + return value; + } + } + + [Fact] + public async Task Async_factory_infers_ports_and_preserves_cardinality() + { + var services = new ServiceCollection(); + var factoryCalls = 0; + BindingNode? created = null; + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.async", component => + component + .UseFactory(async _ => + { + factoryCalls++; + await Task.Yield(); + return created = new BindingNode(); + }) + .HasInput( + "Input", + static node => node.Input, + ComponentPortLinkCardinality.Single) + .HasOutput( + "Output", + static node => node.Output, + ComponentPortLinkCardinality.Single)); + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + + factoryCalls.ShouldBe(0); + var instance = await descriptor.Factory(Context(provider)); + + factoryCalls.ShouldBe(1); + created.ShouldNotBeNull(); + descriptor.Inputs["Input"].MessageType.ShouldBe(typeof(string)); + descriptor.Inputs["Input"].LinkCardinality.ShouldBe(ComponentPortLinkCardinality.Single); + descriptor.Outputs["Output"].MessageType.ShouldBe(typeof(int)); + descriptor.Outputs["Output"].LinkCardinality.ShouldBe(ComponentPortLinkCardinality.Single); + instance.Inputs["Input"].ShouldBeOfType>() + .Target.ShouldBeSameAs(created.Input); + instance.Outputs["Output"].ShouldBeOfType>() + .Source.ShouldBeSameAs(created.Output); + + await instance.DisposeAsync(); + } + + [Fact] + public async Task Async_activation_preserves_explicit_completion_and_all_cleanup_owners() + { + var services = new ServiceCollection(); + var explicitCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + var ownerDisposeCount = 0; + BindingNode? created = null; + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.async-activation", component => + component + .UseFactory(Activate) + .HasOutput("Output", static node => node.Output)); + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + + var instance = await descriptor.Factory(Context(provider)); + + instance.Node.ShouldBeSameAs(created.ShouldNotBeNull()); + instance.Completion.ShouldBeSameAs(explicitCompletion.Task); + await instance.DisposeAsync(); + created.DisposeCount.ShouldBe(1); + ownerDisposeCount.ShouldBe(1); + + async ValueTask> Activate( + ComponentActivationContext _) + { + await Task.Yield(); + return new ComponentNodeActivation( + created = new BindingNode(), + explicitCompletion.Task, + () => + { + ownerDisposeCount++; + return ValueTask.CompletedTask; + }); + } + } + + [Fact] + public void Typed_component_without_HasEvents_has_no_implicit_event_output() + { + var services = new ServiceCollection(); + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.no-events", component => + component + .UseFactory(static _ => new BindingNode()) + .HasOutput("Output", static node => node.Output)); + + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + + descriptor.Outputs.Keys.ShouldBe(["Output"]); + descriptor.Outputs.ContainsKey("Events").ShouldBeFalse(); + } + + [Fact] + public async Task Normal_output_may_use_Events_when_no_event_port_uses_that_name() + { + var services = new ServiceCollection(); + BindingNode? created = null; + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.events-output", component => + component + .UseFactory(_ => created = new BindingNode()) + .HasOutput("Events", static node => node.Output)); + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + + var instance = await descriptor.Factory(Context(provider)); + + descriptor.Outputs.Keys.ShouldBe(["Events"]); + descriptor.Outputs["Events"].MessageType.ShouldBe(typeof(int)); + instance.Outputs["Events"].ShouldBeOfType>() + .Source.ShouldBeSameAs(created.ShouldNotBeNull().Output); + await instance.DisposeAsync(); + } + + [Fact] + public async Task Multiple_named_event_ports_bind_their_selected_sources_independently() + { + var services = new ServiceCollection(); + BindingNode? created = null; + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.multiple-events", component => + component + .UseFactory(_ => created = new BindingNode()) + .HasEvents("Diagnostics", static node => node.Events) + .HasEvents("Audit", static node => node.AuditEvents)); + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + var instance = await descriptor.Factory(Context(provider)); + var diagnostics = instance.Outputs["Diagnostics"] + .ShouldBeOfType>(); + var audit = instance.Outputs["Audit"] + .ShouldBeOfType>(); + var diagnosticReceive = diagnostics.Source.ReceiveAsync(); + var auditReceive = audit.Source.ReceiveAsync(); + + var node = created.ShouldNotBeNull(); + node.Events.Post(new FlowEvent { Name = "diagnostic" }).ShouldBeTrue(); + node.AuditEvents.Post(new FlowEvent { Name = "audit" }).ShouldBeTrue(); + + (await diagnosticReceive.WaitAsync(TimeSpan.FromSeconds(5))).Value.Name + .ShouldBe("diagnostic"); + (await auditReceive.WaitAsync(TimeSpan.FromSeconds(5))).Value.Name + .ShouldBe("audit"); + descriptor.Outputs.Keys.ShouldBe(["Diagnostics", "Audit"]); + descriptor.Outputs.Values.All(port => port.MessageType == typeof(ComponentEvent)) + .ShouldBeTrue(); + + await instance.DisposeAsync(); + } + + [Fact] + public void Normal_and_event_outputs_share_one_duplicate_name_boundary() + { + var services = new ServiceCollection(); + + var exception = Should.Throw(() => + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.duplicate", component => + component + .UseFactory(static _ => new BindingNode()) + .HasOutput("Events", static node => node.Output) + .HasEvents("Events", static node => node.Events))); + + exception.Message.ShouldContain("output port 'Events'"); + exception.Message.ShouldContain("already registered"); + services.ShouldNotContain(registration => registration.ServiceType == typeof(ComponentDescriptor)); + } + + [Theory] + [InlineData("input")] + [InlineData("signal")] + [InlineData("output")] + [InlineData("events")] + public void Typed_builder_rejects_null_selectors_before_registration(string role) + { + var services = new ServiceCollection(); + + var exception = Should.Throw(() => + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.null-selector", component => + { + var bindings = component.UseFactory(CreateNode); + switch (role) + { + case "input": + bindings.HasInput("Input", null!); + break; + case "signal": + bindings.HasSignalInput("Signal", null!); + break; + case "output": + bindings.HasOutput("Output", null!); + break; + case "events": + bindings.HasEvents("Events", null!); + break; + default: + throw new ArgumentOutOfRangeException(nameof(role)); + } + })); + + exception.ParamName.ShouldBe("selector"); + services.ShouldNotContain(registration => registration.ServiceType == typeof(ComponentDescriptor)); + } + + [Fact] + public void Registration_rejects_null_or_multiple_factory_modes_without_partial_state() + { + var nullFactoryServices = new ServiceCollection(); + var nullFactory = Should.Throw(() => + nullFactoryServices.AddFluxFlowComponents().Advanced.AddDynamicComponent( + "test.null-factory", + component => component.UseFactory( + (Func)null!))); + + nullFactory.ParamName.ShouldBe("value"); + nullFactoryServices.ShouldNotContain(registration => + registration.ServiceType == typeof(ComponentDescriptor)); + + var multipleFactoryServices = new ServiceCollection(); + var multipleFactory = Should.Throw(() => + multipleFactoryServices.AddFluxFlowComponents().Advanced.AddDynamicComponent( + "test.multiple-factories", + component => + { + component.UseFactory(CreateNode); + component.UseInstanceFactory(static _ => + throw new InvalidOperationException("Instance factory should not run.")); + })); + + multipleFactory.Message.ShouldContain("test.multiple-factories"); + multipleFactory.Message.ShouldContain("exactly one factory mode"); + multipleFactoryServices.ShouldNotContain(registration => + registration.ServiceType == typeof(ComponentDescriptor)); + } + + [Fact] + public async Task Typed_factory_null_node_failure_identifies_component_and_cleans_no_owner() + { + var services = new ServiceCollection(); + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.null-node", component => + component.UseFactory( + (Func)(static _ => null!))); + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + + var exception = await Should.ThrowAsync(async () => + await descriptor.Factory(Context(provider))); + + exception.Message.ShouldContain("test.null-node"); + exception.Message.ShouldContain("null node"); + } + + [Fact] + public async Task Typed_activation_failure_disposes_node_and_additional_owner_once() + { + var services = new ServiceCollection(); + var ownerDisposeCount = 0; + BindingNode? created = null; + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.null-binding", component => + component + .UseFactory(_ => new ComponentNodeActivation( + created = new BindingNode(), + disposeAsync: () => + { + ownerDisposeCount++; + return ValueTask.CompletedTask; + })) + .HasInput("Input", static _ => null!)); + using var provider = services.BuildServiceProvider(); + var descriptor = provider.GetRequiredService(); + + var exception = await Should.ThrowAsync(async () => + await descriptor.Factory(Context(provider))); + + exception.Message.ShouldContain("test.null-binding"); + exception.Message.ShouldContain("Input"); + exception.Message.ShouldContain("returned null"); + created.ShouldNotBeNull().DisposeCount.ShouldBe(1); + ownerDisposeCount.ShouldBe(1); + } + + [Fact] + public void Equivalent_typed_registration_is_idempotent_and_changed_selector_conflicts() + { + var services = new ServiceCollection(); + var builder = services.AddFluxFlowComponents().Advanced + .AddDynamicComponent("test.identity", ConfigureEquivalent) + .AddDynamicComponent("test.identity", ConfigureEquivalent); + + services.Count(registration => registration.ServiceType == typeof(ComponentDescriptor)) + .ShouldBe(1); + + var exception = Should.Throw(() => + builder.AddDynamicComponent("test.identity", ConfigureChangedSelector)); + + exception.Message.ShouldContain("test.identity"); + exception.Message.ShouldContain("conflicting descriptor registration"); + services.Count(registration => registration.ServiceType == typeof(ComponentDescriptor)) + .ShouldBe(1); + } + + private static void ConfigureEquivalent(RuntimeComponentRegistrationBuilder component) + => component + .UseFactory(CreateNode) + .HasInput("Input", SelectInput) + .HasOutput("Output", SelectOutput) + .HasEvents("Diagnostics", SelectEvents); + + private static void ConfigureChangedSelector(RuntimeComponentRegistrationBuilder component) + => component + .UseFactory(CreateNode) + .HasInput("Input", SelectAlternateInput) + .HasOutput("Output", SelectOutput) + .HasEvents("Diagnostics", SelectEvents); + + private static BindingNode CreateNode(ComponentActivationContext _) => new(); + + private static ITargetBlock> SelectInput(BindingNode node) => node.Input; + + private static ITargetBlock> SelectAlternateInput(BindingNode node) + => node.AlternateInput; + + private static ISourceBlock> SelectOutput(BindingNode node) => node.Output; + + private static ISourceBlock SelectEvents(BindingNode node) => node.Events; + + private static ComponentActivationContext Context(IServiceProvider services) + => new( + services, + "Orders", + "Worker", + new ComponentDefinition("test.typed")); + + private static void AssertCanonicalPortMethods(Type builderType) + { + var methodNames = builderType + .GetMethods( + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.DeclaredOnly) + .Select(static method => method.Name) + .Order(StringComparer.Ordinal) + .ToArray(); + + methodNames.ShouldBe( + [ + "HasEvents", + "HasInput", + "HasOutput", + "HasSignalInput" + ], + $"{builderType.Name} must expose only the canonical Has port DSL."); + methodNames.ShouldNotContain( + static name => name.StartsWith("Add", StringComparison.Ordinal), + $"{builderType.Name} must not retain a public Add port alias."); + } + + private sealed class BindingNode : IFlowNode + { + private readonly TaskCompletionSource _completion = new( + TaskCreationOptions.RunContinuationsAsynchronously); + private int _disposeCount; + + public BufferBlock> Input { get; } = new(); + + public BufferBlock> AlternateInput { get; } = new(); + + public BufferBlock> Output { get; } = new(); + + public BufferBlock Events { get; } = new(); + + public BufferBlock AuditEvents { get; } = new(); + + public RecordingSignalTarget Signal { get; } = new(); + + public Task Completion => _completion.Task; + + public int DisposeCount => Volatile.Read(ref _disposeCount); + + public void Complete() + { + Input.Complete(); + AlternateInput.Complete(); + Output.Complete(); + Events.Complete(); + AuditEvents.Complete(); + Signal.Complete(); + _completion.TrySetResult(); + } + + public void Fault(Exception exception) + { + ArgumentNullException.ThrowIfNull(exception); + ((IDataflowBlock)Input).Fault(exception); + ((IDataflowBlock)AlternateInput).Fault(exception); + ((IDataflowBlock)Output).Fault(exception); + ((IDataflowBlock)Events).Fault(exception); + ((IDataflowBlock)AuditEvents).Fault(exception); + Signal.Fault(exception); + _completion.TrySetException(exception); + } + + public ValueTask DisposeAsync() + { + if (Interlocked.Increment(ref _disposeCount) == 1) + Complete(); + return ValueTask.CompletedTask; + } + } + + private sealed class RecordingSignalTarget : IFlowSignalTarget + { + private readonly TaskCompletionSource _completion = new( + TaskCreationOptions.RunContinuationsAsynchronously); + + public Task Completion => _completion.Task; + + public ValueTask SendAsync( + FlowMessage signal, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(true); + } + + public void Complete() => _completion.TrySetResult(); + + public void Fault(Exception exception) => _completion.TrySetException(exception); + } +} diff --git a/tests/FluxFlow.Composition.Tests/TestCompositionNodes.cs b/tests/FluxFlow.Composition.Tests/TestCompositionNodes.cs index 65d5335f..8cf5b415 100644 --- a/tests/FluxFlow.Composition.Tests/TestCompositionNodes.cs +++ b/tests/FluxFlow.Composition.Tests/TestCompositionNodes.cs @@ -69,9 +69,13 @@ public static ComponentCatalog Create(BuildTracker? tracker = null) return ValueTask.FromResult(ComponentInstance.Create( node, outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); + addressableEvents: [ComponentPorts.Events("Events", node.Events)])); }, - outputs: [ComponentPorts.Metadata("Output")]), + outputs: + [ + ComponentPorts.Metadata("Output"), + ComponentPorts.Metadata("Events") + ]), new ComponentDescriptor( TestNodeTypes.TickingSource, _ => @@ -80,9 +84,13 @@ public static ComponentCatalog Create(BuildTracker? tracker = null) return ValueTask.FromResult(ComponentInstance.Create( node, outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); + addressableEvents: [ComponentPorts.Events("Events", node.Events)])); }, - outputs: [ComponentPorts.Metadata("Output")]), + outputs: + [ + ComponentPorts.Metadata("Output"), + ComponentPorts.Metadata("Events") + ]), new ComponentDescriptor( TestNodeTypes.IntSource, _ => @@ -91,9 +99,13 @@ public static ComponentCatalog Create(BuildTracker? tracker = null) return ValueTask.FromResult(ComponentInstance.Create( node, outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); + addressableEvents: [ComponentPorts.Events("Events", node.Events)])); }, - outputs: [ComponentPorts.Metadata("Output")]), + outputs: + [ + ComponentPorts.Metadata("Output"), + ComponentPorts.Metadata("Events") + ]), new ComponentDescriptor( TestNodeTypes.Uppercase, _ => @@ -103,10 +115,14 @@ public static ComponentCatalog Create(BuildTracker? tracker = null) node, inputs: [ComponentPorts.Input("Input", node.Input)], outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); + addressableEvents: [ComponentPorts.Events("Events", node.Events)])); }, inputs: [ComponentPorts.Metadata("Input")], - outputs: [ComponentPorts.Metadata("Output")]), + outputs: + [ + ComponentPorts.Metadata("Output"), + ComponentPorts.Metadata("Events") + ]), new ComponentDescriptor( TestNodeTypes.Sink, context => @@ -117,9 +133,10 @@ public static ComponentCatalog Create(BuildTracker? tracker = null) return ValueTask.FromResult(ComponentInstance.Create( node, inputs: [ComponentPorts.Input("Input", node.Input)], - events: node.Events)); + addressableEvents: [ComponentPorts.Events("Events", node.Events)])); }, - inputs: [ComponentPorts.Metadata("Input")]), + inputs: [ComponentPorts.Metadata("Input")], + outputs: [ComponentPorts.Metadata("Events")]), new ComponentDescriptor( TestNodeTypes.TrackedSource, _ => @@ -128,9 +145,13 @@ public static ComponentCatalog Create(BuildTracker? tracker = null) return ValueTask.FromResult(ComponentInstance.Create( node, outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); + addressableEvents: [ComponentPorts.Events("Events", node.Events)])); }, - outputs: [ComponentPorts.Metadata("Output")]), + outputs: + [ + ComponentPorts.Metadata("Output"), + ComponentPorts.Metadata("Events") + ]), new ComponentDescriptor( TestNodeTypes.Failing, _ => throw new InvalidOperationException("factory failed")) diff --git a/tests/FluxFlow.Composition.Tests/TypedCodeFirstApplicationAuthoringTests.cs b/tests/FluxFlow.Composition.Tests/TypedCodeFirstApplicationAuthoringTests.cs new file mode 100644 index 00000000..6f675613 --- /dev/null +++ b/tests/FluxFlow.Composition.Tests/TypedCodeFirstApplicationAuthoringTests.cs @@ -0,0 +1,563 @@ +using System.Threading.Tasks.Dataflow; +using FluxFlow.Composition.Authoring; +using FluxFlow.Composition.Links; +using FluxFlow.Composition.Model; +using FluxFlow.Nodes; +using Shouldly; +using Xunit; + +namespace FluxFlow.Composition.Tests; + +public sealed class TypedCodeFirstApplicationAuthoringTests +{ + [Fact] + public void Complete_contracts_add_configured_and_configuration_free_components_with_inferred_handles_and_owned_descriptors() + { + var runtimeConfigurations = 0; + var activations = 0; + var optionsCreated = 0; + var optionsApplied = 0; + var handlesCreated = 0; + var routerContract = ComponentContract.Create( + " test.router ", + component => + { + runtimeConfigurations++; + ConfigureRuntime(component, _ => + { + activations++; + return new AuthoringNode(); + }); + }, + () => + { + optionsCreated++; + return new RouterOptions(); + }, + (options, definition) => + { + optionsApplied++; + definition.Set("Minimum", options.Minimum); + definition.Set("Label", options.Label); + }, + component => + { + handlesCreated++; + return new RouterHandle(component); + }); + var sinkContract = ComponentContract.Create( + "test.sink", + component => + { + runtimeConfigurations++; + ConfigureRuntime(component, _ => + { + activations++; + return new AuthoringNode(); + }); + }, + static component => new InputComponentHandle(component, "Orders", "Events")); + runtimeConfigurations.ShouldBe(2); + activations.ShouldBe(0); + var application = new ApplicationDefinitionBuilder(); + application.AddWorkflow("Main", out var workflow); + + workflow + .AddComponent( + "Router", + routerContract, + options => + { + options.Minimum = 17; + options.Label = "priority"; + }, + out var router) + .AddComponent("Sink", sinkContract, out var sink) + .ShouldBeSameAs(workflow); + + router.ShouldBeOfType(); + sink.ShouldBeOfType>(); + router.Type.ShouldBe("test.router"); + router.Address.Value.ShouldBe("Main.Router"); + router.Input.Address.Value.ShouldBe("Main.Router.Orders"); + router.Approved.Address.Value.ShouldBe("Main.Router.Approved"); + router.Rejected.Address.Value.ShouldBe("Main.Router.Rejected"); + router.Refresh.Address.Value.ShouldBe("Main.Router.Refresh"); + router.Events.Address.Value.ShouldBe("Main.Router.Events"); + sink.Input.Address.Value.ShouldBe("Main.Sink.Orders"); + sink.Events.Address.Value.ShouldBe("Main.Sink.Events"); + optionsCreated.ShouldBe(1); + optionsApplied.ShouldBe(1); + handlesCreated.ShouldBe(1); + activations.ShouldBe(0); + + var definition = application.Build(); + var routerDefinition = definition.Workflows["Main"].Components["Router"]; + routerDefinition.Type.ShouldBe("test.router"); + routerDefinition.Properties.Keys.ShouldBe(["Label", "Minimum"], ignoreOrder: true); + routerDefinition.Properties["Minimum"].GetInt32().ShouldBe(17); + routerDefinition.Properties["Label"].GetString().ShouldBe("priority"); + definition.Workflows["Main"].Components["Sink"].Type.ShouldBe("test.sink"); + definition.Links.ShouldBeEmpty(); + definition.ComponentDescriptors.Select(static descriptor => descriptor.Type) + .ShouldBe(["test.router", "test.sink"]); + definition.ComponentDescriptors[0].ShouldBeSameAs(routerContract.Descriptor); + definition.ComponentDescriptors[1].ShouldBeSameAs(sinkContract.Descriptor); + routerContract.Type.ShouldBe("test.router"); + routerContract.Descriptor.ProcessingCapabilities.ShouldBe( + CompositionProcessingCapabilities.ParallelRelaxedOrder); + routerContract.Descriptor.Inputs.Keys.ShouldBe( + ["Orders", "Refresh", "Signal"], + ignoreOrder: true); + routerContract.Descriptor.Inputs["Refresh"].Kind.ShouldBe(ComponentPortKind.Signal); + routerContract.Descriptor.Outputs.Keys.ShouldBe( + ["Approved", "Events", "Orders", "Rejected"], + ignoreOrder: true); + routerContract.Descriptor.Outputs["Events"].MessageType.ShouldBe(typeof(ComponentEvent)); + routerContract.Descriptor.Options.Keys.ShouldBe(["minimum"]); + routerContract.Descriptor.Options["minimum"].IsRequired.ShouldBeTrue(); + routerContract.Descriptor.Resources.Keys.ShouldBe(["clock"]); + routerContract.Descriptor.Resources["clock"].IsRequired.ShouldBeTrue(); + ((ICollection)definition.ComponentDescriptors).IsReadOnly.ShouldBeTrue(); + activations.ShouldBe(0); + } + + [Fact] + public void Typed_contract_failures_are_atomic_and_allow_same_name_retry_without_descriptor_leak() + { + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + var distinctive = new DistinctiveException("handle creation failed"); + var failHandle = true; + var unstable = ComponentContract.Create( + "test.unstable", + ConfigureRuntime, + component => + { + if (failHandle) + throw distinctive; + return new OutputComponentHandle(component, "Value", "Events"); + }); + + var caught = Should.Throw(() => + workflow.AddComponent("Retry", unstable)); + caught.ShouldBeSameAs(distinctive); + + failHandle = false; + var recovered = workflow.AddComponent("Retry", unstable); + recovered.Address.Value.ShouldBe("Main.Retry"); + + var applyFailure = new DistinctiveException("option application failed"); + var brokenOptions = ComponentContract.Create( + "test.options", + ConfigureRuntime, + static () => new RouterOptions(), + (_, _) => throw applyFailure, + static component => new RouterHandle(component)); + Should.Throw(() => + workflow.AddComponent("Options", brokenOptions, static _ => { })) + .ShouldBeSameAs(applyFailure); + workflow.AddComponent( + "Options", + ComponentContract.Create( + "test.recovered", + ConfigureRuntime, + static component => new RouterHandle(component))); + + var nullContract = Should.Throw(() => + workflow.AddComponent( + "NullContract", + (ComponentContract)null!)); + nullContract.ParamName.ShouldBe("component"); + var nullConfigure = Should.Throw(() => + workflow.AddComponent( + "NullConfigure", + ComponentContract.Create( + "test.configured", + ConfigureRuntime, + static () => new RouterOptions(), + static (_, _) => { }, + static component => new RouterHandle(component)), + (Action)null!)); + nullConfigure.ParamName.ShouldBe("configure"); + + var definition = application.Build(); + definition.Workflows["Main"].Components.Keys.ShouldBe( + ["Options", "Retry"], + ignoreOrder: true); + definition.Workflows["Main"].Components.ContainsKey("NullContract").ShouldBeFalse(); + definition.Workflows["Main"].Components.ContainsKey("NullConfigure").ShouldBeFalse(); + definition.ComponentDescriptors.Select(static descriptor => descriptor.Type) + .ShouldBe(["test.recovered", "test.unstable"]); + var descriptorTypes = definition.ComponentDescriptors + .Select(static descriptor => descriptor.Type) + .ToArray(); + descriptorTypes.ShouldNotContain("test.options"); + descriptorTypes.ShouldNotContain("test.configured"); + } + + [Fact] + public void Contract_factories_capture_complete_descriptors_without_activation_and_validate_every_delegate() + { + var invalidType = Should.Throw(() => + ComponentContract.Create( + " ", + ConfigureRuntime, + static component => new RouterHandle(component))); + invalidType.ParamName.ShouldBe("type"); + + var runtimeConfiguration = Should.Throw(() => + ComponentContract.Create( + "test.simple", + null!, + static component => new RouterHandle(component))); + runtimeConfiguration.ParamName.ShouldBe("configureRuntime"); + + var simpleHandle = Should.Throw(() => + ComponentContract.Create( + "test.simple", + ConfigureRuntime, + null!)); + simpleHandle.ParamName.ShouldBe("createHandle"); + + var optionsFactory = Should.Throw(() => + ComponentContract.Create( + "test.configured", + ConfigureRuntime, + null!, + static (_, _) => { }, + static component => new RouterHandle(component))); + optionsFactory.ParamName.ShouldBe("createOptions"); + + var apply = Should.Throw(() => + ComponentContract.Create( + "test.configured", + ConfigureRuntime, + static () => new RouterOptions(), + null!, + static component => new RouterHandle(component))); + apply.ParamName.ShouldBe("apply"); + + var configuredHandle = Should.Throw(() => + ComponentContract.Create( + "test.configured", + ConfigureRuntime, + static () => new RouterOptions(), + static (_, _) => { }, + null!)); + configuredHandle.ParamName.ShouldBe("createHandle"); + + var configurationFailure = new DistinctiveException("runtime configuration failed"); + Should.Throw(() => + ComponentContract.Create( + "test.failed-runtime", + _ => throw configurationFailure, + static component => new RouterHandle(component))) + .ShouldBeSameAs(configurationFailure); + + var missingFactory = Should.Throw(() => + ComponentContract.Create( + "test.missing-factory", + static component => component.AddOption("enabled"), + static component => new RouterHandle(component))); + missingFactory.Message.ShouldContain("test.missing-factory"); + missingFactory.Message.ShouldContain(nameof(RuntimeComponentRegistrationBuilder.UseFactory)); + } + + [Fact] + public void Repeated_contract_use_deduplicates_sorted_definition_descriptors_and_conflicting_contracts_fail_atomically() + { + var zulu = ComponentContract.Create( + "test.zulu", + ConfigureRuntime, + static component => new RouterHandle(component)); + var alpha = ComponentContract.Create( + "test.alpha", + ConfigureRuntime, + static component => new RouterHandle(component)); + var conflictingZulu = ComponentContract.Create( + "test.zulu", + ConfigureRuntime, + static component => new RouterHandle(component)); + conflictingZulu.Descriptor.ShouldNotBeSameAs(zulu.Descriptor); + var application = new ApplicationDefinitionBuilder(); + application + .AddWorkflow("Main", out var main) + .AddWorkflow("Secondary", out var secondary); + + main.AddComponent("ZuluOne", zulu); + main.AddComponent("Alpha", alpha); + secondary.AddComponent("ZuluTwo", zulu); + var conflict = Should.Throw(() => + secondary.AddComponent("Conflict", conflictingZulu)); + + conflict.Message.ShouldContain("test.zulu"); + conflict.Message.ShouldContain("conflicting contracts"); + var definition = application.Build(); + definition.ComponentDescriptors.Select(static descriptor => descriptor.Type) + .ShouldBe(["test.alpha", "test.zulu"]); + definition.ComponentDescriptors[0].ShouldBeSameAs(alpha.Descriptor); + definition.ComponentDescriptors[1].ShouldBeSameAs(zulu.Descriptor); + definition.Workflows["Main"].Components.Keys.ShouldBe( + ["Alpha", "ZuluOne"], + ignoreOrder: true); + definition.Workflows["Secondary"].Components.Keys.ShouldBe(["ZuluTwo"]); + definition.Workflows["Secondary"].Components.ContainsKey("Conflict").ShouldBeFalse(); + } + + [Fact] + public void Direct_connect_returns_same_output_and_records_ordered_local_and_cross_workflow_fanout() + { + var application = new ApplicationDefinitionBuilder(); + application + .AddWorkflow("Main", out var main) + .AddWorkflow("Audit", out var audit); + var sourceContract = ComponentContract.Create( + "test.source", + ConfigureRuntime, + static component => new OutputComponentHandle(component, "Orders", "Events")); + var sinkContract = ComponentContract.Create( + "test.sink", + ConfigureRuntime, + static component => new InputComponentHandle(component, "Orders", "Events")); + var auditContract = ComponentContract.Create( + "test.audit", + ConfigureRuntime, + static component => new SignalComponentHandle(component)); + var source = main.AddComponent( + "Source", + sourceContract); + var priority = main.AddComponent( + "Priority", + sinkContract); + var standard = main.AddComponent( + "Standard", + sinkContract); + var auditSink = audit.AddComponent( + "Recorder", + auditContract); + + var returned = source.Output + .ConnectTo(priority.Input) + .ConnectTo(standard.Input, "input.Priority == false") + .ConnectTo(auditSink.Signal, static order => order.Priority); + + returned.ShouldBeSameAs(source.Output); + var definition = application.Build(); + definition.Links.Count.ShouldBe(3); + definition.Links.Select(static link => link.Source.Value) + .ShouldAllBe(static source => source == "Main.Source.Orders"); + definition.Links.Select(static link => link.Target.Value).ShouldBe( + [ + "Main.Priority.Orders", + "Main.Standard.Orders", + "Audit.Recorder.Signal" + ]); + definition.Links[0].IsConditional.ShouldBeFalse(); + definition.Links[1].ConditionExpression.ShouldBe("input.Priority == false"); + definition.Links[2].ConditionExpression.ShouldBeNull(); + definition.Links[2].IsConditional.ShouldBeTrue(); + definition.Links.ShouldAllBe(static link => + link.MessageType == typeof(Order) && + link.DeclarationSide == ApplicationLinkDeclarationSide.Output); + } + + [Fact] + public void Connection_entry_points_share_scope_owner_duplicate_and_cardinality_rules() + { + var application = new ApplicationDefinitionBuilder(); + application + .AddWorkflow("Main", out var main) + .AddWorkflow("Audit", out var audit); + var source = main.AddComponent("Source", "test.source"); + var local = main.AddComponent("Local", "test.sink"); + var remote = audit.AddComponent("Remote", "test.sink"); + var sourceOutput = source.Output( + "Value", + ComponentPortLinkCardinality.Single); + var localInput = local.Input("Value"); + var remoteInput = remote.Input("Value"); + + var wrongScope = Should.Throw(() => + main.Connect(sourceOutput, remoteInput)); + wrongScope.Message.ShouldContain("Audit"); + application.Connect(sourceOutput, remoteInput).ShouldBeSameAs(application); + + var cardinality = Should.Throw(() => + sourceOutput.ConnectTo(localInput)); + cardinality.Message.ShouldContain("Main.Source.Value"); + cardinality.Message.ShouldContain("only one connection"); + + var foreignApplication = new ApplicationDefinitionBuilder(); + var foreign = foreignApplication.AddWorkflow("Foreign"); + var foreignInput = foreign.AddComponent("Sink", "test.sink").Input("Value"); + var ownership = Should.Throw(() => + application.Connect(sourceOutput, foreignInput)); + ownership.Message.ShouldContain("different application definition builder"); + + var definition = application.Build(); + definition.Links.ShouldHaveSingleItem(); + definition.Links[0].Target.ShouldBe(remoteInput.Address); + Should.Throw(() => + application.Connect(sourceOutput, remoteInput)); + } + + [Fact] + public void Null_conditions_fail_before_connection_mutation_and_preserve_parameter_names() + { + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + var source = workflow.AddComponent("Source", "test.source"); + var sink = workflow.AddComponent("Sink", "test.sink"); + var output = source.Output("Value"); + var input = sink.Input("Value"); + + var nullString = Should.Throw(() => + output.ConnectTo(input, (string)null!)); + nullString.ParamName.ShouldBe("condition"); + var blankString = Should.Throw(() => + workflow.Connect(output, input, " ")); + blankString.ParamName.ShouldBe("condition"); + var nullPredicate = Should.Throw(() => + application.Connect(output, input, (Func)null!)); + nullPredicate.ParamName.ShouldBe("when"); + + output.ConnectTo(input).ShouldBeSameAs(output); + var definition = application.Build(); + definition.Links.ShouldHaveSingleItem(); + definition.Links[0].IsConditional.ShouldBeFalse(); + } + + private sealed class RouterHandle : AuthoredComponentHandle + { + public RouterHandle(ComponentHandle definition) + : base(definition) + { + Input = definition.Input("Orders"); + Approved = definition.Output("Approved"); + Rejected = definition.Output("Rejected"); + Refresh = definition.SignalInput("Refresh"); + Events = definition.Output("Events"); + } + + public InputPortHandle Input { get; } + + public OutputPortHandle Approved { get; } + + public OutputPortHandle Rejected { get; } + + public SignalInputPortHandle Refresh { get; } + + public OutputPortHandle Events { get; } + } + + private sealed class SignalComponentHandle : AuthoredComponentHandle + { + public SignalComponentHandle(ComponentHandle definition) + : base(definition) + { + Signal = definition.SignalInput("Signal"); + Events = definition.Output("Events"); + } + + public SignalInputPortHandle Signal { get; } + + public OutputPortHandle Events { get; } + } + + private sealed class RouterOptions + { + public int Minimum { get; set; } + + public string? Label { get; set; } + } + + private sealed record Order(bool Priority = false); + + private static void ConfigureRuntime(RuntimeComponentRegistrationBuilder component) + => ConfigureRuntime(component, static _ => new AuthoringNode()); + + private static void ConfigureRuntime( + RuntimeComponentRegistrationBuilder component, + Func factory) + { + component.UseProcessing(CompositionProcessingCapabilities.ParallelRelaxedOrder); + component + .UseFactory(factory) + .HasInput("Orders", static node => node.OrdersInput) + .HasSignalInput("Refresh", static node => node.Refresh) + .HasSignalInput("Signal", static node => node.Signal) + .HasOutput("Approved", static node => node.Approved) + .HasOutput("Rejected", static node => node.Rejected) + .HasOutput("Orders", static node => node.OrdersOutput) + .HasEvents("Events", static node => node.Events); + component.AddOption("minimum", isRequired: true); + component.AddResource("clock", isRequired: true); + } + + private sealed class AuthoringNode : IFlowNode + { + public BufferBlock> OrdersInput { get; } = new(); + + public RecordingSignalTarget Refresh { get; } = new(); + + public RecordingSignalTarget Signal { get; } = new(); + + public BufferBlock> Approved { get; } = new(); + + public BufferBlock> Rejected { get; } = new(); + + public BufferBlock> OrdersOutput { get; } = new(); + + public BufferBlock Events { get; } = new(); + + public Task Completion => Task.CompletedTask; + + public void Complete() + { + OrdersInput.Complete(); + Refresh.Complete(); + Signal.Complete(); + Approved.Complete(); + Rejected.Complete(); + OrdersOutput.Complete(); + Events.Complete(); + } + + public void Fault(Exception exception) + { + ArgumentNullException.ThrowIfNull(exception); + ((IDataflowBlock)OrdersInput).Fault(exception); + ((IDataflowBlock)Approved).Fault(exception); + ((IDataflowBlock)Rejected).Fault(exception); + ((IDataflowBlock)OrdersOutput).Fault(exception); + ((IDataflowBlock)Events).Fault(exception); + } + + public ValueTask DisposeAsync() + { + Complete(); + return ValueTask.CompletedTask; + } + } + + private sealed class RecordingSignalTarget : IFlowSignalTarget + { + private readonly TaskCompletionSource _completion = new( + TaskCreationOptions.RunContinuationsAsynchronously); + + public Task Completion => _completion.Task; + + public ValueTask SendAsync( + FlowMessage signal, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(true); + } + + public void Complete() => _completion.TrySetResult(); + } + + private sealed class DistinctiveException(string message) : Exception(message); +} diff --git a/tests/FluxFlow.Composition.Tests/TypedCodeFirstApplicationLinkCompilerTests.cs b/tests/FluxFlow.Composition.Tests/TypedCodeFirstApplicationLinkCompilerTests.cs new file mode 100644 index 00000000..472cda66 --- /dev/null +++ b/tests/FluxFlow.Composition.Tests/TypedCodeFirstApplicationLinkCompilerTests.cs @@ -0,0 +1,201 @@ +using FluxFlow.Composition.Authoring; +using FluxFlow.Composition.Links; +using FluxFlow.Composition.Model; +using FluxFlow.Data; +using FluxFlow.Mapping; +using FluxFlow.Nodes; +using Shouldly; +using Xunit; + +namespace FluxFlow.Composition.Tests; + +public sealed class TypedCodeFirstApplicationLinkCompilerTests +{ + [Fact] + public void Compiler_compiles_typed_predicate_without_expression_engine_and_preserves_link_metadata() + { + var minimum = 5; + var application = new ApplicationDefinitionBuilder(); + application + .AddWorkflow("Main", out var main) + .AddWorkflow("Audit", out var audit); + var source = main.AddComponent("Source", "test.source"); + var sink = main.AddComponent("Sink", "test.sink"); + var signal = audit.AddComponent("Signal", "test.signal"); + source.Output("Value") + .ConnectTo(sink.Input("Value"), value => value > minimum) + .ConnectTo(signal.SignalInput("Trigger"), static value => value == 9); + var definition = application.Build(); + + var result = new ApplicationLinkCompiler(CreateCatalog()).Compile(definition); + + result.IsValid.ShouldBeTrue(); + result.Diagnostics.ShouldBeEmpty(); + result.Declarations.ShouldBeEmpty( + "typed predicates must not be projected through portable link declarations."); + result.Links.Count.ShouldBe(2); + var local = result.Links.Single(static link => + link.Target.Value == "Main.Sink.Value"); + local.Source.Value.ShouldBe("Main.Source.Value"); + local.Target.Value.ShouldBe("Main.Sink.Value"); + local.MessageType.ShouldBe(typeof(int)); + local.ConditionExpression.ShouldBeNull(); + local.IsConditional.ShouldBeTrue(); + local.DeclarationSide.ShouldBe(ApplicationLinkDeclarationSide.Output); + local.TryMatch(Context(6), out var localFailure).ShouldBeTrue(); + localFailure.ShouldBeNull(); + local.TryMatch(Context(4), out localFailure).ShouldBeFalse(); + localFailure.ShouldBeNull(); + minimum = 3; + local.TryMatch(Context(4), out localFailure).ShouldBeTrue(); + localFailure.ShouldBeNull(); + + var crossWorkflowSignal = result.Links.Single(static link => + link.Target.Value == "Audit.Signal.Trigger"); + crossWorkflowSignal.Source.Value.ShouldBe("Main.Source.Value"); + crossWorkflowSignal.MessageType.ShouldBe(typeof(int)); + crossWorkflowSignal.TryMatch(Context(9), out var signalFailure).ShouldBeTrue(); + signalFailure.ShouldBeNull(); + crossWorkflowSignal.TryMatch(Context(8), out signalFailure).ShouldBeFalse(); + signalFailure.ShouldBeNull(); + } + + [Fact] + public void Typed_predicate_matcher_handles_false_null_error_and_exception_without_escape() + { + var nullableCalls = 0; + var exception = new DistinctiveException("predicate failed"); + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + var source = workflow.AddComponent("Source", "test.nullable-source"); + var nullableSink = workflow.AddComponent("Nullable", "test.nullable-sink"); + var falseSink = workflow.AddComponent("False", "test.nullable-sink"); + var failingSink = workflow.AddComponent("Failing", "test.nullable-sink"); + source.Output("Value") + .ConnectTo( + nullableSink.Input("Value"), + value => + { + nullableCalls++; + return value is null; + }) + .ConnectTo(falseSink.Input("Value"), static _ => false) + .ConnectTo(failingSink.Input("Value"), _ => throw exception); + var result = new ApplicationLinkCompiler(CreateCatalog()).Compile(application.Build()); + + result.IsValid.ShouldBeTrue(); + var nullable = result.Links.Single(static link => + link.Target.Value == "Main.Nullable.Value"); + nullable.TryMatch(Context(null), out var nullFailure).ShouldBeTrue(); + nullFailure.ShouldBeNull(); + nullableCalls.ShouldBe(1); + + nullable.TryMatch(ErrorContext(), out var errorFailure).ShouldBeFalse(); + errorFailure.ShouldBeNull(); + nullableCalls.ShouldBe(1); + + var falseLink = result.Links.Single(static link => + link.Target.Value == "Main.False.Value"); + falseLink.TryMatch(Context("value"), out var falseFailure).ShouldBeFalse(); + falseFailure.ShouldBeNull(); + + var failing = result.Links.Single(static link => + link.Target.Value == "Main.Failing.Value"); + failing.TryMatch(Context("value"), out var caught).ShouldBeFalse(); + caught.ShouldBeSameAs(exception); + nullable.TryMatch(Context(null), out var laterFailure).ShouldBeTrue(); + laterFailure.ShouldBeNull(); + nullableCalls.ShouldBe(2); + } + + [Fact] + public void Built_link_equality_reuses_same_definition_and_distinguishes_new_predicates() + { + Func predicate = static value => value > 0; + var first = BuildSingleLink(predicate); + var second = BuildSingleLink(predicate); + var firstLink = first.Links.ShouldHaveSingleItem(); + var secondLink = second.Links.ShouldHaveSingleItem(); + + firstLink.Equals(firstLink).ShouldBeTrue(); + firstLink.GetHashCode().ShouldBe(firstLink.GetHashCode()); + firstLink.Equals(secondLink).ShouldBeFalse( + "each newly authored predicate link must own a new immutable revision identity."); + + var firstExpression = BuildSingleLink("value > 0").Links.ShouldHaveSingleItem(); + var secondExpression = BuildSingleLink("value > 0").Links.ShouldHaveSingleItem(); + firstExpression.Equals(secondExpression).ShouldBeTrue(); + firstExpression.GetHashCode().ShouldBe(secondExpression.GetHashCode()); + } + + private static ApplicationDefinition BuildSingleLink(Func when) + { + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + var source = workflow.AddComponent("Source", "test.source"); + var sink = workflow.AddComponent("Sink", "test.sink"); + source.Output("Value").ConnectTo(sink.Input("Value"), when); + return application.Build(); + } + + private static ApplicationDefinition BuildSingleLink(string condition) + { + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + var source = workflow.AddComponent("Source", "test.source"); + var sink = workflow.AddComponent("Sink", "test.sink"); + source.Output("Value").ConnectTo(sink.Input("Value"), condition); + return application.Build(); + } + + private static FlowMapContext Context(T value) + => new() + { + Variables = new Dictionary + { + ["message"] = FlowMessage.Create(value) + } + }; + + private static FlowMapContext Context(int value) => Context(value); + + private static FlowMapContext ErrorContext() + => new() + { + Variables = new Dictionary + { + ["message"] = FlowMessage.CreateError( + new FlowError("test", "failed", "testing")) + } + }; + + private static ComponentCatalog CreateCatalog() + => new( + [ + new ComponentDescriptor( + "test.source", + UnusedFactory, + outputs: [ComponentPorts.Metadata("Value")]), + new ComponentDescriptor( + "test.sink", + UnusedFactory, + inputs: [ComponentPorts.Metadata("Value")]), + new ComponentDescriptor( + "test.signal", + UnusedFactory, + inputs: [ComponentPorts.SignalMetadata("Trigger")]), + new ComponentDescriptor( + "test.nullable-source", + UnusedFactory, + outputs: [ComponentPorts.Metadata("Value")]), + new ComponentDescriptor( + "test.nullable-sink", + UnusedFactory, + inputs: [ComponentPorts.Metadata("Value")]) + ]); + + private static ValueTask UnusedFactory(ComponentActivationContext _) + => throw new InvalidOperationException("Link compilation must not activate component factories."); + + private sealed class DistinctiveException(string message) : Exception(message); +} diff --git a/tests/FluxFlow.Composition.Tests/TypedCodeFirstResourceAuthoringTests.cs b/tests/FluxFlow.Composition.Tests/TypedCodeFirstResourceAuthoringTests.cs new file mode 100644 index 00000000..6479b77e --- /dev/null +++ b/tests/FluxFlow.Composition.Tests/TypedCodeFirstResourceAuthoringTests.cs @@ -0,0 +1,259 @@ +using FluxFlow.Composition.Authoring; +using FluxFlow.Composition.Model; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; + +namespace FluxFlow.Composition.Tests; + +public sealed class TypedCodeFirstResourceAuthoringTests +{ + [Fact] + public void Executable_resource_contracts_capture_definition_and_factory_without_activation() + { + var registrar = new RecordingRegistrar(); + var optionCreations = 0; + var optionApplications = 0; + var handleCreations = 0; + var configured = ApplicationResourceContract.Create( + "test.configured", + registrar, + () => + { + optionCreations++; + return new ResourceOptions(); + }, + (options, definition) => + { + optionApplications++; + definition.Set("Endpoint", options.Endpoint); + definition.Set("Enabled", options.Enabled); + }, + definition => + { + handleCreations++; + return new TestResourceHandle(definition); + }); + var simple = ApplicationResourceContract.Create( + "test.simple", + registrar, + static definition => new TestResourceHandle(definition)); + var application = new ApplicationDefinitionBuilder(); + + var returned = application.AddResource( + "configured", + configured, + options => + { + options.Endpoint = "memory://configured"; + options.Enabled = true; + }, + out var configuredHandle); + var simpleHandle = application.AddResource("simple", simple); + var definition = application.Build(); + + returned.ShouldBeSameAs(application); + configured.Type.ShouldBe("test.configured"); + configuredHandle.Address.Value.ShouldBe("Resources.configured"); + configuredHandle.Name.ShouldBe("configured"); + configuredHandle.Type.ShouldBe(configured.Type); + configuredHandle.Definition.Type.ShouldBe(configured.Type); + simpleHandle.Address.Value.ShouldBe("Resources.simple"); + simpleHandle.Type.ShouldBe(simple.Type); + optionCreations.ShouldBe(1); + optionApplications.ShouldBe(1); + handleCreations.ShouldBe(1); + registrar.RegistrationCount.ShouldBe(0); + + var configuredDefinition = definition.Resources["configured"] + .ShouldBeOfType(); + configuredDefinition.Type.ShouldBe(configured.Type); + configuredDefinition.Properties["Endpoint"].GetString() + .ShouldBe("memory://configured"); + configuredDefinition.Properties["Enabled"].GetBoolean().ShouldBeTrue(); + definition.Resources["simple"].ShouldBeOfType() + .Type.ShouldBe(simple.Type); + definition.ApplicationResourceContracts.ShouldBe([configured, simple]); + registrar.RegistrationCount.ShouldBe(0); + } + + [Fact] + public void Resource_contract_configuration_failures_are_atomic_and_allow_same_name_retry() + { + var registrar = new RecordingRegistrar(); + var valid = Contract("test.valid", registrar); + var nullOptions = ApplicationResourceContract.Create( + "test.null-options", + registrar, + static () => null!, + static (_, _) => { }, + static definition => new TestResourceHandle(definition)); + var nullHandle = ApplicationResourceContract.Create( + "test.null-handle", + registrar, + static _ => null!); + var application = new ApplicationDefinitionBuilder(); + + var configureFailure = Should.Throw(() => + application.AddResource( + "resource", + valid, + _ => throw new InvalidOperationException("configure failed"))); + configureFailure.Message.ShouldBe("configure failed"); + application.AddResource("resource", valid, static options => + options.Endpoint = "memory://recovered"); + + Should.Throw(() => + application.AddResource("null-options", nullOptions, static _ => { })) + .Message.ShouldContain("returned no options builder"); + application.AddResource("null-options", valid, static options => + options.Endpoint = "memory://options-retry"); + + Should.Throw(() => + application.AddResource("null-handle", nullHandle)) + .Message.ShouldContain("returned no handle"); + application.AddResource("null-handle", valid, static options => + options.Endpoint = "memory://handle-retry"); + + var definition = application.Build(); + + definition.Resources.Keys.ShouldBe( + ["resource", "null-options", "null-handle"], + ignoreOrder: true); + definition.ApplicationResourceContracts.ShouldHaveSingleItem().ShouldBeSameAs(valid); + definition.Resources.Values + .Cast() + .Select(static resource => resource.Properties["Endpoint"].GetString()) + .ShouldBe([ + "memory://recovered", + "memory://options-retry", + "memory://handle-retry" + ], ignoreOrder: true); + registrar.RegistrationCount.ShouldBe(0); + } + + [Fact] + public void Exact_resource_contract_reuse_deduplicates_and_distinct_same_identity_contracts_conflict_atomically() + { + var registrar = new RecordingRegistrar(); + var retained = Contract("test.shared", registrar); + var conflicting = Contract("test.shared", registrar); + var application = new ApplicationDefinitionBuilder(); + application.AddResource("first", retained, static options => + options.Endpoint = "memory://first"); + var group = application.AddResourceGroup("nested"); + group.AddResource("second", retained, static options => + options.Endpoint = "memory://second"); + + var conflict = Should.Throw(() => + application.AddResource("conflict", conflicting, static options => + options.Endpoint = "memory://conflict")); + + conflict.Message.ShouldContain(retained.Type); + conflict.Message.ShouldContain("conflicting contracts"); + var definition = application.Build(); + definition.ApplicationResourceContracts.ShouldHaveSingleItem() + .ShouldBeSameAs(retained); + definition.Resources.Keys.ShouldBe(["first", "nested"], ignoreOrder: true); + definition.Resources.ContainsKey("conflict").ShouldBeFalse(); + definition.Resources["nested"].ShouldBeOfType() + .Resources.Keys.ShouldBe(["second"]); + registrar.RegistrationCount.ShouldBe(0); + } + + [Fact] + public void Built_resource_contracts_are_ordinal_read_only_and_owned_by_the_definition() + { + var registrar = new RecordingRegistrar(); + var zulu = Contract("test.zulu", registrar); + var alpha = Contract("test.alpha", registrar); + var application = new ApplicationDefinitionBuilder(); + application.AddResource("zulu", zulu, static options => options.Endpoint = "z"); + application.AddResource("alpha", alpha, static options => options.Endpoint = "a"); + + var definition = application.Build(); + + definition.ApplicationResourceContracts.ShouldBe([alpha, zulu]); + definition.ApplicationResourceContracts[0].ShouldBeSameAs(alpha); + definition.ApplicationResourceContracts[1].ShouldBeSameAs(zulu); + var collection = definition.ApplicationResourceContracts + .ShouldBeAssignableTo>()!; + collection.IsReadOnly.ShouldBeTrue(); + Should.Throw(() => collection.Add(alpha)); + Should.Throw(() => + application.AddResource("late", alpha, static options => options.Endpoint = "late")); + registrar.RegistrationCount.ShouldBe(0); + } + + [Fact] + public void Resource_contract_factories_validate_all_arguments_and_preserve_registrar_identity() + { + var registrar = new RecordingRegistrar(); + var contract = Contract("test.identity", registrar); + + ((IApplicationResourceRegistrar)contract).RegistrationIdentity + .ShouldBeSameAs(registrar); + typeof(ApplicationResourceContract).IsAbstract.ShouldBeTrue(); + typeof(ApplicationResourceContract<>).IsClass.ShouldBeTrue(); + typeof(ApplicationResourceContract<,>).IsClass.ShouldBeTrue(); + + Should.Throw(() => ApplicationResourceContract.Create( + " ", registrar, static definition => new TestResourceHandle(definition))) + .ParamName.ShouldBe("type"); + Should.Throw(() => ApplicationResourceContract.Create( + " test ", registrar, static definition => new TestResourceHandle(definition))) + .ParamName.ShouldBe("type"); + Should.Throw(() => ApplicationResourceContract.Create( + "test", null!, static definition => new TestResourceHandle(definition))) + .ParamName.ShouldBe("registrar"); + Should.Throw(() => ApplicationResourceContract.Create( + "test", registrar, null!)).ParamName.ShouldBe("createHandle"); + Should.Throw(() => ApplicationResourceContract.Create( + "test", registrar, null!, static (_, _) => { }, + static definition => new TestResourceHandle(definition))) + .ParamName.ShouldBe("createOptions"); + Should.Throw(() => ApplicationResourceContract.Create( + "test", registrar, static () => new ResourceOptions(), null!, + static definition => new TestResourceHandle(definition))) + .ParamName.ShouldBe("apply"); + Should.Throw(() => ApplicationResourceContract.Create( + "test", registrar, static () => new ResourceOptions(), static (_, _) => { }, null!)) + .ParamName.ShouldBe("createHandle"); + } + + private static ApplicationResourceContract Contract( + string type, + IApplicationResourceRegistrar registrar) + => ApplicationResourceContract.Create( + type, + registrar, + static () => new ResourceOptions(), + static (options, definition) => definition.Set("Endpoint", options.Endpoint), + static definition => new TestResourceHandle(definition)); + + private sealed class ResourceOptions + { + public string Endpoint { get; set; } = "memory://default"; + + public bool Enabled { get; set; } + } + + private sealed class TestResourceHandle(ResourceHandle definition) + : AuthoredResourceHandle(definition); + + private sealed class RecordingRegistrar : IApplicationResourceRegistrar + { + public int RegistrationCount { get; private set; } + + public void Register(ApplicationResourceRegistrationContext context) + { + ArgumentNullException.ThrowIfNull(context); + RegistrationCount++; + context.Services.AddKeyedSingleton( + "resources.value", + new RegisteredResource(context.RevisionId)); + } + } + + private sealed record RegisteredResource(string RevisionId); +} diff --git a/tests/FluxFlow.DesignerHost.Tests/DesignerHostCatalogTests.cs b/tests/FluxFlow.DesignerHost.Tests/DesignerHostCatalogTests.cs index 86e5a0fb..20d59666 100644 --- a/tests/FluxFlow.DesignerHost.Tests/DesignerHostCatalogTests.cs +++ b/tests/FluxFlow.DesignerHost.Tests/DesignerHostCatalogTests.cs @@ -71,7 +71,7 @@ [new ComponentAttributeName(PortDesignMetadataAttributeNames.Kind)] = output.Kind.ShouldBe(PortKind.Output); output.ValueType.ShouldBe("string"); output.IsPrimary.ShouldBeTrue(); - item.Outputs.ShouldContain(port => port.Name == "Events"); + item.Outputs.Count.ShouldBe(1); } [Fact] @@ -89,7 +89,7 @@ public void Palette_falls_back_to_type_and_general_category() item.Summary.ShouldBeNull(); item.Inputs.ShouldBeEmpty(); item.SignalInputs.ShouldBeEmpty(); - item.Outputs.Select(port => port.Name).ShouldBe(["Events"]); + item.Outputs.ShouldBeEmpty(); } [Fact] diff --git a/tests/FluxFlow.Engine.DurableInput.Tests/DurableApplicationInputsTests.cs b/tests/FluxFlow.Engine.DurableInput.Tests/DurableApplicationInputsTests.cs index 5e5b21f8..b97a69e8 100644 --- a/tests/FluxFlow.Engine.DurableInput.Tests/DurableApplicationInputsTests.cs +++ b/tests/FluxFlow.Engine.DurableInput.Tests/DurableApplicationInputsTests.cs @@ -1,4 +1,5 @@ using FluxFlow.Engine.DurableInput; +using FluxFlow.Composition.Authoring; using FluxFlow.Nodes; using Microsoft.Extensions.Time.Testing; using Shouldly; @@ -8,6 +9,61 @@ namespace FluxFlow.Engine.DurableInput.Tests; public sealed class DurableApplicationInputsTests { + [Fact] + public void Durable_input_handle_surface_accepts_only_typed_message_inputs() + { + var handleParameters = typeof(DurableApplicationInputs) + .GetMethods() + .Where(static method => method.Name == nameof(DurableApplicationInputs.EnqueueAsync)) + .Select(static method => method.GetParameters()[0].ParameterType) + .Where(static type => typeof(PortHandle).IsAssignableFrom(type) || type.IsGenericType) + .ToArray(); + + handleParameters.ShouldHaveSingleItem() + .GetGenericTypeDefinition().ShouldBe(typeof(InputPortHandle<>)); + handleParameters.ShouldNotContain(typeof(SignalInputPortHandle)); + } + + [Fact] + public async Task Typed_input_handle_enqueue_uses_exact_address_contract_and_cancellation() + { + var clock = new FakeTimeProvider(DurableInputTestData.Now); + var store = new DurableInputTestStore(); + var client = CreateClient(store, clock); + var input = CreateInputHandle(); + var message = FlowMessage.Restore( + "typed-payload", + new MessageId("typed-message"), + new TraceId("typed-trace"), + DurableInputTestData.Now.AddMinutes(-1)); + + var result = await client.EnqueueAsync(input, message); + var stored = store.Get(result.Key).Envelope; + + result.Status.ShouldBe(DurableInputEnqueueStatus.Enqueued); + result.Key.ShouldBe(new DurableInputKey(input.Address, message.MessageId)); + stored.Address.ShouldBe(input.Address); + stored.ContractName.ShouldBe("text-v1"); + stored.Payload.GetString().ShouldBe(message.Value); + stored.MessageId.ShouldBe(message.MessageId); + stored.TraceId.ShouldBe(message.TraceId); + + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + var canceled = await Should.ThrowAsync(async () => + await client.EnqueueAsync( + input, + FlowMessage.Create("canceled"), + cancellation.Token)); + + canceled.CancellationToken.ShouldBe(cancellation.Token); + (await Should.ThrowAsync(async () => + await client.EnqueueAsync( + (InputPortHandle)null!, + FlowMessage.Create("missing")))) + .ParamName.ShouldBe("input"); + } + [Fact] public async Task Enqueue_persists_the_exact_message_identity_contract_and_clock_time() { @@ -164,4 +220,13 @@ private static DurableApplicationInputs CreateClient( new DurableInputContract("text-v1", jsonTypeInfo: null) ]), clock); + + private static InputPortHandle CreateInputHandle() + { + var application = new ApplicationDefinitionBuilder(); + return application + .AddWorkflow("Orders") + .AddComponent("Receiver", "test.receiver") + .Input("Input"); + } } diff --git a/tests/FluxFlow.Engine.DurableInput.Tests/DurableInputTestApplication.cs b/tests/FluxFlow.Engine.DurableInput.Tests/DurableInputTestApplication.cs index 466fa02e..6aef1886 100644 --- a/tests/FluxFlow.Engine.DurableInput.Tests/DurableInputTestApplication.cs +++ b/tests/FluxFlow.Engine.DurableInput.Tests/DurableInputTestApplication.cs @@ -86,65 +86,42 @@ private static void RegisterComponents( IServiceCollection services, MessageRecorder recorder, NodeCatalog nodes) - => services.AddFluxFlowComponents() - .AddRuntimeComponent("test.durable-string-a", component => - { - component.UseFactory(_ => ValueTask.FromResult( - StringInstance(new RecordingNode("revision-a", recorder), nodes))); - component.AddInput("Input"); - component.AddOutput("Output"); - }) - .AddRuntimeComponent("test.durable-string-b", component => - { - component.UseFactory(_ => ValueTask.FromResult( - StringInstance(new RecordingNode("revision-b", recorder), nodes))); - component.AddInput("Input"); - component.AddOutput("Output"); - }) - .AddRuntimeComponent("test.durable-integer", component => - { - component.UseFactory(_ => - { - var node = new IntegerNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)])); - }); - component.AddInput("Input"); - component.AddOutput("Output"); - }) - .AddRuntimeComponent("test.durable-blocking", component => - { - component.UseFactory(_ => - { - var node = new BlockingNode(); - nodes.Blocking = node; - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)])); - }); - component.AddInput("Input"); - }) - .AddRuntimeComponent("test.durable-signal", component => - { - component.UseFactory(_ => - { - var node = new SignalNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.SignalInput("Signal", node)])); - }); - component.AddSignalInput("Signal"); - }); - - private static ComponentInstance StringInstance(RecordingNode node, NodeCatalog nodes) + => services.AddFluxFlowComponents().Advanced + .AddDynamicComponent("test.durable-string-a", component => + component + .UseFactory(_ => StringNode(new RecordingNode("revision-a", recorder), nodes)) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output)) + .AddDynamicComponent("test.durable-string-b", component => + component + .UseFactory(_ => StringNode(new RecordingNode("revision-b", recorder), nodes)) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output)) + .AddDynamicComponent("test.durable-integer", component => + component + .UseFactory(static _ => new IntegerNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output)) + .AddDynamicComponent("test.durable-blocking", component => + component + .UseFactory(_ => CreateBlockingNode(nodes)) + .HasInput("Input", static node => node.Input)) + .AddDynamicComponent("test.durable-signal", component => + component + .UseFactory(static _ => new SignalNode()) + .HasSignalInput("Signal", static node => node)); + + private static RecordingNode StringNode(RecordingNode node, NodeCatalog nodes) { nodes.Recording = node; - return ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)]); + return node; + } + + private static BlockingNode CreateBlockingNode(NodeCatalog nodes) + { + var node = new BlockingNode(); + nodes.Blocking = node; + return node; } internal sealed class NodeCatalog diff --git a/tests/FluxFlow.Engine.DurableOutput.Tests/DurableOutputRegistrationTests.cs b/tests/FluxFlow.Engine.DurableOutput.Tests/DurableOutputRegistrationTests.cs index b432917c..8b2bc4d6 100644 --- a/tests/FluxFlow.Engine.DurableOutput.Tests/DurableOutputRegistrationTests.cs +++ b/tests/FluxFlow.Engine.DurableOutput.Tests/DurableOutputRegistrationTests.cs @@ -2,6 +2,7 @@ using System.Text.Json; using System.Text.Json.Serialization.Metadata; using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; using FluxFlow.Engine.Ports; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Time.Testing; @@ -12,6 +13,52 @@ namespace FluxFlow.Engine.DurableOutput.Tests; public sealed class DurableOutputRegistrationTests { + [Fact] + public void Durable_output_handle_surface_accepts_only_typed_outputs() + { + var handleParameters = typeof(DurableOutputRegistrationBuilder) + .GetMethods() + .Where(static method => method.Name == nameof(DurableOutputRegistrationBuilder.Capture)) + .Select(static method => method.GetParameters()[0].ParameterType) + .Where(static type => typeof(PortHandle).IsAssignableFrom(type) || type.IsGenericType) + .ToArray(); + + handleParameters.ShouldHaveSingleItem() + .GetGenericTypeDefinition().ShouldBe(typeof(OutputPortHandle<>)); + handleParameters.ShouldNotContain(typeof(SignalInputPortHandle)); + } + + [Fact] + public void Typed_output_handle_capture_uses_exact_address_type_and_atomic_conflict_rules() + { + var output = CreateOutputHandle(); + var typeInfo = DurableOutputTestData.TypeInfo(); + var alternateTypeInfo = (JsonTypeInfo)new JsonSerializerOptions + { + TypeInfoResolver = new DefaultJsonTypeInfoResolver() + }.GetTypeInfo(typeof(string)); + var builder = new DurableOutputRegistrationBuilder(); + + var first = builder.Capture(output, "text-v1", typeInfo); + var duplicate = builder.Capture(output, "text-v1", typeInfo); + var beforeConflict = builder.Build().Captures.ShouldHaveSingleItem().Value; + var conflict = Should.Throw(() => + builder.Capture(output, "text-v1", alternateTypeInfo)); + var afterConflict = builder.Build().Captures.ShouldHaveSingleItem().Value; + + first.ShouldBeSameAs(builder); + duplicate.ShouldBeSameAs(builder); + beforeConflict.Address.ShouldBe(output.Address); + beforeConflict.PayloadType.ShouldBe(typeof(string)); + beforeConflict.ContractName.ShouldBe("text-v1"); + beforeConflict.JsonTypeInfo.ShouldBeSameAs(typeInfo); + conflict.Message.ShouldContain(output.Address.Value); + afterConflict.ShouldBeSameAs(beforeConflict); + (Should.Throw(() => + builder.Capture((OutputPortHandle)null!, "text-v1", typeInfo))) + .ParamName.ShouldBe("output"); + } + [Fact] public void Builder_captures_exact_flat_declarations_and_equivalent_duplicate_is_idempotent() { @@ -291,4 +338,13 @@ private sealed class NullResolver : IApplicationOutputCaptureResolver { public IApplicationOutputCapture? Resolve(ApplicationAddress address) => null; } + + private static OutputPortHandle CreateOutputHandle() + { + var application = new ApplicationDefinitionBuilder(); + return application + .AddWorkflow("Orders") + .AddComponent("Publisher", "test.publisher") + .Output("Output"); + } } diff --git a/tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlow.Engine.HealthChecks.Tests.csproj b/tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlow.Engine.HealthChecks.Tests.csproj new file mode 100644 index 00000000..d6c79f8b --- /dev/null +++ b/tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlow.Engine.HealthChecks.Tests.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + false + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + diff --git a/tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlowApplicationHealthCheckTests.cs b/tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlowApplicationHealthCheckTests.cs new file mode 100644 index 00000000..5ccb9a0a --- /dev/null +++ b/tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlowApplicationHealthCheckTests.cs @@ -0,0 +1,661 @@ +using System.Text.Json; +using FluxFlow.Composition; +using FluxFlow.Composition.Authoring; +using FluxFlow.Composition.Model; +using FluxFlow.Data; +using FluxFlow.Engine.Ports; +using FluxFlow.Nodes; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Shouldly; +using Xunit; + +namespace FluxFlow.Engine.HealthChecks.Tests; + +public sealed class FluxFlowApplicationHealthCheckTests +{ + private const string HealthyDescription = + "An active FluxFlow application revision is available."; + private const string DegradedDescription = + "The active FluxFlow application revision remains available after the latest update was rejected."; + private const string UnavailableDescription = + "The FluxFlow application has no active ready revision."; + private const string StoppedDescription = + "The FluxFlow application is stopped and is not ready."; + + [Fact] + public async Task Active_running_application_reports_healthy_with_exact_bounded_data() + { + var services = new ServiceCollection(); + services.AddFluxFlow( + ReadyDefinition(), + options => + { + options.StartWithHost = false; + options.InitialRevisionId = "active-7"; + }); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + var started = await application.StartAsync(); + + var result = await CheckAsync(application); + + started.Status.ShouldBe(ApplicationUpdateStatus.Applied); + result.Status.ShouldBe(HealthStatus.Healthy); + result.Description.ShouldBe(HealthyDescription); + result.Exception.ShouldBeNull(); + AssertData( + result, + ("applicationState", "Running"), + ("activeRevisionId", "active-7"), + ("activeSequence", 1L), + ("requestedRevisionId", "active-7"), + ("lastUpdateStatus", "Applied")); + } + + [Fact] + public async Task Unchanged_active_revision_remains_healthy() + { + var source = new MutableDefinitionSource(ReadyDefinition()); + var services = new ServiceCollection(); + services.AddFluxFlow(source, options => + { + options.StartWithHost = false; + options.InitialRevisionId = "initial"; + }); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + await application.StartAsync(); + var active = application.Current; + source.Definition = ReadyDefinition(); + + var unchanged = await application.ReloadAsync("equivalent"); + var result = await CheckAsync(application); + + unchanged.Status.ShouldBe(ApplicationUpdateStatus.Unchanged); + application.Current.ShouldBeSameAs(active); + result.Status.ShouldBe(HealthStatus.Healthy); + result.Description.ShouldBe(HealthyDescription); + AssertData( + result, + ("applicationState", "Running"), + ("activeRevisionId", "initial"), + ("activeSequence", 1L), + ("requestedRevisionId", "equivalent"), + ("lastUpdateStatus", "Unchanged")); + } + + [Fact] + public async Task Rejected_reload_with_active_revision_reports_degraded_and_preserves_active_revision() + { + var source = new MutableDefinitionSource(ReadyDefinition()); + var services = new ServiceCollection(); + services.AddFluxFlow(source, options => + { + options.StartWithHost = false; + options.InitialRevisionId = "retained"; + }); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + await application.StartAsync(); + var active = application.Current; + var definition = application.CurrentDefinition; + source.Failure = new InvalidOperationException("secret diagnostic message"); + + var rejected = await application.ReloadAsync("rejected-request"); + var result = await CheckAsync(application); + + rejected.Status.ShouldBe(ApplicationUpdateStatus.Rejected); + application.State.ShouldBe(ApplicationState.Running); + application.Current.ShouldBeSameAs(active); + application.CurrentDefinition.ShouldBeSameAs(definition); + application.LastUpdate.ShouldBeSameAs(rejected); + result.Status.ShouldBe(HealthStatus.Degraded); + result.Description.ShouldBe(DegradedDescription); + result.Exception.ShouldBeNull(); + AssertData( + result, + ("applicationState", "Running"), + ("activeRevisionId", "retained"), + ("activeSequence", 1L), + ("requestedRevisionId", "rejected-request"), + ("lastUpdateStatus", "Rejected"), + ("diagnosticStage", "Source"), + ("diagnosticCode", "revision.source.load_failed")); + Flatten(result).ShouldNotContain("secret diagnostic message"); + Flatten(result).ShouldNotContain(typeof(InvalidOperationException).FullName!); + } + + [Fact] + public async Task Successful_update_after_rejection_restores_healthy_readiness() + { + var source = new MutableDefinitionSource(ReadyDefinition()); + var services = new ServiceCollection(); + services.AddFluxFlow(source, options => options.StartWithHost = false); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + await application.StartAsync(); + source.Failure = new InvalidOperationException("temporarily unavailable"); + (await application.ReloadAsync("rejected")).IsRejected.ShouldBeTrue(); + (await CheckAsync(application)).Status.ShouldBe(HealthStatus.Degraded); + source.Failure = null; + source.Definition = ReadyDefinition(); + + var recovered = await application.ReloadAsync("recovered"); + var result = await CheckAsync(application); + + recovered.Status.ShouldBe(ApplicationUpdateStatus.Unchanged); + result.Status.ShouldBe(HealthStatus.Healthy); + result.Description.ShouldBe(HealthyDescription); + result.Data["requestedRevisionId"].ShouldBe("recovered"); + result.Data["lastUpdateStatus"].ShouldBe("Unchanged"); + result.Data.ContainsKey("diagnosticStage").ShouldBeFalse(); + result.Data.ContainsKey("diagnosticCode").ShouldBeFalse(); + } + + [Fact] + public async Task Active_revision_stays_healthy_and_operational_while_candidate_reload_is_held_in_preparation() + { + var initial = IdentityDefinition(CreateIdentityContract( + static _ => ValueTask.FromResult(new HealthIdentityNode()))); + var source = new MutableDefinitionSource(initial.Definition); + var services = new ServiceCollection(); + services.AddFluxFlow(source, options => + { + options.StartWithHost = false; + options.InitialRevisionId = "active"; + }); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + (await application.StartAsync()).IsApplied.ShouldBeTrue(); + var active = application.Current; + var activeDefinition = application.CurrentDefinition; + var gate = new PreparationGate(); + source.Definition = IdentityDefinition(CreateIdentityContract( + _ => gate.CreateNodeAsync())).Definition; + + var reload = application.ReloadAsync("candidate").AsTask(); + await gate.Entered; + try + { + application.State.ShouldBe(ApplicationState.Reloading); + application.Current.ShouldBeSameAs(active); + application.CurrentDefinition.ShouldBeSameAs(activeDefinition); + + var result = await CheckAsync(application); + result.Status.ShouldBe(HealthStatus.Healthy); + result.Description.ShouldBe(HealthyDescription); + AssertData( + result, + ("applicationState", "Reloading"), + ("activeRevisionId", "active"), + ("activeSequence", 1L), + ("requestedRevisionId", "active"), + ("lastUpdateStatus", "Applied")); + + var receive = application.Ports.ReceiveAsync( + initial.Handle.Output, + TimeSpan.FromSeconds(5)); + var sent = await application.Ports.SendAsync( + initial.Handle.Input, + FlowMessage.Create("still-serving")); + var received = await receive; + + sent.Status.ShouldBe(PortSendStatus.Accepted); + received.Status.ShouldBe(PortReceiveStatus.Received); + received.Message!.Value.ShouldBe("still-serving"); + } + finally + { + gate.Release(); + } + + var applied = await reload; + applied.IsApplied.ShouldBeTrue(); + application.State.ShouldBe(ApplicationState.Running); + application.Current!.RevisionId.ShouldBe("candidate"); + } + + [Fact] + public async Task Rejected_initial_start_without_active_revision_reports_unhealthy() + { + var services = new ServiceCollection(); + services.AddFluxFlow( + new FailingDefinitionSource("private source failure"), + options => + { + options.StartWithHost = false; + options.InitialRevisionId = "failed-start"; + }); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + + var rejected = await application.StartAsync(); + var result = await CheckAsync(application); + + rejected.Status.ShouldBe(ApplicationUpdateStatus.Rejected); + application.State.ShouldBe(ApplicationState.Degraded); + application.Current.ShouldBeNull(); + result.Status.ShouldBe(HealthStatus.Unhealthy); + result.Description.ShouldBe(UnavailableDescription); + result.Exception.ShouldBeNull(); + AssertData( + result, + ("applicationState", "Degraded"), + ("requestedRevisionId", "failed-start"), + ("lastUpdateStatus", "Rejected"), + ("diagnosticStage", "Source"), + ("diagnosticCode", "revision.source.load_failed")); + Flatten(result).ShouldNotContain("private source failure"); + } + + [Fact] + public async Task Empty_application_without_active_revision_reports_unhealthy_without_starting_it() + { + var source = new CountingDefinitionSource(); + var services = new ServiceCollection(); + services.AddFluxFlow(source, options => options.StartWithHost = false); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + + var result = await CheckAsync(application); + + result.Status.ShouldBe(HealthStatus.Unhealthy); + result.Description.ShouldBe(UnavailableDescription); + AssertData(result, ("applicationState", "Empty")); + source.LoadCount.ShouldBe(0); + application.State.ShouldBe(ApplicationState.Empty); + application.Current.ShouldBeNull(); + application.LastUpdate.ShouldBeNull(); + } + + [Theory] + [InlineData(ApplicationState.Empty)] + [InlineData(ApplicationState.Starting)] + [InlineData(ApplicationState.Degraded)] + public void Non_ready_states_fail_closed_even_with_an_impossible_current_snapshot( + ApplicationState state) + { + var result = FluxFlowApplicationHealthCheck.CreateResult( + state, + Snapshot("active"), + Update(ApplicationUpdateStatus.Applied, "requested")); + + result.Status.ShouldBe(HealthStatus.Unhealthy); + result.Description.ShouldBe(UnavailableDescription); + result.Data["applicationState"].ShouldBe(state.ToString()); + result.Data.Count.ShouldBeLessThanOrEqualTo(7); + } + + [Theory] + [InlineData(ApplicationState.Stopping)] + [InlineData(ApplicationState.Stopped)] + public void Stopping_and_stopped_states_fail_closed_even_with_an_impossible_current_snapshot( + ApplicationState state) + { + var result = FluxFlowApplicationHealthCheck.CreateResult( + state, + Snapshot("active"), + Update(ApplicationUpdateStatus.Applied, "requested")); + + result.Status.ShouldBe(HealthStatus.Unhealthy); + result.Description.ShouldBe(StoppedDescription); + result.Data["applicationState"].ShouldBe(state.ToString()); + result.Data.Count.ShouldBeLessThanOrEqualTo(7); + } + + [Theory] + [InlineData(ApplicationState.Running)] + [InlineData(ApplicationState.Reloading)] + public void Running_or_reloading_without_current_fails_closed(ApplicationState state) + { + var result = FluxFlowApplicationHealthCheck.CreateResult( + state, + current: null, + Update(ApplicationUpdateStatus.Applied, "requested")); + + result.Status.ShouldBe(HealthStatus.Unhealthy); + result.Description.ShouldBe(UnavailableDescription); + result.Data.ContainsKey("activeRevisionId").ShouldBeFalse(); + result.Data.ContainsKey("activeSequence").ShouldBeFalse(); + result.Data.Count.ShouldBeLessThanOrEqualTo(7); + } + + [Theory] + [InlineData(ApplicationState.Running)] + [InlineData(ApplicationState.Reloading)] + public void Running_or_reloading_with_current_and_rejected_update_reports_degraded( + ApplicationState state) + { + var result = FluxFlowApplicationHealthCheck.CreateResult( + state, + Snapshot("active"), + Update(ApplicationUpdateStatus.Rejected, "requested")); + + result.Status.ShouldBe(HealthStatus.Degraded); + result.Description.ShouldBe(DegradedDescription); + result.Data["activeRevisionId"].ShouldBe("active"); + result.Data["lastUpdateStatus"].ShouldBe("Rejected"); + } + + [Theory] + [InlineData(ApplicationState.Running, ApplicationUpdateStatus.Applied)] + [InlineData(ApplicationState.Running, ApplicationUpdateStatus.Unchanged)] + [InlineData(ApplicationState.Reloading, ApplicationUpdateStatus.Applied)] + [InlineData(ApplicationState.Reloading, ApplicationUpdateStatus.Unchanged)] + public void Running_or_reloading_with_current_and_non_rejected_update_reports_healthy( + ApplicationState state, + ApplicationUpdateStatus updateStatus) + { + var result = FluxFlowApplicationHealthCheck.CreateResult( + state, + Snapshot("active"), + Update(updateStatus, "requested")); + + result.Status.ShouldBe(HealthStatus.Healthy); + result.Description.ShouldBe(HealthyDescription); + result.Data["activeRevisionId"].ShouldBe("active"); + result.Data["lastUpdateStatus"].ShouldBe(updateStatus.ToString()); + } + + [Fact] + public async Task Stopped_and_disposed_application_report_unhealthy_deterministically() + { + var services = new ServiceCollection(); + services.AddFluxFlow(ReadyDefinition(), options => options.StartWithHost = false); + var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + await application.StartAsync(); + var check = new FluxFlowApplicationHealthCheck(application); + + await application.StopAsync(); + var stopped = await check.CheckHealthAsync(new HealthCheckContext()); + await application.DisposeAsync(); + var disposed = await check.CheckHealthAsync(new HealthCheckContext()); + + application.State.ShouldBe(ApplicationState.Stopped); + application.Current.ShouldBeNull(); + stopped.Status.ShouldBe(HealthStatus.Unhealthy); + stopped.Description.ShouldBe(StoppedDescription); + disposed.Status.ShouldBe(HealthStatus.Unhealthy); + disposed.Description.ShouldBe(StoppedDescription); + AssertData( + stopped, + ("applicationState", "Stopped"), + ("requestedRevisionId", "initial"), + ("lastUpdateStatus", "Applied")); + AssertData( + disposed, + ("applicationState", "Stopped"), + ("requestedRevisionId", "initial"), + ("lastUpdateStatus", "Applied")); + await provider.DisposeAsync(); + } + + [Fact] + public async Task Health_check_honors_pre_canceled_token() + { + var check = new FluxFlowApplicationHealthCheck(application: null); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + var exception = await Should.ThrowAsync(() => + check.CheckHealthAsync(new HealthCheckContext(), cancellation.Token)); + + exception.CancellationToken.ShouldBe(cancellation.Token); + } + + [Fact] + public void Health_check_data_is_bounded_uses_only_the_last_diagnostic_and_excludes_sensitive_details() + { + const string secret = "credential=not-for-health-data"; + var snapshot = new ApplicationSnapshot + { + Sequence = 42, + RevisionId = "active-revision", + ActivatedAt = new DateTimeOffset(2026, 8, 8, 10, 0, 0, TimeSpan.Zero), + Definition = ApplicationDefinitionJson.Deserialize( + $$""" + { + "Resources": { + "private-resource": { + "Type": "private.type", + "Secret": "{{secret}}" + } + }, + "Workflows": {} + } + """) + }; + var update = new ApplicationUpdateResult + { + Status = ApplicationUpdateStatus.Rejected, + RequestedRevisionId = "requested-revision", + ActiveRevision = snapshot, + Diagnostics = + [ + Diagnostic(ApplicationUpdateStage.Planning, "first.code", "first message"), + Diagnostic(ApplicationUpdateStage.Activation, "last.code", secret) + ] + }; + + var result = FluxFlowApplicationHealthCheck.CreateResult( + ApplicationState.Running, + snapshot, + update); + + result.Status.ShouldBe(HealthStatus.Degraded); + result.Exception.ShouldBeNull(); + AssertData( + result, + ("applicationState", "Running"), + ("activeRevisionId", "active-revision"), + ("activeSequence", 42L), + ("requestedRevisionId", "requested-revision"), + ("lastUpdateStatus", "Rejected"), + ("diagnosticStage", "Activation"), + ("diagnosticCode", "last.code")); + var flattened = Flatten(result); + flattened.ShouldNotContain("first.code"); + flattened.ShouldNotContain("first message"); + flattened.ShouldNotContain(secret); + flattened.ShouldNotContain("private-resource"); + flattened.ShouldNotContain("private.type"); + flattened.ShouldNotContain(nameof(FlowError.Details)); + } + + [Fact] + public async Task Health_check_observation_does_not_mutate_application_state_revision_ports_or_last_update() + { + var services = new ServiceCollection(); + services.AddFluxFlow(ReadyDefinition(), options => options.StartWithHost = false); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + await application.StartAsync(); + var state = application.State; + var current = application.Current; + var definition = application.CurrentDefinition; + var lastUpdate = application.LastUpdate; + var ports = application.Ports; + + var first = await CheckAsync(application); + var second = await CheckAsync(application); + + first.Status.ShouldBe(HealthStatus.Healthy); + second.Status.ShouldBe(first.Status); + second.Description.ShouldBe(first.Description); + second.Data.Count.ShouldBe(first.Data.Count); + foreach (var (key, value) in first.Data) + second.Data[key].ShouldBe(value); + application.State.ShouldBe(state); + application.Current.ShouldBeSameAs(current); + application.CurrentDefinition.ShouldBeSameAs(definition); + application.LastUpdate.ShouldBeSameAs(lastUpdate); + application.Ports.ShouldBeSameAs(ports); + } + + private static Task CheckAsync(FluxFlowApplication application) + => new FluxFlowApplicationHealthCheck(application) + .CheckHealthAsync(new HealthCheckContext()); + + private static ApplicationDefinition ReadyDefinition() + => ApplicationDefinitionJson.Deserialize( + """ + { + "Resources": {}, + "Workflows": { + "Main": {} + } + } + """); + + private static ComponentContract> + CreateIdentityContract( + Func> factory) + => ComponentContract.Create( + "test.health.identity", + component => component + .UseFactory(factory) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events), + static component => new InputOutputComponentHandle( + component, + "Input", + "Output", + "Events")); + + private static ( + ApplicationDefinition Definition, + InputOutputComponentHandle Handle) IdentityDefinition( + ComponentContract> contract) + { + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + var handle = workflow.AddComponent("Value", contract); + return (application.Build(), handle); + } + + private static ApplicationSnapshot Snapshot(string revisionId) + => new() + { + Sequence = 7, + RevisionId = revisionId, + ActivatedAt = new DateTimeOffset(2026, 8, 8, 10, 0, 0, TimeSpan.Zero), + Definition = new ApplicationDefinition() + }; + + private static ApplicationUpdateResult Update( + ApplicationUpdateStatus status, + string revisionId) + => new() + { + Status = status, + RequestedRevisionId = revisionId + }; + + private static ApplicationUpdateDiagnostic Diagnostic( + ApplicationUpdateStage stage, + string code, + string secret) + => new() + { + Stage = stage, + Error = new FlowError( + code, + secret, + "secret-source", + false, + JsonSerializer.SerializeToElement(new + { + secret, + exceptionType = "Secret.Exception" + })) + }; + + private static void AssertData( + HealthCheckResult result, + params (string Key, object Value)[] expected) + { + result.Data.Count.ShouldBe(expected.Length); + result.Data.Count.ShouldBeLessThanOrEqualTo(7); + result.Data.Keys.Order(StringComparer.Ordinal).ShouldBe( + expected.Select(static item => item.Key).Order(StringComparer.Ordinal)); + foreach (var (key, value) in expected) + result.Data[key].ShouldBe(value); + } + + private static string Flatten(HealthCheckResult result) + => string.Join( + "|", + new[] { result.Description } + .Concat(result.Data.Keys) + .Concat(result.Data.Values.Select(static value => value.ToString()))); + + private sealed class MutableDefinitionSource(ApplicationDefinition definition) + : IApplicationDefinitionSource + { + public ApplicationDefinition Definition { get; set; } = definition; + + public Exception? Failure { get; set; } + + public ValueTask LoadAsync( + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return Failure is null + ? ValueTask.FromResult(Definition) + : ValueTask.FromException(Failure); + } + } + + private sealed class FailingDefinitionSource(string message) + : IApplicationDefinitionSource + { + public ValueTask LoadAsync( + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromException( + new InvalidOperationException(message)); + } + } + + private sealed class CountingDefinitionSource : IApplicationDefinitionSource + { + public int LoadCount { get; private set; } + + public ValueTask LoadAsync( + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + LoadCount++; + return ValueTask.FromResult(new ApplicationDefinition()); + } + } + + private sealed class PreparationGate + { + private readonly TaskCompletionSource _entered = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _release = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task Entered => _entered.Task; + + public async ValueTask CreateNodeAsync() + { + _entered.TrySetResult(); + await _release.Task.ConfigureAwait(false); + return new HealthIdentityNode(); + } + + public void Release() => _release.TrySetResult(); + } + + private sealed class HealthIdentityNode : FlowNode + { + protected override async Task ProcessAsync(FlowMessage message) + => await EmitAsync(message, Stopping).ConfigureAwait(false); + } +} diff --git a/tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlowHealthCheckRegistrationTests.cs b/tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlowHealthCheckRegistrationTests.cs new file mode 100644 index 00000000..523c7495 --- /dev/null +++ b/tests/FluxFlow.Engine.HealthChecks.Tests/FluxFlowHealthCheckRegistrationTests.cs @@ -0,0 +1,207 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using FluxFlow.Composition.Model; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; + +namespace FluxFlow.Engine.HealthChecks.Tests; + +public sealed class FluxFlowHealthCheckRegistrationTests +{ + [Fact] + public void Public_surface_exposes_only_the_single_standard_builder_extension() + { + var assembly = typeof(FluxFlowHealthChecksBuilderExtensions).Assembly; + var exported = assembly.GetExportedTypes(); + var extensionType = exported.ShouldHaveSingleItem(); + + extensionType.ShouldBe(typeof(FluxFlowHealthChecksBuilderExtensions)); + var method = extensionType.GetMethods( + BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) + .ShouldHaveSingleItem(); + method.Name.ShouldBe(nameof(FluxFlowHealthChecksBuilderExtensions.AddFluxFlowApplication)); + method.ReturnType.ShouldBe(typeof(IHealthChecksBuilder)); + method.GetParameters().Select(static parameter => parameter.ParameterType) + .ShouldBe(new[] { typeof(IHealthChecksBuilder) }); + method.GetCustomAttribute().ShouldNotBeNull(); + typeof(FluxFlowApplicationHealthCheck).IsPublic.ShouldBeFalse(); + var marker = extensionType.GetNestedTypes(BindingFlags.NonPublic) + .Single(static type => + type.Name == "FluxFlowApplicationHealthCheckRegistrationMarker"); + marker.IsNestedPrivate.ShouldBeTrue(); + } + + [Fact] + public async Task Plain_AddFluxFlow_does_not_register_a_health_check() + { + var services = new ServiceCollection(); + services.AddFluxFlow(new ApplicationDefinition(), options => options.StartWithHost = false); + services.AddHealthChecks(); + AddTestLogging(services); + await using var provider = services.BuildServiceProvider(); + + var options = provider.GetRequiredService>().Value; + var report = await provider.GetRequiredService().CheckHealthAsync(); + + options.Registrations.ShouldBeEmpty(); + report.Entries.ShouldBeEmpty(); + } + + [Fact] + public async Task Health_check_registration_returns_the_standard_builder_and_resolves_the_application_singleton() + { + var services = new ServiceCollection(); + services.AddFluxFlow( + ReadyDefinition(), + options => + { + options.StartWithHost = false; + options.InitialRevisionId = "registered"; + }); + var builder = services.AddHealthChecks(); + + var returned = builder.AddFluxFlowApplication(); + + returned.ShouldBeSameAs(builder); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + await application.StartAsync(); + var registration = provider + .GetRequiredService>() + .Value.Registrations.ShouldHaveSingleItem(); + var check = registration.Factory(provider); + var result = await check.CheckHealthAsync(new HealthCheckContext()); + + registration.Name.ShouldBe("fluxflow.application"); + registration.FailureStatus.ShouldBe(HealthStatus.Unhealthy); + registration.Tags.Count.ShouldBe(2); + registration.Tags.ShouldContain("fluxflow"); + registration.Tags.ShouldContain("ready"); + check.ShouldBeOfType(); + result.Status.ShouldBe(HealthStatus.Healthy); + result.Data["activeRevisionId"].ShouldBe("registered"); + } + + [Fact] + public async Task Repeated_health_check_registration_is_idempotent_and_preserves_unrelated_checks() + { + var services = new ServiceCollection(); + services.AddFluxFlow(ReadyDefinition(), options => options.StartWithHost = false); + var builder = services.AddHealthChecks(); + AddTestLogging(services); + builder.AddCheck( + "sentinel", + () => HealthCheckResult.Healthy("sentinel healthy"), + tags: ["other"]); + + builder.AddFluxFlowApplication(); + builder.AddFluxFlowApplication(); + + CountPrivateRegistrationMarkers(services).ShouldBe(1); + await using var provider = services.BuildServiceProvider(); + await provider.GetRequiredService().StartAsync(); + var registrations = provider + .GetRequiredService>() + .Value.Registrations; + var report = await provider.GetRequiredService().CheckHealthAsync(); + + registrations.Count.ShouldBe(2); + registrations.Count(static registration => + registration.Name == "fluxflow.application").ShouldBe(1); + registrations.Count(static registration => registration.Name == "sentinel").ShouldBe(1); + report.Entries.Keys.Order(StringComparer.Ordinal) + .ShouldBe(new[] { "fluxflow.application", "sentinel" }); + report.Entries["fluxflow.application"].Status.ShouldBe(HealthStatus.Healthy); + report.Entries["sentinel"].Status.ShouldBe(HealthStatus.Healthy); + report.Entries["sentinel"].Description.ShouldBe("sentinel healthy"); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Health_check_registration_is_order_independent_from_AddFluxFlow( + bool registerHealthFirst) + { + var services = new ServiceCollection(); + if (registerHealthFirst) + services.AddHealthChecks().AddFluxFlowApplication(); + + services.AddFluxFlow(ReadyDefinition(), options => options.StartWithHost = false); + + if (!registerHealthFirst) + services.AddHealthChecks().AddFluxFlowApplication(); + + AddTestLogging(services); + + await using var provider = services.BuildServiceProvider(); + await provider.GetRequiredService().StartAsync(); + + var report = await provider.GetRequiredService().CheckHealthAsync(); + + report.Entries.ShouldHaveSingleItem().Key.ShouldBe("fluxflow.application"); + report.Status.ShouldBe(HealthStatus.Healthy); + } + + [Fact] + public async Task Missing_application_registration_reports_unhealthy_with_exact_unavailable_data() + { + var services = new ServiceCollection(); + services.AddHealthChecks().AddFluxFlowApplication(); + AddTestLogging(services); + await using var provider = services.BuildServiceProvider(); + + var report = await provider.GetRequiredService().CheckHealthAsync(); + var entry = report.Entries.ShouldHaveSingleItem(); + + entry.Key.ShouldBe("fluxflow.application"); + entry.Value.Status.ShouldBe(HealthStatus.Unhealthy); + entry.Value.Description.ShouldBe("FluxFlow application services are not registered."); + entry.Value.Exception.ShouldBeNull(); + entry.Value.Data.Count.ShouldBe(1); + entry.Value.Data["applicationState"].ShouldBe("Unavailable"); + } + + [Fact] + public void Health_check_registration_adds_no_hosted_service_background_worker_or_polling_state() + { + var services = new ServiceCollection(); + services.AddFluxFlow(new ApplicationDefinition()); + var builder = services.AddHealthChecks(); + var hostedBefore = services.Count(static descriptor => + descriptor.ServiceType == typeof(IHostedService)); + + builder.AddFluxFlowApplication().AddFluxFlowApplication(); + + services.Count(static descriptor => descriptor.ServiceType == typeof(IHostedService)) + .ShouldBe(hostedBefore); + CountPrivateRegistrationMarkers(services).ShouldBe(1); + } + + private static ApplicationDefinition ReadyDefinition() + => ApplicationDefinitionJson.Deserialize( + """ + { + "Resources": {}, + "Workflows": { + "Main": {} + } + } + """); + + private static void AddTestLogging(IServiceCollection services) + { + services.AddSingleton(NullLoggerFactory.Instance); + services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>)); + } + + private static int CountPrivateRegistrationMarkers(IServiceCollection services) + => services.Count(static descriptor => + descriptor.ImplementationInstance?.GetType().Name == + "FluxFlowApplicationHealthCheckRegistrationMarker"); +} diff --git a/tests/FluxFlow.Engine.Tests/ApplicationPortHandleTests.cs b/tests/FluxFlow.Engine.Tests/ApplicationPortHandleTests.cs new file mode 100644 index 00000000..2d6ebff2 --- /dev/null +++ b/tests/FluxFlow.Engine.Tests/ApplicationPortHandleTests.cs @@ -0,0 +1,381 @@ +using System.Threading.Tasks.Dataflow; +using FluxFlow.Composition.Authoring; +using FluxFlow.Engine.Ports; +using FluxFlow.Nodes; +using Shouldly; +using Xunit; + +namespace FluxFlow.Engine.Tests; + +public sealed class ApplicationPortHandleTests +{ + private static readonly TimeSpan TestTimeout = TimeSpan.FromSeconds(5); + + [Fact] + public void Typed_handle_surface_is_thin_and_keeps_attachment_operations_internal() + { + var publicMethods = typeof(ApplicationPorts) + .GetMethods() + .Where(static method => method.DeclaringType == typeof(ApplicationPorts)) + .ToArray(); + + AssertHandleOverload(publicMethods, nameof(ApplicationPorts.SendAsync), typeof(InputPortHandle<>)); + AssertHandleOverload(publicMethods, nameof(ApplicationPorts.SendAsync), typeof(SignalInputPortHandle)); + AssertHandleOverload(publicMethods, nameof(ApplicationPorts.ReceiveAsync), typeof(OutputPortHandle<>)); + AssertHandleOverload(publicMethods, nameof(ApplicationPorts.ObserveAsync), typeof(OutputPortHandle<>)); + publicMethods + .Single(method => + method.Name == nameof(ApplicationPorts.SendAndReceiveAsync) && + IsGenericParameter(method.GetParameters()[0].ParameterType, typeof(InputPortHandle<>))) + .GetParameters()[1].ParameterType.GetGenericTypeDefinition() + .ShouldBe(typeof(OutputPortHandle<>)); + publicMethods.Select(static method => method.Name) + .ShouldNotContain("AttachInputAsync"); + publicMethods.Select(static method => method.Name) + .ShouldNotContain("AttachSignalInputAsync"); + publicMethods.Select(static method => method.Name) + .ShouldNotContain("AttachOutput"); + } + + [Fact] + public async Task Typed_handles_send_receive_observe_and_request_through_their_exact_addresses() + { + var handles = CreateHandles(); + await using var runtime = CreateRuntime(handles); + var ports = new ApplicationPorts(() => runtime); + var inputTarget = new BufferBlock>(); + var signalTarget = new RecordingSignalTarget(); + var outputSource = new BufferBlock>(); + var replySource = new BufferBlock>(); + var response = new TaskCompletionSource>( + TaskCreationOptions.RunContinuationsAsynchronously); + var requestTarget = new ActionBlock>(request => + { + var reply = request.With($"reply:{request.Value}"); + response.TrySetResult(reply).ShouldBeTrue(); + replySource.Post(reply).ShouldBeTrue(); + }); + + await using var inputAttachment = await runtime.AttachInputAsync( + handles.Input, + inputTarget); + await using var signalAttachment = await runtime.AttachSignalInputAsync( + handles.Signal, + signalTarget); + await using var requestAttachment = await runtime.AttachInputAsync( + handles.Request, + requestTarget); + using var outputAttachment = runtime.AttachOutput(handles.Output, outputSource); + using var replyAttachment = runtime.AttachOutput(handles.Reply, replySource); + var observationResult = await ports.ObserveAsync(handles.Output, capacity: 2); + await using var observation = observationResult.Observation.ShouldNotBeNull(); + var receive = ports.ReceiveAsync(handles.Output, TestTimeout); + + var inputMessage = FlowMessage.Restore( + "input", + new MessageId("input-message"), + new TraceId("input-trace"), + DateTimeOffset.Parse("2026-08-08T10:00:00+00:00")); + var signalMessage = FlowMessage.Restore( + 42, + new MessageId("signal-message"), + new TraceId("signal-trace"), + DateTimeOffset.Parse("2026-08-08T10:01:00+00:00")); + var outputMessage = FlowMessage.Restore( + "output", + new MessageId("output-message"), + new TraceId("output-trace"), + DateTimeOffset.Parse("2026-08-08T10:02:00+00:00")); + var request = FlowMessage.Restore( + "question", + new MessageId("request-message"), + new TraceId("request-trace"), + DateTimeOffset.Parse("2026-08-08T10:03:00+00:00")); + + var inputResult = await ports.SendAsync(handles.Input, inputMessage); + var signalResult = await ports.SendAsync(handles.Signal, signalMessage); + outputSource.Post(outputMessage).ShouldBeTrue(); + var requestResult = await ports.SendAndReceiveAsync( + handles.Request, + handles.Reply, + request, + TestTimeout); + + inputResult.Port.ShouldBe(handles.Input.Address); + inputResult.Status.ShouldBe(PortSendStatus.Accepted); + (await inputTarget.ReceiveAsync().WaitAsync(TestTimeout)).ShouldBeSameAs(inputMessage); + signalResult.Port.ShouldBe(handles.Signal.Address); + signalResult.Status.ShouldBe(PortSendStatus.Accepted); + var receivedSignal = await signalTarget.Received.WaitAsync(TestTimeout); + receivedSignal.Value.ShouldBe(signalMessage.Value); + receivedSignal.MessageId.ShouldBe(signalMessage.MessageId); + receivedSignal.TraceId.ShouldBe(signalMessage.TraceId); + + observationResult.Port.ShouldBe(handles.Output.Address); + observationResult.Status.ShouldBe(PortObserveStatus.Started); + observation.Port.ShouldBe(handles.Output.Address); + observation.Capacity.ShouldBe(2); + var received = await receive.WaitAsync(TestTimeout); + received.Port.ShouldBe(handles.Output.Address); + received.Status.ShouldBe(PortReceiveStatus.Received); + received.Message.ShouldBeSameAs(outputMessage); + (await observation.Messages.ReceiveAsync().WaitAsync(TestTimeout)) + .ShouldBeSameAs(outputMessage); + + var exactResponse = await response.Task.WaitAsync(TestTimeout); + requestResult.InputPort.ShouldBe(handles.Request.Address); + requestResult.OutputPort.ShouldBe(handles.Reply.Address); + requestResult.Status.ShouldBe(PortRequestStatus.Received); + requestResult.Response.ShouldBeSameAs(exactResponse); + requestResult.Response!.Value.ShouldBe("reply:question"); + requestResult.Response.TraceId.ShouldBe(request.TraceId); + } + + [Fact] + public async Task Typed_handle_attachments_bind_message_signal_and_output_to_exact_runtime_ports() + { + var handles = CreateHandles(); + await using var runtime = CreateRuntime(handles); + var inputTarget = new BufferBlock>(); + var signalTarget = new RecordingSignalTarget(); + var outputSource = new BufferBlock>(); + await using var inputAttachment = await runtime.AttachInputAsync( + handles.Input, + inputTarget); + await using var signalAttachment = await runtime.AttachSignalInputAsync( + handles.Signal, + signalTarget); + using var outputAttachment = runtime.AttachOutput(handles.Output, outputSource); + var inputMessage = FlowMessage.Create("input"); + var signalMessage = FlowMessage.Create(new SignalPayload(17)); + var outputMessage = FlowMessage.Create("output"); + var receive = runtime.ReceiveAsync(handles.Output, TestTimeout); + + (await runtime.SendAsync(handles.Input, inputMessage)).Status + .ShouldBe(PortSendStatus.Accepted); + (await runtime.SendAsync(handles.Signal, signalMessage)).Status + .ShouldBe(PortSendStatus.Accepted); + outputSource.Post(outputMessage).ShouldBeTrue(); + + (await inputTarget.ReceiveAsync().WaitAsync(TestTimeout)).ShouldBeSameAs(inputMessage); + var receivedSignal = await signalTarget.Received.WaitAsync(TestTimeout); + receivedSignal.Value.ShouldBe(signalMessage.Value); + receivedSignal.TraceId.ShouldBe(signalMessage.TraceId); + var output = await receive.WaitAsync(TestTimeout); + output.Port.ShouldBe(handles.Output.Address); + output.Message.ShouldBeSameAs(outputMessage); + + await inputAttachment.DisposeAsync(); + await signalAttachment.DisposeAsync(); + outputAttachment.Dispose(); + + (await runtime.SendAsync(handles.Input, FlowMessage.Create("late"))).Status + .ShouldBe(PortSendStatus.Unavailable); + (await runtime.SendAsync(handles.Signal, FlowMessage.Create("late"))).Status + .ShouldBe(PortSendStatus.Unavailable); + (await runtime.ReceiveAsync(handles.Output)).Status + .ShouldBe(PortReceiveStatus.Unavailable); + } + + [Fact] + public async Task Typed_handle_operations_preserve_timeout_cancellation_and_type_direction_errors() + { + var handles = CreateHandles(); + await using var runtime = CreateRuntime(handles); + var ports = new ApplicationPorts(() => runtime); + var idleOutput = new BufferBlock>(); + var idleReply = new BufferBlock>(); + var acceptedRequest = new BufferBlock>(); + using var idleAttachment = runtime.AttachOutput(handles.Output, idleOutput); + using var replyAttachment = runtime.AttachOutput(handles.Reply, idleReply); + await using var requestAttachment = await runtime.AttachInputAsync( + handles.Request, + acceptedRequest); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + var sendCanceled = await Should.ThrowAsync(async () => + await ports.SendAsync(handles.Input, FlowMessage.Create("value"), cancellation.Token)); + var signalCanceled = await Should.ThrowAsync(async () => + await ports.SendAsync(handles.Signal, FlowMessage.Create("signal"), cancellation.Token)); + var receiveCanceled = await Should.ThrowAsync(async () => + await ports.ReceiveAsync(handles.Output, cancellationToken: cancellation.Token)); + var observeCanceled = await Should.ThrowAsync(async () => + await ports.ObserveAsync(handles.Output, cancellationToken: cancellation.Token)); + var requestCanceled = await Should.ThrowAsync(async () => + await ports.SendAndReceiveAsync( + handles.Request, + handles.Reply, + FlowMessage.Create("request"), + cancellationToken: cancellation.Token)); + var inputAttachCanceled = await Should.ThrowAsync(async () => + await runtime.AttachInputAsync( + handles.Input, + new BufferBlock>(), + cancellation.Token)); + var signalAttachCanceled = await Should.ThrowAsync(async () => + await runtime.AttachSignalInputAsync( + handles.Signal, + new RecordingSignalTarget(), + cancellation.Token)); + + sendCanceled.CancellationToken.ShouldBe(cancellation.Token); + signalCanceled.CancellationToken.ShouldBe(cancellation.Token); + receiveCanceled.CancellationToken.ShouldBe(cancellation.Token); + observeCanceled.CancellationToken.ShouldBe(cancellation.Token); + requestCanceled.CancellationToken.ShouldBe(cancellation.Token); + inputAttachCanceled.CancellationToken.ShouldBe(cancellation.Token); + signalAttachCanceled.CancellationToken.ShouldBe(cancellation.Token); + + var timedOut = await ports.ReceiveAsync( + handles.Output, + TimeSpan.FromMilliseconds(20)); + timedOut.Port.ShouldBe(handles.Output.Address); + timedOut.Status.ShouldBe(PortReceiveStatus.TimedOut); + timedOut.Message.ShouldBeNull(); + var requestTimedOut = await ports.SendAndReceiveAsync( + handles.Request, + handles.Reply, + FlowMessage.Create("unanswered"), + TimeSpan.FromMilliseconds(20)); + requestTimedOut.InputPort.ShouldBe(handles.Request.Address); + requestTimedOut.OutputPort.ShouldBe(handles.Reply.Address); + requestTimedOut.Status.ShouldBe(PortRequestStatus.TimedOut); + requestTimedOut.Response.ShouldBeNull(); + + var wrongInputType = handles.Definition.Input(handles.Input.Name); + var wrongOutputType = handles.Definition.Output(handles.Output.Name); + var outputAsInput = handles.Definition.Input(handles.Output.Name); + var inputAsOutput = handles.Definition.Output(handles.Input.Name); + + var inputTypeError = await Should.ThrowAsync(async () => + await ports.SendAsync(wrongInputType, FlowMessage.Create(42))); + var outputTypeError = await Should.ThrowAsync(async () => + await ports.ReceiveAsync(wrongOutputType)); + var inputDirectionError = await Should.ThrowAsync(async () => + await ports.SendAsync(outputAsInput, FlowMessage.Create("value"))); + var outputDirectionError = await Should.ThrowAsync(async () => + await ports.ReceiveAsync(inputAsOutput)); + + inputTypeError.Message.ShouldContain(typeof(int).ToString()); + inputTypeError.Message.ShouldContain(typeof(string).ToString()); + outputTypeError.Message.ShouldContain(typeof(int).ToString()); + outputTypeError.Message.ShouldContain(typeof(string).ToString()); + inputDirectionError.Message.ShouldContain(handles.Output.Address.Value); + outputDirectionError.Message.ShouldContain(handles.Input.Address.Value); + + (await Should.ThrowAsync(async () => + await ports.SendAsync((InputPortHandle)null!, FlowMessage.Create("value")))) + .ParamName.ShouldBe("input"); + (await Should.ThrowAsync(async () => + await ports.ReceiveAsync((OutputPortHandle)null!))) + .ParamName.ShouldBe("output"); + } + + [Fact] + public async Task Address_based_application_port_overloads_remain_callable_and_behaviorally_identical() + { + var handles = CreateHandles(); + await using var runtime = CreateRuntime(handles); + var ports = new ApplicationPorts(() => runtime); + var first = FlowMessage.Create("first"); + var second = FlowMessage.Create("second"); + + var typedSend = await ports.SendAsync(handles.Input, first); + var addressSend = await ports.SendAsync(handles.Input.Address, second); + var stringSend = await ports.SendAsync(handles.Input.Address.Value, second); + var typedReceive = await ports.ReceiveAsync(handles.Output); + var addressReceive = await ports.ReceiveAsync(handles.Output.Address); + var stringReceive = await ports.ReceiveAsync(handles.Output.Address.Value); + var typedObserve = await ports.ObserveAsync(handles.Output); + var addressObserve = await ports.ObserveAsync(handles.Output.Address); + var stringObserve = await ports.ObserveAsync(handles.Output.Address.Value); + + typedSend.ShouldBe(new PortSendResult + { + Port = handles.Input.Address, + Status = PortSendStatus.Unavailable + }); + addressSend.ShouldBe(typedSend); + stringSend.ShouldBe(typedSend); + typedReceive.Status.ShouldBe(PortReceiveStatus.Unavailable); + addressReceive.ShouldBe(typedReceive); + stringReceive.ShouldBe(typedReceive); + typedObserve.Status.ShouldBe(PortObserveStatus.Unavailable); + addressObserve.ShouldBe(typedObserve); + stringObserve.ShouldBe(typedObserve); + } + + private static ApplicationPortRuntime CreateRuntime(PortHandles handles) + => new ApplicationPortRuntimeBuilder() + .AddInput(handles.Input.Address) + .AddSignalInput(handles.Signal.Address) + .AddInput(handles.Request.Address) + .AddOutput(handles.Output.Address) + .AddOutput(handles.Reply.Address) + .Build(); + + private static void AssertHandleOverload( + IEnumerable methods, + string methodName, + Type firstParameter) + => methods.Count(method => + method.Name == methodName && + IsGenericParameter(method.GetParameters()[0].ParameterType, firstParameter)) + .ShouldBe(1); + + private static bool IsGenericParameter(Type candidate, Type expected) + => expected.IsGenericTypeDefinition + ? candidate.IsGenericType && candidate.GetGenericTypeDefinition() == expected + : candidate == expected; + + private static PortHandles CreateHandles() + { + var application = new ApplicationDefinitionBuilder(); + var definition = application + .AddWorkflow("main") + .AddComponent("node", "test.ports"); + return new PortHandles( + definition, + definition.Input("Input"), + definition.SignalInput("Signal"), + definition.Input("Request"), + definition.Output("Output"), + definition.Output("Reply")); + } + + private sealed record PortHandles( + ComponentHandle Definition, + InputPortHandle Input, + SignalInputPortHandle Signal, + InputPortHandle Request, + OutputPortHandle Output, + OutputPortHandle Reply); + + private sealed record SignalPayload(int Value); + + private sealed class RecordingSignalTarget : IFlowSignalTarget + { + private readonly TaskCompletionSource _completion = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _received = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task Completion => _completion.Task; + + public Task Received => _received.Task; + + public ValueTask SendAsync( + FlowMessage signal, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(_received.TrySetResult(new ReceivedSignal( + signal.Value, + signal.MessageId, + signal.TraceId))); + } + } + + private sealed record ReceivedSignal(object? Value, MessageId MessageId, TraceId TraceId); +} diff --git a/tests/FluxFlow.Engine.Tests/ApplicationResourceContractRuntimeTests.cs b/tests/FluxFlow.Engine.Tests/ApplicationResourceContractRuntimeTests.cs new file mode 100644 index 00000000..d19914b1 --- /dev/null +++ b/tests/FluxFlow.Engine.Tests/ApplicationResourceContractRuntimeTests.cs @@ -0,0 +1,589 @@ +using System.Collections.Concurrent; +using System.Runtime.ExceptionServices; +using System.Runtime.CompilerServices; +using System.Threading.Tasks.Dataflow; +using FluxFlow.Composition; +using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; +using FluxFlow.Composition.DependencyInjection; +using FluxFlow.Composition.Model; +using FluxFlow.Engine.Ports; +using FluxFlow.Nodes; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; + +namespace FluxFlow.Engine.Tests; + +public sealed class ApplicationResourceContractRuntimeTests +{ + private static readonly TimeSpan TestTimeout = TimeSpan.FromSeconds(5); + + [Fact] + public async Task Code_first_resource_contract_executes_from_definition_without_host_registrar() + { + var tracker = new ResourceLifetimeTracker(); + var registrar = new PrefixResourceRegistrar(); + var resourceContract = CreateResourceContract(registrar); + var fixture = Definition(resourceContract, CreateNodeContract(), "embedded"); + var services = new ServiceCollection(); + services.AddSingleton(tracker); + services.AddFluxFlow( + fixture.Definition, + options => options.StartWithHost = false); + services.ShouldNotContain(static descriptor => + descriptor.ServiceType == typeof(IApplicationResourceRegistrar)); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + + var started = await application.StartAsync(); + var response = await SendAsync(application.Ports, fixture, "value"); + + started.Status.ShouldBe(ApplicationUpdateStatus.Applied); + registrar.RegistrationCount.ShouldBe(1); + application.CurrentDefinition.ShouldBeSameAs(fixture.Definition); + application.CurrentDefinition!.ApplicationResourceContracts + .ShouldHaveSingleItem().ShouldBeSameAs(resourceContract); + response.ShouldBe("embedded:value"); + tracker.Created("embedded").ShouldBe(1); + tracker.Disposed("embedded").ShouldBe(0); + + await application.StopAsync(); + tracker.Disposed("embedded").ShouldBe(1); + } + + [Fact] + public async Task Embedded_and_explicit_exact_registrar_identity_runs_once_per_revision() + { + var tracker = new ResourceLifetimeTracker(); + var registrar = new PrefixResourceRegistrar(); + var fixture = Definition( + CreateResourceContract(registrar), + CreateNodeContract(), + "deduplicated"); + var services = new ServiceCollection(); + services.AddSingleton(tracker); + services.AddApplicationResourceRegistrar(registrar); + services.AddFluxFlow( + fixture.Definition, + options => options.StartWithHost = false); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + + (await application.StartAsync()).Status.ShouldBe(ApplicationUpdateStatus.Applied); + + registrar.RegistrationCount.ShouldBe(1); + (await SendAsync(application.Ports, fixture, "once")) + .ShouldBe("deduplicated:once"); + tracker.Created("deduplicated").ShouldBe(1); + + await application.StopAsync(); + tracker.Disposed("deduplicated").ShouldBe(1); + } + + [Fact] + public async Task Hot_reload_adds_reuses_replaces_and_removes_resource_contracts_with_exact_owned_disposal() + { + var tracker = new ResourceLifetimeTracker(); + var initialRegistrar = new PrefixResourceRegistrar(); + var replacementRegistrar = new PrefixResourceRegistrar(); + var nodeContract = CreateNodeContract(); + var initialContract = CreateResourceContract(initialRegistrar); + var initial = Definition( + initialContract, + nodeContract, + "initial"); + var sameIdentity = Definition( + initialContract, + nodeContract, + "initial"); + var replacement = Definition( + CreateResourceContract(replacementRegistrar), + nodeContract, + "replacement"); + var empty = new ApplicationDefinitionBuilder().Build(); + var services = new ServiceCollection(); + services.AddSingleton(tracker); + services.AddFluxFlow( + empty, + options => options.StartWithHost = false); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + + (await application.StartAsync()).Status.ShouldBe(ApplicationUpdateStatus.Unchanged); + var added = await application.ApplyAsync("resource-addition", initial.Definition); + + added.Status.ShouldBe(ApplicationUpdateStatus.Applied); + added.PreviousRevision.ShouldBeNull(); + application.CurrentDefinition.ShouldBeSameAs(initial.Definition); + (await SendAsync(application.Ports, initial, "one")).ShouldBe("initial:one"); + var unchanged = await application.ApplyAsync( + "rebuilt-same-contract-identity", + sameIdentity.Definition); + + unchanged.Status.ShouldBe(ApplicationUpdateStatus.Unchanged); + application.CurrentDefinition.ShouldBeSameAs(sameIdentity.Definition); + initialRegistrar.RegistrationCount.ShouldBe(1); + tracker.Created("initial").ShouldBe(1); + tracker.Disposed("initial").ShouldBe(0); + var replaced = await application.ApplyAsync("resource-replacement", replacement.Definition); + + replaced.Status.ShouldBe(ApplicationUpdateStatus.Applied); + replaced.PreviousRevision.ShouldNotBeNull(); + application.CurrentDefinition.ShouldBeSameAs(replacement.Definition); + replacementRegistrar.RegistrationCount.ShouldBe(1); + tracker.Created("initial").ShouldBe(1); + tracker.Disposed("initial").ShouldBe(1); + tracker.Created("replacement").ShouldBe(1); + tracker.Disposed("replacement").ShouldBe(0); + (await SendAsync(application.Ports, replacement, "two")) + .ShouldBe("replacement:two"); + + var removed = await application.ApplyAsync("resource-removal", empty); + + removed.Status.ShouldBe(ApplicationUpdateStatus.Applied); + application.CurrentDefinition.ShouldBeSameAs(empty); + application.CurrentDefinition!.ApplicationResourceContracts.ShouldBeEmpty(); + tracker.Disposed("replacement").ShouldBe(1); + await application.StopAsync(); + tracker.Disposed("replacement").ShouldBe(1); + } + + [Fact] + public async Task Failed_resource_contract_revision_preserves_active_resource_factory_route_and_ownership() + { + var tracker = new ResourceLifetimeTracker(); + var initialRegistrar = new PrefixResourceRegistrar(); + var candidateRegistrar = new PrefixResourceRegistrar(); + var initial = Definition( + CreateResourceContract(initialRegistrar), + CreateNodeContract(), + "active"); + var candidate = Definition( + CreateResourceContract(candidateRegistrar), + CreateNodeContract(failAfterResourceResolution: true), + "candidate"); + var services = new ServiceCollection(); + services.AddSingleton(tracker); + services.AddFluxFlow( + initial.Definition, + options => options.StartWithHost = false); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + + (await application.StartAsync()).Status.ShouldBe(ApplicationUpdateStatus.Applied); + var activeRevision = application.Current; + var activeDefinition = application.CurrentDefinition; + (await SendAsync(application.Ports, initial, "before")).ShouldBe("active:before"); + + var rejected = await application.ApplyAsync("failed-resource", candidate.Definition); + + rejected.Status.ShouldBe(ApplicationUpdateStatus.Rejected); + rejected.ActiveRevision.ShouldBeSameAs(activeRevision); + rejected.Diagnostics.ShouldContain(diagnostic => + diagnostic.Error.Details.HasValue && + diagnostic.Error.Details.Value.GetProperty("exceptionMessage").GetString()! + .Contains("candidate activation failed", StringComparison.Ordinal)); + application.Current.ShouldBeSameAs(activeRevision); + application.CurrentDefinition.ShouldBeSameAs(activeDefinition); + candidateRegistrar.RegistrationCount.ShouldBe(1); + tracker.Created("candidate").ShouldBe(1); + tracker.Disposed("candidate").ShouldBe(1); + tracker.Disposed("active").ShouldBe(0); + (await SendAsync(application.Ports, initial, "after")).ShouldBe("active:after"); + + await application.StopAsync(); + tracker.Disposed("active").ShouldBe(1); + } + + [Fact] + public async Task Successful_resource_contract_replacement_retires_registrar_closure() + { + await using var context = RunOnTerminatedThread( + static () => CreateResourceRetirementContext()); + + ForceFullCollection(); + context.Closure.IsAlive.ShouldBeFalse(); + + await context.Application.StopAsync(); + } + + [Fact] + public async Task Json_resource_definition_still_requires_explicit_host_registrar() + { + const string json = + "{\"Resources\":{\"Prefix\":{\"Type\":\"test.prefix-resource\",\"Value\":\"json\"}}," + + "\"Workflows\":{\"Main\":{\"Worker\":{\"Type\":\"test.resource-node\"," + + "\"Resource\":\"Resources.Prefix\"}}}}"; + var definition = ApplicationDefinitionJson.Deserialize(json); + var nodeContract = CreateNodeContract(); + var missingServices = new ServiceCollection(); + missingServices.AddSingleton(new ResourceLifetimeTracker()); + missingServices.AddFluxFlow( + definition, + options => options.StartWithHost = false) + .AddComponent(nodeContract); + await using var missingProvider = missingServices.BuildServiceProvider(); + var missing = missingProvider.GetRequiredService(); + + var rejected = await missing.StartAsync(); + + rejected.Status.ShouldBe(ApplicationUpdateStatus.Rejected); + rejected.Diagnostics.ShouldContain(diagnostic => + diagnostic.Error.Details.HasValue && + diagnostic.Error.Details.Value.GetProperty("exceptionMessage").GetString()! + .Contains("no keyed service", StringComparison.OrdinalIgnoreCase)); + missing.CurrentDefinition.ShouldBeNull(); + definition.ApplicationResourceContracts.ShouldBeEmpty(); + await missing.StopAsync(); + + var tracker = new ResourceLifetimeTracker(); + var registrar = new PrefixResourceRegistrar(); + var explicitServices = new ServiceCollection(); + explicitServices.AddSingleton(tracker); + explicitServices.AddApplicationResourceRegistrar(registrar); + explicitServices.AddFluxFlow( + definition, + options => options.StartWithHost = false) + .AddComponent(nodeContract); + await using var explicitProvider = explicitServices.BuildServiceProvider(); + var explicitApplication = explicitProvider.GetRequiredService(); + + var started = await explicitApplication.StartAsync(); + started.Status.ShouldBe( + ApplicationUpdateStatus.Applied, + string.Join( + Environment.NewLine, + started.Diagnostics.Select(static diagnostic => + $"{diagnostic.Stage}: {diagnostic.Error.Code}: {diagnostic.Error.Message}: " + + $"{diagnostic.Error.Details?.GetRawText()}"))); + var input = ApplicationAddress.WorkflowPort("Main", "Worker", "Input"); + var output = ApplicationAddress.WorkflowPort("Main", "Worker", "Output"); + var receive = explicitApplication.Ports.ReceiveAsync(output, TestTimeout); + var sent = await explicitApplication.Ports.SendAsync(input, FlowMessage.Create("value")); + + sent.Status.ShouldBe(PortSendStatus.Accepted); + (await receive).Message!.Value.ShouldBe("json:value"); + registrar.RegistrationCount.ShouldBe(1); + await explicitApplication.StopAsync(); + tracker.Disposed("json").ShouldBe(1); + } + + private static ApplicationResourceContract + CreateResourceContract(IApplicationResourceRegistrar registrar) + => ApplicationResourceContract.Create( + "test.prefix-resource", + registrar, + static () => new PrefixResourceOptions(), + static (options, definition) => definition.Set("Value", options.Value), + static definition => new PrefixResourceHandle(definition)); + + private static ComponentContract> + CreateNodeContract(bool failAfterResourceResolution = false) + => ComponentContract.Create>( + "test.resource-node", + component => + { + component.AddResource("Resource", isRequired: true); + component + .UseFactory(context => + { + var resource = context.GetRequiredResource("Resource"); + if (failAfterResourceResolution) + throw new InvalidOperationException("candidate activation failed"); + return new PrefixNode(resource.Value); + }) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); + }, + static () => new ResourceNodeOptions(), + static (options, definition) => + definition.UseResource("Resource", options.Resource!.Definition), + static component => new InputOutputComponentHandle( + component, + "Input", + "Output", + "Events")); + + private static ResourceDefinitionFixture Definition( + ApplicationResourceContract resourceContract, + ComponentContract> nodeContract, + string value) + { + var builder = new ApplicationDefinitionBuilder(); + var resource = builder.AddResource( + "Prefix", + resourceContract, + options => options.Value = value); + var node = builder.AddWorkflow("Main").AddComponent( + "Worker", + nodeContract, + options => options.Resource = resource); + return new ResourceDefinitionFixture(builder.Build(), node); + } + + private static async Task SendAsync( + ApplicationPorts ports, + ResourceDefinitionFixture fixture, + string value) + { + var receive = ports.ReceiveAsync(fixture.Node.Output, TestTimeout); + var sent = await ports.SendAsync(fixture.Node.Input, FlowMessage.Create(value)); + sent.Status.ShouldBe(PortSendStatus.Accepted); + return (await receive).Message!.Value; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static LifetimeFixture CreateLifetimeFixture() + { + var closure = new RegistrarClosure(); + var contract = CreateResourceContract(new DelegateRegistrar(closure.Register)); + var builder = new ApplicationDefinitionBuilder(); + builder.AddResource("Prefix", contract, static options => options.Value = "captured"); + return new LifetimeFixture( + new MutableDefinitionSource(builder.Build()), + new WeakReference(closure)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static ResourceRetirementAssertionContext CreateResourceRetirementContext() + { + var fixture = CreateLifetimeFixture(); + var services = new ServiceCollection(); + services.AddSingleton(new ResourceLifetimeTracker()); + services.AddFluxFlow( + fixture.Source, + options => options.StartWithHost = false); + var provider = services.BuildServiceProvider(); + + try + { + var application = provider.GetRequiredService(); + application.StartAsync().GetAwaiter().GetResult().Status + .ShouldBe(ApplicationUpdateStatus.Applied); + fixture.Closure.IsAlive.ShouldBeTrue(); + ReplaceLifetimeRevisionAsync(application, fixture.Source).GetAwaiter().GetResult(); + return new ResourceRetirementAssertionContext( + provider, + application, + fixture.Closure); + } + catch + { + provider.DisposeAsync().AsTask().GetAwaiter().GetResult(); + throw; + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static async Task ReplaceLifetimeRevisionAsync( + FluxFlowApplication application, + MutableDefinitionSource source) + { + var builder = new ApplicationDefinitionBuilder(); + builder.AddResource( + "Prefix", + CreateResourceContract(new PrefixResourceRegistrar()), + static options => options.Value = "replacement"); + source.Definition = builder.Build(); + + var replacement = await application.ReloadAsync("resource-contract-replacement"); + + replacement.Status.ShouldBe(ApplicationUpdateStatus.Applied); + replacement.PreviousRevision.ShouldNotBeNull(); + application.CurrentDefinition.ShouldBeSameAs(source.Definition); + application.LastUpdate!.PreviousRevision.ShouldBeNull(); + } + + private static T RunOnTerminatedThread(Func operation) + where T : class + { + T? result = null; + ExceptionDispatchInfo? failure = null; + var thread = new Thread(() => + { + try + { + result = operation(); + } + catch (Exception exception) + { + failure = ExceptionDispatchInfo.Capture(exception); + } + }) + { + IsBackground = true + }; + + thread.Start(); + thread.Join(); + failure?.Throw(); + return result ?? throw new InvalidOperationException( + "The resource retirement assertion thread completed without a result."); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void ForceFullCollection() + { + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); + GC.WaitForPendingFinalizers(); + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); + } + + private static IEnumerable<(ApplicationAddress Address, ResourceInstanceDefinition Definition)> + FlattenResources( + IReadOnlyDictionary resources, + IReadOnlyList? path = null) + { + path ??= []; + foreach (var (name, resource) in resources) + { + string[] next = [.. path, name]; + if (resource is ResourceGroupDefinition group) + { + foreach (var nested in FlattenResources(group.Resources, next)) + yield return nested; + } + else + { + yield return ( + ApplicationAddress.Resource(next), + (ResourceInstanceDefinition)resource); + } + } + } + + private sealed record ResourceDefinitionFixture( + ApplicationDefinition Definition, + InputOutputComponentHandle Node); + + private sealed class PrefixResourceOptions + { + public string Value { get; set; } = "default"; + } + + private sealed class ResourceNodeOptions + { + public PrefixResourceHandle? Resource { get; set; } + } + + private sealed class PrefixResourceHandle(ResourceHandle definition) + : AuthoredResourceHandle(definition); + + private sealed class PrefixResource(string value, ResourceLifetimeTracker tracker) + : IDisposable + { + private int _disposed; + + public string Value { get; } = value; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + tracker.RecordDisposed(Value); + } + } + + private sealed class PrefixResourceRegistrar : IApplicationResourceRegistrar + { + public int RegistrationCount { get; private set; } + + public void Register(ApplicationResourceRegistrationContext context) + { + RegistrationCount++; + var tracker = context.HostServices.GetRequiredService(); + foreach (var (address, resource) in FlattenResources(context.Definition.Resources)) + { + if (!string.Equals(resource.Type, "test.prefix-resource", StringComparison.Ordinal)) + continue; + + var value = resource.Properties["Value"].GetString()!; + context.Services.AddFluxFlowResource( + address, + _ => + { + tracker.RecordCreated(value); + return new PrefixResource(value, tracker); + }); + } + } + } + + private sealed class DelegateRegistrar(Action register) + : IApplicationResourceRegistrar + { + public void Register(ApplicationResourceRegistrationContext context) => register(context); + } + + private sealed class RegistrarClosure + { + public void Register(ApplicationResourceRegistrationContext context) + { + var tracker = context.HostServices.GetRequiredService(); + foreach (var (address, resource) in FlattenResources(context.Definition.Resources)) + { + if (!string.Equals(resource.Type, "test.prefix-resource", StringComparison.Ordinal)) + continue; + var value = resource.Properties["Value"].GetString()!; + context.Services.AddFluxFlowResource( + address, + _ => + { + tracker.RecordCreated(value); + return new PrefixResource(value, tracker); + }); + } + } + } + + private sealed class ResourceLifetimeTracker + { + private readonly ConcurrentDictionary _created = + new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _disposed = + new(StringComparer.Ordinal); + + public int Created(string value) => _created.GetValueOrDefault(value); + + public int Disposed(string value) => _disposed.GetValueOrDefault(value); + + public void RecordCreated(string value) => _created.AddOrUpdate(value, 1, static (_, count) => count + 1); + + public void RecordDisposed(string value) => _disposed.AddOrUpdate(value, 1, static (_, count) => count + 1); + } + + private sealed class PrefixNode(string prefix) : FlowNode + { + protected override async Task ProcessAsync(FlowMessage message) + => await EmitAsync(message.With($"{prefix}:{message.Value}"), Stopping) + .ConfigureAwait(false); + } + + private sealed class MutableDefinitionSource(ApplicationDefinition definition) + : IApplicationDefinitionSource + { + public ApplicationDefinition Definition { get; set; } = definition; + + public ValueTask LoadAsync( + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(Definition); + } + } + + private sealed record LifetimeFixture(MutableDefinitionSource Source, WeakReference Closure); + + private sealed class ResourceRetirementAssertionContext( + ServiceProvider provider, + FluxFlowApplication application, + WeakReference closure) : IAsyncDisposable + { + public FluxFlowApplication Application { get; } = application; + + public WeakReference Closure { get; } = closure; + + public ValueTask DisposeAsync() => provider.DisposeAsync(); + } +} diff --git a/tests/FluxFlow.Engine.Tests/ApplicationRevisionPlannerTests.cs b/tests/FluxFlow.Engine.Tests/ApplicationRevisionPlannerTests.cs index 81820fd3..99107d93 100644 --- a/tests/FluxFlow.Engine.Tests/ApplicationRevisionPlannerTests.cs +++ b/tests/FluxFlow.Engine.Tests/ApplicationRevisionPlannerTests.cs @@ -1,7 +1,9 @@ using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; using FluxFlow.Composition.Model; using FluxFlow.Engine.Internal.Revisions; using FluxFlow.Data; +using FluxFlow.Nodes; using Shouldly; using System.Text.Json; using Xunit; @@ -212,6 +214,91 @@ public void Workflow_changes_are_whole_workflow_revision_units() plan.AffectedWorkflows.ShouldBe(["Orders"]); } + [Fact] + public void Revision_planner_reuses_same_built_definition_and_changes_for_new_code_predicate() + { + Func predicate = static value => value > 0; + var current = BuildCodeFirst(predicate); + var unchanged = new ApplicationRevisionPlanner().Plan(current, current); + var rebuilt = new ApplicationRevisionPlanner().Plan( + current, + BuildCodeFirst(predicate)); + + unchanged.IsValid.ShouldBeTrue(); + unchanged.HasChanges.ShouldBeFalse(); + unchanged.WorkflowChanges.ShouldBeEmpty(); + unchanged.AffectedWorkflows.ShouldBeEmpty(); + + rebuilt.IsValid.ShouldBeTrue(); + rebuilt.HasChanges.ShouldBeTrue(); + rebuilt.WorkflowChanges.ShouldBe( + [ + new ApplicationWorkflowRevisionChange + { + Workflow = "Main", + Kind = ApplicationRevisionChangeKind.Updated + } + ]); + rebuilt.AffectedWorkflows.ShouldBe(["Main"]); + } + + [Fact] + public void Revision_planner_reuses_same_descriptor_and_changes_used_workflow_for_new_descriptor_identity() + { + var contract = CreatePlannerContract(); + var current = BuildContractDefinition(contract); + var sameBuilt = new ApplicationRevisionPlanner().Plan(current, current); + var rebuiltWithSameContract = new ApplicationRevisionPlanner().Plan( + current, + BuildContractDefinition(contract)); + var replacementContract = CreatePlannerContract(); + replacementContract.Descriptor.ShouldNotBeSameAs(contract.Descriptor); + var replaced = new ApplicationRevisionPlanner().Plan( + current, + BuildContractDefinition(replacementContract)); + + sameBuilt.IsValid.ShouldBeTrue(); + sameBuilt.HasChanges.ShouldBeFalse(); + sameBuilt.WorkflowChanges.ShouldBeEmpty(); + rebuiltWithSameContract.IsValid.ShouldBeTrue(); + rebuiltWithSameContract.HasChanges.ShouldBeFalse(); + rebuiltWithSameContract.WorkflowChanges.ShouldBeEmpty(); + replaced.IsValid.ShouldBeTrue(); + replaced.HasChanges.ShouldBeTrue(); + replaced.WorkflowChanges.ShouldHaveSingleItem().ShouldBe( + new ApplicationWorkflowRevisionChange + { + Workflow = "Main", + Kind = ApplicationRevisionChangeKind.Updated + }); + replaced.AffectedWorkflows.ShouldBe(["Main"]); + } + + [Fact] + public void Added_removed_and_changed_expression_links_update_the_owning_workflow() + { + var noLinks = BuildCodeFirst(condition: null); + var firstExpression = BuildCodeFirst("value > 0"); + var changedExpression = BuildCodeFirst("value >= 0"); + var planner = new ApplicationRevisionPlanner(); + + var added = planner.Plan(noLinks, firstExpression); + var changed = planner.Plan(firstExpression, changedExpression); + var removed = planner.Plan(changedExpression, noLinks); + + foreach (var plan in new[] { added, changed, removed }) + { + plan.IsValid.ShouldBeTrue(); + plan.WorkflowChanges.ShouldHaveSingleItem().ShouldBe( + new ApplicationWorkflowRevisionChange + { + Workflow = "Main", + Kind = ApplicationRevisionChangeKind.Updated + }); + plan.AffectedWorkflows.ShouldBe(["Main"]); + } + } + [Fact] public void Revision_event_copies_and_orders_transport_values() { @@ -251,6 +338,57 @@ public void Revision_event_copies_and_orders_transport_values() "\"isTransient\":false,\"details\":null}}"); } + private static ApplicationDefinition BuildCodeFirst(Func when) + { + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + var source = workflow.AddComponent("Source", "source"); + var sink = workflow.AddComponent("Sink", "sink"); + source.Output("Output").ConnectTo(sink.Input("Input"), when); + return application.Build(); + } + + private static ApplicationDefinition BuildCodeFirst(string? condition) + { + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + var source = workflow.AddComponent("Source", "source"); + var sink = workflow.AddComponent("Sink", "sink"); + if (condition is not null) + source.Output("Output").ConnectTo(sink.Input("Input"), condition); + return application.Build(); + } + + private static ComponentContract CreatePlannerContract() + => ComponentContract.Create( + "test.planner", + static component => component.UseFactory(static _ => new PlannerNode()), + static component => new PlannerHandle(component)); + + private static ApplicationDefinition BuildContractDefinition( + ComponentContract contract) + { + var application = new ApplicationDefinitionBuilder(); + application.AddWorkflow("Main").AddComponent("Node", contract); + return application.Build(); + } + + private sealed class PlannerHandle(ComponentHandle definition) + : AuthoredComponentHandle(definition); + + private sealed class PlannerNode : IFlowNode + { + public Task Completion => Task.CompletedTask; + + public void Complete() + { + } + + public void Fault(Exception exception) => ArgumentNullException.ThrowIfNull(exception); + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + private static ApplicationDefinition Read(string json) => ApplicationDefinitionJson.Deserialize(json); } diff --git a/tests/FluxFlow.Engine.Tests/ApplicationRuntimeAssemblerTests.cs b/tests/FluxFlow.Engine.Tests/ApplicationRuntimeAssemblerTests.cs index 0d6c36a5..04ceae6c 100644 --- a/tests/FluxFlow.Engine.Tests/ApplicationRuntimeAssemblerTests.cs +++ b/tests/FluxFlow.Engine.Tests/ApplicationRuntimeAssemblerTests.cs @@ -1,6 +1,9 @@ +using System.Runtime.ExceptionServices; +using System.Runtime.CompilerServices; using System.Threading.Tasks.Dataflow; using FluxFlow.Composition; using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; using FluxFlow.Composition.DependencyInjection; using FluxFlow.Engine.Internal.Revisions; using FluxFlow.Composition.Model; @@ -22,8 +25,8 @@ public sealed class ApplicationRuntimeAssemblerTests ApplicationAddress.WorkflowPort("Orders", "First", "Input"); private static readonly ApplicationAddress Output = ApplicationAddress.WorkflowPort("Orders", "Second", "Output"); - private static readonly ApplicationAddress FirstEvents = - ApplicationAddress.WorkflowPort("Orders", "First", "Events"); + private static readonly ApplicationAddress FirstDiagnostics = + ApplicationAddress.WorkflowPort("Orders", "First", "Diagnostics"); private static readonly ApplicationAddress ThirdInput = ApplicationAddress.WorkflowPort("Orders", "Third", "Input"); private static readonly ApplicationAddress ThirdOutput = @@ -62,7 +65,7 @@ public async Task Canonical_json_builds_direct_ports_links_resources_and_revisio var firstReceive = ports.ReceiveAsync(Output, TimeSpan.FromSeconds(5)); var eventReceive = ports.ReceiveAsync( - FirstEvents, + FirstDiagnostics, TimeSpan.FromSeconds(5)); (await ports.SendAsync(Input, FlowMessage.Create("value"))) .Status.ShouldBe(PortSendStatus.Accepted); @@ -212,7 +215,291 @@ public async Task Revision_that_changes_a_port_payload_type_replaces_the_generat } [Fact] - public async Task Obsolete_component_type_is_rejected_by_the_runtime_assembler() + public async Task Code_first_definition_executes_embedded_contracts_without_host_registration() + { + var auditValues = new HashSet(StringComparer.Ordinal) { "priority" }; + var definition = CodeFirstRoutingDefinition(auditValues); + var signalTracker = new SignalTracker(); + var services = new ServiceCollection(); + services.AddSingleton(signalTracker); + services.AddFluxFlow(definition) + .AddTestRuntimeAssembler(static _ => { }); + await using var provider = services.BuildServiceProvider(); + var host = provider.GetRequiredService(); + var access = provider.GetRequiredService(); + + provider.GetRequiredService().Descriptors.ShouldBeEmpty(); + definition.ComponentDescriptors.Select(static descriptor => descriptor.Type) + .ShouldBe(["test.identity-string", "test.signal"]); + + var started = await host.StartAsync(); + + started.IsApplied.ShouldBeTrue(string.Join( + Environment.NewLine, + started.Diagnostics.Select(static diagnostic => + $"{diagnostic.Stage}: {diagnostic.Error.Code}: {diagnostic.Error.Message}: {diagnostic.Error.Details}"))); + host.CurrentDefinition.ShouldBeSameAs(definition); + var ports = access.GetRequiredPorts(); + var sourceInput = ApplicationAddress.WorkflowPort("Main", "Source", "Input"); + var priorityOutput = ApplicationAddress.WorkflowPort("Main", "Priority", "Output"); + var standardOutput = ApplicationAddress.WorkflowPort("Main", "Standard", "Output"); + var auditOutput = ApplicationAddress.WorkflowPort("Audit", "Recorder", "Output"); + var priorityReceive = ports.ReceiveAsync(priorityOutput, TimeSpan.FromSeconds(5)); + var auditReceive = ports.ReceiveAsync(auditOutput, TimeSpan.FromSeconds(5)); + + (await ports.SendAsync(sourceInput, FlowMessage.Create("priority"))) + .Status.ShouldBe(PortSendStatus.Accepted); + + (await priorityReceive).Message!.Value.ShouldBe("priority"); + (await auditReceive).Message!.Value.ShouldBe("priority"); + (await signalTracker.NextAsync()).ShouldBe("priority"); + + var standardReceive = ports.ReceiveAsync(standardOutput, TimeSpan.FromSeconds(5)); + (await ports.SendAsync(sourceInput, FlowMessage.Create("standard"))) + .Status.ShouldBe(PortSendStatus.Accepted); + (await standardReceive).Message!.Value.ShouldBe("standard"); + host.State.ShouldBe(ApplicationState.Running); + + await host.StopAsync(); + } + + [Fact] + public async Task Effective_catalog_deduplicates_same_descriptor_and_runs_mixed_embedded_and_host_registered_components() + { + var embeddedActivations = 0; + var hostActivations = 0; + var embedded = CreateStringIdentityContract( + "test.embedded", + _ => + { + embeddedActivations++; + return new IdentityNode(); + }); + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + var first = workflow.AddComponent("First", embedded); + var second = workflow.AddComponent("Second", "test.host"); + first.Output.ConnectTo(second.Input("Input")); + var definition = application.Build(); + var services = new ServiceCollection(); + services.AddFluxFlow(definition) + .AddComponent(embedded) + .Advanced.AddDynamicComponent("test.host", component => component + .UseFactory(_ => + { + hostActivations++; + return new IdentityNode(); + }) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events)); + await using var provider = services.BuildServiceProvider(); + var host = provider.GetRequiredService(); + var access = provider.GetRequiredService(); + + var started = await host.StartAsync(); + + started.IsApplied.ShouldBeTrue(string.Join( + Environment.NewLine, + started.Diagnostics.Select(static diagnostic => + $"{diagnostic.Stage}: {diagnostic.Error.Code}: {diagnostic.Error.Message}: {diagnostic.Error.Details}"))); + embeddedActivations.ShouldBe(1); + hostActivations.ShouldBe(1); + provider.GetRequiredService().Descriptors + .Single(descriptor => descriptor.Type == "test.embedded") + .ShouldBeSameAs(embedded.Descriptor); + var ports = access.GetRequiredPorts(); + var input = ApplicationAddress.WorkflowPort("Main", "First", "Input"); + var output = ApplicationAddress.WorkflowPort("Main", "Second", "Output"); + var receive = ports.ReceiveAsync(output, TimeSpan.FromSeconds(5)); + (await ports.SendAsync(input, FlowMessage.Create("mixed"))) + .Status.ShouldBe(PortSendStatus.Accepted); + (await receive).Message!.Value.ShouldBe("mixed"); + + await host.StopAsync(); + } + + [Fact] + public async Task Effective_catalog_rejects_distinct_same_type_descriptors_before_activation_and_preserves_active_revision() + { + var activeActivations = 0; + var rejectedActivations = 0; + var activeContract = CreateStringIdentityContract( + "test.identity", + _ => + { + activeActivations++; + return new IdentityNode(); + }); + var initialBuilder = new ApplicationDefinitionBuilder(); + initialBuilder.AddWorkflow("Main").AddComponent("Value", "test.identity"); + var initial = initialBuilder.Build(); + var rejectedContract = CreateStringIdentityContract( + "test.identity", + _ => + { + rejectedActivations++; + return new IdentityNode(); + }); + var rejectedBuilder = new ApplicationDefinitionBuilder(); + rejectedBuilder.AddWorkflow("Main").AddComponent("Value", rejectedContract); + var rejectedDefinition = rejectedBuilder.Build(); + var services = new ServiceCollection(); + services.AddFluxFlow(initial).AddComponent(activeContract); + await using var provider = services.BuildServiceProvider(); + var host = provider.GetRequiredService(); + var access = provider.GetRequiredService(); + (await host.StartAsync()).IsApplied.ShouldBeTrue(); + activeActivations.ShouldBe(1); + var activePorts = access.GetRequiredPorts(); + var input = ApplicationAddress.WorkflowPort("Main", "Value", "Input"); + var output = ApplicationAddress.WorkflowPort("Main", "Value", "Output"); + + var rejected = await host.ApplyAsync("conflicting-contract", rejectedDefinition); + + rejected.IsRejected.ShouldBeTrue(); + rejectedActivations.ShouldBe(0); + var conflictMessage = rejected.Diagnostics.ShouldHaveSingleItem() + .Error.Details!.Value.GetProperty("exceptionMessage").GetString()!; + conflictMessage.ShouldContain("test.identity"); + conflictMessage.ShouldContain("conflicting descriptor registrations"); + host.CurrentDefinition.ShouldBeSameAs(initial); + access.GetRequiredPorts().ShouldBeSameAs(activePorts); + var receive = activePorts.ReceiveAsync(output, TimeSpan.FromSeconds(5)); + (await activePorts.SendAsync(input, FlowMessage.Create("still-active"))) + .Status.ShouldBe(PortSendStatus.Accepted); + (await receive).Message!.Value.ShouldBe("still-active"); + activeActivations.ShouldBe(1); + + await host.StopAsync(); + } + + [Fact] + public async Task Hot_reload_introduces_removes_and_replaces_embedded_contracts_without_rebuilding_services() + { + var alphaActivations = 0; + var betaActivations = 0; + var replacementActivations = 0; + var alpha = CreateStringIdentityContract("test.alpha", _ => + { + alphaActivations++; + return new IdentityNode(); + }); + var beta = CreateStringIdentityContract("test.beta", _ => + { + betaActivations++; + return new IdentityNode(); + }); + var replacementBeta = CreateStringIdentityContract("test.beta", _ => + { + replacementActivations++; + return new IdentityNode(); + }); + var initial = IdentityContractsDefinition(("Alpha", alpha)); + var expanded = IdentityContractsDefinition(("Alpha", alpha), ("Beta", beta)); + var removed = IdentityContractsDefinition(("Beta", beta)); + var replaced = IdentityContractsDefinition(("Beta", replacementBeta)); + var services = new ServiceCollection(); + services.AddFluxFlow(initial); + await using var provider = services.BuildServiceProvider(); + var host = provider.GetRequiredService(); + var access = provider.GetRequiredService(); + + (await host.StartAsync()).IsApplied.ShouldBeTrue(); + alphaActivations.ShouldBe(1); + (await host.ApplyAsync("expanded", expanded)).IsApplied.ShouldBeTrue(); + host.CurrentDefinition.ShouldBeSameAs(expanded); + alphaActivations.ShouldBe(2); + betaActivations.ShouldBe(1); + (await host.ApplyAsync("removed", removed)).IsApplied.ShouldBeTrue(); + host.CurrentDefinition.ShouldBeSameAs(removed); + betaActivations.ShouldBe(2); + (await host.ApplyAsync("replaced", replaced)).IsApplied.ShouldBeTrue(); + host.CurrentDefinition.ShouldBeSameAs(replaced); + replacementActivations.ShouldBe(1); + betaActivations.ShouldBe(2); + var ports = access.GetRequiredPorts(); + var input = ApplicationAddress.WorkflowPort("Main", "Beta", "Input"); + var output = ApplicationAddress.WorkflowPort("Main", "Beta", "Output"); + var receive = ports.ReceiveAsync(output, TimeSpan.FromSeconds(5)); + (await ports.SendAsync(input, FlowMessage.Create("replacement"))) + .Status.ShouldBe(PortSendStatus.Accepted); + (await receive).Message!.Value.ShouldBe("replacement"); + + await host.StopAsync(); + } + + [Fact] + public async Task Failed_contract_replacement_retains_previous_factory_and_route() + { + var activeActivations = 0; + var failedActivations = 0; + var activeContract = CreateStringIdentityContract("test.identity", _ => + { + activeActivations++; + return new IdentityNode(); + }); + var failingContract = CreateStringIdentityContract("test.identity", _ => + { + failedActivations++; + throw new InvalidOperationException("Replacement contract factory failed."); + }); + var initial = IdentityContractsDefinition(("Value", activeContract)); + var replacement = IdentityContractsDefinition(("Value", failingContract)); + var services = new ServiceCollection(); + services.AddFluxFlow(initial); + await using var provider = services.BuildServiceProvider(); + var host = provider.GetRequiredService(); + var access = provider.GetRequiredService(); + (await host.StartAsync()).IsApplied.ShouldBeTrue(); + var activePorts = access.GetRequiredPorts(); + + var failed = await host.ApplyAsync("failed-contract", replacement); + + failed.IsRejected.ShouldBeTrue(); + activeActivations.ShouldBe(1); + failedActivations.ShouldBe(1); + failed.Diagnostics.ShouldHaveSingleItem().Error.Details!.Value + .GetProperty("exceptionMessage").GetString()! + .ShouldContain("Replacement contract factory failed."); + host.CurrentDefinition.ShouldBeSameAs(initial); + access.GetRequiredPorts().ShouldBeSameAs(activePorts); + var input = ApplicationAddress.WorkflowPort("Main", "Value", "Input"); + var output = ApplicationAddress.WorkflowPort("Main", "Value", "Output"); + var receive = activePorts.ReceiveAsync(output, TimeSpan.FromSeconds(5)); + (await activePorts.SendAsync(input, FlowMessage.Create("retained"))) + .Status.ShouldBe(PortSendStatus.Accepted); + (await receive).Message!.Value.ShouldBe("retained"); + + await host.StopAsync(); + } + + [Fact] + public async Task Successful_contract_replacement_retires_captured_factory_closure() + { + await using var context = RunOnTerminatedThread( + static () => CreateContractRetirementContext()); + + ForceFullCollection(); + context.Closure.IsAlive.ShouldBeFalse(); + + await context.Application.StopAsync(); + } + + [Fact] + public async Task Successful_code_predicate_replacement_retires_captured_closure() + { + await using var context = RunOnTerminatedThread( + static () => CreatePredicateRetirementContext()); + + ForceFullCollection(); + context.Closure.IsAlive.ShouldBeFalse(); + + await context.Application.StopAsync(); + } + + [Fact] + public async Task Json_definition_still_requires_explicit_host_registration() { var services = new ServiceCollection(); services.AddFluxFlow(IdentityDefinition("test.identity-legacy")) @@ -222,6 +509,7 @@ public async Task Obsolete_component_type_is_rejected_by_the_runtime_assembler() var started = await host.StartAsync(); + host.CurrentDefinition.ShouldBeNull(); started.IsRejected.ShouldBeTrue(); var diagnostic = started.Diagnostics.ShouldHaveSingleItem(); diagnostic.Stage.ShouldBe(ApplicationUpdateStage.ComponentPreparation); @@ -239,20 +527,18 @@ public async Task Nested_processing_profile_resources_are_mapped_into_component_ var services = new ServiceCollection(); services.AddFluxFlow(ProcessingDefinition()) .AddTestRuntimeAssembler(services => - services.AddFluxFlowComponents().AddRuntimeComponent("test.processing", component => + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.processing", component => { - component.UseFactory(context => - { - captured = context.BindConfiguration(); - var node = new IdentityNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)])); - }); - component.AddInput("Input"); - component.AddOutput("Output"); component.UseProcessing(CompositionProcessingCapabilities.ParallelRelaxedOrder); + component + .UseFactory(context => + { + captured = context.BindConfiguration(); + return new IdentityNode(); + }) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); })); await using var provider = services.BuildServiceProvider(); var host = provider.GetRequiredService(); @@ -274,13 +560,10 @@ public async Task Disposed_assembler_rejects_prepared_generation_adoption_and_cl var services = new ServiceCollection(); services.AddFluxFlow(BlockingSourceDefinition()) .AddTestRuntimeAssembler(services => - services.AddFluxFlowComponents().AddRuntimeComponent("test.blocking-source", component => - { - component.UseFactory(_ => ValueTask.FromResult(ComponentInstance.Create( - source, - outputs: [ComponentPorts.Output("Output", source.Output)]))); - component.AddOutput("Output"); - })); + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.blocking-source", component => + component + .UseFactory(_ => source) + .HasOutput("Output", static node => node.Output))); await using var provider = services.BuildServiceProvider(); var host = provider.GetRequiredService(); var assembler = provider.GetRequiredService(); @@ -299,8 +582,14 @@ public async Task Disposed_assembler_rejects_prepared_generation_adoption_and_cl access.Ports.ShouldBeNull(); } - [Fact] - public async Task Descriptor_that_does_not_match_registration_is_disposed_on_rejection() + [Theory] + [InlineData(AdvancedPortMismatch.Missing)] + [InlineData(AdvancedPortMismatch.Extra)] + [InlineData(AdvancedPortMismatch.Renamed)] + [InlineData(AdvancedPortMismatch.Mistyped)] + [InlineData(AdvancedPortMismatch.WrongSignalKind)] + public async Task Advanced_instance_factory_port_mismatch_is_rejected_and_disposed( + AdvancedPortMismatch mismatch) { var tracker = new DescriptorTracker(); var services = new ServiceCollection(); @@ -316,14 +605,21 @@ public async Task Descriptor_that_does_not_match_registration_is_disposed_on_rej } """)) .AddTestRuntimeAssembler(services => - services.AddFluxFlowComponents().AddRuntimeComponent("test.invalid", component => + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.invalid", component => { - component.UseFactory(_ => + var instance = component.UseInstanceFactory(_ => ValueTask.FromResult( + CreateMismatchedInstance(tracker, mismatch))); + switch (mismatch) { - var node = new TrackedNode(tracker); - return ValueTask.FromResult(ComponentInstance.Create(node)); - }); - component.AddInput("Input"); + case AdvancedPortMismatch.Extra: + break; + case AdvancedPortMismatch.WrongSignalKind: + instance.HasSignalInput("Input"); + break; + default: + instance.HasInput("Input"); + break; + } })); await using var provider = services.BuildServiceProvider(); var host = provider.GetRequiredService(); @@ -332,6 +628,11 @@ public async Task Descriptor_that_does_not_match_registration_is_disposed_on_rej result.IsApplied.ShouldBeFalse(); result.Status.ShouldBe(ApplicationUpdateStatus.Rejected); + result.Diagnostics.ShouldContain(failure => + failure.Stage == ApplicationUpdateStage.ComponentPreparation && + failure.Error.Details!.Value.GetProperty("exceptionMessage").GetString()!.Contains( + "Orders.Invalid", + StringComparison.Ordinal)); tracker.Disposed.ShouldBe(1); provider.GetRequiredService().Ports.ShouldBeNull(); } @@ -355,16 +656,14 @@ public async Task Later_factory_failure_disposes_components_created_earlier_in_p } """)) .AddTestRuntimeAssembler(services => - services.AddFluxFlowComponents().AddRuntimeComponent("test.partial", component => - { + services.AddFluxFlowComponents().Advanced.AddDynamicComponent("test.partial", component => component.UseFactory(_ => { if (Interlocked.Increment(ref factoryCalls) == 2) throw new InvalidOperationException("Factory failed."); - return ValueTask.FromResult(ComponentInstance.Create(new TrackedNode(tracker))); - }); - })); + return new TrackedNode(tracker); + }))); await using var provider = services.BuildServiceProvider(); var host = provider.GetRequiredService(); @@ -420,36 +719,16 @@ public async Task Eager_source_output_is_linked_before_source_start() services.AddSingleton(tracker); services.AddFluxFlow(EagerSourceDefinition()) .AddTestRuntimeAssembler( - services => services.AddFluxFlowComponents() - .AddRuntimeComponent("test.eager-source", component => - { - component.UseFactory(static _ => - { - var source = new EagerSource(); - return ValueTask.FromResult(ComponentInstance.Create( - source, - outputs: - [ - ComponentPorts.Output("Output", source.Output) - ])); - }); - component.AddOutput("Output"); - }) - .AddRuntimeComponent("test.source-recorder", component => - { - component.UseFactory(static context => - { - var node = new SourceRecordingNode( - context.Services.GetRequiredService()); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: - [ - ComponentPorts.Input("Input", node.Input) - ])); - }); - component.AddInput("Input"); - }), + services => services.AddFluxFlowComponents().Advanced + .AddDynamicComponent("test.eager-source", component => + component + .UseFactory(static _ => new EagerSource()) + .HasOutput("Output", static source => source.Output)) + .AddDynamicComponent("test.source-recorder", component => + component + .UseFactory(static context => new SourceRecordingNode( + context.Services.GetRequiredService())) + .HasInput("Input", static node => node.Input)), context => context.Services.AddSingleton( context.HostServices.GetRequiredService())); await using var provider = services.BuildServiceProvider(); @@ -474,21 +753,19 @@ public async Task Application_output_capacity_configures_stable_ports_without_ov options.OutputCapacity = 7; }) .AddTestRuntimeAssembler(services => - services.AddFluxFlowComponents().AddRuntimeComponent( + services.AddFluxFlowComponents().Advanced.AddDynamicComponent( "test.capacity", component => { - component.UseFactory(context => - { - captured = context.BindConfiguration(); - var node = new IdentityNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)])); - }); - component.AddInput("Input"); - component.AddOutput("Output"); + component + .UseFactory(context => + { + captured = context.BindConfiguration(); + return new IdentityNode(); + }) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); })); await using var provider = services.BuildServiceProvider(); var host = provider.GetRequiredService(); @@ -584,104 +861,83 @@ public async Task Fan_in_source_fault_is_reported_once_during_revision_drain() } private static void AddFanInTestComponents(IServiceCollection services) - => services.AddFluxFlowComponents() - .AddRuntimeComponent("test.manual-source", component => - { - component.UseFactory(static context => - { - var source = new ManualSource(); - context.Services.GetRequiredService() - .Add(context.ComponentName, source); - return ValueTask.FromResult(ComponentInstance.Create( - source, - outputs: [ComponentPorts.Output("Output", source.Output)])); - }); - component.AddOutput("Output"); - }) - .AddRuntimeComponent("test.source-recorder", component => - { - component.UseFactory(static context => - { - var node = new SourceRecordingNode( - context.Services.GetRequiredService()); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)])); - }); - component.AddInput("Input"); - }); + => services.AddFluxFlowComponents().Advanced + .AddDynamicComponent("test.manual-source", component => + component + .UseFactory(static context => + { + var source = new ManualSource(); + context.Services.GetRequiredService() + .Add(context.ComponentName, source); + return source; + }) + .HasOutput("Output", static source => source.Output)) + .AddDynamicComponent("test.source-recorder", component => + component + .UseFactory(static context => new SourceRecordingNode( + context.Services.GetRequiredService())) + .HasInput("Input", static node => node.Input)); + + private static ComponentInstance CreateMismatchedInstance( + DescriptorTracker tracker, + AdvancedPortMismatch mismatch) + { + var node = new TrackedNode(tracker); + return mismatch switch + { + AdvancedPortMismatch.Missing => ComponentInstance.Create(node), + AdvancedPortMismatch.Extra => ComponentInstance.Create( + node, + inputs: [ComponentPorts.Input("Extra", node.Input)]), + AdvancedPortMismatch.Renamed => ComponentInstance.Create( + node, + inputs: [ComponentPorts.Input("Other", node.Input)]), + AdvancedPortMismatch.Mistyped => ComponentInstance.Create( + node, + inputs: [ComponentPorts.Input("Input", node.IntegerInput)]), + AdvancedPortMismatch.WrongSignalKind => ComponentInstance.Create( + node, + inputs: [ComponentPorts.Input("Input", node.Input)]), + _ => throw new ArgumentOutOfRangeException(nameof(mismatch)) + }; + } private static void AddTestComponents(IServiceCollection services) - => services.AddFluxFlowComponents() - .AddRuntimeComponent("test.prefix", component => - { - component.UseFactory(static context => - { - var resource = context.GetRequiredResource("Prefix"); - var node = new PrefixNode(resource.Value); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); - }); - component.AddInput("Input"); - component.AddOutput("Output"); - }) - .AddRuntimeComponent("test.revision-events", component => - { - component.UseFactory(static context => - { - var tracker = context.Services.GetRequiredService(); - var node = new RevisionEventNode(tracker); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - events: node.Events)); - }); - component.AddInput("Input"); - }) - .AddRuntimeComponent("test.identity-string", component => - { - component.UseFactory(static _ => - { - var node = new IdentityNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); - }); - component.AddInput("Input"); - component.AddOutput("Output"); - }) - .AddRuntimeComponent("test.identity-integer", component => - { - component.UseFactory(static _ => - { - var node = new IdentityNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)], - events: node.Events)); - }); - component.AddInput("Input"); - component.AddOutput("Output"); - }) - .AddRuntimeComponent("test.final-output", component => - { - component.UseFactory(static _ => - { - var node = new FinalOutputNode(); - return ValueTask.FromResult(ComponentInstance.Create( - node, - inputs: [ComponentPorts.Input("Input", node.Input)], - outputs: [ComponentPorts.Output("Output", node.Output)])); - }); - component.AddInput("Input"); - component.AddOutput("Output"); - }); + => services.AddFluxFlowComponents().Advanced + .AddDynamicComponent("test.prefix", component => + component + .UseFactory(static context => + { + var resource = context.GetRequiredResource("Prefix"); + return new PrefixNode(resource.Value); + }) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Diagnostics", static node => node.Events)) + .AddDynamicComponent("test.revision-events", component => + component + .UseFactory(static context => new RevisionEventNode( + context.Services.GetRequiredService())) + .HasInput("Input", static node => node.Input) + .HasEvents("Events", static node => node.Events)) + .AddDynamicComponent("test.identity-string", component => + component + .UseFactory(static _ => new IdentityNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events)) + .AddDynamicComponent("test.identity-integer", component => + component + .UseFactory(static _ => new IdentityNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events)) + .AddDynamicComponent("test.final-output", component => + component + .UseFactory(static _ => new FinalOutputNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events)); private static void RegisterResources(ApplicationResourceRegistrationContext context) { @@ -795,6 +1051,225 @@ private static ApplicationDefinition CapacityDefinition() } """); + private static ApplicationDefinition CodeFirstRoutingDefinition( + IReadOnlySet auditValues) + { + var identity = CreateStringIdentityContract("test.identity-string"); + var signalContract = ComponentContract.Create( + "test.signal", + static component => component + .UseFactory(static context => new SignalTargetNode( + context.Services.GetRequiredService())) + .HasSignalInput("Signal", static node => node), + static component => new SignalComponentHandle(component)); + var application = new ApplicationDefinitionBuilder(); + application + .AddWorkflow("Main", out var main) + .AddWorkflow("Audit", out var audit); + var source = main.AddComponent("Source", identity); + var priority = main.AddComponent("Priority", identity); + var standard = main.AddComponent("Standard", identity); + var recorder = audit.AddComponent("Recorder", identity); + var signal = audit.AddComponent("Signal", signalContract); + + source.Output + .ConnectTo( + priority.Input, + static value => value == "priority") + .ConnectTo( + standard.Input, + static value => value == "standard") + .ConnectTo( + recorder.Input, + auditValues.Contains) + .ConnectTo( + signal.Signal, + static value => value == "priority"); + return application.Build(); + } + + private static ComponentContract> + CreateStringIdentityContract(string type) + => CreateStringIdentityContract(type, static _ => new IdentityNode()); + + private static ComponentContract> + CreateStringIdentityContract( + string type, + Func> factory) + => ComponentContract.Create( + type, + component => component + .UseFactory(factory) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events), + static component => new InputOutputComponentHandle( + component, + "Input", + "Output", + "Events")); + + private static ApplicationDefinition IdentityContractsDefinition( + params (string Name, + ComponentContract> Contract)[] components) + { + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + foreach (var (name, contract) in components) + workflow.AddComponent(name, contract); + return application.Build(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static ContractRevisionFixture CreateContractRevisionFixture() + { + var closure = new ContractFactoryClosure(); + var contract = CreateStringIdentityContract("test.identity", closure.CreateNode); + return new ContractRevisionFixture( + new MutableDefinitionSource(IdentityContractsDefinition(("Value", contract))), + new WeakReference(closure)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static async Task ReplaceContractRevisionAsync( + FluxFlowApplication host, + MutableDefinitionSource source) + { + source.Definition = IdentityContractsDefinition( + ("Value", CreateStringIdentityContract("test.identity"))); + var replacement = await host.ReloadAsync("contract-replacement"); + + replacement.IsApplied.ShouldBeTrue(string.Join( + Environment.NewLine, + replacement.Diagnostics.Select(static diagnostic => + $"{diagnostic.Stage}: {diagnostic.Error.Code}: {diagnostic.Error.Message}"))); + replacement.PreviousRevision.ShouldNotBeNull(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static PredicateRevisionFixture CreatePredicateRevisionFixture() + { + var closure = new PredicateClosure("allowed"); + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + var source = workflow.AddComponent("Source", "test.identity-string"); + var sink = workflow.AddComponent("Sink", "test.identity-string"); + source.Output("Output").ConnectTo( + sink.Input("Input"), + closure.Matches); + return new PredicateRevisionFixture( + new MutableDefinitionSource(application.Build()), + new WeakReference(closure)); + } + + private static ApplicationDefinition CodeFirstUnlinkedDefinition() + { + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + workflow.AddComponent("Source", "test.identity-string"); + workflow.AddComponent("Sink", "test.identity-string"); + return application.Build(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static async Task ReplacePredicateRevisionAsync( + FluxFlowApplication host, + MutableDefinitionSource source) + { + source.Definition = CodeFirstUnlinkedDefinition(); + var replacement = await host.ReloadAsync("replacement"); + + replacement.IsApplied.ShouldBeTrue(string.Join( + Environment.NewLine, + replacement.Diagnostics.Select(static diagnostic => + $"{diagnostic.Stage}: {diagnostic.Error.Code}: {diagnostic.Error.Message}"))); + replacement.PreviousRevision.ShouldNotBeNull(); + host.CurrentDefinition.ShouldBeSameAs(source.Definition); + host.LastUpdate!.PreviousRevision.ShouldBeNull(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static RetirementAssertionContext CreateContractRetirementContext() + { + var fixture = CreateContractRevisionFixture(); + var services = new ServiceCollection(); + services.AddFluxFlow(fixture.Source, options => options.StartWithHost = false); + var provider = services.BuildServiceProvider(); + + try + { + var application = provider.GetRequiredService(); + application.StartAsync().GetAwaiter().GetResult().IsApplied.ShouldBeTrue(); + fixture.Closure.IsAlive.ShouldBeTrue(); + ReplaceContractRevisionAsync(application, fixture.Source).GetAwaiter().GetResult(); + return new RetirementAssertionContext(provider, application, fixture.Closure); + } + catch + { + provider.DisposeAsync().AsTask().GetAwaiter().GetResult(); + throw; + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static RetirementAssertionContext CreatePredicateRetirementContext() + { + var fixture = CreatePredicateRevisionFixture(); + var services = new ServiceCollection(); + services.AddFluxFlow(fixture.Source, options => options.StartWithHost = false) + .AddTestRuntimeAssembler(AddTestComponents); + var provider = services.BuildServiceProvider(); + + try + { + var application = provider.GetRequiredService(); + application.StartAsync().GetAwaiter().GetResult().IsApplied.ShouldBeTrue(); + fixture.Closure.IsAlive.ShouldBeTrue(); + ReplacePredicateRevisionAsync(application, fixture.Source).GetAwaiter().GetResult(); + return new RetirementAssertionContext(provider, application, fixture.Closure); + } + catch + { + provider.DisposeAsync().AsTask().GetAwaiter().GetResult(); + throw; + } + } + + private static T RunOnTerminatedThread(Func operation) + where T : class + { + T? result = null; + ExceptionDispatchInfo? failure = null; + var thread = new Thread(() => + { + try + { + result = operation(); + } + catch (Exception exception) + { + failure = ExceptionDispatchInfo.Capture(exception); + } + }) + { + IsBackground = true + }; + + thread.Start(); + thread.Join(); + failure?.Throw(); + return result ?? throw new InvalidOperationException( + "The retirement assertion thread completed without a result."); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void ForceFullCollection() + { + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); + GC.WaitForPendingFinalizers(); + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); + } + private static ApplicationDefinition IdentityDefinition(string type) => ApplicationDefinitionJson.Deserialize( $$""" @@ -1106,6 +1581,8 @@ public void Add(string value) private sealed class TrackedNode(DescriptorTracker tracker) : FlowNode { + public BufferBlock> IntegerInput { get; } = new(); + protected override Task ProcessAsync(FlowMessage message) => Task.CompletedTask; @@ -1116,6 +1593,106 @@ protected override ValueTask OnDisposeAsync() } } + private sealed class SignalTracker + { + private readonly TaskCompletionSource _next = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public void Record(object? value) => _next.TrySetResult(value); + + public Task NextAsync() + => _next.Task.WaitAsync(TimeSpan.FromSeconds(5)); + } + + private sealed record PredicateRevisionFixture( + MutableDefinitionSource Source, + WeakReference Closure); + + private sealed record ContractRevisionFixture( + MutableDefinitionSource Source, + WeakReference Closure); + + private sealed class RetirementAssertionContext( + ServiceProvider provider, + FluxFlowApplication application, + WeakReference closure) : IAsyncDisposable + { + public FluxFlowApplication Application { get; } = application; + + public WeakReference Closure { get; } = closure; + + public ValueTask DisposeAsync() => provider.DisposeAsync(); + } + + private sealed class PredicateClosure(string accepted) + { + public bool Matches(string value) => value == accepted; + } + + private sealed class ContractFactoryClosure + { + public IdentityNode CreateNode(ComponentActivationContext _) + => new(); + } + + private sealed class MutableDefinitionSource(ApplicationDefinition definition) + : IApplicationDefinitionSource + { + public ApplicationDefinition Definition { get; set; } = definition; + + public ValueTask LoadAsync( + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(Definition); + } + } + + private sealed class SignalComponentHandle : AuthoredComponentHandle + { + public SignalComponentHandle(ComponentHandle definition) + : base(definition) + => Signal = definition.SignalInput("Signal"); + + public SignalInputPortHandle Signal { get; } + } + + private sealed class SignalTargetNode(SignalTracker tracker) : IFlowNode, IFlowSignalTarget + { + private readonly TaskCompletionSource _completion = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task Completion => _completion.Task; + + public ValueTask SendAsync( + FlowMessage signal, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + tracker.Record(signal.Value); + return ValueTask.FromResult(true); + } + + public void Complete() => _completion.TrySetResult(); + + public void Fault(Exception exception) => _completion.TrySetException(exception); + + public ValueTask DisposeAsync() + { + Complete(); + return ValueTask.CompletedTask; + } + } + + public enum AdvancedPortMismatch + { + Missing, + Extra, + Renamed, + Mistyped, + WrongSignalKind + } + private sealed class RevisionEventNode(RevisionEventTracker tracker) : FlowNode { diff --git a/tests/FluxFlow.Engine.Tests/ApplicationRuntimeConcurrencyTests.cs b/tests/FluxFlow.Engine.Tests/ApplicationRuntimeConcurrencyTests.cs new file mode 100644 index 00000000..24ffe067 --- /dev/null +++ b/tests/FluxFlow.Engine.Tests/ApplicationRuntimeConcurrencyTests.cs @@ -0,0 +1,708 @@ +using System.Threading.Tasks.Dataflow; +using FluxFlow.Composition; +using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; +using FluxFlow.Composition.DependencyInjection; +using FluxFlow.Composition.Model; +using FluxFlow.Data; +using FluxFlow.Engine.Hosting; +using FluxFlow.Engine.Ports; +using FluxFlow.Nodes; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; +using ApplicationResourceRegistrationContext = FluxFlow.Composition.ApplicationResourceRegistrationContext; + +namespace FluxFlow.Engine.Tests; + +public sealed class ApplicationRuntimeConcurrencyTests +{ + private const int RequestBatchCount = 4; + private const int RequestsPerBatch = 16; + private const int RevisionAttemptCount = 8; + private static readonly TimeSpan DeadlockGuard = TimeSpan.FromSeconds(10); + + [Fact] + public async Task Concurrent_requests_in_repeated_batches_preserve_every_value_and_trace_exactly_once() + { + var lifetime = new LifetimeTracker(); + var fixture = CreateRuntimeDefinition("reply:", lifetime); + var services = new ServiceCollection(); + services.AddFluxFlow(fixture.Definition, options => options.StartWithHost = false); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + var assembler = provider.GetRequiredService(); + + (await application.StartAsync()).Status.ShouldBe(ApplicationUpdateStatus.Applied); + var ports = application.Ports; + var runtime = assembler.GetRequiredPorts(); + var rejections = new BufferBlock(); + using var rejectionLink = runtime.Rejections.LinkTo( + rejections, + new DataflowLinkOptions { PropagateCompletion = true }); + var evidence = new List(RequestBatchCount * RequestsPerBatch); + + for (var batch = 0; batch < RequestBatchCount; batch++) + { + var release = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + var requests = Enumerable.Range(0, RequestsPerBatch) + .Select(async index => + { + await release.Task; + var request = FlowMessage.Create($"batch-{batch}:request-{index}"); + var operation = ports.SendAndReceiveAsync( + fixture.Node.Input, + fixture.Node.Output, + request); + var result = await operation.WaitAsync(DeadlockGuard); + return new RequestEvidence(request, result); + }) + .ToArray(); + + release.TrySetResult(true).ShouldBeTrue(); + evidence.AddRange(await Task.WhenAll(requests)); + } + + evidence.Count.ShouldBe(RequestBatchCount * RequestsPerBatch); + evidence.Select(static item => item.Request.Value) + .Distinct(StringComparer.Ordinal).Count().ShouldBe(evidence.Count); + evidence.Select(static item => item.Request.TraceId) + .Distinct().Count().ShouldBe(evidence.Count); + foreach (var item in evidence) + { + item.Result.Status.ShouldBe(PortRequestStatus.Received); + item.Result.InputPort.ShouldBe(fixture.Node.Input.Address); + item.Result.OutputPort.ShouldBe(fixture.Node.Output.Address); + item.Result.Response.ShouldNotBeNull(); + item.Result.Response.TraceId.ShouldBe(item.Request.TraceId); + item.Result.Response.Value.ShouldBe($"reply:{item.Request.Value}"); + } + + runtime.ShouldBeSameAs(assembler.GetRequiredPorts()); + application.Ports.ShouldBeSameAs(ports); + runtime.Status.Ports.ShouldAllBe(static status => status.PendingMessages == 0); + + await application.StopAsync(); + await rejections.Completion.WaitAsync(DeadlockGuard); + Drain(rejections).ShouldBeEmpty(); + lifetime.Created.ShouldBe(1); + lifetime.Disposed.ShouldBe(1); + } + + [Fact] + public async Task Repeated_compatible_reloads_preserve_stable_ports_exact_routing_and_single_retirement() + { + var lifetimes = new List(); + var initialLifetime = new LifetimeTracker(); + lifetimes.Add(initialLifetime); + var currentFixture = CreateRuntimeDefinition("revision-0:", initialLifetime); + var services = new ServiceCollection(); + services.AddFluxFlow(currentFixture.Definition, options => options.StartWithHost = false); + var provider = services.BuildServiceProvider(); + + try + { + var application = provider.GetRequiredService(); + var assembler = provider.GetRequiredService(); + var started = await application.StartAsync(); + started.Status.ShouldBe(ApplicationUpdateStatus.Applied); + var stablePorts = application.Ports; + var stableRuntime = assembler.GetRequiredPorts(); + var stableInput = currentFixture.Node.Input; + var stableOutput = currentFixture.Node.Output; + + await AssertRoutedBatchAsync( + stablePorts, + stableInput, + stableOutput, + revision: 0, + expectedPrefix: "revision-0:"); + + for (var attempt = 1; attempt <= RevisionAttemptCount; attempt++) + { + var previousFixture = currentFixture; + var currentLifetime = new LifetimeTracker(); + lifetimes.Add(currentLifetime); + currentFixture = CreateRuntimeDefinition($"revision-{attempt}:", currentLifetime); + currentFixture.Contract.Descriptor.ShouldNotBeSameAs(previousFixture.Contract.Descriptor); + var previousSnapshot = application.Current; + + var applied = await application.ApplyAsync( + $"compatible-{attempt}", + currentFixture.Definition); + + applied.Status.ShouldBe(ApplicationUpdateStatus.Applied); + applied.RequestedRevisionId.ShouldBe($"compatible-{attempt}"); + applied.PreviousRevision.ShouldBeSameAs(previousSnapshot); + applied.ActiveRevision.ShouldBeSameAs(application.Current); + application.CurrentDefinition.ShouldBeSameAs(currentFixture.Definition); + application.Current!.Sequence.ShouldBe(attempt + 1L); + application.Current.RevisionId.ShouldBe($"compatible-{attempt}"); + application.Ports.ShouldBeSameAs(stablePorts); + assembler.GetRequiredPorts().ShouldBeSameAs(stableRuntime); + stableRuntime.CurrentRevision!.RevisionId.ShouldBe($"compatible-{attempt}"); + stableRuntime.CurrentRevision.Sequence.ShouldBe(attempt + 1L); + lifetimes.Take(attempt).ShouldAllBe(static tracker => tracker.Disposed == 1); + currentLifetime.Created.ShouldBe(1); + currentLifetime.Disposed.ShouldBe(0); + + await AssertRoutedBatchAsync( + stablePorts, + stableInput, + stableOutput, + attempt, + $"revision-{attempt}:"); + } + + await application.StopAsync(); + await application.StopAsync(); + stableRuntime.Status.State.ShouldBe(ApplicationRuntimeState.Disposed); + } + finally + { + await provider.DisposeAsync(); + } + + lifetimes.Count.ShouldBe(RevisionAttemptCount + 1); + lifetimes.ShouldAllBe(static tracker => tracker.Created == 1); + lifetimes.ShouldAllBe(static tracker => tracker.Disposed == 1); + } + + [Fact] + public async Task Repeated_rejected_reloads_preserve_active_route_and_dispose_each_candidate_once() + { + var activeLifetime = new LifetimeTracker(); + var activeResourceLifetime = new LifetimeTracker(); + var activeGuardAttempts = new FactoryAttemptTracker(); + var active = CreateGuardedDefinition( + "active:", + activeLifetime, + activeResourceLifetime, + activeGuardAttempts, + failGuard: false); + var services = new ServiceCollection(); + services.AddFluxFlow(active.Definition, options => options.StartWithHost = false); + await using var provider = services.BuildServiceProvider(); + var application = provider.GetRequiredService(); + var assembler = provider.GetRequiredService(); + + (await application.StartAsync()).Status.ShouldBe(ApplicationUpdateStatus.Applied); + var activeSnapshot = application.Current; + var activeDefinition = application.CurrentDefinition; + var activePorts = application.Ports; + var activeRuntime = assembler.GetRequiredPorts(); + var candidateLifetimes = new List(); + var candidateResourceLifetimes = new List(); + activeLifetime.Created.ShouldBe(2); + activeLifetime.Disposed.ShouldBe(0); + activeResourceLifetime.Created.ShouldBe(1); + activeResourceLifetime.Disposed.ShouldBe(0); + activeGuardAttempts.Attempts.ShouldBe(1); + + for (var attempt = 1; attempt <= RevisionAttemptCount; attempt++) + { + await AssertSingleRouteAsync( + activePorts, + active.Route.Input, + active.Route.Output, + $"before-{attempt}", + "active:"); + var candidateLifetime = new LifetimeTracker(); + candidateLifetimes.Add(candidateLifetime); + var candidateResourceLifetime = new LifetimeTracker(); + candidateResourceLifetimes.Add(candidateResourceLifetime); + var candidateGuardAttempts = new FactoryAttemptTracker(); + var candidate = CreateGuardedDefinition( + $"candidate-{attempt}:", + candidateLifetime, + candidateResourceLifetime, + candidateGuardAttempts, + failGuard: true); + candidate.RouteContract.Descriptor.ShouldNotBeSameAs(active.RouteContract.Descriptor); + + var rejected = await application.ApplyAsync( + $"rejected-{attempt}", + candidate.Definition); + + rejected.Status.ShouldBe(ApplicationUpdateStatus.Rejected); + rejected.RequestedRevisionId.ShouldBe($"rejected-{attempt}"); + rejected.ActiveRevision.ShouldBeSameAs(activeSnapshot); + rejected.PreviousRevision.ShouldBeSameAs(activeSnapshot); + var diagnostic = rejected.Diagnostics.ShouldHaveSingleItem(); + diagnostic.Stage.ShouldBe(ApplicationUpdateStage.ComponentPreparation); + diagnostic.Error.Code.ShouldBe("revision.preparation.failed"); + diagnostic.Error.Details!.Value.GetProperty("exceptionMessage").GetString()! + .ShouldContain($"candidate-{attempt} activation failed"); + application.State.ShouldBe(ApplicationState.Running); + application.Current.ShouldBeSameAs(activeSnapshot); + application.CurrentDefinition.ShouldBeSameAs(activeDefinition); + application.Ports.ShouldBeSameAs(activePorts); + assembler.GetRequiredPorts().ShouldBeSameAs(activeRuntime); + activeRuntime.CurrentRevision!.RevisionId.ShouldBe("initial"); + activeRuntime.CurrentRevision.Sequence.ShouldBe(1); + activeLifetime.Disposed.ShouldBe(0); + activeResourceLifetime.Disposed.ShouldBe(0); + candidateGuardAttempts.Attempts.ShouldBe(1); + candidateLifetime.Created.ShouldBeLessThanOrEqualTo(1); + candidateLifetime.Disposed.ShouldBe(candidateLifetime.Created); + candidateLifetimes.ShouldAllBe(static tracker => tracker.Disposed == tracker.Created); + candidateResourceLifetime.Created.ShouldBe(1); + candidateResourceLifetime.Disposed.ShouldBe(1); + candidateResourceLifetimes.ShouldAllBe(static tracker => + tracker.Created == 1 && tracker.Disposed == 1); + + await AssertSingleRouteAsync( + activePorts, + active.Route.Input, + active.Route.Output, + $"after-{attempt}", + "active:"); + } + + await application.StopAsync(); + await application.StopAsync(); + activeLifetime.Disposed.ShouldBe(2); + activeResourceLifetime.Disposed.ShouldBe(1); + candidateLifetimes.Count.ShouldBe(RevisionAttemptCount); + candidateLifetimes.ShouldAllBe(static tracker => tracker.Disposed == tracker.Created); + candidateResourceLifetimes.Count.ShouldBe(RevisionAttemptCount); + candidateResourceLifetimes.ShouldAllBe(static tracker => + tracker.Created == 1 && tracker.Disposed == 1); + } + + [Fact] + public async Task Stop_during_causally_blocked_processing_drains_every_accepted_message_and_disposes_once() + { + var gate = new ProcessingGate(); + var componentLifetime = new LifetimeTracker(); + var resourceLifetime = new LifetimeTracker(); + var fixture = CreateShutdownDefinition(gate, componentLifetime, resourceLifetime); + var services = new ServiceCollection(); + services.AddFluxFlow(fixture.Definition, options => options.StartWithHost = false); + var provider = services.BuildServiceProvider(); + Task? stop = null; + + try + { + var application = provider.GetRequiredService(); + var assembler = provider.GetRequiredService(); + (await application.StartAsync()).Status.ShouldBe(ApplicationUpdateStatus.Applied); + var activeRuntime = assembler.GetRequiredPorts(); + var observed = await application.Ports.ObserveAsync(fixture.Node.Output, capacity: 8); + observed.Status.ShouldBe(PortObserveStatus.Started); + await using var observation = observed.Observation!; + var values = new[] { "first", "second", "third", "fourth" }; + var collect = ReadExactlyAsync(observation, values.Length); + + foreach (var value in values) + { + var sent = await application.Ports.SendAsync( + fixture.Node.Input, + FlowMessage.Create(value)); + sent.Status.ShouldBe(PortSendStatus.Accepted); + } + + await gate.Entered.WaitAsync(DeadlockGuard); + stop = application.StopAsync().AsTask(); + application.State.ShouldBe(ApplicationState.Stopping); + stop.IsCompleted.ShouldBeFalse(); + componentLifetime.Disposed.ShouldBe(0); + resourceLifetime.Disposed.ShouldBe(0); + + gate.Release(); + await stop.WaitAsync(DeadlockGuard); + var drained = await collect.WaitAsync(DeadlockGuard); + + drained.Select(static message => message.Value).ShouldBe( + values.Select(static value => $"drained:{value}")); + application.State.ShouldBe(ApplicationState.Stopped); + application.Current.ShouldBeNull(); + activeRuntime.Status.State.ShouldBe(ApplicationRuntimeState.Disposed); + activeRuntime.Status.Ports.ShouldAllBe(static status => + status.Availability == ApplicationPortAvailability.Completed && + status.PendingMessages == 0); + (await activeRuntime.SendAsync( + fixture.Node.Input.Address, + FlowMessage.Create("late"))) + .Status.ShouldBe(PortSendStatus.Completed); + componentLifetime.Created.ShouldBe(1); + componentLifetime.Disposed.ShouldBe(1); + resourceLifetime.Created.ShouldBe(1); + resourceLifetime.Disposed.ShouldBe(1); + + await application.StopAsync(); + componentLifetime.Disposed.ShouldBe(1); + resourceLifetime.Disposed.ShouldBe(1); + } + finally + { + gate.Release(); + if (stop is not null) + await stop.WaitAsync(DeadlockGuard); + await provider.DisposeAsync(); + } + + componentLifetime.Disposed.ShouldBe(1); + resourceLifetime.Disposed.ShouldBe(1); + } + + private static RuntimeDefinitionFixture CreateRuntimeDefinition( + string prefix, + LifetimeTracker lifetime) + { + var contract = CreatePrefixContract("test.hardening.runtime", lifetime); + var builder = new ApplicationDefinitionBuilder(); + var node = builder.AddWorkflow("Main").AddComponent( + "Value", + contract, + options => options.Prefix = prefix); + return new RuntimeDefinitionFixture(builder.Build(), node, contract); + } + + private static GuardedDefinitionFixture CreateGuardedDefinition( + string prefix, + LifetimeTracker lifetime, + LifetimeTracker resourceLifetime, + FactoryAttemptTracker guardAttempts, + bool failGuard) + { + const string resourceName = "CandidateOwnership"; + var resourceContract = CreateOwnershipResourceContract( + "test.hardening.rejection-resource", + resourceName, + resourceLifetime); + var routeContract = CreatePrefixContract("test.hardening.route", lifetime); + var guardContract = ComponentContract.Create>( + "test.hardening.guard", + component => + { + component.AddResource("Ownership", isRequired: true); + component + .UseFactory(context => + { + _ = context.GetRequiredResource("Ownership"); + guardAttempts.Record(); + if (failGuard) + { + throw new InvalidOperationException( + $"{context.GetConfigurationValue("Prefix")} activation failed"); + } + + return new TrackedPrefixNode( + context.GetConfigurationValue("Prefix")!, + lifetime); + }) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); + }, + static () => new GuardOptions(), + static (options, definition) => + { + definition.Set("Prefix", options.Prefix); + definition.UseResource("Ownership", options.Resource!.Definition); + }, + CreateInputOutputHandle); + var builder = new ApplicationDefinitionBuilder(); + var resource = builder.AddResource(resourceName, resourceContract); + var workflow = builder.AddWorkflow("Main"); + var route = workflow.AddComponent( + "AValue", + routeContract, + options => options.Prefix = prefix); + workflow.AddComponent( + "ZGuard", + guardContract, + options => + { + options.Prefix = failGuard ? prefix.TrimEnd(':') : "active-guard"; + options.Resource = resource; + }); + return new GuardedDefinitionFixture(builder.Build(), route, routeContract); + } + + private static ComponentContract> + CreatePrefixContract(string type, LifetimeTracker lifetime) + => ComponentContract.Create>( + type, + component => component + .UseFactory(context => new TrackedPrefixNode( + context.GetConfigurationValue("Prefix")!, + lifetime)) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events), + static () => new PrefixOptions(), + static (options, definition) => definition.Set("Prefix", options.Prefix), + CreateInputOutputHandle); + + private static InputOutputComponentHandle CreateInputOutputHandle( + ComponentHandle component) + => new(component, "Input", "Output", "Events"); + + private static ShutdownDefinitionFixture CreateShutdownDefinition( + ProcessingGate gate, + LifetimeTracker componentLifetime, + LifetimeTracker resourceLifetime) + { + var resourceContract = CreateOwnershipResourceContract( + "test.hardening.ownership", + "Ownership", + resourceLifetime); + var componentContract = ComponentContract.Create>( + "test.hardening.blocking", + component => + { + component.AddResource("Ownership", isRequired: true); + component + .UseFactory(context => + { + _ = context.GetRequiredResource("Ownership"); + return new BlockingDrainNode(gate, componentLifetime); + }) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); + }, + static () => new OwnershipComponentOptions(), + static (options, definition) => + definition.UseResource("Ownership", options.Resource!.Definition), + CreateInputOutputHandle); + var builder = new ApplicationDefinitionBuilder(); + var resource = builder.AddResource("Ownership", resourceContract); + var node = builder.AddWorkflow("Main").AddComponent( + "Value", + componentContract, + options => options.Resource = resource); + return new ShutdownDefinitionFixture(builder.Build(), node); + } + + private static ApplicationResourceContract + CreateOwnershipResourceContract( + string type, + string resourceName, + LifetimeTracker lifetime) + => ApplicationResourceContract.Create( + type, + new OwnershipResourceRegistrar(resourceName, lifetime), + static resource => new OwnershipResourceHandle(resource)); + + private static async Task AssertRoutedBatchAsync( + ApplicationPorts ports, + InputPortHandle input, + OutputPortHandle output, + int revision, + string expectedPrefix) + { + for (var index = 0; index < 4; index++) + { + await AssertSingleRouteAsync( + ports, + input, + output, + $"revision-{revision}:value-{index}", + expectedPrefix); + } + } + + private static async Task AssertSingleRouteAsync( + ApplicationPorts ports, + InputPortHandle input, + OutputPortHandle output, + string value, + string expectedPrefix) + { + var request = FlowMessage.Create(value); + var result = await ports.SendAndReceiveAsync(input, output, request) + .WaitAsync(DeadlockGuard); + + result.Status.ShouldBe(PortRequestStatus.Received); + result.Response.ShouldNotBeNull(); + result.Response.TraceId.ShouldBe(request.TraceId); + result.Response.Value.ShouldBe($"{expectedPrefix}{value}"); + } + + private static async Task>> ReadExactlyAsync( + PortObservation observation, + int count) + { + var messages = new List>(count); + while (messages.Count < count) + { + messages.Add(await observation.Messages.ReceiveAsync() + .WaitAsync(DeadlockGuard)); + } + + return messages; + } + + private static IReadOnlyList Drain(BufferBlock source) + { + var values = new List(); + while (source.TryReceive(out var value)) + values.Add(value); + return values; + } + + private sealed record RequestEvidence( + FlowMessage Request, + PortRequestResult Result); + + private sealed record RuntimeDefinitionFixture( + ApplicationDefinition Definition, + InputOutputComponentHandle Node, + ComponentContract> Contract); + + private sealed record GuardedDefinitionFixture( + ApplicationDefinition Definition, + InputOutputComponentHandle Route, + ComponentContract> RouteContract); + + private sealed record ShutdownDefinitionFixture( + ApplicationDefinition Definition, + InputOutputComponentHandle Node); + + private sealed class PrefixOptions + { + public string Prefix { get; set; } = string.Empty; + } + + private sealed class OwnershipComponentOptions + { + public OwnershipResourceHandle? Resource { get; set; } + } + + private sealed class GuardOptions + { + public string Prefix { get; set; } = string.Empty; + + public OwnershipResourceHandle? Resource { get; set; } + } + + private sealed class TrackedPrefixNode : FlowNode + { + private readonly string _prefix; + private readonly LifetimeTracker _lifetime; + + public TrackedPrefixNode(string prefix, LifetimeTracker lifetime) + { + _prefix = prefix; + _lifetime = lifetime; + _lifetime.RecordCreated(); + } + + protected override async Task ProcessAsync(FlowMessage message) + => await EmitAsync(message.With($"{_prefix}{message.Value}"), Stopping) + .ConfigureAwait(false); + + protected override ValueTask OnDisposeAsync() + { + _lifetime.RecordDisposed(); + return ValueTask.CompletedTask; + } + } + + private sealed class BlockingDrainNode : FlowNode + { + private readonly ProcessingGate _gate; + private readonly LifetimeTracker _lifetime; + private int _processed; + + public BlockingDrainNode(ProcessingGate gate, LifetimeTracker lifetime) + { + _gate = gate; + _lifetime = lifetime; + _lifetime.RecordCreated(); + } + + protected override async Task ProcessAsync(FlowMessage message) + { + if (Interlocked.Increment(ref _processed) == 1) + { + _gate.MarkEntered(); + await _gate.Released.ConfigureAwait(false); + } + + await EmitAsync(message.With($"drained:{message.Value}"), Stopping) + .ConfigureAwait(false); + } + + protected override ValueTask OnDisposeAsync() + { + _lifetime.RecordDisposed(); + return ValueTask.CompletedTask; + } + } + + private sealed class ProcessingGate + { + private readonly TaskCompletionSource _entered = + new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _released = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task Entered => _entered.Task; + + public Task Released => _released.Task; + + public void MarkEntered() => _entered.TrySetResult(true); + + public void Release() => _released.TrySetResult(true); + } + + private sealed class LifetimeTracker + { + private int _created; + private int _disposed; + + public int Created => Volatile.Read(ref _created); + + public int Disposed => Volatile.Read(ref _disposed); + + public void RecordCreated() => Interlocked.Increment(ref _created); + + public void RecordDisposed() => Interlocked.Increment(ref _disposed); + } + + private sealed class FactoryAttemptTracker + { + private int _attempts; + + public int Attempts => Volatile.Read(ref _attempts); + + public void Record() => Interlocked.Increment(ref _attempts); + } + + private sealed class OwnershipResourceHandle(ResourceHandle resource) + : AuthoredResourceHandle(resource); + + private sealed class OwnershipResource : IAsyncDisposable + { + private readonly LifetimeTracker _lifetime; + + public OwnershipResource(LifetimeTracker lifetime) + { + _lifetime = lifetime; + _lifetime.RecordCreated(); + } + + public ValueTask DisposeAsync() + { + _lifetime.RecordDisposed(); + return ValueTask.CompletedTask; + } + } + + private sealed class OwnershipResourceRegistrar( + string resourceName, + LifetimeTracker lifetime) + : IApplicationResourceRegistrar + { + public void Register(ApplicationResourceRegistrationContext context) + => context.Services.AddFluxFlowResource( + ApplicationAddress.Resource(resourceName), + _ => new OwnershipResource(lifetime)); + } +} diff --git a/tests/FluxFlow.Engine.Tests/ApplicationRuntimeSignalsTests.cs b/tests/FluxFlow.Engine.Tests/ApplicationRuntimeSignalsTests.cs index 425b5bd7..3d5160f8 100644 --- a/tests/FluxFlow.Engine.Tests/ApplicationRuntimeSignalsTests.cs +++ b/tests/FluxFlow.Engine.Tests/ApplicationRuntimeSignalsTests.cs @@ -6,6 +6,7 @@ using FluxFlow.Data; using FluxFlow.Composition; using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; using FluxFlow.Composition.Links; using FluxFlow.Composition.Model; using FluxFlow.Engine.Ports; @@ -23,6 +24,8 @@ public sealed class ApplicationRuntimeSignalsTests { private static readonly ApplicationAddress Input = ApplicationAddress.WorkflowPort("Main", "Sink", "Input"); + private static readonly ApplicationAddress HealthyInput = + ApplicationAddress.WorkflowPort("Main", "Healthy", "Input"); private static readonly ApplicationAddress Output = ApplicationAddress.WorkflowPort("Main", "Source", "Output"); @@ -123,7 +126,6 @@ public async Task System_event_publication_is_ordered_and_backpressures_when_ful } var blocked = runtime.PublishSystemEventAsync(EventMessage("event-blocked")).AsTask(); - await Task.Delay(50); blocked.IsCompleted.ShouldBeFalse(); slow.AcceptPostponed(); @@ -144,9 +146,7 @@ public async Task Diagnostics_reject_overflow_promptly_and_preserve_accepted_ord for (var index = 1; index <= ApplicationPortRuntimeBuilder.DefaultSystemOutputCapacity; index++) runtime.TryPublishDiagnostic(DiagnosticMessage($"diagnostic-{index}")).ShouldBeTrue(); - var startedAt = Stopwatch.GetTimestamp(); runtime.TryPublishDiagnostic(DiagnosticMessage("overflow")).ShouldBeFalse(); - Stopwatch.GetElapsedTime(startedAt).ShouldBeLessThan(TimeSpan.FromSeconds(1)); slow.AcceptPostponed(); slow.Accepted.Single().Value.Name.ShouldBe("diagnostic-0"); @@ -213,6 +213,93 @@ public async Task Link_condition_failure_emits_a_trace_correlated_system_event_a sink.TryReceive(out _).ShouldBeFalse(); } + [Fact] + public async Task Code_predicate_exception_is_route_local_reports_endpoints_and_later_messages_continue() + { + var distinctive = new InvalidOperationException("typed predicate failed"); + await using var runtime = new ApplicationPortRuntimeBuilder() + .AddOutput(Output) + .AddInput(Input) + .AddInput(HealthyInput) + .Build(); + var failingSink = new BufferBlock>(); + var healthySink = new BufferBlock>(); + await using var failingAttachment = await runtime.AttachInputAsync(Input, failingSink); + await using var healthyAttachment = await runtime.AttachInputAsync( + HealthyInput, + healthySink); + var links = CompileTypedLinks(_ => throw distinctive); + using var failingRoute = runtime.Connect(links.Single(static link => link.IsConditional)); + using var healthyRoute = runtime.Connect(links.Single(static link => !link.IsConditional)); + var source = new BufferBlock>(); + using var sourceAttachment = runtime.AttachOutput(Output, source); + var eventReceive = runtime.ReceiveAsync( + ApplicationAddress.SystemEvents, + TimeSpan.FromSeconds(5)); + var first = FlowMessage.Create("first"); + + source.Post(first).ShouldBeTrue(); + + (await healthySink.ReceiveAsync().WaitAsync(TimeSpan.FromSeconds(5))) + .ShouldBeSameAs(first); + var systemEvent = (await eventReceive).Message!; + systemEvent.Value.Name.ShouldBe(ApplicationSystemEventNames.LinkConditionFailed); + systemEvent.Value.Subject.ShouldBe(Output.Value); + systemEvent.Value.Error!.Message.ShouldBe(distinctive.Message); + systemEvent.Value.Error.Details!.Value.GetProperty("port").GetString() + .ShouldBe(Output.Value); + systemEvent.Value.Error.Details.Value.GetProperty("relatedPort").GetString() + .ShouldBe(Input.Value); + systemEvent.TraceId.ShouldBe(first.TraceId); + systemEvent.CausationId.ShouldBe(first.MessageId); + failingSink.TryReceive(out _).ShouldBeFalse(); + runtime.Status.State.ShouldBe(ApplicationRuntimeState.Active); + + var later = FlowMessage.Create("later"); + source.Post(later).ShouldBeTrue(); + (await healthySink.ReceiveAsync().WaitAsync(TimeSpan.FromSeconds(5))) + .ShouldBeSameAs(later); + runtime.Status.State.ShouldBe(ApplicationRuntimeState.Active); + } + + [Fact] + public async Task Conditional_error_skips_payload_predicate_while_unconditional_sibling_receives() + { + var predicateCalls = 0; + await using var runtime = new ApplicationPortRuntimeBuilder() + .AddOutput(Output) + .AddInput(Input) + .AddInput(HealthyInput) + .Build(); + var conditionalSink = new BufferBlock>(); + var unconditionalSink = new BufferBlock>(); + await using var conditionalAttachment = await runtime.AttachInputAsync(Input, conditionalSink); + await using var unconditionalAttachment = await runtime.AttachInputAsync( + HealthyInput, + unconditionalSink); + var links = CompileTypedLinks(_ => + { + predicateCalls++; + return true; + }); + using var conditionalRoute = runtime.Connect( + links.Single(static link => link.IsConditional)); + using var unconditionalRoute = runtime.Connect( + links.Single(static link => !link.IsConditional)); + var source = new BufferBlock>(); + using var sourceAttachment = runtime.AttachOutput(Output, source); + var error = FlowMessage.CreateError( + new DataFlowError("test", "failure", "testing")); + + source.Post(error).ShouldBeTrue(); + + (await unconditionalSink.ReceiveAsync().WaitAsync(TimeSpan.FromSeconds(5))) + .ShouldBeSameAs(error); + predicateCalls.ShouldBe(0); + conditionalSink.TryReceive(out _).ShouldBeFalse(); + runtime.Status.State.ShouldBe(ApplicationRuntimeState.Active); + } + [Fact] public async Task Source_fault_emits_component_event_and_only_makes_that_output_unavailable() { @@ -346,19 +433,22 @@ public async Task Diagnostic_system_link_rejection_is_reported_once_without_recu var target = new PostponedTarget>(); await using var targetAttachment = await runtime.AttachInputAsync(Input, target); using var route = runtime.Connect(CompileSystemDiagnosticLink()); + var recordedRejections = new BufferBlock(); + using var rejectionLink = runtime.Rejections.LinkTo( + recordedRejections, + new DataflowLinkOptions { PropagateCompletion = true }); runtime.TryPublishDiagnostic(DiagnosticMessage("first")).ShouldBeTrue(); await target.Offered.WaitAsync(TimeSpan.FromSeconds(5)); runtime.TryPublishDiagnostic(DiagnosticMessage("second")).ShouldBeTrue(); - var rejection = await runtime.Rejections.ReceiveAsync().WaitAsync(TimeSpan.FromSeconds(5)); + var rejection = await recordedRejections.ReceiveAsync().WaitAsync(TimeSpan.FromSeconds(5)); rejection.Reason.ShouldBe(ApplicationPortRejectionReason.Full); rejection.RelatedPort.ShouldBe(ApplicationAddress.SystemDiagnostics); - await Task.Delay(100); - ((IReceivableSourceBlock)runtime.Rejections) - .TryReceive(out _) - .ShouldBeFalse(); target.AcceptPostponed(); + await runtime.DisposeAsync(); + await recordedRejections.Completion.WaitAsync(TimeSpan.FromSeconds(5)); + recordedRejections.TryReceive(out _).ShouldBeFalse(); } [Fact] @@ -559,6 +649,36 @@ private static CompiledApplicationLink CompileFailingLink() return result.Links.Single(); } + private static IReadOnlyList CompileTypedLinks( + Func when) + { + var application = new ApplicationDefinitionBuilder(); + var workflow = application.AddWorkflow("Main"); + var source = workflow.AddComponent("Source", "source"); + var sink = workflow.AddComponent("Sink", "sink"); + var healthy = workflow.AddComponent("Healthy", "sink"); + source.Output("Output") + .ConnectTo(sink.Input("Input"), when) + .ConnectTo(healthy.Input("Input")); + var catalog = new ComponentCatalog( + [ + new ComponentDescriptor( + "source", + UnusedFactory, + outputs: [ComponentPorts.Metadata("Output")]), + new ComponentDescriptor( + "sink", + UnusedFactory, + inputs: [ComponentPorts.Metadata("Input")]) + ]); + + var result = new ApplicationLinkCompiler(catalog).Compile(application.Build()); + + result.IsValid.ShouldBeTrue(string.Join(Environment.NewLine, result.Diagnostics)); + result.Links.Count.ShouldBe(2); + return result.Links; + } + private static CompiledApplicationLink CompileSystemDiagnosticLink() { var definition = ApplicationDefinitionJson.Deserialize( diff --git a/tests/FluxFlow.Engine.Tests/CompositionServiceProviderSnapshotTests.cs b/tests/FluxFlow.Engine.Tests/CompositionServiceProviderSnapshotTests.cs index eaa8f168..ea3ed105 100644 --- a/tests/FluxFlow.Engine.Tests/CompositionServiceProviderSnapshotTests.cs +++ b/tests/FluxFlow.Engine.Tests/CompositionServiceProviderSnapshotTests.cs @@ -108,6 +108,69 @@ public async Task Owned_services_are_disposed_once_while_explicit_bridges_remain Should.Throw(() => snapshot.GetService(typeof(TrackedService))); } + [Fact] + public async Task Snapshot_primary_services_override_host_fallback_for_unkeyed_and_keyed_resolution() + { + var hostUnkeyed = new TrackedService(); + var hostKeyed = new TrackedService(); + var hostServices = new ServiceCollection(); + hostServices.AddSingleton(hostUnkeyed); + hostServices.AddKeyedSingleton("shared", hostKeyed); + await using var hostProvider = hostServices.BuildServiceProvider(); + var revisionUnkeyed = new TrackedService(); + var revisionKeyed = new TrackedService(); + var revisionServices = new ServiceCollection(); + revisionServices.AddSingleton(_ => revisionUnkeyed); + revisionServices.AddKeyedSingleton( + "shared", + (_, _) => revisionKeyed); + var snapshot = new CompositionServiceProviderSnapshotBuilder() + .AddServices(revisionServices) + .Build( + CompositionProviderBoundary.ResourceRevision, + "resources-primary", + fallbackProvider: hostProvider); + + snapshot.GetRequiredService().ShouldBeSameAs(revisionUnkeyed); + snapshot.GetRequiredKeyedService("shared") + .ShouldBeSameAs(revisionKeyed); + + await snapshot.DisposeAsync(); + + revisionUnkeyed.DisposeCount.ShouldBe(1); + revisionKeyed.DisposeCount.ShouldBe(1); + hostUnkeyed.DisposeCount.ShouldBe(0); + hostKeyed.DisposeCount.ShouldBe(0); + } + + [Fact] + public async Task Snapshot_resolves_unkeyed_and_keyed_host_fallback_without_taking_ownership() + { + var hostUnkeyed = new TrackedService(); + var hostKeyed = new TrackedService(); + var hostServices = new ServiceCollection(); + hostServices.AddSingleton(hostUnkeyed); + hostServices.AddKeyedSingleton("host-only", hostKeyed); + await using var hostProvider = hostServices.BuildServiceProvider(); + var snapshot = new CompositionServiceProviderSnapshotBuilder() + .Build( + CompositionProviderBoundary.ResourceRevision, + "resources-fallback", + fallbackProvider: hostProvider); + + snapshot.GetRequiredService().ShouldBeSameAs(hostUnkeyed); + snapshot.GetRequiredKeyedService("host-only") + .ShouldBeSameAs(hostKeyed); + + await snapshot.DisposeAsync(); + + hostUnkeyed.DisposeCount.ShouldBe(0); + hostKeyed.DisposeCount.ShouldBe(0); + hostProvider.GetRequiredService().ShouldBeSameAs(hostUnkeyed); + hostProvider.GetRequiredKeyedService("host-only") + .ShouldBeSameAs(hostKeyed); + } + [Fact] public async Task External_host_snapshot_never_takes_provider_ownership() { diff --git a/tests/FluxFlow.Fluent.Tests/FlowBuilderTests.cs b/tests/FluxFlow.Fluent.Tests/FlowBuilderTests.cs index 1827d738..95787da8 100644 --- a/tests/FluxFlow.Fluent.Tests/FlowBuilderTests.cs +++ b/tests/FluxFlow.Fluent.Tests/FlowBuilderTests.cs @@ -5,6 +5,46 @@ namespace FluxFlow.Fluent.Tests; public sealed class FlowBuilderTests { + [Fact] + public async Task Then_and_To_compile_to_canonical_components_catalog_ports_and_links() + { + await using var flow = Flow + .From(new StringSourceNode(["value"])) + .Then(new UppercaseNode()) + .To(new CollectSinkNode(new StringCollector())) + .Build(); + + var definition = flow.Definition; + var components = definition.Workflows["main"].Components; + + components.Keys.ShouldBe( + ["node0001", "node0002", "node0003"], + ignoreOrder: true); + components["node0001"].Type.ShouldBe("fluent.node.0001"); + components["node0002"].Type.ShouldBe("fluent.node.0002"); + components["node0003"].Type.ShouldBe("fluent.node.0003"); + definition.ComponentDescriptors.Select(static descriptor => descriptor.Type) + .ShouldBe([ + "fluent.node.0001", + "fluent.node.0002", + "fluent.node.0003" + ]); + definition.ComponentDescriptors[0].Inputs.ShouldBeEmpty(); + definition.ComponentDescriptors[0].Outputs.Keys.ShouldBe(["Output", "Events"]); + definition.ComponentDescriptors[1].Inputs.Keys.ShouldBe(["Input"]); + definition.ComponentDescriptors[1].Outputs.Keys.ShouldBe(["Output", "Events"]); + definition.ComponentDescriptors[2].Inputs.Keys.ShouldBe(["Input"]); + definition.ComponentDescriptors[2].Outputs.Keys.ShouldBe(["Output", "Events"]); + definition.Links.Count.ShouldBe(2); + definition.Links[0].Source.Value.ShouldBe("main.node0001.Output"); + definition.Links[0].Target.Value.ShouldBe("main.node0002.Input"); + definition.Links[0].MessageType.ShouldBe(typeof(string)); + definition.Links[1].Source.Value.ShouldBe("main.node0002.Output"); + definition.Links[1].Target.Value.ShouldBe("main.node0003.Input"); + definition.Links[1].MessageType.ShouldBe(typeof(string)); + definition.ApplicationResourceContracts.ShouldBeEmpty(); + } + [Fact] public async Task Linear_flow_runs_source_through_node_to_sink() { @@ -117,15 +157,27 @@ public async Task StopAsync_completes_an_unbounded_source() } [Fact] - public async Task Graph_exposes_aggregated_event_stream_and_runtime() + public async Task Graph_exposes_canonical_definition_application_and_aggregated_events_only() { await using var flow = Flow - .From(new StringSourceNode(["x"])) + .From(new TickingSourceNode()) .To(new CollectSinkNode(new StringCollector())) .Build(); flow.Events.ShouldNotBeNull(); - flow.Runtime.ShouldNotBeNull(); + flow.Application.ShouldNotBeNull(); + flow.Application.CurrentDefinition.ShouldBeNull(); + flow.Definition.Workflows.Keys.ShouldBe(["main"]); + flow.Definition.Workflows["main"].Components.Count.ShouldBe(2); + flow.Definition.ComponentDescriptors.Count.ShouldBe(2); + flow.Definition.Links.ShouldHaveSingleItem(); + typeof(FlowGraph).GetProperty("Runtime").ShouldBeNull(); + + await flow.StartAsync(); + + flow.Application.CurrentDefinition.ShouldBeSameAs(flow.Definition); + await flow.StopAsync(new CancellationTokenSource(TimeSpan.FromSeconds(5)).Token); + await flow.Completion.WaitAsync(TimeSpan.FromSeconds(5)); } [Fact] diff --git a/tests/FluxFlow.Fluent.Tests/FlowObservationTests.cs b/tests/FluxFlow.Fluent.Tests/FlowObservationTests.cs index 4f25570f..f63b2cee 100644 --- a/tests/FluxFlow.Fluent.Tests/FlowObservationTests.cs +++ b/tests/FluxFlow.Fluent.Tests/FlowObservationTests.cs @@ -48,6 +48,48 @@ public async Task Flow_without_observers_still_completes_when_a_node_errors() collector.Items.ShouldBeEmpty(); } + [Fact] + public async Task Error_messages_remain_observable_workflow_data_on_the_canonical_graph() + { + var errors = new ErrorCollector(); + + await using var flow = Flow + .From(new StringSourceNode(["value"])) + .Then(new FaultingNode("expected failure")) + .To(new CollectErrorSinkNode(errors)) + .Build(); + + await flow.StartAsync(); + await flow.Completion.WaitAsync(TimeSpan.FromSeconds(5)); + + var error = errors.Items.ShouldHaveSingleItem(); + error.Code.ShouldBe("node.processing_failed"); + error.Message.ShouldBe("expected failure"); + error.Category.ShouldBe("processing"); + error.IsTransient.ShouldBeFalse(); + error.Details.ShouldNotBeNull() + .GetProperty("exceptionType").GetString() + .ShouldBe(typeof(InvalidOperationException).FullName); + } + + [Fact] + public async Task Throwing_event_observer_is_isolated_from_canonical_workflow_delivery() + { + var collector = new StringCollector(); + + await using var flow = Flow + .From(new StringSourceNode(["value"])) + .OnEvent(static _ => throw new InvalidOperationException("observer failure")) + .Then(new EventNode("observed")) + .To(new CollectSinkNode(collector)) + .Build(); + + await flow.StartAsync(); + await flow.Completion.WaitAsync(TimeSpan.FromSeconds(5)); + + collector.Items.ShouldBe(["value"]); + } + [Fact] public void OnEvent_rejects_a_null_handler() { diff --git a/tests/FluxFlow.Fluent.Tests/TestFlowNodes.cs b/tests/FluxFlow.Fluent.Tests/TestFlowNodes.cs index 3418907f..d0da0623 100644 --- a/tests/FluxFlow.Fluent.Tests/TestFlowNodes.cs +++ b/tests/FluxFlow.Fluent.Tests/TestFlowNodes.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks.Dataflow; +using FluxFlow.Data; using FluxFlow.Nodes; namespace FluxFlow.Fluent.Tests; @@ -28,6 +29,26 @@ public void Add(string item) } } +internal sealed class ErrorCollector +{ + private readonly List _items = []; + + public IReadOnlyList Items + { + get + { + lock (_items) + return _items.ToArray(); + } + } + + public void Add(FlowError error) + { + lock (_items) + _items.Add(error); + } +} + /// Emits a fixed set of messages in order, then completes. internal sealed class StringSourceNode(IReadOnlyList messages) : FlowSource { @@ -122,6 +143,18 @@ protected override Task ProcessAsync(FlowMessage message) => throw new InvalidOperationException(errorMessage); } +internal sealed class CollectErrorSinkNode(ErrorCollector collector) : FlowNode +{ + protected override bool HandlesErrors => true; + + protected override Task ProcessAsync(FlowMessage message) + { + if (message.Error is not null) + collector.Add(message.Error); + return Task.CompletedTask; + } +} + /// Emits a named event for each message, then passes the message through unchanged. internal sealed class EventNode(string eventName) : FlowNode { diff --git a/tests/FluxFlow.Release.Tests/CodeFirstApplicationAuthoringConventionTests.cs b/tests/FluxFlow.Release.Tests/CodeFirstApplicationAuthoringConventionTests.cs new file mode 100644 index 00000000..194f614d --- /dev/null +++ b/tests/FluxFlow.Release.Tests/CodeFirstApplicationAuthoringConventionTests.cs @@ -0,0 +1,444 @@ +using System.Reflection; +using FluxFlow.Composition; +using FluxFlow.Composition.Addressing; +using FluxFlow.Composition.Authoring; +using FluxFlow.Composition.Links; +using FluxFlow.Composition.Model; +using Shouldly; +using Xunit; + +namespace FluxFlow.Release.Tests; + +public sealed class CodeFirstApplicationAuthoringConventionTests +{ + [Fact] + public void Executable_resource_typed_port_and_advanced_registration_surfaces_are_explicit() + { + var resourceFactory = typeof(ApplicationResourceContract); + var simpleResourceContract = typeof(ApplicationResourceContract<>); + var configuredResourceContract = typeof(ApplicationResourceContract<,>); + + resourceFactory.IsAbstract.ShouldBeTrue(); + resourceFactory.IsSealed.ShouldBeFalse(); + resourceFactory.GetConstructors(BindingFlags.Public | BindingFlags.Instance) + .ShouldBeEmpty(); + resourceFactory.GetProperty(nameof(ApplicationResourceContract.Type))! + .SetMethod.ShouldBeNull(); + resourceFactory.GetProperty("Registrar", BindingFlags.Public | BindingFlags.Instance) + .ShouldBeNull(); + AssertResourceContractShape(simpleResourceContract, handleParameterIndex: 0); + AssertResourceContractShape(configuredResourceContract, handleParameterIndex: 1); + + var createMethods = resourceFactory.GetMethods( + BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) + .Where(static method => method.Name == nameof(ApplicationResourceContract.Create)) + .OrderBy(static method => method.GetGenericArguments().Length) + .ToArray(); + createMethods.Length.ShouldBe(2); + AssertResourceCreateShape(createMethods[0], configured: false); + AssertResourceCreateShape(createMethods[1], configured: true); + + var customHandleConstructor = typeof(AuthoredResourceHandle) + .GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance) + .ShouldHaveSingleItem(); + customHandleConstructor.IsFamily.ShouldBeTrue(); + customHandleConstructor.GetParameters() + .Select(static parameter => parameter.ParameterType) + .ShouldBe([typeof(ResourceHandle)]); + var rawDefinition = typeof(AuthoredResourceHandle) + .GetProperty(nameof(AuthoredResourceHandle.Definition))!; + rawDefinition.PropertyType.ShouldBe(typeof(ResourceHandle)); + rawDefinition.GetMethod!.IsPublic.ShouldBeTrue(); + rawDefinition.SetMethod.ShouldBeNull(); + + var contracts = typeof(ApplicationDefinition) + .GetProperty(nameof(ApplicationDefinition.ApplicationResourceContracts))!; + contracts.PropertyType.ShouldBe( + typeof(IReadOnlyList)); + contracts.GetMethod!.IsPublic.ShouldBeTrue(); + contracts.SetMethod.ShouldBeNull(); + + var root = ReleaseTestPaths.FindRepositoryRoot(); + var applicationPorts = File.ReadAllText(Path.Combine( + root, + "src", + "FluxFlow.Engine", + "ApplicationPorts.cs")); + applicationPorts.ShouldContain("InputPortHandle input"); + applicationPorts.ShouldContain("SignalInputPortHandle input"); + applicationPorts.ShouldContain("OutputPortHandle output"); + applicationPorts.ShouldContain("InputPortHandle input"); + applicationPorts.ShouldContain("OutputPortHandle output"); + applicationPorts.ShouldContain("return SendAsync(input.Address"); + applicationPorts.ShouldContain("return ReceiveAsync(output.Address"); + applicationPorts.ShouldContain("return ObserveAsync(output.Address"); + applicationPorts.ShouldNotContain("public ValueTask Attach"); + applicationPorts.ShouldNotContain("public IDisposable Attach"); + + var normalRegistrationMethods = typeof(FluxFlowRegistrationBuilder).GetMethods( + BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); + normalRegistrationMethods.ShouldNotContain(static method => + method.Name == "AddRuntimeComponent" || + method.Name == "AddDynamicComponent"); + typeof(FluxFlowRegistrationBuilder).GetProperty(nameof(FluxFlowRegistrationBuilder.Advanced))! + .PropertyType.ShouldBe(typeof(AdvancedFluxFlowRegistrationBuilder)); + var dynamicMethod = typeof(AdvancedFluxFlowRegistrationBuilder).GetMethods( + BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .ShouldHaveSingleItem(); + dynamicMethod.Name.ShouldBe(nameof(AdvancedFluxFlowRegistrationBuilder.AddDynamicComponent)); + dynamicMethod.ReturnType.ShouldBe(typeof(AdvancedFluxFlowRegistrationBuilder)); + dynamicMethod.GetParameters().Select(static parameter => parameter.ParameterType) + .ShouldBe([ + typeof(string), + typeof(Action) + ]); + } + + [Fact] + public void Typed_code_first_public_surface_matches_the_complete_contract() + { + var assembly = typeof(ApplicationDefinitionBuilder).Assembly; + var factoryType = typeof(ComponentContract); + var simpleContract = typeof(ComponentContract<>); + var configuredContract = typeof(ComponentContract<,>); + + factoryType.IsAbstract.ShouldBeTrue(); + factoryType.IsSealed.ShouldBeFalse(); + factoryType.GetConstructors(BindingFlags.Public | BindingFlags.Instance) + .ShouldBeEmpty(); + factoryType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance) + .ShouldHaveSingleItem().IsFamilyAndAssembly.ShouldBeTrue(); + AssertContractShape(simpleContract, handleParameterIndex: 0); + AssertContractShape(configuredContract, handleParameterIndex: 1); + assembly.GetType( + "FluxFlow.Composition.Authoring.ComponentAuthoringContract", + throwOnError: false) + .ShouldBeNull(); + assembly.GetType( + "FluxFlow.Composition.Authoring.ComponentAuthoringContract`1", + throwOnError: false) + .ShouldBeNull(); + assembly.GetType( + "FluxFlow.Composition.Authoring.ComponentAuthoringContract`2", + throwOnError: false) + .ShouldBeNull(); + factoryType.GetProperty(nameof(ComponentContract.Type))!.SetMethod.ShouldBeNull(); + factoryType.GetProperty(nameof(ComponentContract.Descriptor))!.PropertyType + .ShouldBe(typeof(ComponentDescriptor)); + factoryType.GetProperty(nameof(ComponentContract.Descriptor))!.SetMethod.ShouldBeNull(); + var customHandleConstructor = typeof(AuthoredComponentHandle) + .GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance) + .ShouldHaveSingleItem(); + customHandleConstructor.IsFamily.ShouldBeTrue( + "application and family assemblies must be able to define meaningful custom handles."); + customHandleConstructor.GetParameters() + .Select(static parameter => parameter.ParameterType) + .ShouldBe([typeof(ComponentHandle)]); + var rawDefinition = typeof(AuthoredComponentHandle).GetProperty("Definition")!; + rawDefinition.PropertyType.ShouldBe(typeof(ComponentHandle)); + rawDefinition.GetMethod!.IsPublic.ShouldBeTrue(); + rawDefinition.SetMethod.ShouldBeNull(); + + var createMethods = factoryType.GetMethods( + BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) + .Where(static method => method.Name == "Create") + .OrderBy(static method => method.GetGenericArguments().Length) + .ToArray(); + createMethods.Length.ShouldBe(2); + AssertCreateShape(createMethods[0], configured: false); + AssertCreateShape(createMethods[1], configured: true); + + var componentDescriptors = typeof(ApplicationDefinition) + .GetProperty(nameof(ApplicationDefinition.ComponentDescriptors))!; + componentDescriptors.PropertyType.ShouldBe(typeof(IReadOnlyList)); + componentDescriptors.GetMethod!.IsPublic.ShouldBeTrue(); + componentDescriptors.SetMethod.ShouldBeNull(); + var typedAddComponents = typeof(WorkflowDefinitionBuilder) + .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(static method => method.Name == nameof(WorkflowDefinitionBuilder.AddComponent)) + .Where(static method => method.GetParameters().Any(parameter => + parameter.ParameterType.IsGenericType && + (parameter.ParameterType.GetGenericTypeDefinition() == typeof(ComponentContract<>) || + parameter.ParameterType.GetGenericTypeDefinition() == typeof(ComponentContract<,>)))) + .ToArray(); + typedAddComponents.Length.ShouldBe(4); + + var links = typeof(ApplicationDefinition).GetProperty("Links")!; + links.CanRead.ShouldBeTrue(); + links.SetMethod.ShouldBeNull(); + links.PropertyType.IsGenericType.ShouldBeTrue(); + links.PropertyType.GetGenericTypeDefinition().ShouldBe(typeof(IReadOnlyList<>)); + var linkType = links.PropertyType.GetGenericArguments().ShouldHaveSingleItem(); + linkType.Name.ShouldBe("ApplicationLinkDefinition"); + linkType.IsPublic.ShouldBeTrue(); + linkType.IsSealed.ShouldBeTrue(); + linkType.GetConstructors(BindingFlags.Public | BindingFlags.Instance).ShouldBeEmpty(); + + var linkProperties = linkType.GetProperties( + BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .OrderBy(static property => property.Name, StringComparer.Ordinal) + .ToArray(); + linkProperties.Select(static property => property.Name).ShouldBe( + [ + "ConditionExpression", + "DeclarationSide", + "IsConditional", + "MessageType", + "Source", + "Target" + ]); + linkProperties.ShouldAllBe(static property => + property.CanRead && property.SetMethod == null); + linkType.GetProperty("Source")!.PropertyType.ShouldBe(typeof(ApplicationAddress)); + linkType.GetProperty("Target")!.PropertyType.ShouldBe(typeof(ApplicationAddress)); + linkType.GetProperty("MessageType")!.PropertyType.ShouldBe(typeof(Type)); + linkType.GetProperty("ConditionExpression")!.PropertyType.ShouldBe(typeof(string)); + linkType.GetProperty("IsConditional")!.PropertyType.ShouldBe(typeof(bool)); + linkType.GetProperty("DeclarationSide")!.PropertyType + .ShouldBe(typeof(ApplicationLinkDeclarationSide)); + + AssertConnectionTriplets(typeof(OutputPortHandle<>), "ConnectTo", direct: true); + AssertConnectionTriplets(typeof(WorkflowDefinitionBuilder), "Connect", direct: false); + AssertConnectionTriplets(typeof(ApplicationDefinitionBuilder), "Connect", direct: false); + } + + [Fact] + public void Code_first_builder_public_surface_has_no_serialization_export_designer_or_async_predicate_API() + { + var publicTypes = typeof(ApplicationDefinitionBuilder).Assembly + .GetExportedTypes() + .Where(static type => type.Namespace is not null && + type.Namespace.StartsWith("FluxFlow.Composition", StringComparison.Ordinal)) + .ToArray(); + var graphAuthoringMethods = publicTypes + .Where(static type => IsCodeFirstGraphSurface(type)) + .SelectMany(static type => type.GetMethods( + BindingFlags.Public | + BindingFlags.Instance | + BindingFlags.Static | + BindingFlags.DeclaredOnly)) + .ToArray(); + + graphAuthoringMethods.ShouldNotContain(static method => + method.Name.Contains("Json", StringComparison.OrdinalIgnoreCase) || + method.Name.Contains("Serialize", StringComparison.OrdinalIgnoreCase) || + method.Name.Contains("Export", StringComparison.OrdinalIgnoreCase) || + method.Name.Contains("Designer", StringComparison.OrdinalIgnoreCase)); + graphAuthoringMethods.ShouldNotContain(static method => + method.ReturnType == typeof(Task) || + method.ReturnType == typeof(ValueTask) || + method.ReturnType.IsGenericType && + (method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>) || + method.ReturnType.GetGenericTypeDefinition() == typeof(ValueTask<>))); + graphAuthoringMethods + .SelectMany(static method => method.GetParameters()) + .ShouldNotContain(static parameter => + parameter.ParameterType.IsGenericType && + parameter.ParameterType.GetGenericTypeDefinition() == typeof(System.Linq.Expressions.Expression<>)); + typeof(ApplicationDefinitionBuilder) + .GetMethod(nameof(ApplicationDefinitionBuilder.Build), Type.EmptyTypes)! + .ReturnType.ShouldBe(typeof(ApplicationDefinition)); + } + + private static bool IsCodeFirstGraphSurface(Type type) + => type.Namespace == typeof(ApplicationDefinitionBuilder).Namespace && + (type == typeof(ApplicationDefinitionBuilder) || + type == typeof(WorkflowDefinitionBuilder) || + type == typeof(ComponentHandle) || + type == typeof(AuthoredComponentHandle) || + type.Name.StartsWith("ComponentContract", StringComparison.Ordinal) || + type.Name.EndsWith("PortHandle", StringComparison.Ordinal)); + + [Fact] + public void Sample_workspace_uses_typed_contract_handles_without_raw_link_reconstruction() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var source = File.ReadAllText(Path.Combine( + root, + "samples", + "FluxFlow.SampleApp", + "SampleWorkspaceDefinition.cs")); + + source.ShouldContain("new ApplicationDefinitionBuilder()"); + source.ShouldContain(".AddWorkflow("); + source.ShouldContain(".AddComponent("); + source.ShouldContain(".ConnectTo("); + source.ShouldNotContain("ApplicationDefinitionJson"); + source.ShouldNotContain("JsonDocument"); + source.ShouldNotContain("new ComponentDefinition("); + source.ShouldNotContain(".Input<"); + source.ShouldNotContain(".Output<"); + source.ShouldNotContain("ApplicationAddress.Parse("); + } + + [Fact] + public void Designer_source_uses_only_the_explicit_contract_wrapper_without_graph_authoring_or_csharp_export() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var designerRoots = new[] + { + Path.Combine(root, "src", "FluxFlow.Components.Designer"), + Path.Combine(root, "src", "FluxFlow.Designer"), + Path.Combine(root, "src", "FluxFlow.Designer.Abstractions") + }; + var sources = designerRoots + .Where(Directory.Exists) + .SelectMany(static directory => + Directory.EnumerateFiles(directory, "*.cs", SearchOption.AllDirectories)) + .Where(static path => + !path.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) && + !path.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) + .ToArray(); + + sources.ShouldNotBeEmpty(); + var combined = string.Join(Environment.NewLine, sources.Select(File.ReadAllText)); + combined.ShouldContain("public static class DesignedComponentContract"); + combined.ShouldContain("ComponentContract"); + combined.ShouldContain("ComponentContract"); + combined.ShouldContain("IDesignedComponentContract"); + combined.ShouldNotContain("ApplicationDefinitionBuilder"); + combined.ShouldNotContain("ComponentAuthoringContract"); + combined.ShouldNotContain("ConnectTo("); + combined.ShouldNotContain("ExportCSharp"); + combined.ShouldNotContain("ExportCode"); + } + + private static void AssertContractShape(Type contractType, int handleParameterIndex) + { + contractType.IsPublic.ShouldBeTrue(); + contractType.IsSealed.ShouldBeFalse(); + contractType.GetConstructors(BindingFlags.Public | BindingFlags.Instance).ShouldBeEmpty(); + contractType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance) + .ShouldHaveSingleItem().IsFamilyOrAssembly.ShouldBeTrue(); + var handleParameter = contractType.GetGenericArguments()[handleParameterIndex]; + handleParameter.GetGenericParameterConstraints() + .ShouldContain(typeof(AuthoredComponentHandle)); + } + + private static void AssertResourceContractShape(Type contractType, int handleParameterIndex) + { + contractType.IsPublic.ShouldBeTrue(); + contractType.IsSealed.ShouldBeFalse(); + contractType.GetConstructors(BindingFlags.Public | BindingFlags.Instance) + .ShouldBeEmpty(); + contractType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance) + .ShouldHaveSingleItem().IsFamilyOrAssembly.ShouldBeTrue(); + contractType.GetGenericArguments()[handleParameterIndex] + .GetGenericParameterConstraints() + .ShouldContain(typeof(AuthoredResourceHandle)); + } + + private static void AssertResourceCreateShape(MethodInfo method, bool configured) + { + method.IsGenericMethodDefinition.ShouldBeTrue(); + var genericArguments = method.GetGenericArguments(); + genericArguments.Length.ShouldBe(configured ? 2 : 1); + var optionsType = configured ? genericArguments[0] : null; + var handleType = genericArguments[^1]; + handleType.GetGenericParameterConstraints() + .ShouldContain(typeof(AuthoredResourceHandle)); + + var parameters = method.GetParameters(); + parameters.Length.ShouldBe(configured ? 5 : 3); + parameters[0].Name.ShouldBe("type"); + parameters[0].ParameterType.ShouldBe(typeof(string)); + parameters[1].Name.ShouldBe("registrar"); + parameters[1].ParameterType.ShouldBe(typeof(IApplicationResourceRegistrar)); + var index = 2; + if (configured) + { + parameters[index].Name.ShouldBe("createOptions"); + parameters[index++].ParameterType.ShouldBe( + typeof(Func<>).MakeGenericType(optionsType!)); + parameters[index].Name.ShouldBe("apply"); + parameters[index++].ParameterType.ShouldBe( + typeof(Action<,>).MakeGenericType(optionsType!, typeof(ResourceDefinitionBuilder))); + } + + parameters[index].Name.ShouldBe("createHandle"); + parameters[index].ParameterType.ShouldBe( + typeof(Func<,>).MakeGenericType(typeof(ResourceHandle), handleType)); + method.ReturnType.GetGenericTypeDefinition().ShouldBe( + configured + ? typeof(ApplicationResourceContract<,>) + : typeof(ApplicationResourceContract<>)); + } + + private static void AssertCreateShape(MethodInfo method, bool configured) + { + method.IsGenericMethodDefinition.ShouldBeTrue(); + var genericArguments = method.GetGenericArguments(); + genericArguments.Length.ShouldBe(configured ? 2 : 1); + var optionsType = configured ? genericArguments[0] : null; + var handleType = genericArguments[^1]; + handleType.GetGenericParameterConstraints() + .ShouldContain(typeof(AuthoredComponentHandle)); + + var parameters = method.GetParameters(); + parameters.Length.ShouldBe(configured ? 5 : 3); + parameters[0].Name.ShouldBe("type"); + parameters[0].ParameterType.ShouldBe(typeof(string)); + var index = 1; + parameters[index].Name.ShouldBe("configureRuntime"); + parameters[index++].ParameterType.ShouldBe( + typeof(Action<>).MakeGenericType(typeof(RuntimeComponentRegistrationBuilder))); + if (configured) + { + parameters[index].Name.ShouldBe("createOptions"); + parameters[index++].ParameterType.ShouldBe(typeof(Func<>).MakeGenericType(optionsType!)); + parameters[index].Name.ShouldBe("apply"); + parameters[index++].ParameterType.ShouldBe( + typeof(Action<,>).MakeGenericType(optionsType!, typeof(ComponentDefinitionBuilder))); + } + + parameters[index].Name.ShouldBe("createHandle"); + parameters[index].ParameterType.ShouldBe( + typeof(Func<,>).MakeGenericType(typeof(ComponentHandle), handleType)); + method.ReturnType.GetGenericTypeDefinition().ShouldBe( + configured + ? typeof(ComponentContract<,>) + : typeof(ComponentContract<>)); + method.ReturnType.GetGenericArguments().ShouldBe( + configured + ? [optionsType!, handleType] + : [handleType]); + } + + private static void AssertConnectionTriplets(Type type, string methodName, bool direct) + { + var methods = type.GetMethods( + BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(method => method.Name == methodName) + .ToArray(); + + methods.Length.ShouldBe(6); + foreach (var targetKind in new[] { typeof(InputPortHandle<>), typeof(SignalInputPortHandle) }) + { + var targetMethods = methods + .Where(method => IsTarget(method.GetParameters()[direct ? 0 : 1].ParameterType, targetKind)) + .OrderBy(static method => method.GetParameters().Length) + .ThenBy(static method => method.GetParameters()[^1].ParameterType == typeof(string) ? 0 : 1) + .ToArray(); + + targetMethods.Length.ShouldBe(3); + targetMethods[0].GetParameters().Length.ShouldBe(direct ? 1 : 2); + targetMethods[1].GetParameters()[^1].Name.ShouldBe("condition"); + targetMethods[1].GetParameters()[^1].ParameterType.ShouldBe(typeof(string)); + targetMethods[1].GetParameters()[^1].IsOptional.ShouldBeFalse(); + targetMethods[2].GetParameters()[^1].Name.ShouldBe("when"); + targetMethods[2].GetParameters()[^1].ParameterType.IsGenericType.ShouldBeTrue(); + targetMethods[2].GetParameters()[^1].ParameterType.GetGenericTypeDefinition() + .ShouldBe(typeof(Func<,>)); + targetMethods[2].GetParameters()[^1].IsOptional.ShouldBeFalse(); + targetMethods.ShouldAllBe(method => + method.ReturnType == (direct ? typeof(OutputPortHandle<>) : type) || + direct && method.ReturnType.IsGenericType && + method.ReturnType.GetGenericTypeDefinition() == typeof(OutputPortHandle<>)); + } + } + + private static bool IsTarget(Type actual, Type expected) + => expected.IsGenericTypeDefinition + ? actual.IsGenericType && actual.GetGenericTypeDefinition() == expected + : actual == expected; +} diff --git a/tests/FluxFlow.Release.Tests/ComponentCompositionMetadataConventionTests.cs b/tests/FluxFlow.Release.Tests/ComponentCompositionMetadataConventionTests.cs index 2ece9873..cac5e192 100644 --- a/tests/FluxFlow.Release.Tests/ComponentCompositionMetadataConventionTests.cs +++ b/tests/FluxFlow.Release.Tests/ComponentCompositionMetadataConventionTests.cs @@ -5,6 +5,7 @@ using FluxFlow.Components.Designer; using FluxFlow.Components.Designer.Contracts; using FluxFlow.Composition; +using FluxFlow.Composition.Authoring; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Xunit; @@ -35,31 +36,26 @@ public sealed partial class ComponentCompositionMetadataConventionTests ]; [Fact] - public void Extracted_factory_methods_are_resolved_for_metadata_conventions() + public void Extracted_typed_factory_methods_are_resolved_for_metadata_conventions() { const string implementation = """ internal static class ExtractedFactories { - internal static ValueTask CreateAsync( + private static readonly object State = new(); + + internal static async ValueTask> CreateAsync( ComponentActivationContext context) { var options = context.BindConfiguration(); + await Task.Yield(); throw new NotSupportedException(); } } """; - const string registration = """ - internal static ComponentDescriptor ExampleDescriptor { get; } = new( - ExampleComponentDefinition.Types.Example, - ExtractedFactories.CreateAsync); - """; var factories = ReadFactoryOptionTypes(implementation, "fixture"); + factories.Keys.ShouldBe(["CreateAsync"]); factories["CreateAsync"].ShouldBe(["ExampleOptions"]); - - var match = ComponentDescriptorRegistrationRegex().Match(registration); - match.Success.ShouldBeTrue(); - match.Groups["factory"].Value.ShouldBe("ExtractedFactories.CreateAsync"); } [Fact] @@ -998,7 +994,10 @@ public void Component_composition_bound_options_are_described_or_explicitly_omit var project = LoadProject(root, entry); var assembly = LoadPackageAssembly(project, entry.PackageId); var metadataItems = CreateComponentMetadata(assembly, entry.PackageId); - var boundOptionTypesByNodeType = ReadDefaultComponentOptionTypes(projectDirectory, entry.PackageId); + var boundOptionTypesByNodeType = ReadDefaultComponentOptionTypes( + assembly, + projectDirectory, + entry.PackageId); foreach (var metadata in metadataItems) { @@ -1107,7 +1106,10 @@ public void Component_composition_designer_metadata_defaults_match_bound_option_ var project = LoadProject(root, entry); var assembly = LoadPackageAssembly(project, entry.PackageId); var metadataItems = CreateComponentMetadata(assembly, entry.PackageId); - var boundOptionTypesByNodeType = ReadDefaultComponentOptionTypes(projectDirectory, entry.PackageId); + var boundOptionTypesByNodeType = ReadDefaultComponentOptionTypes( + assembly, + projectDirectory, + entry.PackageId); foreach (var metadata in metadataItems) { @@ -1145,7 +1147,10 @@ public void Component_composition_required_bound_options_are_required_in_designe var project = LoadProject(root, entry); var assembly = LoadPackageAssembly(project, entry.PackageId); var metadataItems = CreateComponentMetadata(assembly, entry.PackageId); - var boundOptionTypesByNodeType = ReadDefaultComponentOptionTypes(projectDirectory, entry.PackageId); + var boundOptionTypesByNodeType = ReadDefaultComponentOptionTypes( + assembly, + projectDirectory, + entry.PackageId); foreach (var metadata in metadataItems) { @@ -1184,7 +1189,10 @@ public void Component_composition_numeric_metadata_bounds_are_accepted_by_bound_ var project = LoadProject(root, entry); var assembly = LoadPackageAssembly(project, entry.PackageId); var metadataItems = CreateComponentMetadata(assembly, entry.PackageId); - var boundOptionTypesByNodeType = ReadDefaultComponentOptionTypes(projectDirectory, entry.PackageId); + var boundOptionTypesByNodeType = ReadDefaultComponentOptionTypes( + assembly, + projectDirectory, + entry.PackageId); foreach (var metadata in metadataItems) { @@ -1515,11 +1523,21 @@ private static IEnumerable ReadConfigurationKeys( } private static IReadOnlyDictionary ReadDefaultComponentOptionTypes( + Assembly assembly, string projectDirectory, string packageId) { var registrationContent = File.ReadAllText( ReadSingleServiceCollectionExtensionsFile(projectDirectory, packageId)); + var authoringContent = string.Join( + Environment.NewLine, + Directory + .EnumerateFiles( + projectDirectory, + "*AuthoringExtensions.cs", + SearchOption.AllDirectories) + .Order(StringComparer.Ordinal) + .Select(File.ReadAllText)); var componentTypesContent = ReadDefinitionSection( File.ReadAllText(ReadSingleComponentTypesFile(projectDirectory, packageId)), "Types"); @@ -1533,15 +1551,36 @@ private static IReadOnlyDictionary ReadDefaultComponentOptionT ReadCompositionImplementationContent(projectDirectory), packageId); var optionTypesByNodeType = new Dictionary(StringComparer.Ordinal); - - foreach (Match match in FlatComponentRegistrationRegex().Matches(registrationContent)) - { + var contractsByProperty = assembly + .GetExportedTypes() + .SelectMany(static type => type.GetProperties( + BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)) + .Where(static property => + typeof(ComponentContract).IsAssignableFrom(property.PropertyType)) + .ToDictionary(static property => property.Name, StringComparer.Ordinal); + var declarations = CompleteContractDeclarationRegex().Matches(authoringContent); + + declarations.Count.ShouldBe( + contractsByProperty.Count, + $"{packageId} must declare every exported complete component contract exactly once in authoring source."); + foreach (Match match in declarations) + { + var propertyName = match.Groups["property"].Value; + contractsByProperty.TryGetValue(propertyName, out var contractProperty) + .ShouldBeTrue( + $"{packageId} complete contract declaration '{propertyName}' must resolve to an exported contract property."); + var contract = contractProperty!.GetValue(null) + .ShouldBeAssignableTo(); + var completeContract = contract!; var componentTypeConstant = match.Groups["componentType"].Value.Split('.')[^1]; componentTypeConstants.TryGetValue(componentTypeConstant, out var componentType) .ShouldBeTrue( - $"{packageId} flat component type constant '{componentTypeConstant}' must resolve."); + $"{packageId} complete contract type constant '{componentTypeConstant}' must resolve."); + completeContract.Type.ShouldBe( + componentType, + $"{packageId} complete contract '{propertyName}' must own the type selected by its declaration."); - var configureMethod = match.Groups["configure"].Value; + var configureMethod = match.Groups["configure"].Value.Split('.')[^1]; var configureBody = ReadMethodBody(registrationContent, configureMethod, packageId); var matchingFactories = optionTypesByFactory.Keys .Where(factoryName => Regex.IsMatch( @@ -1552,7 +1591,9 @@ private static IReadOnlyDictionary ReadDefaultComponentOptionT matchingFactories.ShouldHaveSingleItem( $"{packageId} configuration method '{configureMethod}' for '{componentType}' must select one factory that binds configuration."); - optionTypesByNodeType[componentType!] = optionTypesByFactory[matchingFactories[0]]; + optionTypesByNodeType.Add( + completeContract.Type, + optionTypesByFactory[matchingFactories[0]]); } optionTypesByNodeType.ShouldNotBeEmpty( @@ -2682,16 +2723,13 @@ private sealed record ResourceLookupUsage( [GeneratedRegex(@"BindConfiguration<(?[^>]+)>")] private static partial Regex BindConfigurationRegex(); - [GeneratedRegex(@"internal\s+static\s+ComponentDescriptor\s+\w+\s*\{\s*get;\s*\}\s*=\s*(?:new|Create\w*(?:<[^>]+>)?)\s*\(\s*(?\w+ComponentDefinition\.Types\.\w+)\s*,\s*(?[\w.]+)", RegexOptions.Singleline)] - private static partial Regex ComponentDescriptorRegistrationRegex(); - - [GeneratedRegex(@"\.AddComponent\s*\(\s*(?[\w.]+)\s*,\s*(?\w+)\s*\)")] - private static partial Regex FlatComponentRegistrationRegex(); + [GeneratedRegex(@"public\s+static\s+ComponentContract\s*<.*?>\s+(?\w+)\s*\{\s*get;\s*\}\s*=\s*(?:DesignedComponentContract\.Create|Create\w*(?:\s*<.*?>)?)\s*\(\s*(?[\w.]+)\s*,\s*(?[\w.]+)", RegexOptions.Singleline)] + private static partial Regex CompleteContractDeclarationRegex(); - [GeneratedRegex(@"(?:private|internal)\s+static\s+(?:async\s+)?ValueTask\s+(?\w+)(?:<[^>]+>)?\s*\([^)]*\)\s*\{(?.*?)\n \}", RegexOptions.Singleline)] + [GeneratedRegex(@"^[ \t]*(?:private|internal)\s+static\s+(?:async\s+)?[\w.]+(?:<[^()\r\n]+>)?(?:\[\])?\??\s+(?\w+)(?:<[^>\r\n]+>)?\s*\([^)]*\)\s*\{(?.*?)\n \}", RegexOptions.Multiline | RegexOptions.Singleline)] private static partial Regex PrivateFactoryMethodBlockRegex(); - [GeneratedRegex(@"(?:private|internal)\s+static\s+(?:async\s+)?ValueTask\s+(?\w+)(?:<[^>]+>)?\s*\([^)]*\)\s*=>\s*(?.*?);", RegexOptions.Singleline)] + [GeneratedRegex(@"^[ \t]*(?:private|internal)\s+static\s+(?:async\s+)?[\w.]+(?:<[^()\r\n]+>)?(?:\[\])?\??\s+(?\w+)(?:<[^>\r\n]+>)?\s*\([^)]*\)\s*=>\s*(?.*?);", RegexOptions.Multiline | RegexOptions.Singleline)] private static partial Regex PrivateFactoryExpressionMethodRegex(); [GeneratedRegex(@"(?\w+)(?:<[^>]+>)?\s*\(")] diff --git a/tests/FluxFlow.Release.Tests/ComponentFamilyAuthoringConventionTests.cs b/tests/FluxFlow.Release.Tests/ComponentFamilyAuthoringConventionTests.cs index 090e0035..702ca9f3 100644 --- a/tests/FluxFlow.Release.Tests/ComponentFamilyAuthoringConventionTests.cs +++ b/tests/FluxFlow.Release.Tests/ComponentFamilyAuthoringConventionTests.cs @@ -19,6 +19,7 @@ using FluxFlow.Components.Storage.Composition; using FluxFlow.Components.Timers.Composition; using FluxFlow.Components.Validation.Composition; +using FluxFlow.Composition; using FluxFlow.Composition.Authoring; using Shouldly; using Xunit; @@ -142,6 +143,158 @@ public void Explicit_19_family_matrix_exposes_complete_fluent_capture_convention fluentCount.ShouldBe(55); } + [Fact] + public void Explicit_19_family_matrix_exposes_44_complete_contracts_with_exact_descriptors_and_events() + { + AuthoringFamilies.Length.ShouldBe(19); + var contractCount = 0; + + foreach (var family in AuthoringFamilies) + { + var originals = family.AuthoringType + .GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(static method => + method.ReturnType != typeof(WorkflowDefinitionBuilder) && + IsWorkflowExtension(method) && + !HasOutParameter(method)) + .ToArray(); + var expectedProperties = family.MethodNames + .Select(static methodName => methodName["Add".Length..]) + .OrderBy(static name => name, StringComparer.Ordinal) + .ToArray(); + var contractContainer = family.AuthoringType.Assembly + .GetExportedTypes() + .Where(static type => type.IsAbstract && type.IsSealed) + .Where(type => expectedProperties.All(propertyName => + type.GetProperty( + propertyName, + BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) is not null)) + .ShouldHaveSingleItem( + $"{family.AuthoringType.Assembly.GetName().Name} must expose one public static contract container."); + var properties = contractContainer.GetProperties( + BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) + .OrderBy(static property => property.Name, StringComparer.Ordinal) + .ToArray(); + + contractContainer.Name.ShouldEndWith("Components"); + properties.Select(static property => property.Name).ShouldBe(expectedProperties); + properties.Length.ShouldBe(originals.Length); + + foreach (var original in originals) + { + var propertyName = original.Name["Add".Length..]; + var property = properties + .Where(candidate => candidate.Name == propertyName) + .ShouldHaveSingleItem(); + property.GetMethod!.IsPublic.ShouldBeTrue(); + property.GetMethod.IsStatic.ShouldBeTrue(); + property.SetMethod.ShouldBeNull(); + var contractType = property.PropertyType; + contractType.IsGenericType.ShouldBeTrue(); + var contractDefinition = contractType.GetGenericTypeDefinition(); + (contractDefinition == typeof(ComponentContract<>) || + contractDefinition == typeof(ComponentContract<,>)).ShouldBeTrue( + $"{contractContainer.Name}.{propertyName} must expose a typed component contract."); + var handleType = contractType.GetGenericArguments()[^1]; + handleType.ShouldBe(original.ReturnType); + typeof(AuthoredComponentHandle).IsAssignableFrom(handleType).ShouldBeTrue(); + var events = handleType.GetProperty( + "Events", + BindingFlags.Public | BindingFlags.Instance); + events.ShouldNotBeNull( + $"{contractContainer.Name}.{propertyName} handle must expose explicit Events."); + var eventsProperty = events!; + eventsProperty.PropertyType.ShouldBe(typeof(OutputPortHandle)); + eventsProperty.GetMethod!.IsPublic.ShouldBeTrue(); + eventsProperty.SetMethod.ShouldBeNull(); + var contract = property.GetValue(null) + .ShouldBeAssignableTo(); + var completeContract = contract!; + completeContract.Type.ShouldNotBeNullOrWhiteSpace(); + completeContract.Type.ShouldBe(completeContract.Type.Trim()); + completeContract.Descriptor.Type.ShouldBe(completeContract.Type); + completeContract.Descriptor.Outputs["Events"].MessageType + .ShouldBe(typeof(ComponentEvent)); + completeContract.Descriptor.Outputs["Events"].Kind + .ShouldBe(ComponentPortKind.Message); + completeContract.Descriptor.Inputs.Values.ShouldAllBe(static port => + !string.IsNullOrWhiteSpace(port.Name) && port.MessageType != null); + completeContract.Descriptor.Outputs.Values.ShouldAllBe(static port => + !string.IsNullOrWhiteSpace(port.Name) && port.MessageType != null); + completeContract.Descriptor.Options.Values.ShouldAllBe(static option => + !string.IsNullOrWhiteSpace(option.Name) && option.ValueType != null); + completeContract.Descriptor.Resources.Values.ShouldAllBe(static resource => + !string.IsNullOrWhiteSpace(resource.Name) && resource.ServiceType != null); + contractCount++; + } + } + + contractCount.ShouldBe(44); + } + + [Fact] + public void All_19_family_package_readmes_explain_code_first_descriptor_ownership_and_explicit_portable_registration() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var sourceRoot = Path.Combine(root, "src"); + var packageReadmes = Directory + .EnumerateFiles(sourceRoot, "README.md", SearchOption.AllDirectories) + .ToArray(); + var resolved = AuthoringFamilies.Select(family => + { + var assemblyName = family.AuthoringType.Assembly.GetName().Name; + assemblyName.ShouldNotBeNull(); + var nonNullAssemblyName = assemblyName!; + var readme = packageReadmes + .Where(path => string.Equals( + Path.GetFileName(Path.GetDirectoryName(path)), + nonNullAssemblyName, + StringComparison.Ordinal)) + .ShouldHaveSingleItem( + $"{nonNullAssemblyName} must own exactly one package README under src."); + + return (AssemblyName: nonNullAssemblyName, Readme: readme); + }).ToArray(); + + resolved.Length.ShouldBe(19); + resolved.Select(static item => item.Readme) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Count() + .ShouldBe(19); + + var mqttAssemblyName = typeof(MqttApplicationAuthoringExtensions).Assembly.GetName().Name; + mqttAssemblyName.ShouldNotBeNull(); + var nonNullMqttAssemblyName = mqttAssemblyName!; + var mqttReadme = resolved.Single(item => item.AssemblyName == nonNullMqttAssemblyName).Readme; + Path.GetRelativePath(root, mqttReadme).Replace('\\', '/').ShouldBe( + $"src/Mqtt/{nonNullMqttAssemblyName}/README.md"); + + foreach (var family in resolved) + { + var relativeReadme = Path.GetRelativePath(root, family.Readme).Replace('\\', '/'); + var normalized = string.Join( + ' ', + File.ReadAllText(family.Readme) + .Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); + + (normalized.Contains("A definition built from", StringComparison.Ordinal) && + normalized.Contains("retains its executable descriptor", StringComparison.Ordinal) && + normalized.Contains("complete contract", StringComparison.Ordinal)) + .ShouldBeTrue( + $"{relativeReadme} must state that complete code-first definitions retain executable descriptors."); + normalized.Contains( + "Normal code-first hosting therefore calls only `AddFluxFlow(definition)` and does not repeat the family registration", + StringComparison.Ordinal) + .ShouldBeTrue( + $"{relativeReadme} must state the single normal code-first registration boundary."); + normalized.Contains( + "Use that service registration for JSON/configuration, catalog, or dynamic definitions", + StringComparison.Ordinal) + .ShouldBeTrue( + $"{relativeReadme} must reserve explicit family registration for portable or dynamic definitions."); + } + } + private static bool IsWorkflowExtension(MethodInfo method) { var parameters = method.GetParameters(); diff --git a/tests/FluxFlow.Release.Tests/ComponentFamilyRegistrationMatrixTests.cs b/tests/FluxFlow.Release.Tests/ComponentFamilyRegistrationMatrixTests.cs index 37fc1723..ffc20b30 100644 --- a/tests/FluxFlow.Release.Tests/ComponentFamilyRegistrationMatrixTests.cs +++ b/tests/FluxFlow.Release.Tests/ComponentFamilyRegistrationMatrixTests.cs @@ -20,6 +20,7 @@ using FluxFlow.Components.Timers.Composition; using FluxFlow.Components.Validation.Composition; using FluxFlow.Composition; +using FluxFlow.Nodes; using Microsoft.Extensions.DependencyInjection; using Shouldly; using System.Xml.Linq; @@ -215,6 +216,42 @@ public void Explicit_family_matrix_registers_all_44_declarations_idempotently() allTypes.Distinct(StringComparer.Ordinal).Count().ShouldBe(44); } + [Fact] + public void Explicit_family_matrix_keeps_all_44_explicit_event_outputs() + { + var eventOutputs = new List<(string Family, string Type)>(); + + foreach (var family in Families) + { + var services = new ServiceCollection(); + family.Register(services); + using var provider = services.BuildServiceProvider(); + var designCatalog = provider.GetRequiredService(); + + foreach (var descriptor in ReadDescriptors(services)) + { + descriptor.Outputs.TryGetValue("Events", out var events).ShouldBeTrue( + $"{family.Name} '{descriptor.Type}' must explicitly retain its established Events output."); + events.ShouldNotBeNull().MessageType.ShouldBe(typeof(ComponentEvent)); + events.Kind.ShouldBe(ComponentPortKind.Message); + + designCatalog.TryGet(new ComponentType(descriptor.Type), out var metadata) + .ShouldBeTrue($"{family.Name} '{descriptor.Type}' has no matching design metadata."); + var designedEvents = metadata.ShouldNotBeNull().Ports + .Single(port => port.Name.Value == "Events"); + designedEvents.Direction.ShouldBe(PortDirection.Output); + designedEvents.MessageType.ShouldBe(typeof(ComponentEvent)); + designedEvents.ValueType?.Value.ShouldBe(nameof(ComponentEvent)); + eventOutputs.Add((family.Name, descriptor.Type)); + } + } + + Families.Count.ShouldBe(19); + eventOutputs.Count.ShouldBe(44); + eventOutputs.Select(static item => item.Type) + .Distinct(StringComparer.Ordinal).Count().ShouldBe(44); + } + [Fact] public void Reliable_capacity_options_use_positive_ranges_and_output_delivery_guidance() { @@ -427,10 +464,9 @@ public void Explicit_family_matrix_rejects_conflicting_registrations_clearly() var services = new ServiceCollection(); family.Register(services); var original = ReadDescriptors(services).First(); - var action = () => services.AddFluxFlowComponents().AddRuntimeComponent( + var action = () => services.AddFluxFlowComponents().Advanced.AddDynamicComponent( original.Type, - component => component.UseFactory(static _ => - throw new InvalidOperationException("Conflicting factory should not run."))); + component => component.UseFactory(static _ => new ConflictingRegistrationNode())); var exception = action.ShouldThrow(); exception.Message.ShouldContain(original.Type); @@ -559,7 +595,7 @@ private static void AssertFinalPresentationMatchesDescriptor( .ShouldBe(ProcessingName); var events = metadata.Ports.Single(port => - string.Equals(port.Name.Value, ComponentEvents.PortName, StringComparison.Ordinal)); + string.Equals(port.Name.Value, "Events", StringComparison.Ordinal)); events.Direction.ShouldBe(PortDirection.Output); events.MessageType.ShouldBe(typeof(ComponentEvent)); events.ValueType?.Value.ShouldBe(nameof(ComponentEvent)); @@ -806,4 +842,18 @@ private sealed record RegistrationOrderSnapshot( IReadOnlyList DeclarationTypes, IReadOnlyList DesignTypes, IReadOnlyList RuntimeTypes); + + private sealed class ConflictingRegistrationNode : IFlowNode + { + public Task Completion { get; } = Task.CompletedTask; + + public void Complete() + { + } + + public void Fault(Exception exception) + => ArgumentNullException.ThrowIfNull(exception); + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } } diff --git a/tests/FluxFlow.Release.Tests/DocumentationBoundaryTests.cs b/tests/FluxFlow.Release.Tests/DocumentationBoundaryTests.cs index c8ba466f..2cb2a6bc 100644 --- a/tests/FluxFlow.Release.Tests/DocumentationBoundaryTests.cs +++ b/tests/FluxFlow.Release.Tests/DocumentationBoundaryTests.cs @@ -5,6 +5,43 @@ namespace FluxFlow.Release.Tests; public sealed class DocumentationBoundaryTests { + [Fact] + public void Code_first_docs_keep_normal_contracts_resources_ports_and_fluent_on_the_canonical_surface() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var normalDocuments = new[] + { + Path.Combine(root, "docs", "03-node-authoring.md"), + Path.Combine(root, "docs", "04-package-authoring.md"), + Path.Combine(root, "docs", "39-typed-code-first-authoring.md"), + Path.Combine(root, "docs", "40-unified-component-contracts.md"), + Path.Combine(root, "src", "FluxFlow.Engine", "README.md") + }; + var normal = string.Join( + Environment.NewLine, + normalDocuments.Select(File.ReadAllText)); + + normal.Contains("ComponentContract", StringComparison.Ordinal).ShouldBeTrue(); + normal.Contains("ApplicationResourceContract", StringComparison.Ordinal).ShouldBeTrue(); + normal.Contains("InputPortHandle", StringComparison.Ordinal).ShouldBeTrue(); + normal.Contains("OutputPortHandle", StringComparison.Ordinal).ShouldBeTrue(); + normal.Contains("Advanced.AddDynamicComponent", StringComparison.Ordinal).ShouldBeTrue(); + normal.Contains("AddRuntimeComponent(", StringComparison.Ordinal).ShouldBeFalse(); + + var fluent = File.ReadAllText( + Path.Combine(root, "src", "FluxFlow.Fluent", "README.md")); + fluent.Contains("ApplicationDefinition", StringComparison.Ordinal).ShouldBeTrue(); + fluent.Contains("FluxFlowApplication", StringComparison.Ordinal).ShouldBeTrue(); + fluent.Contains("ApplicationRuntime", StringComparison.Ordinal).ShouldBeFalse(); + + var publicOverview = File.ReadAllText( + Path.Combine(root, "docs", "14-public-api-overview.md")); + publicOverview.Contains("ApplicationResourceContract", StringComparison.Ordinal) + .ShouldBeTrue(); + publicOverview.Contains("ApplicationRuntime`", StringComparison.Ordinal) + .ShouldBeFalse(); + } + [Fact] public void Definition_docs_lead_with_canonical_composition_application_model() { @@ -58,9 +95,11 @@ public void Package_authoring_docs_keep_engine_modules_out_of_default_package_sh .ShouldBeTrue("package authoring docs should keep node packages on FluxFlow.Nodes."); defaultSection.Contains("FluxFlowRegistrationBuilder", StringComparison.Ordinal) .ShouldBeTrue("package authoring docs should show builder-first optional component registration."); - (defaultSection.Contains("component.AddInput", StringComparison.Ordinal) && - defaultSection.Contains("component.AddOutput", StringComparison.Ordinal)) - .ShouldBeTrue("package authoring docs should show flat component authoring."); + (defaultSection.Contains(".UseFactory(", StringComparison.Ordinal) && + defaultSection.Contains(".HasInput(", StringComparison.Ordinal) && + defaultSection.Contains(".HasOutput(", StringComparison.Ordinal) && + defaultSection.Contains(".HasEvents(", StringComparison.Ordinal)) + .ShouldBeTrue("package authoring docs should show typed flat component authoring with explicit events."); defaultSection.Contains("AddOrders", StringComparison.Ordinal) .ShouldBeTrue("package authoring docs should show a family-level registration extension."); text.Contains("IFlowNodeModule", StringComparison.Ordinal) diff --git a/tests/FluxFlow.Release.Tests/HealthReadinessConventionTests.cs b/tests/FluxFlow.Release.Tests/HealthReadinessConventionTests.cs new file mode 100644 index 00000000..9eda629d --- /dev/null +++ b/tests/FluxFlow.Release.Tests/HealthReadinessConventionTests.cs @@ -0,0 +1,252 @@ +using System.Xml.Linq; +using Shouldly; +using Xunit; + +namespace FluxFlow.Release.Tests; + +public sealed class HealthReadinessConventionTests +{ + private const string ProjectDirectory = "FluxFlow.Engine.HealthChecks"; + + [Fact] + public void Health_integration_package_is_optional_standard_only_and_manifested() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var projectPath = Path.Combine( + root, + "src", + ProjectDirectory, + "FluxFlow.Engine.HealthChecks.csproj"); + var project = XDocument.Load(projectPath); + + ReadProperty(project, "TargetFrameworks").ShouldBe("net8.0;net10.0"); + ReadProperty(project, "PackageId").ShouldBe("FluxFlow.Engine.HealthChecks"); + ReadProperty(project, "AssemblyName").ShouldBe("FluxFlow.Engine.HealthChecks"); + ReadProperty(project, "RootNamespace").ShouldBe("FluxFlow.Engine.HealthChecks"); + ReadProperty(project, "Version").ShouldBe("1.0.0"); + ReadIncludes(project, "PackageReference") + .ShouldBe(new[] { "Microsoft.Extensions.Diagnostics.HealthChecks" }); + ReadIncludes(project, "ProjectReference") + .ShouldBe(new[] { @"..\FluxFlow.Engine\FluxFlow.Engine.csproj" }); + project.Descendants().ShouldNotContain(static element => + element.Name.LocalName == "FrameworkReference"); + + var manifest = PackageManifest.Read(root); + var entry = manifest.Single(static candidate => + candidate.Alias == "engine-healthchecks"); + entry.TagPrefix.ShouldBe("engine-healthchecks"); + entry.PackageId.ShouldBe("FluxFlow.Engine.HealthChecks"); + entry.Project.ShouldBe("src/FluxFlow.Engine.HealthChecks/FluxFlow.Engine.HealthChecks.csproj"); + entry.NotesName.ShouldBe("FluxFlow.Engine.HealthChecks"); + entry.BinaryCompatibilityBaseline.ShouldBeNull(); + manifest.Count(static candidate => + candidate.PackageId == "FluxFlow.Engine.HealthChecks").ShouldBe(1); + } + + [Fact] + public void Health_integration_public_surface_is_one_standard_builder_extension() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var extension = ReadSource(root, "FluxFlowHealthChecksBuilderExtensions.cs"); + var check = ReadSource(root, "FluxFlowApplicationHealthCheck.cs"); + + extension.ShouldContain("public static class FluxFlowHealthChecksBuilderExtensions"); + CountOccurrences( + extension, + "public static IHealthChecksBuilder AddFluxFlowApplication(").ShouldBe(1); + extension.ShouldContain("this IHealthChecksBuilder builder"); + extension.ShouldContain("return builder;"); + extension.ShouldContain("private sealed class FluxFlowApplicationHealthCheckRegistrationMarker;"); + extension.ShouldContain("provider.GetService()"); + extension.ShouldContain("\"fluxflow.application\""); + extension.ShouldContain("HealthStatus.Unhealthy"); + extension.ShouldContain("[\"fluxflow\", \"ready\"]"); + extension.ShouldNotContain("Options"); + extension.ShouldNotContain("public sealed class FluxFlowApplicationHealthCheck"); + + check.ShouldContain("internal sealed class FluxFlowApplicationHealthCheck"); + check.ShouldContain(": IHealthCheck"); + check.ShouldContain("public Task CheckHealthAsync("); + check.ShouldNotContain("public sealed"); + check.ShouldNotContain("public record"); + check.ShouldNotContain("public enum"); + } + + [Fact] + public void Health_check_source_has_exact_mapping_bounded_data_and_no_polling_scanning_or_io() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var extension = ReadSource(root, "FluxFlowHealthChecksBuilderExtensions.cs"); + var check = ReadSource(root, "FluxFlowApplicationHealthCheck.cs"); + var source = extension + Environment.NewLine + check; + + check.ShouldContain("cancellationToken.ThrowIfCancellationRequested();"); + check.ShouldContain("state is ApplicationState.Stopping or ApplicationState.Stopped"); + check.ShouldContain("state is not (ApplicationState.Running or ApplicationState.Reloading)"); + check.ShouldContain("lastUpdate?.Status == ApplicationUpdateStatus.Rejected"); + check.ShouldContain("HealthCheckResult.Healthy("); + check.ShouldContain("HealthCheckResult.Degraded("); + check.ShouldContain("HealthCheckResult.Unhealthy("); + check.ShouldContain("lastUpdate.Diagnostics.LastOrDefault()"); + + var expectedKeys = new[] + { + "applicationState", + "activeRevisionId", + "activeSequence", + "requestedRevisionId", + "lastUpdateStatus", + "diagnosticStage", + "diagnosticCode" + }; + foreach (var key in expectedKeys) + { + var expectedOccurrences = key == "applicationState" ? 2 : 1; + CountOccurrences(check, $"[\"{key}\"]").ShouldBe(expectedOccurrences); + } + + var forbidden = new[] + { + "System.Reflection", + "Assembly.Load", + "GetAssemblies(", + "BackgroundService", + "IHostedService", + "PeriodicTimer", + "System.Threading.Timer", + "Task.Delay(", + "Task.Run(", + "Thread.Sleep(", + "while (", + "File.", + "Directory.", + "HttpClient", + "DbConnection", + "SqlConnection", + "ReloadAsync(", + "ApplyAsync(", + "StartAsync(", + "StopAsync(" + }; + foreach (var value in forbidden) + source.ShouldNotContain(value); + } + + [Fact] + public void Health_check_reads_state_and_references_forward_then_reverse_and_fails_closed_on_a_torn_observation() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var source = ReadSource(root, "FluxFlowApplicationHealthCheck.cs") + .ReplaceLineEndings("\n"); + + AssertInOrder( + source, + "var stateBefore = application.State;", + "var currentBefore = application.Current;", + "var lastUpdateBefore = application.LastUpdate;", + "var lastUpdateAfter = application.LastUpdate;", + "var currentAfter = application.Current;", + "var stateAfter = application.State;"); + source.ShouldContain("stateBefore != stateAfter"); + source.ShouldContain("!ReferenceEquals(currentBefore, currentAfter)"); + source.ShouldContain("!ReferenceEquals(lastUpdateBefore, lastUpdateAfter)"); + AssertInOrder( + source, + "if (stateBefore != stateAfter ||", + "current: null,", + "lastUpdateAfter));", + "return Task.FromResult(CreateResult(\n stateAfter,\n currentAfter,"); + } + + [Fact] + public void Health_readiness_docs_define_opt_in_registration_exact_mapping_and_host_owned_endpoint() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var dedicated = File.ReadAllText(Path.Combine( + root, + "docs", + "42-application-health-readiness.md")); + var hosting = File.ReadAllText(Path.Combine( + root, + "docs", + "05-hosting-and-observability.md")); + var packageReadme = File.ReadAllText(Path.Combine( + root, + "src", + ProjectDirectory, + "README.md")); + var publicOverview = File.ReadAllText(Path.Combine( + root, + "docs", + "14-public-api-overview.md")); + var docsIndex = File.ReadAllText(Path.Combine(root, "docs", "README.md")); + var rootReadme = File.ReadAllText(Path.Combine(root, "README.md")); + + dedicated.ShouldContain("standard .NET health-check"); + dedicated.ShouldContain("services.AddHealthChecks()"); + dedicated.ShouldContain(".AddFluxFlowApplication();"); + dedicated.ShouldContain("name: `fluxflow.application`"); + dedicated.ShouldContain("tags: `fluxflow`, `ready`"); + dedicated.ShouldContain("configured failure status: `Unhealthy`"); + dedicated.ShouldContain("| `Healthy` | `Running` or `Reloading`"); + dedicated.ShouldContain("| `Degraded` | `Running` or `Reloading`"); + dedicated.ShouldContain("| `Unhealthy` | FluxFlow is not registered"); + dedicated.ShouldContain("The result may contain only these seven keys:"); + dedicated.ShouldContain("Cancellation is propagated immediately with the caller's token."); + dedicated.ShouldContain("app.MapHealthChecks("); + dedicated.ShouldContain("The package itself has no ASP.NET Core dependency"); + dedicated.ShouldContain("adds no hosted service, worker, timer, polling loop"); + dedicated.ShouldContain("does not report:"); + dedicated.ShouldContain("process liveness"); + dedicated.ShouldContain("database, broker, HTTP endpoint"); + + hosting.ShouldContain("## Optional Application Readiness"); + hosting.ShouldContain("at most lifecycle state"); + hosting.ShouldContain("performs no polling"); + packageReadme.ShouldContain("Optional standard .NET readiness integration"); + packageReadme.ShouldContain("It adds no worker,"); + publicOverview.ShouldContain("### FluxFlow.Engine.HealthChecks 1.x"); + publicOverview.ShouldContain("at most seven bounded metadata"); + docsIndex.ShouldContain("42. [Application Health Readiness](42-application-health-readiness.md)"); + rootReadme.ShouldContain("[Application Health Readiness](docs/42-application-health-readiness.md)"); + } + + private static string ReadSource(string root, string fileName) + => File.ReadAllText(Path.Combine(root, "src", ProjectDirectory, fileName)); + + private static string ReadProperty(XDocument project, string name) + => project.Descendants() + .Single(element => element.Name.LocalName == name) + .Value.Trim(); + + private static string[] ReadIncludes(XDocument project, string itemName) + => project.Descendants() + .Where(element => element.Name.LocalName == itemName) + .Select(element => element.Attribute("Include")!.Value) + .Order(StringComparer.Ordinal) + .ToArray(); + + private static void AssertInOrder(string source, params string[] values) + { + var previous = -1; + foreach (var value in values) + { + var current = source.IndexOf(value, StringComparison.Ordinal); + current.ShouldBeGreaterThan(previous); + previous = current; + } + } + + private static int CountOccurrences(string text, string value) + { + var count = 0; + var start = 0; + while ((start = text.IndexOf(value, start, StringComparison.Ordinal)) >= 0) + { + count++; + start += value.Length; + } + + return count; + } +} diff --git a/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs b/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs index c0fd5f8b..00b42f1a 100644 --- a/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs +++ b/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs @@ -12,21 +12,41 @@ public sealed class PackageConsumerAcceptanceScriptTests private const string FixtureDirectory = "package-consumer-acceptance"; private const string FixtureProject = "FluxFlow.PackageConsumerAcceptance.csproj"; - private static readonly IReadOnlyDictionary ExpectedPackageVersions = + private static readonly IReadOnlyDictionary ExpectedFixturePackageVersions = new Dictionary(StringComparer.Ordinal) { ["FluxFlow.Engine"] = "$(FluxFlowEngineVersion)", + ["FluxFlow.Engine.HealthChecks"] = "$(FluxFlowEngineHealthChecksVersion)", ["FluxFlow.Engine.DurableInput.SqlFile"] = "$(FluxFlowDurableInputSqlFileVersion)", ["FluxFlow.Engine.DurableOutput.SqlFile"] = "$(FluxFlowDurableOutputSqlFileVersion)", - ["FluxFlow.Fluent"] = "$(FluxFlowFluentVersion)" + ["FluxFlow.Fluent"] = "$(FluxFlowFluentVersion)", + ["Microsoft.Extensions.Hosting"] = "8.0.1" }; + private static readonly string[] RestartSeedMarkers = + [ + "PACKAGE_ACCEPTANCE_RESTART_SEED_INPUT=restart-input", + "PACKAGE_ACCEPTANCE_RESTART_SEED_OUTPUT=restart-preapplied-output", + "PACKAGE_ACCEPTANCE_RESTART_SEED_OK=True" + ]; + + private static readonly string[] RestartRecoveryMarkers = + [ + "PACKAGE_ACCEPTANCE_RESTART_INPUT_RECOVERED=True", + "PACKAGE_ACCEPTANCE_RESTART_WORKFLOW_OUTPUT_CAPTURED=True", + "PACKAGE_ACCEPTANCE_RESTART_PENDING_OUTPUT_RESUMED=True", + "PACKAGE_ACCEPTANCE_RESTART_OUTPUT_RECOVERED=True", + "PACKAGE_ACCEPTANCE_RESTART_IDEMPOTENCY_OK=True", + "PACKAGE_ACCEPTANCE_RESTART_OK=True" + ]; + private static readonly string[] RequiredAliases = [ "nodes", "mapping", "composition", "engine", + "engine-healthchecks", "fluent", "engine-durable-input", "engine-durable-input-sqlfile", @@ -53,7 +73,7 @@ public void Acceptance_fixture_is_a_net8_package_only_consumer() element => element.Attribute("Version")!.Value, StringComparer.Ordinal); - packageVersions.ShouldBe(ExpectedPackageVersions); + packageVersions.ShouldBe(ExpectedFixturePackageVersions); project.Descendants().ShouldNotContain(element => element.Name.LocalName == "ProjectReference"); var projectText = File.ReadAllText(projectPath); @@ -64,12 +84,15 @@ public void Acceptance_fixture_is_a_net8_package_only_consumer() } [Fact] - public void Acceptance_fixture_exercises_engine_fluent_and_sql_file_reopen_paths() + public void Acceptance_fixture_exercises_independent_json_complete_code_first_and_sql_file_reopen_paths() { var root = ReleaseTestPaths.FindRepositoryRoot(); var source = File.ReadAllText(GetFixturePath(root, "Program.cs")); CountOccurrences(source, "PACKAGE_ACCEPTANCE_ENGINE_OK=True").ShouldBe(1); + CountOccurrences(source, "PACKAGE_ACCEPTANCE_CODE_FIRST_OK=True").ShouldBe(1); + CountOccurrences(source, "PACKAGE_ACCEPTANCE_RESOURCE_OK=True").ShouldBe(1); + CountOccurrences(source, "PACKAGE_ACCEPTANCE_HEALTH_OK=True").ShouldBe(1); CountOccurrences(source, "PACKAGE_ACCEPTANCE_FLUENT_OK=True").ShouldBe(1); CountOccurrences(source, "PACKAGE_ACCEPTANCE_DURABILITY_OK=True").ShouldBe(1); CountOccurrences(source, "PACKAGE_ACCEPTANCE_OK=True").ShouldBe(1); @@ -87,6 +110,62 @@ public void Acceptance_fixture_exercises_engine_fluent_and_sql_file_reopen_paths source.ShouldContain("PortReceiveStatus.Received"); source.ShouldContain("PACKAGE-JSON"); + source.ShouldContain("RunCodeFirstEngineScenarioAsync()"); + source.ShouldContain("new ApplicationDefinitionBuilder()"); + source.ShouldContain(".AddWorkflow(\"Acceptance\", out var workflow)"); + CountOccurrences(source, "AcceptanceComponents.Uppercase").ShouldBe(2); + CountOccurrences(source, "AcceptanceComponents.PrefixedUppercase").ShouldBe(1); + source.ShouldContain("first.Output.ConnectTo("); + source.ShouldContain("when: static value =>"); + source.ShouldContain("definitionBuilder.Build()"); + var codeFirstScenario = ExtractSourceSection( + source, + "static async Task RunCodeFirstEngineScenarioAsync()", + "static async Task RunDurabilityScenarioAsync()"); + codeFirstScenario.ShouldContain("Ports.SendAsync("); + codeFirstScenario.ShouldContain("first.Input,"); + codeFirstScenario.ShouldContain("Ports.ReceiveAsync("); + codeFirstScenario.ShouldContain("second.Output,"); + codeFirstScenario.ShouldNotContain("first.Input.Address"); + codeFirstScenario.ShouldNotContain("second.Output.Address"); + codeFirstScenario.ShouldContain( + ".AddResource(\"Prefix\", AcceptanceResources.Prefix, out var prefix)"); + codeFirstScenario.ShouldContain("definitionBuilder.Build()"); + codeFirstScenario.ShouldNotContain("AddApplicationResourceRegistrar"); + source.ShouldContain("ApplicationResourceContract"); + source.ShouldContain("ApplicationResourceContract.Create("); + source.ShouldContain(": AuthoredResourceHandle(definition)"); + source.ShouldContain("AcceptanceResourceRegistrar : IApplicationResourceRegistrar"); + source.ShouldContain("context.Services.AddSingleton(new AcceptancePrefix(\"RESOURCE-\"))"); + source.ShouldContain("context.Services.GetRequiredService()"); + source.ShouldContain("RESOURCE-PACKAGE-CODE"); + source.ShouldContain("ComponentContract"); + source.ShouldContain("ComponentContract.Create("); + source.ShouldContain("class UppercaseComponentHandle(ComponentHandle definition)"); + source.ShouldContain(": AuthoredComponentHandle(definition)"); + source.ShouldContain("OutputPortHandle Events"); + source.ShouldNotContain("ComponentAuthoringContract"); + source.ShouldNotContain(".AddRuntimeComponent("); + + var jsonScenario = ExtractSourceSection( + source, + "static async Task RunEngineScenarioAsync()", + "static async Task RunFluentScenarioAsync()"); + jsonScenario.ShouldContain("var definition = ApplicationDefinitionJson.Deserialize(definitionJson);"); + jsonScenario.ShouldContain("services.AddFluxFlowComponents()"); + jsonScenario.ShouldContain(".AddComponent(AcceptanceComponents.Uppercase)"); + jsonScenario.ShouldContain( + "var unchanged = await application.ApplyAsync(\"package-json-unchanged\", definition);"); + jsonScenario.ShouldContain( + "var rejected = await application.ApplyAsync(\"package-json-invalid\", invalidDefinition);"); + jsonScenario.ShouldContain("PACKAGE-JSON-AFTER-REJECTION"); + CountOccurrences(jsonScenario, "AcceptanceComponents.Uppercase").ShouldBe(1); + codeFirstScenario.ShouldContain("definitionBuilder.Build()"); + codeFirstScenario.ShouldContain("services.AddFluxFlow("); + codeFirstScenario.ShouldNotContain("AddFluxFlowComponents"); + CountOccurrences(codeFirstScenario, "AcceptanceComponents.Uppercase").ShouldBe(1); + CountOccurrences(codeFirstScenario, "AcceptanceComponents.PrefixedUppercase").ShouldBe(1); + source.ShouldContain("var graph = Flow"); source.ShouldContain(".From(new SingleValueSource("); source.ShouldContain(".Then(new UppercaseNode())"); @@ -112,15 +191,196 @@ public void Acceptance_fixture_exercises_engine_fluent_and_sql_file_reopen_paths source.ShouldContain("persistedOutput.Envelope.Payload.GetRawText()"); } + [Fact] + public void Acceptance_fixture_json_path_proves_unchanged_apply_and_rejected_candidate_without_losing_active_route() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var source = File.ReadAllText(GetFixturePath(root, "Program.cs")); + var jsonScenario = ExtractSourceSection( + source, + "static async Task RunEngineScenarioAsync()", + "static async Task RunFluentScenarioAsync()"); + + CountOccurrences(jsonScenario, "ApplicationDefinitionJson.Deserialize(").ShouldBe(2); + jsonScenario.ShouldContain( + "var definition = ApplicationDefinitionJson.Deserialize(definitionJson);"); + jsonScenario.ShouldContain("services.AddFluxFlow("); + jsonScenario.ShouldContain("definition,"); + jsonScenario.ShouldContain("var activeRevision = application.Current;"); + jsonScenario.ShouldContain("var activeDefinition = application.CurrentDefinition;"); + jsonScenario.ShouldContain("ReferenceEquals(activeDefinition, definition)"); + + jsonScenario.ShouldContain( + "var unchanged = await application.ApplyAsync(\"package-json-unchanged\", definition);"); + jsonScenario.ShouldContain("unchanged.Status == ApplicationUpdateStatus.Unchanged"); + jsonScenario.ShouldContain("ReferenceEquals(unchanged.ActiveRevision, activeRevision)"); + + jsonScenario.ShouldContain("\"Type\": \"acceptance.unavailable\""); + jsonScenario.ShouldContain( + "var invalidDefinition = ApplicationDefinitionJson.Deserialize(invalidDefinitionJson);"); + jsonScenario.ShouldContain( + "var rejected = await application.ApplyAsync(\"package-json-invalid\", invalidDefinition);"); + jsonScenario.ShouldContain("rejected.Status == ApplicationUpdateStatus.Rejected"); + jsonScenario.ShouldContain("ReferenceEquals(rejected.ActiveRevision, activeRevision)"); + CountOccurrences(jsonScenario, "ReferenceEquals(application.Current, activeRevision)") + .ShouldBe(2); + CountOccurrences(jsonScenario, "ReferenceEquals(application.CurrentDefinition, activeDefinition)") + .ShouldBe(2); + + jsonScenario.ShouldContain( + "await AssertJsonRouteAsync(application, \"package-json\", \"PACKAGE-JSON\");"); + jsonScenario.ShouldContain("\"package-json-after-rejection\","); + jsonScenario.ShouldContain("\"PACKAGE-JSON-AFTER-REJECTION\""); + jsonScenario.ShouldContain("\"Acceptance.Uppercase.Input\""); + jsonScenario.ShouldContain("\"Acceptance.Uppercase.Output\""); + jsonScenario.ShouldContain("PortSendStatus.Accepted"); + jsonScenario.ShouldContain("PortReceiveStatus.Received"); + + var rejectedIndex = jsonScenario.IndexOf( + "var rejected = await application.ApplyAsync", + StringComparison.Ordinal); + var retainedRouteIndex = jsonScenario.IndexOf( + "\"package-json-after-rejection\"", + StringComparison.Ordinal); + var stopIndex = jsonScenario.IndexOf("await application.StopAsync();", StringComparison.Ordinal); + rejectedIndex.ShouldBeGreaterThanOrEqualTo(0); + retainedRouteIndex.ShouldBeGreaterThan(rejectedIndex); + stopIndex.ShouldBeGreaterThan(retainedRouteIndex); + + CountOccurrences(source, "PACKAGE_ACCEPTANCE_ENGINE_OK=True").ShouldBe(1); + source.IndexOf("await RunEngineScenarioAsync();", StringComparison.Ordinal).ShouldBeLessThan( + source.IndexOf( + "Console.WriteLine(\"PACKAGE_ACCEPTANCE_ENGINE_OK=True\");", + StringComparison.Ordinal)); + jsonScenario.ShouldNotContain("PACKAGE_ACCEPTANCE_ENGINE_OK=True"); + } + + [Fact] + public void Acceptance_fixture_executes_optional_standard_health_readiness_from_packages_only() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var source = File.ReadAllText(GetFixturePath(root, "Program.cs")); + var project = File.ReadAllText(GetFixturePath(root, FixtureProject)); + + project.ShouldContain( + ""); + project.ShouldContain("FluxFlowEngineHealthChecksVersion is required."); + project.ShouldNotContain("ProjectReference"); + + source.ShouldContain("using FluxFlow.Engine.HealthChecks;"); + source.ShouldContain("using Microsoft.Extensions.Diagnostics.HealthChecks;"); + CountOccurrences(source, "PACKAGE_ACCEPTANCE_HEALTH_OK=True").ShouldBe(1); + CountOccurrences(source, "services.AddHealthChecks()").ShouldBe(1); + CountOccurrences(source, ".AddFluxFlowApplication();").ShouldBe(1); + source.ShouldContain("GetRequiredService()"); + source.ShouldContain(".CheckHealthAsync(static registration =>"); + source.ShouldContain("\"fluxflow.application\""); + source.ShouldContain("health.Status == HealthStatus.Healthy"); + source.ShouldContain("health.Entries.Count == 1"); + source.ShouldContain("healthEntry.Tags.Order(StringComparer.Ordinal).SequenceEqual([\"fluxflow\", \"ready\"])"); + source.ShouldContain("healthEntry.Data[\"activeRevisionId\"] as string"); + source.ShouldContain("application.Current?.RevisionId"); + source.ShouldNotContain("class AcceptanceHealthCheck"); + source.ShouldNotContain(": IHealthCheck"); + source.ShouldNotContain("BackgroundService"); + source.ShouldNotContain("PeriodicTimer"); + source.ShouldNotContain("System.Reflection"); + } + + [Fact] + public void Acceptance_restart_fixture_uses_explicit_hosted_recovery_and_idempotent_receipts() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var fixturePath = Path.Combine(root, "eng", FixtureDirectory); + var program = File.ReadAllText(Path.Combine(fixturePath, "Program.cs")); + var restart = File.ReadAllText(Path.Combine(fixturePath, "RestartDurabilityScenario.cs")); + + Directory.GetFiles(fixturePath, "*.cs", SearchOption.TopDirectoryOnly) + .Select(Path.GetFileName) + .OrderBy(fileName => fileName, StringComparer.Ordinal) + .ShouldBe(["Program.cs", "RestartDurabilityScenario.cs"]); + + CountOccurrences(program, "durability-restart-seed").ShouldBe(1); + CountOccurrences(program, "durability-restart-recover").ShouldBe(1); + program.ShouldContain("args.Length != 2"); + program.ShouldContain("Path.IsPathFullyQualified(args[1])"); + program.ShouldContain("if (args.Length > 0)"); + program.ShouldContain("default:"); + program.ShouldContain("Unknown package-consumer acceptance mode"); + program.ShouldContain("Restart durability modes require exactly one absolute data-directory argument."); + program.ShouldContain("The restart durability data directory must be absolute."); + program.ShouldContain("RestartDurabilityScenario.SeedAsync(restartDataDirectory)"); + program.ShouldContain("RestartDurabilityScenario.RecoverAsync(restartDataDirectory)"); + program.ShouldNotContain("System.Reflection"); + + restart.ShouldContain("new(2026, 8, 7, 8, 0, 0, TimeSpan.Zero)"); + restart.ShouldContain("LeaseUntil = SeedAt.AddMinutes(1)"); + restart.ShouldContain("RecoveryAt = SeedAt.AddMinutes(2)"); + restart.ShouldContain("new DurableInputLeaseRequest("); + restart.ShouldContain("\"restart-seed-input\""); + restart.ShouldContain("new DurableOutputDeliveryLeaseRequest("); + restart.ShouldContain("\"restart-seed-output\""); + restart.ShouldContain("inputLease.OwnerId"); + restart.ShouldContain("inputLease.LeasedAt == SeedAt"); + restart.ShouldContain("inputLease.Attempt == 1"); + restart.ShouldContain("inputLease.LeaseToken != Guid.Empty"); + restart.ShouldContain("outputLease.OwnerId"); + restart.ShouldContain("outputLease.LeasedAt == SeedAt"); + restart.ShouldContain("outputLease.Attempt == 1"); + restart.ShouldContain("outputLease.LeaseToken != Guid.Empty"); + + restart.ShouldContain("Host.CreateApplicationBuilder()"); + restart.ShouldContain("AddSingleton(new FixedUtcTimeProvider(RecoveryAt))"); + restart.ShouldContain("builder.Services.AddFluxFlow(Definition)"); + restart.ShouldContain(".Advanced.AddDynamicComponent(\"acceptance.restart.uppercase\""); + restart.ShouldNotContain(".AddRuntimeComponent("); + restart.ShouldContain("AddFluxFlowSqlFileDurableInput"); + restart.ShouldContain("AddFluxFlowSqlFileDurableOutput"); + restart.ShouldContain("AddFluxFlowDurableInput(options =>"); + restart.ShouldContain("RestartJsonContext.Default.String"); + restart.ShouldContain("outputs.Capture("); + restart.ShouldContain("AddSingleton(deliveryHandler)"); + restart.ShouldContain("AddFluxFlowDurableOutputDelivery(options =>"); + restart.ShouldContain("input.DeliveredCount == 1 && output.CompletedCount == 2"); + restart.ShouldContain("status.TotalCount == 1"); + restart.ShouldContain("status.CapturedCount == 2"); + restart.ShouldContain("status.UnmaterializedCount == 0"); + + restart.ShouldContain("FileMode.CreateNew"); + restart.ShouldContain("envelope.Key.Address.Value"); + restart.ShouldContain("envelope.Key.MessageId.Value"); + restart.ShouldContain("A durable output identity was reused with different effect content."); + restart.ShouldContain("records.Count == 2"); + restart.ShouldContain("PreappliedOutputValue"); + restart.ShouldContain("WorkflowOutputValue"); + restart.IndexOf("exactly-once", StringComparison.OrdinalIgnoreCase).ShouldBe(-1); + restart.ShouldNotContain("System.Reflection"); + restart.ShouldNotContain("Thread.Sleep"); + restart.ShouldContain("new CancellationTokenSource(TimeSpan.FromSeconds(20))"); + restart.ShouldContain("WaitAsync(timeout.Token)"); + restart.ShouldContain("WaitAsync(TimeSpan.FromSeconds(5))"); + + restart.ShouldContain("InputMessageId = \"restart-input\""); + restart.ShouldContain("PreappliedOutputMessageId = \"restart-preapplied-output\""); + restart.ShouldContain("PACKAGE_ACCEPTANCE_RESTART_SEED_INPUT={input.MessageId.Value}"); + restart.ShouldContain( + "PACKAGE_ACCEPTANCE_RESTART_SEED_OUTPUT={preappliedOutput.MessageId.Value}"); + CountOccurrences(restart, RestartSeedMarkers[2]).ShouldBe(1); + foreach (var marker in RestartRecoveryMarkers) + CountOccurrences(restart, marker).ShouldBe(1); + } + [Fact] public void Acceptance_gate_is_part_of_the_complete_ci_rehearsal() { var root = ReleaseTestPaths.FindRepositoryRoot(); var workflow = File.ReadAllText(Path.Combine(root, ".github", "workflows", "ci.yml")); - CountOccurrences( - workflow, - "./eng/package-consumer-acceptance.ps1 -PackPackages").ShouldBe(1); + const string acceptanceCommand = "./eng/package-consumer-acceptance.ps1 -PackPackages"; + CountOccurrences(workflow, acceptanceCommand).ShouldBe(1); + workflow.IndexOf("- name: Test", StringComparison.Ordinal).ShouldBeGreaterThanOrEqualTo(0); + workflow.IndexOf(acceptanceCommand, StringComparison.Ordinal).ShouldBeGreaterThan( + workflow.IndexOf("- name: Test", StringComparison.Ordinal)); } [Fact] @@ -154,9 +414,26 @@ public async Task Acceptance_script_prepare_only_resolves_exact_closure_without_ restoreCommand.ShouldNotContain("--source"); AssertTopLevelVersionArguments(restoreCommand, fixture.Packages); + var defaultCommand = ReadOutputValue( + result.StandardOutput, + "PACKAGE_ACCEPTANCE_RUN_COMMAND="); + var seedCommand = ReadOutputValue( + result.StandardOutput, + "PACKAGE_ACCEPTANCE_RESTART_SEED_COMMAND="); + var recoveryCommand = ReadOutputValue( + result.StandardOutput, + "PACKAGE_ACCEPTANCE_RESTART_RECOVERY_COMMAND="); + var restartDataDirectory = Path.Combine(fixture.WorkDirectory, "restart-durability"); + defaultCommand.ShouldNotContain("durability-restart-"); + seedCommand.ShouldEndWith($"-- durability-restart-seed {restartDataDirectory}"); + recoveryCommand.ShouldEndWith($"-- durability-restart-recover {restartDataDirectory}"); + foreach (var command in new[] { defaultCommand, seedCommand, recoveryCommand }) + AssertTopLevelVersionArguments(command, fixture.Packages); + Directory.Exists(fixture.PackageSource).ShouldBeFalse(); Directory.Exists(fixture.WorkDirectory).ShouldBeFalse(); File.Exists(fixture.DotnetArgumentsPath).ShouldBeFalse(); + File.Exists(fixture.DotnetProcessesPath).ShouldBeFalse(); } [Fact] @@ -170,7 +447,13 @@ public async Task Acceptance_script_rejects_a_fixture_project_reference_before_p "ItemGroup", new XElement("ProjectReference", new XAttribute("Include", "repository.csproj")))); project.Save(Path.Combine(rejectedFixture, FixtureProject)); - File.Copy(GetFixturePath(root, "Program.cs"), Path.Combine(rejectedFixture, "Program.cs")); + foreach (var sourcePath in Directory.GetFiles( + Path.Combine(root, "eng", FixtureDirectory), + "*.cs", + SearchOption.TopDirectoryOnly)) + { + File.Copy(sourcePath, Path.Combine(rejectedFixture, Path.GetFileName(sourcePath))); + } var result = await ReleaseScriptRunner.RunAsync( root, @@ -237,10 +520,12 @@ public async Task Acceptance_script_restores_verifies_builds_and_runs_from_retai result.ExitCode.ShouldBe(0, result.ToString()); var invocations = File.ReadAllLines(fixture.DotnetArgumentsPath); - invocations.Length.ShouldBe(3); + invocations.Length.ShouldBe(5); invocations[0].ShouldStartWith("restore "); invocations[1].ShouldStartWith("build "); invocations[2].ShouldStartWith("run "); + invocations[3].ShouldStartWith("run "); + invocations[4].ShouldStartWith("run "); CountOccurrences(invocations[0], "--no-cache").ShouldBe(1); CountOccurrences(invocations[0], "--packages").ShouldBe(1); @@ -251,9 +536,33 @@ public async Task Acceptance_script_restores_verifies_builds_and_runs_from_retai invocations[1].ShouldContain("--no-restore"); invocations[2].ShouldContain("--no-build"); invocations[2].ShouldContain("--no-restore"); + var restartDataDirectory = Path.Combine(fixture.WorkDirectory, "restart-durability"); + invocations[2].ShouldNotContain("durability-restart-"); + invocations[3].ShouldEndWith($"-- durability-restart-seed {restartDataDirectory}"); + invocations[4].ShouldEndWith($"-- durability-restart-recover {restartDataDirectory}"); foreach (var invocation in invocations) AssertTopLevelVersionArguments(invocation, fixture.Packages); + var processInvocations = File.ReadAllLines(fixture.DotnetProcessesPath) + .Select(line => line.Split('|', 2)) + .ToArray(); + processInvocations.Length.ShouldBe(5); + processInvocations.Select(parts => parts[1]).ShouldBe(invocations); + processInvocations.Skip(2).Select(parts => parts[0]).Distinct().Count().ShouldBe(3); + + Directory.GetFiles( + Path.Combine(root, "eng", FixtureDirectory), + "*.cs", + SearchOption.TopDirectoryOnly) + .Select(Path.GetFileName) + .OrderBy(fileName => fileName, StringComparer.Ordinal) + .ShouldBe(Directory.GetFiles( + fixture.WorkDirectory, + "*.cs", + SearchOption.TopDirectoryOnly) + .Select(Path.GetFileName) + .OrderBy(fileName => fileName, StringComparer.Ordinal)); + var sourceConfig = XDocument.Load(Path.Combine(fixture.WorkDirectory, "NuGet.config")); var packageSources = sourceConfig .Descendants("packageSources") @@ -272,8 +581,10 @@ public async Task Acceptance_script_restores_verifies_builds_and_runs_from_retai .ShouldBe(fixture.Packages .Select(package => $"PACKAGE_ACCEPTANCE_VERIFIED={package.PackageId}/{package.Version}") .OrderBy(line => line, StringComparer.Ordinal)); - foreach (var marker in RequiredMarkers()) + foreach (var marker in AllRequiredMarkers()) CountOccurrences(result.StandardOutput, marker).ShouldBe(1); + CountOccurrences(result.StandardOutput, "PACKAGE_ACCEPTANCE_RESTART_COMPLETE=True") + .ShouldBe(1); result.StandardOutput.ShouldContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); Directory.Exists(fixture.WorkDirectory).ShouldBeTrue(); @@ -289,6 +600,40 @@ public async Task Acceptance_script_restores_verifies_builds_and_runs_from_retai } } + [Fact] + public async Task Acceptance_script_stops_before_recovery_when_seed_marker_is_missing() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + using var fixture = AcceptanceTestFixture.Create(root); + var environment = fixture.CreateEnvironment(); + environment["FAKE_DOTNET_OMIT_MARKER"] = "PACKAGE_ACCEPTANCE_RESTART_SEED_OK=True"; + + var result = await ReleaseScriptRunner.RunAsync( + root, + "package-consumer-acceptance.ps1", + environment, + "-PackageSource", + fixture.PackageSource, + "-WorkDirectory", + fixture.WorkDirectory); + + result.ExitCode.ShouldNotBe(0); + result.ToString().ShouldContain("Package consumer restart seed must emit"); + result.ToString().ShouldContain("PACKAGE_ACCEPTANCE_RESTART_SEED_OK=True"); + result.ToString().ShouldContain("observed 0"); + result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_RESTART_COMPLETE=True"); + result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); + var invocations = File.ReadAllLines(fixture.DotnetArgumentsPath); + invocations.Length.ShouldBe(4); + invocations[3].ShouldContain("-- durability-restart-seed "); + invocations.ShouldNotContain(invocation => + invocation.Contains("durability-restart-recover", StringComparison.Ordinal)); + Directory.Exists(fixture.WorkDirectory).ShouldBeTrue(); + File.Exists(Path.Combine(fixture.WorkDirectory, "RestartDurabilityScenario.cs")) + .ShouldBeTrue(); + Directory.Exists(fixture.PackageSource).ShouldBeTrue(); + } + public static TheoryData InvalidResolutionModes => new() { @@ -326,13 +671,20 @@ public async Task Acceptance_script_rejects_project_or_non_candidate_resolution( Directory.Exists(fixture.PackageSource).ShouldBeTrue(); } - [Fact] - public async Task Acceptance_script_cleans_owned_workdir_after_missing_marker_failure() + [Theory] + [InlineData("omit", 0)] + [InlineData("duplicate", 2)] + public async Task Acceptance_script_cleans_owned_workdir_after_invalid_recovery_marker_count( + string markerMutation, + int observedCount) { var root = ReleaseTestPaths.FindRepositoryRoot(); using var fixture = AcceptanceTestFixture.Create(root); var environment = fixture.CreateEnvironment(); - environment["FAKE_DOTNET_OMIT_MARKER"] = "PACKAGE_ACCEPTANCE_DURABILITY_OK=True"; + const string invalidMarker = "PACKAGE_ACCEPTANCE_RESTART_IDEMPOTENCY_OK=True"; + environment["FAKE_DOTNET_OMIT_MARKER"] = markerMutation == "omit" ? invalidMarker : null; + environment["FAKE_DOTNET_DUPLICATE_MARKER"] = + markerMutation == "duplicate" ? invalidMarker : null; var candidateBytes = fixture.Packages.ToDictionary( package => package.PackageId, package => File.ReadAllBytes(fixture.GetCandidateArchive(package)), @@ -346,10 +698,12 @@ public async Task Acceptance_script_cleans_owned_workdir_after_missing_marker_fa fixture.PackageSource); result.ExitCode.ShouldNotBe(0); - result.ToString().ShouldContain("PACKAGE_ACCEPTANCE_DURABILITY_OK=True"); - result.ToString().ShouldContain("observed 0"); + result.ToString().ShouldContain("Package consumer restart recovery must emit"); + result.ToString().ShouldContain(invalidMarker); + result.ToString().ShouldContain($"observed {observedCount}"); + result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_RESTART_COMPLETE=True"); result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); - File.ReadAllLines(fixture.DotnetArgumentsPath).Length.ShouldBe(3); + File.ReadAllLines(fixture.DotnetArgumentsPath).Length.ShouldBe(5); var ownedWorkDirectory = ReadOutputValue(result.StandardOutput, "PACKAGE_ACCEPTANCE_WORK_DIR="); Directory.Exists(ownedWorkDirectory).ShouldBeFalse(); @@ -372,13 +726,18 @@ public async Task Acceptance_script_pack_mode_cleans_owned_source_and_workdir_af result.ExitCode.ShouldBe(0, result.ToString()); result.StandardOutput.ShouldContain("PACKAGE_ACCEPTANCE_PACK_PACKAGES=True"); + foreach (var marker in AllRequiredMarkers()) + CountOccurrences(result.StandardOutput, marker).ShouldBe(1); + result.StandardOutput.ShouldContain("PACKAGE_ACCEPTANCE_RESTART_COMPLETE=True"); result.StandardOutput.ShouldContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); var invocations = File.ReadAllLines(fixture.DotnetArgumentsPath); - invocations.Length.ShouldBe(12); - invocations.Take(9).ShouldAllBe(invocation => invocation.StartsWith("pack ", StringComparison.Ordinal)); - invocations[9].ShouldStartWith("restore "); - invocations[10].ShouldStartWith("build "); - invocations[11].ShouldStartWith("run "); + invocations.Length.ShouldBe(15); + invocations.Take(10).ShouldAllBe(invocation => invocation.StartsWith("pack ", StringComparison.Ordinal)); + invocations[10].ShouldStartWith("restore "); + invocations[11].ShouldStartWith("build "); + invocations[12].ShouldStartWith("run "); + invocations[13].ShouldContain("-- durability-restart-seed "); + invocations[14].ShouldContain("-- durability-restart-recover "); var ownedPackageSource = ReadOutputValue(result.StandardOutput, "PACKAGE_ACCEPTANCE_PACKAGE_SOURCE="); var ownedWorkDirectory = ReadOutputValue(result.StandardOutput, "PACKAGE_ACCEPTANCE_WORK_DIR="); @@ -410,11 +769,13 @@ private static void AssertTopLevelVersionArguments( string invocation, IReadOnlyCollection packages) { - foreach (var expected in ExpectedPackageVersions) + foreach (var expected in ExpectedFixturePackageVersions.Where(expected => + expected.Key.StartsWith("FluxFlow.", StringComparison.Ordinal))) { var alias = expected.Key switch { "FluxFlow.Engine" => "engine", + "FluxFlow.Engine.HealthChecks" => "engine-healthchecks", "FluxFlow.Fluent" => "fluent", "FluxFlow.Engine.DurableInput.SqlFile" => "engine-durable-input-sqlfile", "FluxFlow.Engine.DurableOutput.SqlFile" => "engine-durable-output-sqlfile", @@ -432,10 +793,16 @@ private static void AssertTopLevelVersionArguments( } } - private static string[] RequiredMarkers() + private static IEnumerable AllRequiredMarkers() + => DefaultMarkers().Concat(RestartSeedMarkers).Concat(RestartRecoveryMarkers); + + private static string[] DefaultMarkers() => [ "PACKAGE_ACCEPTANCE_ENGINE_OK=True", + "PACKAGE_ACCEPTANCE_CODE_FIRST_OK=True", + "PACKAGE_ACCEPTANCE_RESOURCE_OK=True", + "PACKAGE_ACCEPTANCE_HEALTH_OK=True", "PACKAGE_ACCEPTANCE_FLUENT_OK=True", "PACKAGE_ACCEPTANCE_DURABILITY_OK=True", "PACKAGE_ACCEPTANCE_OK=True" @@ -457,6 +824,18 @@ private static string NormalizePath(string path) .Replace('/', Path.DirectorySeparatorChar) .Replace('\\', Path.DirectorySeparatorChar); + private static string ExtractSourceSection( + string source, + string startMarker, + string endMarker) + { + var start = source.IndexOf(startMarker, StringComparison.Ordinal); + start.ShouldBeGreaterThanOrEqualTo(0); + var end = source.IndexOf(endMarker, start, StringComparison.Ordinal); + end.ShouldBeGreaterThan(start); + return source[start..end]; + } + private static int CountOccurrences(string text, string value) { var count = 0; @@ -489,6 +868,7 @@ private AcceptanceTestFixture(string repositoryRoot, bool createCandidateSource) WorkDirectory = Path.Combine(Root, "consumer-work"); PackageCache = Path.Combine(WorkDirectory, "packages"); DotnetArgumentsPath = Path.Combine(Root, "dotnet-arguments.txt"); + DotnetProcessesPath = Path.Combine(Root, "dotnet-processes.txt"); DotnetCurrentArgumentsPath = Path.Combine(Root, "dotnet-current-arguments.txt"); var metadataPath = Path.Combine(Root, "packages.json"); File.WriteAllText(metadataPath, JsonSerializer.Serialize(Packages)); @@ -498,6 +878,7 @@ private AcceptanceTestFixture(string repositoryRoot, bool createCandidateSource) Environment = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["FAKE_DOTNET_ARGUMENTS"] = DotnetArgumentsPath, + ["FAKE_DOTNET_PROCESSES"] = DotnetProcessesPath, ["FAKE_DOTNET_CURRENT_ARGUMENTS"] = DotnetCurrentArgumentsPath, ["FAKE_DOTNET_DRIVER"] = driverPath, ["FAKE_DOTNET_METADATA"] = metadataPath, @@ -529,6 +910,8 @@ private AcceptanceTestFixture(string repositoryRoot, bool createCandidateSource) public string DotnetArgumentsPath { get; } + public string DotnetProcessesPath { get; } + private string DotnetCurrentArgumentsPath { get; } private string FakeDotnetDirectory { get; } @@ -590,6 +973,7 @@ exec pwsh -NoLogo -NoProfile -File "$FAKE_DOTNET_DRIVER" $ErrorActionPreference = "Stop" $CommandArguments = @(Get-Content -LiteralPath $env:FAKE_DOTNET_CURRENT_ARGUMENTS) Add-Content -LiteralPath $env:FAKE_DOTNET_ARGUMENTS -Value ($CommandArguments -join " ") + Add-Content -LiteralPath $env:FAKE_DOTNET_PROCESSES -Value "$PID|$($CommandArguments -join " ")" $packages = @(Get-Content -LiteralPath $env:FAKE_DOTNET_METADATA -Raw | ConvertFrom-Json) function Read-Argument { @@ -673,15 +1057,44 @@ exit 0 } if ($operation -eq "run") { - $markers = @( - "PACKAGE_ACCEPTANCE_ENGINE_OK=True", - "PACKAGE_ACCEPTANCE_FLUENT_OK=True", - "PACKAGE_ACCEPTANCE_DURABILITY_OK=True", - "PACKAGE_ACCEPTANCE_OK=True" - ) + $mode = @($CommandArguments | Where-Object { $_ -like "durability-restart-*" }) + $markers = if ($mode.Count -eq 0) { + @( + "PACKAGE_ACCEPTANCE_ENGINE_OK=True", + "PACKAGE_ACCEPTANCE_CODE_FIRST_OK=True", + "PACKAGE_ACCEPTANCE_RESOURCE_OK=True", + "PACKAGE_ACCEPTANCE_HEALTH_OK=True", + "PACKAGE_ACCEPTANCE_FLUENT_OK=True", + "PACKAGE_ACCEPTANCE_DURABILITY_OK=True", + "PACKAGE_ACCEPTANCE_OK=True" + ) + } + elseif ($mode[0] -eq "durability-restart-seed") { + @( + "PACKAGE_ACCEPTANCE_RESTART_SEED_INPUT=restart-input", + "PACKAGE_ACCEPTANCE_RESTART_SEED_OUTPUT=restart-preapplied-output", + "PACKAGE_ACCEPTANCE_RESTART_SEED_OK=True" + ) + } + elseif ($mode[0] -eq "durability-restart-recover") { + @( + "PACKAGE_ACCEPTANCE_RESTART_INPUT_RECOVERED=True", + "PACKAGE_ACCEPTANCE_RESTART_WORKFLOW_OUTPUT_CAPTURED=True", + "PACKAGE_ACCEPTANCE_RESTART_PENDING_OUTPUT_RESUMED=True", + "PACKAGE_ACCEPTANCE_RESTART_OUTPUT_RECOVERED=True", + "PACKAGE_ACCEPTANCE_RESTART_IDEMPOTENCY_OK=True", + "PACKAGE_ACCEPTANCE_RESTART_OK=True" + ) + } + else { + throw "Fake dotnet received unexpected acceptance mode '$($mode[0])'." + } foreach ($marker in $markers) { if ($marker -ne $env:FAKE_DOTNET_OMIT_MARKER) { Write-Output $marker + if ($marker -eq $env:FAKE_DOTNET_DUPLICATE_MARKER) { + Write-Output $marker + } } } } diff --git a/tests/FluxFlow.Release.Tests/PerformanceHardeningConventionTests.cs b/tests/FluxFlow.Release.Tests/PerformanceHardeningConventionTests.cs new file mode 100644 index 00000000..7c86e6a7 --- /dev/null +++ b/tests/FluxFlow.Release.Tests/PerformanceHardeningConventionTests.cs @@ -0,0 +1,168 @@ +using System.Text.RegularExpressions; +using Shouldly; +using Xunit; + +namespace FluxFlow.Release.Tests; + +public sealed class PerformanceHardeningConventionTests +{ + [Fact] + public void Benchmark_project_is_a_manual_non_packable_net10_suite_with_eight_cases() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var benchmarkDirectory = Path.Combine( + root, + "benchmarks", + "FluxFlow.Engine.Benchmarks"); + var solution = File.ReadAllText(Path.Combine(root, "FluxFlow.sln")); + var project = File.ReadAllText(Path.Combine( + benchmarkDirectory, + "FluxFlow.Engine.Benchmarks.csproj")); + var program = File.ReadAllText(Path.Combine(benchmarkDirectory, "Program.cs")); + + solution.ShouldContain( + @"benchmarks\FluxFlow.Engine.Benchmarks\FluxFlow.Engine.Benchmarks.csproj"); + project.ShouldContain("net10.0"); + project.ShouldContain("false"); + program.ShouldContain("BenchmarkSwitcher"); + program.ShouldContain(".FromAssembly(typeof(Program).Assembly)"); + program.ShouldContain(".Run(args);"); + + var benchmarkFiles = Directory.GetFiles( + benchmarkDirectory, + "*Benchmarks.cs", + SearchOption.TopDirectoryOnly) + .Select(Path.GetFileName) + .OrderBy(static name => name, StringComparer.Ordinal) + .ToArray(); + benchmarkFiles.ShouldBe(new[] + { + "ApplicationLinkCompilationBenchmarks.cs", + "ApplicationMessagingBenchmarks.cs", + "ApplicationTopologyBenchmarks.cs" + }); + + var messaging = ReadBenchmarkSource(benchmarkDirectory, "ApplicationMessagingBenchmarks.cs"); + var topology = ReadBenchmarkSource(benchmarkDirectory, "ApplicationTopologyBenchmarks.cs"); + var compilation = ReadBenchmarkSource( + benchmarkDirectory, + "ApplicationLinkCompilationBenchmarks.cs"); + AssertBenchmarkClass(messaging, expectedBenchmarkMethods: 3); + AssertBenchmarkClass(topology, expectedBenchmarkMethods: 1); + AssertBenchmarkClass(compilation, expectedBenchmarkMethods: 1); + messaging.ShouldContain("[GlobalCleanup]"); + topology.ShouldContain("[GlobalCleanup]"); + compilation.ShouldNotContain("[GlobalCleanup]"); + CountOccurrences(messaging, "[Params(").ShouldBe(0); + CountOccurrences(topology, "[Params(").ShouldBe(1); + CountOccurrences(compilation, "[Params(").ShouldBe(1); + topology.ShouldContain("[Params(1, 8)]"); + compilation.ShouldContain("[Params(1, 32, 128)]"); + + const int messagingCases = 3; + const int topologyCases = 2; + const int compilationCases = 3; + (messagingCases + topologyCases + compilationCases).ShouldBe(8); + } + + [Fact] + public void Performance_baseline_is_indexed_and_keeps_timing_out_of_ci() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var documentName = "43-performance-concurrency-lifetime-baseline.md"; + var index = File.ReadAllText(Path.Combine(root, "docs", "README.md")); + var baseline = File.ReadAllText(Path.Combine(root, "docs", documentName)); + + index.ShouldContain($"({documentName})"); + baseline.ShouldContain("not CI"); + baseline.ShouldContain("pass/fail thresholds"); + baseline.ShouldContain("Timing is never used as correctness evidence."); + baseline.ShouldContain("Benchmark jobs remain"); + baseline.ShouldContain("manual evidence"); + + var workflowSources = Directory.GetFiles( + Path.Combine(root, ".github", "workflows"), + "*.yml", + SearchOption.TopDirectoryOnly) + .Select(File.ReadAllText) + .ToArray(); + workflowSources.ShouldNotBeEmpty(); + var combinedWorkflows = string.Join(Environment.NewLine, workflowSources); + combinedWorkflows.ShouldNotContain("FluxFlow.Engine.Benchmarks"); + combinedWorkflows.ShouldNotContain("BenchmarkDotNet"); + combinedWorkflows.ShouldNotContain("--job Dry"); + combinedWorkflows.ShouldNotContain("--job Short"); + } + + [Fact] + public void Unconditional_route_skips_the_only_condition_context_allocation() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var source = File.ReadAllText(Path.Combine( + root, + "src", + "FluxFlow.Engine", + "Ports", + "ApplicationOutputPort.cs")); + const string guard = "if (!link.IsConditional)"; + const string context = "new FlowMapContext"; + const string variables = "new Dictionary"; + + CountOccurrences(source, guard).ShouldBe(1); + CountOccurrences(source, context).ShouldBe(1); + CountOccurrences(source, variables).ShouldBe(1); + var guardIndex = source.IndexOf(guard, StringComparison.Ordinal); + var contextIndex = source.IndexOf(context, StringComparison.Ordinal); + var variablesIndex = source.IndexOf(variables, StringComparison.Ordinal); + guardIndex.ShouldBeLessThan(contextIndex); + contextIndex.ShouldBeLessThan(variablesIndex); + source[guardIndex..contextIndex].ShouldContain("return true;"); + } + + [Fact] + public void Diagnostic_attribute_publisher_uses_fixed_arity_builders_without_linq_or_params() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var source = File.ReadAllText(Path.Combine( + root, + "src", + "FluxFlow.Engine", + "Ports", + "ApplicationPortEventPublisher.cs")); + + source.ShouldNotContain("params "); + source.ShouldNotContain(".Where("); + source.ShouldNotContain(".ToDictionary("); + CountOccurrences( + source, + "private static Dictionary CreateAttributes(").ShouldBe(2); + source.ShouldContain("new Dictionary(2, StringComparer.Ordinal)"); + source.ShouldContain("new Dictionary(3, StringComparer.Ordinal)"); + CountOccurrences(source, "private static JsonElement CreateDetails(").ShouldBe(2); + source.ShouldContain("AddAttribute(attributes, first);"); + source.ShouldContain("AddAttribute(attributes, second);"); + source.ShouldContain("AddAttribute(attributes, third);"); + } + + private static string ReadBenchmarkSource(string directory, string fileName) + => File.ReadAllText(Path.Combine(directory, fileName)); + + private static void AssertBenchmarkClass(string source, int expectedBenchmarkMethods) + { + CountOccurrences(source, "[MemoryDiagnoser]").ShouldBe(1); + CountOccurrences(source, "[GlobalSetup]").ShouldBe(1); + Regex.Matches( + source, + @"^\s*\[Benchmark(?:\(|\])", + RegexOptions.CultureInvariant | RegexOptions.Multiline) + .Count.ShouldBe(expectedBenchmarkMethods); + Regex.Matches( + source, + @"\[Benchmark(?:\([^\]]*\))?\]\s+public\s+[^\r\n]+\r?\n\s*=>", + RegexOptions.CultureInvariant) + .Count.ShouldBe(expectedBenchmarkMethods); + } + + private static int CountOccurrences(string source, string value) + => source.Split(value, StringSplitOptions.None).Length - 1; +} diff --git a/tests/FluxFlow.Release.Tests/TypedComponentAuthoringConventionTests.cs b/tests/FluxFlow.Release.Tests/TypedComponentAuthoringConventionTests.cs new file mode 100644 index 00000000..79c80fa2 --- /dev/null +++ b/tests/FluxFlow.Release.Tests/TypedComponentAuthoringConventionTests.cs @@ -0,0 +1,307 @@ +using System.Text.RegularExpressions; +using Shouldly; +using Xunit; + +namespace FluxFlow.Release.Tests; + +public sealed class TypedComponentAuthoringConventionTests +{ + private static readonly string[] FamilyRegistrationSources = + [ + "src/FluxFlow.Components.Assertions.Composition/AssertionsServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Expectations.Composition/ExpectationsServiceCollectionExtensions.cs", + "src/FluxFlow.Components.FileSystem.Composition/FileSystemServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Http.Composition/HttpServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Mapping.Composition/MappingServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Metrics.Composition/MetricsServiceCollectionExtensions.cs", + "src/Mqtt/FluxFlow.Components.Mqtt.Composition/MqttServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Observability.Composition/ObservabilityServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Payloads.Composition/PayloadsServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Projections.Composition/ProjectionsServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Resilience.Composition/ResilienceServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Routing.Composition/RoutingServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Serialization.Composition/SerializationServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Sessions.Composition/SessionsServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Sources.Composition/SourcesServiceCollectionExtensions.cs", + "src/FluxFlow.Components.State.Composition/StateServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Storage.Composition/StorageServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Timers.Composition/TimersServiceCollectionExtensions.cs", + "src/FluxFlow.Components.Validation.Composition/ValidationServiceCollectionExtensions.cs" + ]; + + private static readonly string[] FamilyAuthoringSources = + [ + "src/FluxFlow.Components.Assertions.Composition/AssertionsAuthoringExtensions.cs", + "src/FluxFlow.Components.Expectations.Composition/ExpectationsAuthoringExtensions.cs", + "src/FluxFlow.Components.FileSystem.Composition/FileSystemAuthoringExtensions.cs", + "src/FluxFlow.Components.Http.Composition/HttpAuthoringExtensions.cs", + "src/FluxFlow.Components.Mapping.Composition/MappingAuthoringExtensions.cs", + "src/FluxFlow.Components.Metrics.Composition/MetricsAuthoringExtensions.cs", + "src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttApplicationAuthoringExtensions.cs", + "src/FluxFlow.Components.Observability.Composition/ObservabilityAuthoringExtensions.cs", + "src/FluxFlow.Components.Payloads.Composition/PayloadsAuthoringExtensions.cs", + "src/FluxFlow.Components.Projections.Composition/ProjectionsAuthoringExtensions.cs", + "src/FluxFlow.Components.Resilience.Composition/ResilienceAuthoringExtensions.cs", + "src/FluxFlow.Components.Routing.Composition/RoutingAuthoringExtensions.cs", + "src/FluxFlow.Components.Serialization.Composition/SerializationAuthoringExtensions.cs", + "src/FluxFlow.Components.Sessions.Composition/SessionsAuthoringExtensions.cs", + "src/FluxFlow.Components.Sources.Composition/SourcesAuthoringExtensions.cs", + "src/FluxFlow.Components.State.Composition/StateAuthoringExtensions.cs", + "src/FluxFlow.Components.Storage.Composition/StorageAuthoringExtensions.cs", + "src/FluxFlow.Components.Timers.Composition/TimersAuthoringExtensions.cs", + "src/FluxFlow.Components.Validation.Composition/ValidationAuthoringExtensions.cs" + ]; + + private static readonly AuthoringScope[] SampleAndAcceptanceScopes = + [ + new("Composition sample", ["samples/FluxFlow.CompositionSample/Program.cs"]), + new( + "Sample application", + [ + "samples/FluxFlow.SampleApp/SampleComponentRegistration.cs", + "samples/FluxFlow.SampleApp/OrderNodes.cs", + "samples/FluxFlow.SampleApp/SampleWorkspaceDefinition.cs" + ]), + new("MQTT composition sample", ["samples/FluxFlow.MqttCompositionSample/Program.cs"]), + new( + "Package consumer acceptance fixture", + ["eng/package-consumer-acceptance/Program.cs"]) + ]; + + [Fact] + public void Official_family_sources_create_one_complete_contract_and_register_it_without_duplicate_runtime_configuration() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + + FamilyRegistrationSources.Length.ShouldBe(19); + FamilyAuthoringSources.Length.ShouldBe(19); + var contractDeclarations = 0; + var contractRegistrations = 0; + for (var index = 0; index < FamilyRegistrationSources.Length; index++) + { + var registrationPath = FamilyRegistrationSources[index]; + var authoringPath = FamilyAuthoringSources[index]; + var registration = ReadSource(root, registrationPath); + var authoring = ReadSource(root, authoringPath); + var combined = registration + Environment.NewLine + authoring; + + registration.ShouldContain( + ".AddDesignedComponent(", + Case.Sensitive, + $"{registrationPath} must register the exact designed contract."); + registration.ShouldNotContain( + ".AddRuntimeComponent(", + Case.Sensitive, + $"{registrationPath} must not duplicate contract-owned runtime configuration."); + combined.ShouldNotContain( + ".AddDynamicComponent(", + Case.Sensitive, + $"{registrationPath} is normal family authoring and must not use the advanced dynamic surface."); + authoring.ShouldContain( + "ComponentContract<", + Case.Sensitive, + $"{authoringPath} must expose typed complete contracts."); + authoring.ShouldContain( + "DesignedComponentContract.Create(", + Case.Sensitive, + $"{authoringPath} must create runtime and design metadata from one declaration."); + combined.ShouldContain( + ".UseFactory(", + Case.Sensitive, + $"{registrationPath} must use the typed node-factory path."); + combined.ShouldContain( + ".HasEvents(", + Case.Sensitive, + $"{registrationPath} must explicitly declare component events."); + combined.ShouldNotContain("ComponentAuthoringContract", Case.Sensitive); + AssertNoDuplicatedRuntimePortConstruction(registrationPath, combined); + combined.ShouldNotContain(".UseInstanceFactory(", Case.Sensitive, + $"{registrationPath} is normal family authoring and must not use the raw-instance escape hatch."); + contractDeclarations += CountOccurrences(authoring, "public static ComponentContract<"); + contractRegistrations += CountOccurrences(registration, ".AddDesignedComponent("); + } + + contractDeclarations.ShouldBe(44); + contractRegistrations.ShouldBe(44); + } + + [Fact] + public void Normal_samples_and_package_code_first_path_use_embedded_contracts_without_redundant_runtime_registration() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + + SampleAndAcceptanceScopes.Length.ShouldBe(4); + foreach (var scope in SampleAndAcceptanceScopes) + { + var source = string.Join( + Environment.NewLine, + scope.RelativePaths.Select(path => ReadSource(root, path))); + + source.ShouldContain( + "ComponentContract.Create(", + Case.Sensitive, + $"{scope.Name} must construct complete code-first contracts."); + source.ShouldContain( + ".UseFactory(", + Case.Sensitive, + $"{scope.Name} must show typed node factories."); + source.ShouldContain( + ".HasEvents(", + Case.Sensitive, + $"{scope.Name} must show explicit event-port binding."); + AssertNoDuplicatedRuntimePortConstruction(scope.Name, source); + source.ShouldNotContain("ComponentAuthoringContract", Case.Sensitive); + source.ShouldNotContain(".AddRuntimeComponent(", Case.Sensitive, + $"{scope.Name} must rely on embedded contracts for its normal code-first path."); + source.ShouldNotContain(".AddDynamicComponent(", Case.Sensitive, + $"{scope.Name} must not use the advanced dynamic escape hatch."); + source.ShouldNotContain(".UseInstanceFactory(", Case.Sensitive, + $"{scope.Name} must demonstrate normal typed authoring, not the advanced escape hatch."); + } + } + + [Fact] + public void Mqtt_declares_four_executable_resource_contracts_and_only_configuration_path_registers_AddMqtt() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var authoring = ReadSource( + root, + "src/Mqtt/FluxFlow.Components.Mqtt.Composition/Authoring/MqttApplicationAuthoringExtensions.cs"); + var sample = ReadSource( + root, + "samples/FluxFlow.MqttCompositionSample/Program.cs"); + + authoring.ShouldContain("public static class MqttResources", Case.Sensitive); + CountOccurrences(authoring, "public static ApplicationResourceContract<") + .ShouldBe(4); + CountOccurrences(authoring, "ApplicationResourceContract.Create(") + .ShouldBe(4); + authoring.ShouldContain("MqttCompositionResourceRegistrar", Case.Sensitive); + + var configurationPath = ReadSection( + sample, + "static async Task> RunConfigurationCompositionAsync(", + "static async Task> RunDefinitionApplicationAsync("); + var codeFirstPath = ReadSection( + sample, + "static async Task> RunDefinitionApplicationAsync(", + "static async Task> RunHostedApplicationAsync("); + + configurationPath.ShouldContain("registerMqtt: true", Case.Sensitive); + codeFirstPath.ShouldContain("new ApplicationDefinitionBuilder()", Case.Sensitive); + codeFirstPath.ShouldContain(".AddMqttBroker(", Case.Sensitive); + codeFirstPath.ShouldContain(".AddMqttClient(", Case.Sensitive); + codeFirstPath.ShouldContain("registerMqtt: false", Case.Sensitive); + codeFirstPath.ShouldNotContain(".AddMqtt()", Case.Sensitive); + codeFirstPath.ShouldNotContain("ApplicationDefinitionJson", Case.Sensitive); + } + + [Fact] + public void Code_first_resource_execution_uses_definition_owned_contracts_without_reflection_or_global_scanning() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var source = string.Join( + Environment.NewLine, + new[] + { + "src/FluxFlow.Composition/Authoring/ApplicationResourceContract.cs", + "src/FluxFlow.Composition/Authoring/ApplicationDefinitionBuilder.cs", + "src/FluxFlow.Engine/Hosting/ApplicationRuntimeResourceSnapshotFactory.cs" + }.Select(path => ReadSource(root, path))); + + source.ShouldContain("ApplicationResourceContracts", Case.Sensitive); + source.ShouldContain("RegistrationIdentity", Case.Sensitive); + source.ShouldContain("ReferenceEqualityComparer.Instance", Case.Sensitive); + source.ShouldNotContain("System.Reflection", Case.Sensitive); + source.ShouldNotContain("Activator.CreateInstance", Case.Sensitive); + source.ShouldNotContain("AppDomain.CurrentDomain", Case.Sensitive); + source.ShouldNotContain("GetAssemblies(", Case.Sensitive); + source.ShouldNotContain("Assembly.Load(", Case.Sensitive); + } + + [Fact] + public void Fluent_sources_compile_to_the_canonical_definition_and_application_without_a_parallel_runtime() + { + var root = ReleaseTestPaths.FindRepositoryRoot(); + var source = string.Join( + Environment.NewLine, + new[] + { + "src/FluxFlow.Fluent/FlowGraph.cs", + "src/FluxFlow.Fluent/FlowGraphBuilder.cs" + }.Select(path => ReadSource(root, path))); + + source.ShouldContain("ApplicationDefinitionBuilder _application = new()", Case.Sensitive); + source.ShouldContain("ComponentContract.Create", Case.Sensitive); + source.ShouldContain("services.AddFluxFlow(", Case.Sensitive); + source.ShouldContain("GetRequiredService()", Case.Sensitive); + source.ShouldContain("public ApplicationDefinition Definition", Case.Sensitive); + source.ShouldContain("public FluxFlowApplication Application", Case.Sensitive); + source.ShouldNotContain("ApplicationRuntime", Case.Sensitive); + source.ShouldNotContain("FlowGraphEngine", Case.Sensitive); + source.ShouldNotContain("ComponentInstance.Create(", Case.Sensitive); + } + + private static void AssertNoDuplicatedRuntimePortConstruction(string owner, string source) + { + source.ShouldNotContain("ComponentInstance.Create(", Case.Sensitive, + $"{owner} must let typed UseFactory selectors construct the runtime instance."); + Regex.IsMatch(source, @"(?= 0) + { + count++; + index += token.Length; + } + + return count; + } + + private static string ReadSection(string source, string startMarker, string endMarker) + { + var start = source.IndexOf(startMarker, StringComparison.Ordinal); + start.ShouldBeGreaterThanOrEqualTo(0); + var end = source.IndexOf(endMarker, start, StringComparison.Ordinal); + end.ShouldBeGreaterThan(start); + return source[start..end]; + } + + private static readonly string[] LegacyPortMethodTokens = + [ + ".AddInput(", + ".AddInput<", + ".AddSignalInput(", + ".AddOutput(", + ".AddOutput<", + ".AddEvents(" + ]; + + private sealed record AuthoringScope(string Name, IReadOnlyList RelativePaths); +} From 2756c32571319463fa851171d9436c2de2a80dd1 Mon Sep 17 00:00:00 2001 From: meisa Date: Sat, 8 Aug 2026 22:05:06 +0200 Subject: [PATCH 2/6] Record release candidate validation --- docs/44-release-candidate-consolidation.md | 121 ++++++++++++++++++ docs/README.md | 1 + .../README.md | 28 +++- memory/00-index.md | 3 + memory/01-current-state.md | 25 ++++ memory/304-release-candidate-consolidation.md | 54 ++++++++ 6 files changed, 231 insertions(+), 1 deletion(-) create mode 100644 docs/44-release-candidate-consolidation.md create mode 100644 memory/304-release-candidate-consolidation.md diff --git a/docs/44-release-candidate-consolidation.md b/docs/44-release-candidate-consolidation.md new file mode 100644 index 00000000..77fa70eb --- /dev/null +++ b/docs/44-release-candidate-consolidation.md @@ -0,0 +1,121 @@ +# Release-Candidate Consolidation + +This document records the supported authoring paths and the validation evidence +for the consolidated FluxFlow release candidate. It is a release-readiness +record, not a publication announcement. No package was published and no tag or +release was created. + +## Supported authoring paths + +FluxFlow intentionally supports two independent ways to define an application. +They converge on the same canonical engine, but they serve different use cases. + +### Typed C# code-first + +Code-first applications use complete component and resource contracts. The +application definition retains the executable descriptors that it needs, so a +normal host registers the finished definition once: + +```csharp +var builder = new ApplicationDefinitionBuilder(); +builder.AddWorkflow("main", out var workflow); + +workflow + .AddComponent("source", SampleComponents.Source, out var source) + .AddComponent("upper", SampleComponents.Uppercase, out var upper); + +source.Output.ConnectTo(upper.Input); + +var definition = builder.Build(); +services.AddFluxFlow(definition); +``` + +The shortened example emphasizes the ownership rule: the definition owns the +contracts selected while authoring. Normal code-first use does not repeat those +component or resource registrations in the service-registration section. +Typed handles remain available for sending, receiving, observing, durable +input, and durable-output capture. + +C# predicates and other executable delegates are allowed on this path. A +code-first definition is an in-process executable blueprint; it is not required +to serialize to the portable JSON format. + +### Portable JSON + +Portable JSON remains a separate, data-only source for configuration files, +designers, persistence, and hot reload. It contains portable application data, +not executable C# delegates or embedded runtime factories. + +A JSON host deserializes the definition, explicitly registers the component and +resource packages that may be named by that data, and registers the resulting +definition with FluxFlow. The package catalog is intentionally explicit because +untrusted configuration must not cause reflection-based discovery or magic +activation. + +The package-only acceptance fixture proves that a JSON definition can start and +route by address, that applying the same definition is `Unchanged`, and that an +independently deserialized invalid candidate is `Rejected` without replacing +the active revision. A fresh message routes successfully after that rejection. + +## Consolidation boundaries + +This round did not add a parallel runtime, a new workflow feature, reflection, +assembly scanning, a background worker, polling, or a new dependency. It froze +the accepted typed C# and portable JSON paths and consolidated their release +evidence. + +All 19 component-family package READMEs now state the same boundary: + +- complete contracts own their executable descriptors; +- normal code-first applications call `AddFluxFlow(definition)` without + repeating ordinary family registration; +- explicit family registration remains available for JSON, configuration, + catalog, and advanced dynamic scenarios. + +## Exact candidate + +- Branch: `work/release-candidate-consolidation` +- Candidate commit: `4bf69015b9d3eaa95a45630c91d378c45c5a2aaa` +- Baseline commit: `37c1de35e335d84541ec06ad9f388cfce1b55876` +- Detached validation worktree: + `C:\Users\meisa\AppData\Local\Temp\fluxflow-rc-4bf69015` + +The detached worktree was created from the exact candidate commit. Restore, +build, tests, packaging, formatting, dependency audit, and provider validation +therefore did not depend on untracked source or stale output from the primary +working tree. + +## Validation evidence + +| Requirement | Evidence | +| --- | --- | +| Clean restore | 137 projects restored successfully. | +| CI-style Release build | 137 projects built with `ContinuousIntegrationBuild=true`; 0 warnings and 0 errors. | +| Complete solution tests | 2,675 passed across 67 test projects; 0 failed and 0 warnings. | +| Complete release-governance tests | 191 passed; 0 failed and 0 warnings. | +| Public API freeze | `PublicApiBaselineTests`: 2 passed; 0 failed and 0 warnings. | +| Formatting and whitespace | `dotnet format --verify-no-changes` exited 0; `git diff --check` exited 0. | +| Dependency security | Direct and transitive vulnerability audit reported no vulnerable packages for every solution project. | +| Packed-package consumer | Ten exact candidate packages were packed, hash-verified, restored, built, and executed from an isolated source. The fixture completed its default, seed, and recovery processes and cleaned both owned temporary directories. | +| JSON rollback | Package-only execution proved initial routing, `Unchanged` reapply, invalid-candidate `Rejected`, exact active-revision retention, and successful post-rejection routing. | +| Code-first and resources | Package-only execution emitted the exact code-first and executable-resource success markers without repeated host registration. | +| Optional capabilities | Package-only execution emitted the exact health, Fluent, durability, restart, idempotency, and overall completion markers once each. | +| Real durable input | T-SQL integration: 90 passed, 0 failed, 0 skipped. | +| Real durable output | T-SQL integration: 117 passed, 0 failed, 0 skipped. | +| Provider identity | Both suites used the same pinned provider-image digest, `sha256:ba4c8329f48fb8f02e1416be6a930ebfd71268caee78aa985f3af4315e457c89`. | +| Cleanup | Candidate package source, consumer work directory, SQL containers, and detached-worktree repository state were clean after their gates. | + +The package-only gate performed 15 process invocations: ten package operations, +one restore, one build, and the default, seed, and recovery executions. Its +success markers covered Engine, code-first authoring, executable resources, +health, Fluent, durability, restart seeding and recovery, idempotency, restart +completion, and overall completion. Every required marker appeared exactly +once. + +## Deliberately deferred + +Publication remains a separate authorized action. This consolidation did not +push the branch, open a pull request, create a tag or release, or publish a +package. Provider-specific operational tuning, new component families, and new +workflow features remain future work and are not release blockers for this +candidate. diff --git a/docs/README.md b/docs/README.md index 661cbd49..39ebdb42 100644 --- a/docs/README.md +++ b/docs/README.md @@ -69,6 +69,7 @@ loading them; the runtime accepts only the canonical document shape and names. 41. [End-To-End Code-First Simplification](41-end-to-end-code-first-simplification.md) 42. [Application Health Readiness](42-application-health-readiness.md) 43. [Performance, Concurrency, And Lifetime Baseline](43-performance-concurrency-lifetime-baseline.md) +44. [Release-Candidate Consolidation](44-release-candidate-consolidation.md) Retired documents require an external, one-time conversion. Current runtime guidance uses only the canonical application and component model. diff --git a/goals/2026-08-08-release-candidate-consolidation/README.md b/goals/2026-08-08-release-candidate-consolidation/README.md index 15e6da14..7f84d6ff 100644 --- a/goals/2026-08-08-release-candidate-consolidation/README.md +++ b/goals/2026-08-08-release-candidate-consolidation/README.md @@ -1,7 +1,7 @@ # Goal: Consolidate FluxFlow into a clean release candidate and prove both consumer paths - Date: 2026-08-08 -- State: active +- State: complete - Scope: accumulated code-first, JSON, resource, durability, health, performance, package, sample, documentation, and release-validation changes - Compatibility: freeze the intended public API and portable JSON format; remove only obsolete or contradictory material already superseded by the accepted design - Publication: no push, pull request, tag, release, or package publication without a separate explicit user request @@ -497,3 +497,29 @@ The final handoff must state: - confirmation that nothing was pushed, tagged, released, or published; - a compact `Requirement | Evidence` table citing exact tests, commands, or documents. + +## Execution result + +Completed on 2026-08-08 on branch +`work/release-candidate-consolidation`. The exact implementation candidate is +`4bf69015b9d3eaa95a45630c91d378c45c5a2aaa`. + +The candidate was restored, built, tested, formatted, audited, packed, and run +from a detached clean worktree. Final results were: + +- 137-project restore and CI-style Release build with 0 warnings and 0 errors; +- 2,675/2,675 solution tests across 67 test projects; +- 191/191 release-governance tests and 2/2 public API baseline tests; +- clean formatting, whitespace, and direct/transitive vulnerability gates; +- ten exact candidate packages and 15 package-consumer process invocations, + with every required marker exactly once and owned-directory cleanup; +- real T-SQL durable input: 90/90 with zero skips; +- real T-SQL durable output: 117/117 with zero skips; +- provider digest + `sha256:ba4c8329f48fb8f02e1416be6a930ebfd71268caee78aa985f3af4315e457c89`; +- no remaining candidate worktree change or provider container; +- no push, pull request, tag, release, or package publication. + +The supported paths and full evidence are recorded in +`docs/44-release-candidate-consolidation.md` and +`memory/304-release-candidate-consolidation.md`. diff --git a/memory/00-index.md b/memory/00-index.md index 92891cb5..928bf50f 100644 --- a/memory/00-index.md +++ b/memory/00-index.md @@ -777,6 +777,9 @@ This folder records the extraction work for `FluxFlow.Engine`. coverage, bounded hot-path audit, measured allocation reductions, deterministic concurrency/revision/shutdown proof, and manual-only timing policy. +- `304-release-candidate-consolidation.md`: frozen typed C# and portable JSON + paths, package-only rollback proof, clean committed-snapshot validation, + real SQL-provider evidence, and the no-publication boundary. - `report.md`: original FluxMq migration spike report supplied for review. - `legacy-docs/`: historical pre-cleanup docs; current decisions override older API descriptions in this folder. diff --git a/memory/01-current-state.md b/memory/01-current-state.md index 950fd1c2..4e3e111a 100644 --- a/memory/01-current-state.md +++ b/memory/01-current-state.md @@ -550,3 +550,28 @@ process-restart durability remain independent and preserved. - Temporary worktrees, containers, package sources, archives, caches, and logs were removed. No tag, release, publication, or public-feed mutation occurred. See `memory/291-pr-65-merge-and-post-merge-validation.md`. + +## Consolidated Release Candidate + +- Typed C# code-first definitions now own their complete executable component + and resource contracts. Normal hosts register the finished definition once; + they do not repeat ordinary family registration. +- Portable JSON remains an independent data-only path with explicit package + registration for configuration, persistence, designers, and hot reload. C# + predicates remain intentionally code-first and are not forced into JSON. +- The exact candidate commit + `4bf69015b9d3eaa95a45630c91d378c45c5a2aaa` passed a clean 137-project restore + and CI-style Release build, 2,675 solution tests, 191 release tests, the + public API baseline, formatting, whitespace, and dependency-vulnerability + gates. +- The isolated package-only consumer packed ten exact candidate packages and + completed 15 pack/restore/build/run invocations. It proved code-first, + executable resources, health, Fluent, durability, restart recovery, and JSON + rejection rollback with every required marker exactly once and full owned + directory cleanup. +- Real T-SQL integration passed 90 durable-input and 117 durable-output cases + with zero failures or skips. Both used the recorded pinned provider-image + digest, and their owned containers were removed. +- No push, pull request, tag, release, or package publication occurred. See + `memory/304-release-candidate-consolidation.md` and + `docs/44-release-candidate-consolidation.md`. diff --git a/memory/304-release-candidate-consolidation.md b/memory/304-release-candidate-consolidation.md new file mode 100644 index 00000000..a5089e02 --- /dev/null +++ b/memory/304-release-candidate-consolidation.md @@ -0,0 +1,54 @@ +# Release-Candidate Consolidation + +Date: 2026-08-08 + +The accumulated typed authoring, portable JSON, resources, durability, health, +performance, package-acceptance, sample, and documentation work was +consolidated on `work/release-candidate-consolidation`. + +The exact implementation candidate is +`4bf69015b9d3eaa95a45630c91d378c45c5a2aaa`. It was validated from a detached +clean worktree, not from the primary dirty tree. + +## Final supported model + +- Typed C# code-first definitions retain complete executable component and + resource contracts. Normal hosting registers the definition once with + `AddFluxFlow(definition)` and does not repeat ordinary family registration. +- Portable JSON remains an independent data-only definition path. Its runtime + component/resource catalog is explicit, keeping configuration portable and + avoiding reflection, discovery magic, or hidden activation. +- C# authoring may use executable C# predicates and is not constrained by JSON + serialization. JSON remains the format for configuration, persistence, + designers, and hot reload. +- Both paths execute through the canonical Engine lifecycle and revision model. + +## Consolidation changes + +- The package-only JSON scenario now proves same-definition `Unchanged`, + independent invalid-candidate `Rejected`, exact active-revision retention, + and a fresh successful route after rejection. +- All 19 component-family package READMEs explain contract-owned executable + descriptors, one-line normal code-first registration, and the explicit + portable/dynamic registration boundary. +- Release-governance tests enforce those package documentation and package-only + behavior boundaries. + +## Exact evidence + +- Restore: 137 projects, successful. +- CI-style Release build: 137 projects, 0 warnings, 0 errors. +- Solution: 2,675 passed across 67 test projects, 0 failures, 0 warnings. +- Release tests: 191 passed, 0 failures, 0 warnings. +- Public API baseline: 2 passed, 0 failures, 0 warnings. +- Formatting and whitespace: clean. +- Direct/transitive vulnerability audit: no vulnerable packages. +- Package-only consumer: ten exact candidate packages, 15 process invocations, + all required markers exactly once, and owned source/work directories removed. +- Real T-SQL durable input: 90 passed, 0 failed, 0 skipped. +- Real T-SQL durable output: 117 passed, 0 failed, 0 skipped. +- Both provider gates used the pinned provider-image digest + `sha256:ba4c8329f48fb8f02e1416be6a930ebfd71268caee78aa985f3af4315e457c89`. + +No push, pull request, tag, release, package publication, or external product +mutation occurred. Publication remains a separately authorized step. From 29cb08f9125218c125c628fa10d2e00c70047ca4 Mon Sep 17 00:00:00 2001 From: meisa Date: Sat, 8 Aug 2026 22:43:20 +0200 Subject: [PATCH 3/6] Record external package pilot --- docs/45-external-package-pilot.md | 92 ++++++++++++++++++++++++++++ docs/README.md | 1 + memory/00-index.md | 3 + memory/01-current-state.md | 20 ++++++ memory/305-external-package-pilot.md | 34 ++++++++++ 5 files changed, 150 insertions(+) create mode 100644 docs/45-external-package-pilot.md create mode 100644 memory/305-external-package-pilot.md diff --git a/docs/45-external-package-pilot.md b/docs/45-external-package-pilot.md new file mode 100644 index 00000000..7fcd5757 --- /dev/null +++ b/docs/45-external-package-pilot.md @@ -0,0 +1,92 @@ +# External Package Pilot + +FluxFlow has been validated through a standalone consumer application at +`C:\Projects\FluxFlow.Pilot`. The pilot is outside this repository and has no +project reference to FluxFlow source. + +## Purpose + +The repository acceptance fixture proves release mechanics. The external pilot +adds a developer-adoption check: can a small application understand, configure, +run, reload, observe, stop, and recover FluxFlow using packages alone? + +The pilot intentionally uses the public surface without helper code from this +repository. + +## Scenarios + +### Typed code-first + +The pilot declares one complete uppercase component contract, adds two typed +instances to one workflow, connects typed output to typed input with a C# +predicate, builds the definition, and registers it once with +`AddFluxFlow(definition)`. + +It sends and receives through typed handles, verifies the exact transformed +value, queries the standard readiness check for the active revision, and stops +the application cleanly. It does not repeat ordinary component registration. + +### Portable JSON + +The pilot loads its active and invalid definitions from JSON files. Because +portable JSON contains names rather than executable factories, this path +registers its component catalog explicitly. + +Execution proves: + +- initial addressed routing; +- same-definition `Unchanged`; +- independently loaded invalid candidate `Rejected`; +- exact active revision and definition retention; +- successful routing after rejection; +- clean stop. + +### Restart durability + +One process persists a durable input through the SQL-file provider, acquires a +lease, and exits without settling it. A separate recovery process uses the same +absolute data directory and a deterministic later clock. + +The recovery host observes the expired lease, executes the embedded-contract +workflow, captures the typed output durably, delivers it to an idempotent local +destination, and reaches exact terminal state: one delivered input, one +completed output, and one effect. + +## Package isolation + +The verification runner packs these nine exact packages from a clean source +commit: + +- `FluxFlow.Nodes` 4.0.0 +- `FluxFlow.Mapping` 1.0.3 +- `FluxFlow.Composition` 6.0.0 +- `FluxFlow.Engine` 7.0.0 +- `FluxFlow.Engine.HealthChecks` 1.0.0 +- `FluxFlow.Engine.DurableInput` 1.3.0 +- `FluxFlow.Engine.DurableInput.SqlFile` 1.3.0 +- `FluxFlow.Engine.DurableOutput` 3.0.0 +- `FluxFlow.Engine.DurableOutput.SqlFile` 3.0.0 + +Restore uses a pilot-owned package cache. For every resolved FluxFlow library, +the runner compares the cache SHA-512 with the single candidate archive. The +application project has package references only; the test project's one +project reference remains entirely inside the pilot. + +## Verification result + +- FluxFlow source commit: + `2756c32571319463fa851171d9436c2de2a80dd1` +- Nine candidate archive hashes matched. +- Build: 0 warnings and 0 errors. +- Tests: 5 passed, 0 failed, 0 skipped. +- Formatting verification passed without changes. +- Exact outputs: + `PILOT CODE FIRST`, `PILOT JSON`, `PILOT STILL ACTIVE`, and + `PILOT DURABLE RESTART`. +- Overall marker: `PILOT_VERIFICATION_OK=True`. +- Candidate source, isolated cache, and restart state were removed by the + normal runner. + +The pilot found no blocking public-surface or operational usability defect. No +FluxFlow production source, public API, JSON format, package version, or +dependency changed during this work. diff --git a/docs/README.md b/docs/README.md index 39ebdb42..62ae71b7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -70,6 +70,7 @@ loading them; the runtime accepts only the canonical document shape and names. 42. [Application Health Readiness](42-application-health-readiness.md) 43. [Performance, Concurrency, And Lifetime Baseline](43-performance-concurrency-lifetime-baseline.md) 44. [Release-Candidate Consolidation](44-release-candidate-consolidation.md) +45. [External Package Pilot](45-external-package-pilot.md) Retired documents require an external, one-time conversion. Current runtime guidance uses only the canonical application and component model. diff --git a/memory/00-index.md b/memory/00-index.md index 928bf50f..0c7be8dd 100644 --- a/memory/00-index.md +++ b/memory/00-index.md @@ -780,6 +780,9 @@ This folder records the extraction work for `FluxFlow.Engine`. - `304-release-candidate-consolidation.md`: frozen typed C# and portable JSON paths, package-only rollback proof, clean committed-snapshot validation, real SQL-provider evidence, and the no-publication boundary. +- `305-external-package-pilot.md`: standalone package-only consumer proving + typed C#, portable JSON rollback, readiness, two-process SQL-file recovery, + exact archive hashes, and cleanup outside the source repository. - `report.md`: original FluxMq migration spike report supplied for review. - `legacy-docs/`: historical pre-cleanup docs; current decisions override older API descriptions in this folder. diff --git a/memory/01-current-state.md b/memory/01-current-state.md index 4e3e111a..759f209b 100644 --- a/memory/01-current-state.md +++ b/memory/01-current-state.md @@ -575,3 +575,23 @@ process-restart durability remain independent and preserved. - No push, pull request, tag, release, or package publication occurred. See `memory/304-release-candidate-consolidation.md` and `docs/44-release-candidate-consolidation.md`. + +## External Package Pilot + +- A standalone application at `C:\Projects\FluxFlow.Pilot` consumes nine exact + locally packed FluxFlow packages and contains no project reference back to + this repository. +- Typed code-first execution uses complete contracts, typed connections and + ports, one definition registration, standard readiness, and clean lifecycle. +- Portable JSON execution proves explicit catalog registration, unchanged + apply, invalid-candidate rejection, active-revision retention, and successful + post-rejection routing. +- Separate durability seed and recovery processes prove expired SQL-file input + recovery, workflow execution, durable output capture and delivery, one exact + effect, and terminal store state. +- All nine restore hashes matched their candidate archives; the build had zero + warnings, all five pilot tests passed, formatting was clean, and the runner + removed its package source, cache, and restart state. +- No production source, public API, JSON format, package version, or dependency + changed. See `memory/305-external-package-pilot.md` and + `docs/45-external-package-pilot.md`. diff --git a/memory/305-external-package-pilot.md b/memory/305-external-package-pilot.md new file mode 100644 index 00000000..c79fe821 --- /dev/null +++ b/memory/305-external-package-pilot.md @@ -0,0 +1,34 @@ +# External Package Pilot + +Date: 2026-08-08 + +A standalone consumer was created at `C:\Projects\FluxFlow.Pilot` to validate +FluxFlow outside the repository. It contains no project reference to FluxFlow +source and restores exact locally packed candidate bytes. + +## Boundaries proved + +- Normal typed C# authoring uses complete contracts, typed handles, and one + `AddFluxFlow(definition)` registration without repeated component setup. +- Portable JSON remains explicit: files contain portable names and the host + registers the corresponding catalog deliberately. +- The JSON path preserves the active route across unchanged and rejected + updates. +- Standard readiness reports the exact active revision. +- SQL-file durability survives a real process boundary: an abandoned input + lease is recovered, the workflow runs, output is captured and delivered, and + both stores reach exact terminal state. +- No reflection, scanning, dynamic activation, external infrastructure, or new + FluxFlow dependency was introduced. + +## Evidence + +- Source commit: `2756c32571319463fa851171d9436c2de2a80dd1`. +- Nine exact candidate packages and nine matching restore hashes. +- Warning-free build and clean formatting verification. +- Five focused xUnit/Shouldly tests passed with no failures or skips. +- Exact code-first, health, JSON, durability seed/recovery, and overall markers. +- Candidate feed, isolated cache, and restart state removed after verification. + +The pilot found no blocking adoption defect. Publication remains a separate +decision. From 21fdcd2db0ce2c486b66512a72ff06f249f1444c Mon Sep 17 00:00:00 2001 From: meisa Date: Sat, 8 Aug 2026 23:46:15 +0200 Subject: [PATCH 4/6] Prepare code-first prerelease --- .github/workflows/publish-nuget.yml | 16 +- CHANGELOG.md | 196 +++++++++++++ docs/46-code-first-major-migration.md | 199 +++++++++++++ docs/47-code-first-prerelease-plan.md | 74 +++++ docs/README.md | 2 + .../README.md | 276 ++++++++++++++++++ memory/00-index.md | 3 + memory/01-current-state.md | 10 + .../306-code-first-prerelease-preparation.md | 93 ++++++ ...w.Components.Assertions.Composition.csproj | 2 +- .../CompatibilitySuppressions.xml | 49 ++++ .../FluxFlow.Components.Designer.csproj | 2 +- ...Components.Expectations.Composition.csproj | 2 +- ...w.Components.FileSystem.Composition.csproj | 2 +- ...luxFlow.Components.Http.Composition.csproj | 2 +- ...Flow.Components.Mapping.Composition.csproj | 2 +- ...Flow.Components.Metrics.Composition.csproj | 2 +- ...omponents.Observability.Composition.csproj | 2 +- ...low.Components.Payloads.Composition.csproj | 2 +- ....Components.Projections.Composition.csproj | 2 +- ...w.Components.Resilience.Composition.csproj | 2 +- ...Flow.Components.Routing.Composition.csproj | 2 +- ...omponents.Serialization.Composition.csproj | 2 +- ...low.Components.Sessions.Composition.csproj | 2 +- ...Flow.Components.Sources.Composition.csproj | 2 +- ...uxFlow.Components.State.Composition.csproj | 2 +- ...Flow.Components.Storage.Composition.csproj | 2 +- ...xFlow.Components.Timers.Composition.csproj | 2 +- ...w.Components.Validation.Composition.csproj | 2 +- .../CompatibilitySuppressions.xml | 204 +++++++++++++ .../FluxFlow.Composition.csproj | 2 +- ...luxFlow.Engine.DurableInput.SqlFile.csproj | 2 +- .../FluxFlow.Engine.DurableInput.TSql.csproj | 2 +- .../FluxFlow.Engine.DurableInput.csproj | 2 +- ...uxFlow.Engine.DurableOutput.SqlFile.csproj | 2 +- .../FluxFlow.Engine.DurableOutput.TSql.csproj | 2 +- .../FluxFlow.Engine.DurableOutput.csproj | 2 +- .../FluxFlow.Engine.HealthChecks.csproj | 2 +- src/FluxFlow.Engine/FluxFlow.Engine.csproj | 2 +- .../FluxFlow.Fluent.Hosting.csproj | 2 +- .../CompatibilitySuppressions.xml | 21 ++ src/FluxFlow.Fluent/FluxFlow.Fluent.csproj | 2 +- ...luxFlow.Components.Mqtt.Composition.csproj | 2 +- .../DurabilityPackageVersionTests.cs | 12 +- .../HealthReadinessConventionTests.cs | 2 +- .../PackagePublishWorkflowTests.cs | 59 ++++ 46 files changed, 1233 insertions(+), 45 deletions(-) create mode 100644 docs/46-code-first-major-migration.md create mode 100644 docs/47-code-first-prerelease-plan.md create mode 100644 goals/2026-08-08-code-first-prerelease-release/README.md create mode 100644 memory/306-code-first-prerelease-preparation.md create mode 100644 src/FluxFlow.Components.Designer/CompatibilitySuppressions.xml create mode 100644 src/FluxFlow.Composition/CompatibilitySuppressions.xml create mode 100644 src/FluxFlow.Fluent/CompatibilitySuppressions.xml diff --git a/.github/workflows/publish-nuget.yml b/.github/workflows/publish-nuget.yml index 33a28db9..702dab44 100644 --- a/.github/workflows/publish-nuget.yml +++ b/.github/workflows/publish-nuget.yml @@ -17,9 +17,11 @@ on: permissions: contents: write + id-token: write jobs: release: + environment: release runs-on: ubuntu-24.04 steps: @@ -106,19 +108,19 @@ jobs: -PackageSource "https://api.nuget.org/v3/index.json" ` -ExpectedState Missing + - name: Package feed login + id: nuget-login + uses: NuGet/login@v1 + with: + user: ${{ secrets.NUGET_USER }} + - name: Publish package shell: pwsh - env: - NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }} run: | $ErrorActionPreference = "Stop" $PSNativeCommandUseErrorActionPreference = $true - if ([string]::IsNullOrWhiteSpace($env:NUGET_API_KEY)) { - throw "Add the package feed repository secret before publishing." - } - - dotnet nuget push "artifacts/packages/*.nupkg" --api-key $env:NUGET_API_KEY --source "https://api.nuget.org/v3/index.json" + dotnet nuget push "artifacts/packages/*.nupkg" --api-key "${{ steps.nuget-login.outputs.NUGET_API_KEY }}" --source "https://api.nuget.org/v3/index.json" - name: Verify package feed shell: pwsh diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a250c80..38aa844a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,202 @@ Current framework simplification release train. Historical entries below describ rejected invalid-candidate rollback, exact active revision retention, and a fresh request through the retained JSON route. +## FluxFlow.Composition 7.0.0-rc.1 + +- Replaces split authoring/runtime declarations with complete typed + `ComponentContract` values and explicit named input, output, signal, and + event bindings. +- Adds flat typed C# application authoring, executable resource contracts, + first-class links, C# predicates, and definition-owned runtime descriptors. +- Keeps portable JSON independent and moves raw dynamic component registration + behind the explicit `Advanced` surface. + +## FluxFlow.Components.Designer 6.0.0-rc.1 + +- Aligns designed components with complete component contracts so runtime + descriptors and design metadata share one declaration without activating a + node during catalog construction. +- Removes implicit event-port injection and treats named events as explicit + output metadata. + +## FluxFlow.Components.Assertions.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Expectations.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.FileSystem.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Http.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Mapping.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Metrics.Composition 6.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Mqtt.Composition 7.0.0-rc.1 + +- Adds complete MQTT component and application-resource contracts so a + code-first definition owns both node activation and client-resource + registration. +- Retains explicit MQTT registration for portable JSON and dynamic hosts. + +## FluxFlow.Components.Observability.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Payloads.Composition 6.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Projections.Composition 6.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Resilience.Composition 5.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Routing.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Serialization.Composition 6.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Sessions.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Sources.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.State.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Storage.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts and explicit application + resource ownership for code-first storage workflows. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without moving backend configuration into application options. + +## FluxFlow.Components.Timers.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Components.Validation.Composition 7.0.0-rc.1 + +- Exposes package-owned complete typed contracts for code-first applications. +- Keeps explicit package registration for portable JSON, catalogs, and dynamic + hosts without requiring duplicate registration for code-first definitions. + +## FluxFlow.Engine 8.0.0-rc.1 + +- Executes definition-owned component and resource contracts directly while + preserving explicit host catalogs for portable JSON applications. +- Adds typed application-port operations over the existing addressed runtime + and keeps revision activation, rollback, drain, cleanup, and ownership atomic. +- Makes code-first predicates revision-owned and keeps Fluent on the canonical + Engine lifecycle rather than a parallel runtime. + +## FluxFlow.Fluent 5.0.0-rc.1 + +- Rebuilds the concise fluent facade on canonical `ApplicationDefinition` and + `FluxFlowApplication` execution. +- Preserves branching, fan-in, observation, error-as-data, lifecycle, and typed + handles without a second runtime model. + +## FluxFlow.Fluent.Hosting 5.0.0-rc.1 + +- Hosts the canonical Fluent definition and Engine application through the + standard .NET lifecycle. +- Updates its package dependency floor to the new Fluent major line. + +## FluxFlow.Engine.DurableInput 2.0.0-rc.1 + +- Adds typed input-handle enqueue overloads that delegate to the existing + durable address and preserve cancellation, idempotency, and delivery modes. +- Updates the package dependency floor for the new canonical Engine line. + +## FluxFlow.Engine.DurableInput.SqlFile 2.0.0-rc.1 + +- Carries SQL-file durable input onto the new durable-input and Engine major + line without changing its schema or delivery guarantee. + +## FluxFlow.Engine.DurableInput.TSql 2.0.0-rc.1 + +- Carries networked relational durable input onto the new durable-input and + Engine major line without changing its schema or delivery guarantee. + +## FluxFlow.Engine.DurableOutput 4.0.0-rc.1 + +- Adds typed output-handle capture configuration over the existing durable + address contract and preserves serial at-least-once delivery semantics. +- Updates the package dependency floor for the new canonical Engine line. + +## FluxFlow.Engine.DurableOutput.SqlFile 4.0.0-rc.1 + +- Carries SQL-file durable output onto the new durable-output and Engine major + line without changing its schema or delivery guarantee. + +## FluxFlow.Engine.DurableOutput.TSql 3.0.0-rc.1 + +- Carries networked relational durable output onto the new durable-output and + Engine major line without changing its schema or delivery guarantee. + +## FluxFlow.Engine.HealthChecks 1.0.0-rc.1 + +- Adds the optional standard .NET readiness adapter over existing in-memory + application lifecycle, revision, and rollback state. +- Reports healthy, degraded, and unhealthy status with bounded non-secret data + and no worker, polling, storage query, reflection, or reverse Engine + dependency. + ## FluxFlow.Engine.HealthChecks 1.0.0 - Adds one idempotent standard .NET readiness registration over the existing diff --git a/docs/46-code-first-major-migration.md b/docs/46-code-first-major-migration.md new file mode 100644 index 00000000..9bd9b43f --- /dev/null +++ b/docs/46-code-first-major-migration.md @@ -0,0 +1,199 @@ +# Code-First Major Migration + +This guide covers the breaking authoring changes in the code-first +simplification prerelease. It is for applications and component packages moving +from the previous Composition, Engine, Fluent, and durability lines. + +Portable JSON remains supported. The major change is the compiled C# authoring +surface and the removal of duplicate declarations and registrations. + +## Choose the authoring path first + +Use typed C# when the application is compiled with its workflow definition and +should use C# types, variables, predicates, factories, and dependency injection. +Use portable JSON when the definition must be stored, designed, edited, loaded, +or hot-reloaded as data. + +The paths converge on the same Engine, but they do not serialize into each +other. A C# definition may own executable delegates and contract instances; a +JSON definition never does. + +## Application registration + +The normal code-first host no longer repeats every runtime component after the +definition is built. + +Before: + +```csharp +var definition = definitionBuilder.Build(); + +services.AddFluxFlowComponents() + .AddRuntimeComponent("sample.uppercase", component => + { + component + .UseFactory(static _ => new UppercaseNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); + }); + +services.AddFluxFlow(definition); +``` + +After: + +```csharp +var application = new ApplicationDefinitionBuilder(); +application.AddWorkflow("main", out var workflow); + +workflow.AddComponent( + "upper", + SampleComponents.Uppercase, + out var upper); + +var definition = application.Build(); +services.AddFluxFlow(definition); +``` + +`SampleComponents.Uppercase` is a complete `ComponentContract`. It owns the +portable component type, runtime factory, typed bindings, and typed handle. +`ApplicationDefinition` retains the selected contract, so +`AddFluxFlow(definition)` is the only normal host registration. + +## Component package declarations + +Replace split descriptor/authoring declarations with one package-owned complete +contract. The runtime binding vocabulary describes existing node members: + +- `HasInput`, not `AddInput`; +- `HasSignalInput`, not `AddSignalInput`; +- `HasOutput`, not `AddOutput`; and +- `HasEvents`, not `AddEvents` or an implicit global event port. + +Events are explicit named output ports. A component handle should expose them as +`OutputPortHandle` when the component supports events. + +`ComponentAuthoringContract` has been replaced by `ComponentContract`. +Consumers should select the package's exported complete contract rather than +constructing a second runtime registration. + +## Typed application links + +Replace string targets such as `"sink.Input"` with captured handles: + +```csharp +workflow + .AddComponent("source", SampleComponents.Source, out var source) + .AddComponent("upper", SampleComponents.Uppercase, out var upper) + .AddComponent("sink", SampleComponents.Sink, out var sink); + +source.Output.ConnectTo(upper.Input); +workflow.Connect(upper.Output, sink.Input); +``` + +Use `application.Connect(...)` for an explicit cross-workflow connection. A C# +condition may be supplied directly: + +```csharp +upper.Output.ConnectTo( + sink.Input, + when: static value => value.Length > 0); +``` + +Portable expression strings remain available for JSON-compatible conditions. + +## Typed runtime and durability operations + +Keep the handles captured during authoring. `ApplicationPorts` accepts typed +input, signal-input, and output handles for send, receive, observe, and +request/reply operations. Durable input enqueue and durable output capture also +accept the corresponding typed handles. + +These overloads use the same canonical addresses and runtime implementation; +they do not create a second routing or durability system. + +## Application resources + +Code-first resources use package-owned `ApplicationResourceContract` values. +The definition retains their explicit registrars and the Engine owns their +revision lifetime. A code-first MQTT client, for example, does not require a +second host-side MQTT registrar call. + +JSON cannot carry executable registrars. A JSON host must continue to register +the package behavior that may be named in its data. + +## JSON applications + +The JSON path remains explicit: + +```csharp +var definition = JsonSerializer.Deserialize(json)!; + +services + .AddFluxFlowComponents() + .AddSources(); + +services.AddFluxFlow(definition); +``` + +Keep explicit family registration here. It is the trusted catalog boundary for +portable type names and does not represent duplicate code-first registration. +JSON persistence and hot reload remain data-only and never embed CLR delegates, +component contracts, resource contracts, or service providers. + +## Advanced dynamic registration + +Raw runtime registration is an escape hatch for dynamic catalogs and low-level +integration packages. Move normal direct calls to the explicit advanced +surface: + +```csharp +services + .AddFluxFlowComponents() + .Advanced + .AddDynamicComponent("sample.dynamic", component => + { + component + .UseFactory(static _ => new DynamicNode()) + .HasInput("Input", static node => node.Input) + .HasOutput("Output", static node => node.Output) + .HasEvents("Events", static node => node.Events); + }); +``` + +Do not use this path merely to make a normal code-first definition executable. + +## Fluent applications + +`FluxFlow.Fluent` is now a concise facade over a canonical +`ApplicationDefinition` and `FluxFlowApplication`. Continue using the fluent +syntax, but host and observe the canonical definition/application exposed by the +graph. Replace `FlowGraph.Runtime` with `FlowGraph.Definition` or +`FlowGraph.Application` according to whether the caller needs the immutable +blueprint or the running Engine application. There is no separate Fluent +runtime lifecycle. + +## Readiness + +Application readiness is optional. Add the health package and call its standard +registration only when a host needs a readiness check. The adapter observes +existing application state; it adds no worker, polling, storage query, or +endpoint by itself. + +## Migration checklist + +1. Upgrade the affected package closure to one consistent prerelease wave. +2. Replace `ComponentAuthoringContract` with package-owned complete + `ComponentContract` values. +3. Rename declaration mappings from `Add*` to `Has*` and declare Events + explicitly. +4. Build applications with captured typed handles and typed connections. +5. Remove repeated code-first component and resource registration. +6. Keep explicit package registration for JSON and dynamic catalogs. +7. Move raw registrations to `Advanced.AddDynamicComponent`. +8. Use typed runtime and durability overloads where the authoring handle is + available. +9. Update Fluent hosting to the canonical graph definition/application. +10. Run unchanged, rejected-reload, retained-route, shutdown, and durability + recovery tests before promoting from the prerelease. diff --git a/docs/47-code-first-prerelease-plan.md b/docs/47-code-first-prerelease-plan.md new file mode 100644 index 00000000..dc0d6ab1 --- /dev/null +++ b/docs/47-code-first-prerelease-plan.md @@ -0,0 +1,74 @@ +# Code-First Prerelease Plan + +The code-first simplification is released first as a coordinated prerelease. +This protects the stable package line while consumers validate the breaking +authoring changes through real package restore and execution. + +## Scope + +Exactly 31 packages move. Twenty-seven contain direct candidate changes and four +are dependency-only releases: both durable input providers, both durable output +providers, and Fluent Hosting move with their new parent major lines. The other +29 manifest packages remain at their existing published versions. + +The exact versions and full execution contract are recorded in +`goals/2026-08-08-code-first-prerelease-release/README.md`. + +## Waves + +1. Composition 7.0.0-rc.1. +2. Designer 6.0.0-rc.1 and Engine 8.0.0-rc.1. +3. Nineteen component-composition packages, both durable cores, Engine health + checks, and Fluent. +4. Four durability providers and Fluent Hosting. + +Each wave waits for public indexing, isolated restore/load, and the exact +repository release before the next wave begins. + +## Publication identity + +Every tag is package-specific and targets one immutable merged commit. The +workflow verifies the declared published baseline, archive, package-only +consumer, exact public absence, upload, public-feed restore, and repository +release in that order. + +Publishing uses the `release` environment and trusted short-lived credentials. +The feed-side policy must match: + +- repository owner: `araxis`; +- repository: `FluxFlow`; +- workflow file: `publish-nuget.yml`; and +- environment: `release`. + +The environment secret `NUGET_USER` contains the package-feed profile name, not +an email address. Keep the old repository API-key secret until one trusted +publication has completed, but the workflow no longer consumes it. + +## Failure boundary + +Never treat a network or protocol failure as package absence. Never skip a +duplicate, move a successful tag, or republish a successful version. + +Before rerunning a failure that occurred before upload, prove both the exact +package and repository release are absent. After a successful upload, resume +only incomplete indexing, verification, or release-record work using the +retained artifacts. + +## External acceptance + +After all 31 prereleases are indexed, the separate package-only pilot restores +from the public feed and proves code-first execution, health, portable JSON +rollback, retained routing, and two-process SQL-file durability. Stable +promotion begins only after that public-feed proof is green and recorded. + +## Preparation status + +Local release preparation is green: 137 projects build without warnings, all +2,677 solution tests and 193 release-governance tests pass, all 31 compatibility +operations and package smoke consumers pass, the package-only behavioral +consumer completes, formatting is clean, and no known vulnerable dependency is +reported. The exact versions are absent from the public feed. + +The remaining prerequisite is feed-side trust configuration for the exact +workflow/environment identity, followed by remote review and immutable +dependency-wave publication. diff --git a/docs/README.md b/docs/README.md index 62ae71b7..1ead4215 100644 --- a/docs/README.md +++ b/docs/README.md @@ -71,6 +71,8 @@ loading them; the runtime accepts only the canonical document shape and names. 43. [Performance, Concurrency, And Lifetime Baseline](43-performance-concurrency-lifetime-baseline.md) 44. [Release-Candidate Consolidation](44-release-candidate-consolidation.md) 45. [External Package Pilot](45-external-package-pilot.md) +46. [Code-First Major Migration](46-code-first-major-migration.md) +47. [Code-First Prerelease Plan](47-code-first-prerelease-plan.md) Retired documents require an external, one-time conversion. Current runtime guidance uses only the canonical application and component model. diff --git a/goals/2026-08-08-code-first-prerelease-release/README.md b/goals/2026-08-08-code-first-prerelease-release/README.md new file mode 100644 index 00000000..79529a51 --- /dev/null +++ b/goals/2026-08-08-code-first-prerelease-release/README.md @@ -0,0 +1,276 @@ +# Goal: Publish and externally verify the code-first simplification prerelease + +- Date: 2026-08-08 +- State: in progress +- Scope: release preparation, package version freeze, migration guidance, + trusted publication, public-feed verification, and external pilot validation +- Candidate branch: `work/release-candidate-consolidation` +- Candidate implementation commit: `4bf69015b9d3eaa95a45630c91d378c45c5a2aaa` +- Compatibility: intentional breaking release for the affected package closure +- Publication: prerelease only until the public-feed pilot passes + +## Objective + +Publish the completed FluxFlow simplification as one dependency-safe release +candidate and prove it from a separate package-only application using the public +package feed. + +The outcome must preserve the framework's two first-class authoring paths: + +1. typed C# code-first applications use complete component and resource + contracts, typed handles, C# predicates, and one `AddFluxFlow(definition)` + registration; and +2. portable JSON applications use explicit package registration, remain + serializable, and retain validation, persistence, and hot-reload behavior. + +The release must not reintroduce duplicate registration, reflection-driven +discovery, a parallel Fluent runtime, hidden workers, or backend configuration +inside application options. + +## Principles + +- Keep the normal API flat, explicit, typed, and definition-first. +- Treat breaking public APIs and breaking package dependency floors as major + releases after 1.0. +- Publish one immutable version per package and never reuse or move a successful + package tag. +- Calculate release waves from actual package project references. +- Require exact public absence before publication and exact public presence, + restore, and execution afterward. +- Keep publication fail-closed. Authentication, indexing, package identity, + hash, release-record, or pilot ambiguity is a stop condition. +- Use short-lived trusted publishing credentials. Do not publish with a + long-lived package-feed API key. +- Keep the old repository secret until trusted publishing has succeeded; secret + deletion is outside this goal. +- Promote the same reviewed source and behavior to stable versions only after + prerelease acceptance. Stable promotion is a separate versioned release. + +## Frozen package closure and versions + +The direct source changes affect 27 package projects. Four dependent packages +must also move so their package dependency floors reference the new major line. +The resulting closure is exactly 31 packages. + +| Package | Previous | Prerelease | +| --- | ---: | ---: | +| FluxFlow.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Designer | 5.0.0 | 6.0.0-rc.1 | +| FluxFlow.Components.Assertions.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Expectations.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.FileSystem.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Http.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Mapping.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Metrics.Composition | 5.0.0 | 6.0.0-rc.1 | +| FluxFlow.Components.Mqtt.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Observability.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Payloads.Composition | 5.0.0 | 6.0.0-rc.1 | +| FluxFlow.Components.Projections.Composition | 5.0.0 | 6.0.0-rc.1 | +| FluxFlow.Components.Resilience.Composition | 4.0.0 | 5.0.0-rc.1 | +| FluxFlow.Components.Routing.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Serialization.Composition | 5.0.0 | 6.0.0-rc.1 | +| FluxFlow.Components.Sessions.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Sources.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.State.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Storage.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Timers.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Components.Validation.Composition | 6.0.0 | 7.0.0-rc.1 | +| FluxFlow.Engine | 7.0.0 | 8.0.0-rc.1 | +| FluxFlow.Fluent | 4.0.0 | 5.0.0-rc.1 | +| FluxFlow.Fluent.Hosting | 4.0.0 | 5.0.0-rc.1 | +| FluxFlow.Engine.DurableInput | 1.3.0 | 2.0.0-rc.1 | +| FluxFlow.Engine.DurableInput.SqlFile | 1.3.0 | 2.0.0-rc.1 | +| FluxFlow.Engine.DurableInput.TSql | 1.2.0 | 2.0.0-rc.1 | +| FluxFlow.Engine.DurableOutput | 3.0.0 | 4.0.0-rc.1 | +| FluxFlow.Engine.DurableOutput.SqlFile | 3.0.0 | 4.0.0-rc.1 | +| FluxFlow.Engine.DurableOutput.TSql | 2.0.0 | 3.0.0-rc.1 | +| FluxFlow.Engine.HealthChecks | unpublished | 1.0.0-rc.1 | + +The other 29 manifest packages remain at their published versions. They are +not rebuilt under new identities merely to create a uniform train. + +## Dependency waves + +Generate the plan from `eng/package-release-plan.ps1`, marking the 29 unchanged +aliases already available. The required result is: + +1. Wave 1: `composition`. +2. Wave 2: `components-designer`, `engine`. +3. Wave 3: the 19 component-composition packages plus + `engine-durable-input`, `engine-durable-output`, `engine-healthchecks`, and + `fluent`. +4. Wave 4: both durable-input providers, both durable-output providers, and + `fluent-hosting`. + +Do not begin a dependent wave until every package in the preceding wave is +indexed, independently restorable, and represented by an exact repository +release and assets. + +## Phase 1: Release metadata and migration guide + +1. Update each affected project-owned `` to the frozen prerelease. +2. Keep every `binaryCompatibilityBaseline` at the latest published stable + contract; keep the new health package baseline explicitly `null`. +3. Add a non-empty package-specific changelog section for every prerelease. +4. Add a migration guide that maps retired or discouraged surfaces to the + supported code-first, JSON, and advanced paths. +5. Document that C# definitions are executable in-memory blueprints and are not + required to serialize to JSON. +6. Document the 31-package closure, four dependency waves, public-feed pilot, + stable-promotion boundary, and failure recovery rules. +7. Update the docs index, memory index, and current-state record. + +## Phase 2: Trusted publication + +Migrate `.github/workflows/publish-nuget.yml` from the long-lived API-key secret +to trusted publishing: + +- use the exact existing workflow filename `publish-nuget.yml`; +- use the repository `araxis/FluxFlow`; +- use the `release` environment; +- grant `id-token: write` and the existing required repository-content access; +- call the trusted package-feed login action immediately before the publish + step; +- pass `secrets.NUGET_USER` as the package-feed profile name; +- use the short-lived token output for `dotnet nuget push`; +- preserve the repository's exact-absence check and prohibition on duplicate + skipping; +- verify the public feed before creating the repository release. + +The feed-side trusted-publishing policy and `NUGET_USER` environment secret must +exist before the first publication run. Do not delete the existing API-key +secret during this goal. + +## Phase 3: Local validation + +Before pushing: + +1. verify manifest/project/changelog consistency; +2. run the focused release workflow and package policy tests; +3. restore and build the full solution in Release with CI build settings; +4. run the complete solution and Release-governance tests; +5. run the package-only candidate acceptance gate; +6. run package archive inspection and package smoke checks for the affected + closure; +7. run binary compatibility preflight using each frozen published baseline; +8. run formatting, whitespace, and dependency-vulnerability checks; +9. keep all validation outputs outside source or in ignored artifact paths; and +10. record exact counts, warnings, failures, package identities, and cleanup. + +Intentional major-version breaks must be reviewed, not hidden. If the package +compatibility tool rejects a deliberate removal, use a narrow reviewed +suppression owned by the affected project only; never disable package +validation globally. + +## Phase 4: Review and merge + +1. Commit only the release preparation on the existing neutral branch. +2. Push the branch with upstream tracking. +3. Open one pull request describing the authoring simplification, migration, + package impact, trusted publishing change, and validation evidence. +4. Require all remote checks to pass on the exact head. +5. Merge through the repository's normal protected workflow. +6. Record the immutable merged publication commit. All prerelease tags must + target that exact commit. + +## Phase 5: Prerelease publication + +For each dependency wave: + +1. prove every target version is absent from the public feed; +2. create and push each guarded package tag separately so events are not lost; +3. wait for the exact release workflow to finish; +4. verify package and symbol assets, public indexing, isolated restore/load, and + repository release target; +5. record the workflow run id and result; and +6. stop on any ambiguous publication state. + +If a run fails before publication, prove both the exact package version and +repository release are absent before rerunning the unchanged tag. If upload +succeeds but indexing or release creation fails, never republish or move the +tag; resume only the incomplete post-publication operation from retained +artifacts. + +## Phase 6: External public-feed pilot + +Update the separate `C:\Projects\FluxFlow.Pilot` repository to reference the +exact prerelease versions and use the public feed only. It must have no source +repository project references and no candidate package directory. + +The pilot must prove: + +- typed code-first application construction with complete contracts; +- one `AddFluxFlow(definition)` registration and no duplicate ordinary + component/resource registration; +- typed send/receive and clean lifecycle; +- optional readiness behavior; +- portable JSON startup, unchanged reapply, rejected invalid candidate, + retained active revision, and successful post-rejection routing; +- SQL-file durable input/output state across separate seed and recovery + processes; and +- cleanup of pilot-owned package caches, databases, binaries, and temporary + directories. + +## Stable promotion boundary + +Do not overwrite or relabel prerelease package versions. When the public-feed +pilot and an agreed observation period are complete, create stable project +versions without the `-rc.1` suffix, add stable changelog sections, rerun the +same dependency-wave checks, and publish new immutable stable package versions. + +## Non-goals + +- No new workflow semantics, components, providers, persistence abstractions, + ORMs, background workers, reflection, scanning, or runtime dependencies. +- No attempt to serialize executable C# delegates or resource factories into + portable JSON. +- No republishing of the 29 unaffected stable packages. +- No automatic deletion of the previous package-feed credential. +- No stable release before public prerelease evidence is complete. + +## Acceptance criteria + +- Exactly 31 affected project versions and changelog sections match the frozen + matrix. +- The dependency planner returns exactly the four frozen waves. +- Release workflow governance proves trusted short-lived publication and the + existing fail-closed ordering. +- Local build, tests, release governance, package rehearsal, format, whitespace, + vulnerability, archive, and compatibility gates pass without warnings or + unexplained suppressions. +- One reviewed immutable commit is used for every prerelease tag. +- Every prerelease package is public, independently restorable, hash-identifiable, + and represented by the matching repository release and assets. +- The separate public-feed-only pilot passes all five acceptance facts and + removes its owned temporary state. +- Documentation and memory identify the exact publication commit, pull request, + workflow runs, package versions, pilot commit, evidence, failures, recoveries, + and stable-promotion decision. + +## Local preparation evidence + +The prepared working tree has completed the local pre-publication boundary: + +- all 31 release metadata/changelog preflights passed; +- all 31 exact prerelease versions were confirmed absent from the public feed; +- Release governance passed 193/193 with zero warnings; +- solution restore completed for 137 projects with zero warnings; +- the CI-style Release build completed for 137 projects with zero warnings and + zero errors; +- solution tests passed 2,677/2,677 across 67 projects with zero warnings; +- the pack-mode behavioral acceptance fact passed; +- compatibility-aware package creation passed for all 31 targets against their + exact isolated public baselines; +- only Composition, Designer, and Fluent required reviewed project-owned + compatibility suppressions for intentional major-version breaks; +- the combined source contains 31 package archives and 31 symbol archives; +- archive inspection and isolated package smoke passed 31/31; +- the representative package-only application restored exact candidate bytes, + built without warnings, and passed Engine, code-first, resource, health, + Fluent, SQL-file durability, JSON rollback, and restart recovery markers; +- full-solution formatting and whitespace verification passed; and +- the complete direct/transitive dependency scan reported no known vulnerable + packages. + +Remote review, trusted feed-policy confirmation, publication, and public-feed +pilot execution remain pending. diff --git a/memory/00-index.md b/memory/00-index.md index 0c7be8dd..09c9124e 100644 --- a/memory/00-index.md +++ b/memory/00-index.md @@ -783,6 +783,9 @@ This folder records the extraction work for `FluxFlow.Engine`. - `305-external-package-pilot.md`: standalone package-only consumer proving typed C#, portable JSON rollback, readiness, two-process SQL-file recovery, exact archive hashes, and cleanup outside the source repository. +- `306-code-first-prerelease-preparation.md`: exact 31-package major-version + closure, four dependency waves, migration guidance, trusted-publication + boundary, public-feed pilot requirement, and stable-promotion rule. - `report.md`: original FluxMq migration spike report supplied for review. - `legacy-docs/`: historical pre-cleanup docs; current decisions override older API descriptions in this folder. diff --git a/memory/01-current-state.md b/memory/01-current-state.md index 759f209b..b0536413 100644 --- a/memory/01-current-state.md +++ b/memory/01-current-state.md @@ -9,6 +9,13 @@ durability operations, Fluent uses the canonical Engine lifecycle, and dynamic registration is explicitly advanced. Portable JSON/hot reload and package-only process-restart durability remain independent and preserved. +Release preparation now freezes a 31-package `rc.1` closure for the breaking +code-first surface. Twenty-seven packages contain direct changes and four move +to preserve dependency floors. The plan uses four dependency-derived waves, +trusted short-lived publication credentials, and a separate public-feed-only +pilot before any stable promotion. No prerelease package has been published at +the time of this record; see `memory/306-code-first-prerelease-preparation.md`. + ## Performance And Reliability Boundary - `benchmarks/FluxFlow.Engine.Benchmarks` is a permanent non-packable .NET 10 @@ -45,6 +52,9 @@ process-restart durability remain independent and preserved. `d54f1f4a`; `FluxFlow.Mapping` 1.0.3 was the audited reused prerequisite and was not republished. `FluxFlow.Engine.HealthChecks` 1.0.0 is the new sixtieth manifest entry and has not been published in this workspace round. +- The health package's first candidate version is frozen as `1.0.0-rc.1`. The + other 30 affected packages use next-major `rc.1` versions because the + authoring surface or a required package dependency floor is breaking. - Every new package tag and repository release targets the exact publication commit and contains the exact package plus symbol assets. - All 59 packages restore and load through isolated public-feed-only consumers. diff --git a/memory/306-code-first-prerelease-preparation.md b/memory/306-code-first-prerelease-preparation.md new file mode 100644 index 00000000..f3458767 --- /dev/null +++ b/memory/306-code-first-prerelease-preparation.md @@ -0,0 +1,93 @@ +# Code-First Prerelease Preparation + +Date: 2026-08-08 + +## Decision + +Release the completed code-first simplification as a coordinated prerelease +before stable promotion. The external pilot proved locally packed candidate +bytes, but the final acceptance boundary is a separate application restoring +the exact prerelease from the public package feed. + +## Package closure + +Repository diff and package-project reference analysis found 27 directly +changed package projects. Reverse dependency closure adds the SQL-file and +networked relational durable input/output providers. The final release target +is exactly 31 packages; the remaining 29 manifest packages are reused at their +published versions. + +All affected packages after 1.0 use a next-major `rc.1` version. The new +`FluxFlow.Engine.HealthChecks` package uses `1.0.0-rc.1` with an explicit null +binary-compatibility baseline because it has no published predecessor. + +The planner produces four waves: + +1. Composition. +2. Designer and Engine. +3. Nineteen component-composition packages, durable input/output cores, + health checks, and Fluent. +4. Four durability providers and Fluent Hosting. + +## Migration boundary + +The release guide makes the intended breaks explicit: + +- complete `ComponentContract` values replace split authoring/runtime + declarations; +- port mappings use `HasInput`, `HasSignalInput`, `HasOutput`, and `HasEvents`; +- Events are explicit named outputs; +- typed C# application builders capture handles and connections; +- code-first definitions execute with one `AddFluxFlow(definition)` call; +- JSON applications retain explicit package registration and data-only hot + reload; +- raw dynamic registration lives under `Advanced.AddDynamicComponent`; +- resources are definition-owned through `ApplicationResourceContract`; +- typed runtime/durability operations reuse canonical addresses; and +- Fluent is a facade over the canonical Engine lifecycle. + +## Publication security + +The existing release workflow used a long-lived repository API-key secret. +Preparation migrates it to the `release` environment, `id-token: write`, a +trusted package-feed login action, `secrets.NUGET_USER`, and the generated +short-lived token. +The existing exact-absence, no-duplicate-skip, public verification, and release +ordering remain unchanged. + +The feed-side trusted-publishing policy must match owner `araxis`, repository +`FluxFlow`, workflow file `publish-nuget.yml`, and environment `release` before +publication. The previous repository secret is retained until trusted +publication succeeds; deleting it is outside this goal. + +## Promotion rule + +Prerelease tags and package versions are immutable. Stable promotion creates new +stable versions from a separately reviewed commit after all public packages are +indexed and the external package-only pilot passes code-first, readiness, JSON +rollback, retained-route, and two-process SQL-file durability scenarios using +the public feed only. + +## Current status + +Versions, changelog entries, migration documentation, release plan, and trusted +workflow migration are prepared locally. Exact local evidence is: + +- 31/31 metadata and changelog preflights; +- 31/31 public-absence checks; +- 193/193 Release-governance tests; +- 137-project warning-free restore and CI-style Release build; +- 2,677/2,677 solution tests across 67 projects; +- 31/31 compatibility-aware package operations using isolated public + baselines, with narrow reviewed suppressions only in Composition, Designer, + and Fluent; +- 31/31 archive inspections and 31/31 isolated package smoke consumers; +- one warning-free package-only behavioral build and complete Engine, + code-first, resource, readiness, Fluent, durability, JSON rollback, and + restart-recovery marker set; +- clean solution formatting and whitespace; and +- no known vulnerable direct or transitive dependency. + +Publication remains blocked until the feed-side trusted policy and +`NUGET_USER` environment secret are confirmed, followed by remote review/merge +of the exact release commit. diff --git a/src/FluxFlow.Components.Assertions.Composition/FluxFlow.Components.Assertions.Composition.csproj b/src/FluxFlow.Components.Assertions.Composition/FluxFlow.Components.Assertions.Composition.csproj index 6731dd45..7272bb06 100644 --- a/src/FluxFlow.Components.Assertions.Composition/FluxFlow.Components.Assertions.Composition.csproj +++ b/src/FluxFlow.Components.Assertions.Composition/FluxFlow.Components.Assertions.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Assertions.Composition FluxFlow.Components.Assertions.Composition FluxFlow.Components.Assertions.Composition - 6.0.0 + 7.0.0-rc.1 Optional typed assertion registration and Designer metadata over host-owned keyed expression resources. workflow;dataflow;components;assertions;composition README.md diff --git a/src/FluxFlow.Components.Designer/CompatibilitySuppressions.xml b/src/FluxFlow.Components.Designer/CompatibilitySuppressions.xml new file mode 100644 index 00000000..cc6471ce --- /dev/null +++ b/src/FluxFlow.Components.Designer/CompatibilitySuppressions.xml @@ -0,0 +1,49 @@ + + + + + CP0002 + M:FluxFlow.Components.Designer.ComponentRegistrationBuilder.AddInput``1(System.String,System.String,System.String,System.Int32,System.String,System.Boolean,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net10.0/FluxFlow.Components.Designer.dll + lib/net10.0/FluxFlow.Components.Designer.dll + true + + + CP0002 + M:FluxFlow.Components.Designer.ComponentRegistrationBuilder.AddOutput``1(System.String,System.String,System.String,System.Int32,System.String,System.Boolean,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net10.0/FluxFlow.Components.Designer.dll + lib/net10.0/FluxFlow.Components.Designer.dll + true + + + CP0002 + M:FluxFlow.Components.Designer.ComponentRegistrationBuilder.AddSignalInput(System.String,System.String,System.String,System.Int32,System.String,System.Boolean,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net10.0/FluxFlow.Components.Designer.dll + lib/net10.0/FluxFlow.Components.Designer.dll + true + + + CP0002 + M:FluxFlow.Components.Designer.ComponentRegistrationBuilder.AddInput``1(System.String,System.String,System.String,System.Int32,System.String,System.Boolean,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net8.0/FluxFlow.Components.Designer.dll + lib/net8.0/FluxFlow.Components.Designer.dll + true + + + CP0002 + M:FluxFlow.Components.Designer.ComponentRegistrationBuilder.AddOutput``1(System.String,System.String,System.String,System.Int32,System.String,System.Boolean,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net8.0/FluxFlow.Components.Designer.dll + lib/net8.0/FluxFlow.Components.Designer.dll + true + + + CP0002 + M:FluxFlow.Components.Designer.ComponentRegistrationBuilder.AddSignalInput(System.String,System.String,System.String,System.Int32,System.String,System.Boolean,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net8.0/FluxFlow.Components.Designer.dll + lib/net8.0/FluxFlow.Components.Designer.dll + true + + diff --git a/src/FluxFlow.Components.Designer/FluxFlow.Components.Designer.csproj b/src/FluxFlow.Components.Designer/FluxFlow.Components.Designer.csproj index e1a9614e..6d44fbd8 100644 --- a/src/FluxFlow.Components.Designer/FluxFlow.Components.Designer.csproj +++ b/src/FluxFlow.Components.Designer/FluxFlow.Components.Designer.csproj @@ -4,7 +4,7 @@ FluxFlow.Components.Designer FluxFlow.Components.Designer FluxFlow.Components.Designer - 5.0.0 + 6.0.0-rc.1 Reusable component metadata and canonical application editing contracts for FluxFlow. workflow;dataflow;components;metadata;designer Uses one flat designed-component registration path with automatic immutable catalogs and registration-time metadata finalization; removes competing metadata builders, factories, public declaration, mutable catalog, terminal registration, provider, fallback-resolution, and production friend surfaces. diff --git a/src/FluxFlow.Components.Expectations.Composition/FluxFlow.Components.Expectations.Composition.csproj b/src/FluxFlow.Components.Expectations.Composition/FluxFlow.Components.Expectations.Composition.csproj index dab4f80d..d32ad894 100644 --- a/src/FluxFlow.Components.Expectations.Composition/FluxFlow.Components.Expectations.Composition.csproj +++ b/src/FluxFlow.Components.Expectations.Composition/FluxFlow.Components.Expectations.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Expectations.Composition FluxFlow.Components.Expectations.Composition FluxFlow.Components.Expectations.Composition - 6.0.0 + 7.0.0-rc.1 Canonical projection-event expectation registration and Designer metadata over exact host-owned clock addresses. workflow;dataflow;components;events;expectations;composition README.md diff --git a/src/FluxFlow.Components.FileSystem.Composition/FluxFlow.Components.FileSystem.Composition.csproj b/src/FluxFlow.Components.FileSystem.Composition/FluxFlow.Components.FileSystem.Composition.csproj index a90c8f20..702387f1 100644 --- a/src/FluxFlow.Components.FileSystem.Composition/FluxFlow.Components.FileSystem.Composition.csproj +++ b/src/FluxFlow.Components.FileSystem.Composition/FluxFlow.Components.FileSystem.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.FileSystem.Composition FluxFlow.Components.FileSystem.Composition FluxFlow.Components.FileSystem.Composition - 6.0.0 + 7.0.0-rc.1 FluxFlow.Composition registration and Designer metadata for typed file-system transforms and sources over host-owned keyed clocks. workflow;dataflow;components;files;composition README.md diff --git a/src/FluxFlow.Components.Http.Composition/FluxFlow.Components.Http.Composition.csproj b/src/FluxFlow.Components.Http.Composition/FluxFlow.Components.Http.Composition.csproj index f1219e6f..be96f9b9 100644 --- a/src/FluxFlow.Components.Http.Composition/FluxFlow.Components.Http.Composition.csproj +++ b/src/FluxFlow.Components.Http.Composition/FluxFlow.Components.Http.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Http.Composition FluxFlow.Components.Http.Composition FluxFlow.Components.Http.Composition - 6.0.0 + 7.0.0-rc.1 Canonical HTTP FlowContent/result registration and Designer metadata over host-owned keyed HttpClient resources. workflow;dataflow;components;http;composition README.md diff --git a/src/FluxFlow.Components.Mapping.Composition/FluxFlow.Components.Mapping.Composition.csproj b/src/FluxFlow.Components.Mapping.Composition/FluxFlow.Components.Mapping.Composition.csproj index 852d185e..6f8a01c6 100644 --- a/src/FluxFlow.Components.Mapping.Composition/FluxFlow.Components.Mapping.Composition.csproj +++ b/src/FluxFlow.Components.Mapping.Composition/FluxFlow.Components.Mapping.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Mapping.Composition FluxFlow.Components.Mapping.Composition FluxFlow.Components.Mapping.Composition - 6.0.0 + 7.0.0-rc.1 Optional FluxFlow.Composition adapter for typed and schema-less JSON mapping with value-or-error outputs. workflow;dataflow;components;mapping;composition README.md diff --git a/src/FluxFlow.Components.Metrics.Composition/FluxFlow.Components.Metrics.Composition.csproj b/src/FluxFlow.Components.Metrics.Composition/FluxFlow.Components.Metrics.Composition.csproj index 33c29874..12daefa2 100644 --- a/src/FluxFlow.Components.Metrics.Composition/FluxFlow.Components.Metrics.Composition.csproj +++ b/src/FluxFlow.Components.Metrics.Composition/FluxFlow.Components.Metrics.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Metrics.Composition FluxFlow.Components.Metrics.Composition FluxFlow.Components.Metrics.Composition - 5.0.0 + 6.0.0-rc.1 Canonical metrics result registration and Designer metadata over a host-owned clock. workflow;dataflow;components;metrics;composition README.md diff --git a/src/FluxFlow.Components.Observability.Composition/FluxFlow.Components.Observability.Composition.csproj b/src/FluxFlow.Components.Observability.Composition/FluxFlow.Components.Observability.Composition.csproj index ada7ce54..3dded908 100644 --- a/src/FluxFlow.Components.Observability.Composition/FluxFlow.Components.Observability.Composition.csproj +++ b/src/FluxFlow.Components.Observability.Composition/FluxFlow.Components.Observability.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Observability.Composition FluxFlow.Components.Observability.Composition FluxFlow.Components.Observability.Composition - 6.0.0 + 7.0.0-rc.1 Typed observability registration and Designer metadata over host-owned expression, selector, context, and clock resources. workflow;dataflow;components;observability;composition README.md diff --git a/src/FluxFlow.Components.Payloads.Composition/FluxFlow.Components.Payloads.Composition.csproj b/src/FluxFlow.Components.Payloads.Composition/FluxFlow.Components.Payloads.Composition.csproj index 52a77f9d..8b563a33 100644 --- a/src/FluxFlow.Components.Payloads.Composition/FluxFlow.Components.Payloads.Composition.csproj +++ b/src/FluxFlow.Components.Payloads.Composition/FluxFlow.Components.Payloads.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Payloads.Composition FluxFlow.Components.Payloads.Composition FluxFlow.Components.Payloads.Composition - 5.0.0 + 6.0.0-rc.1 FluxFlow.Composition registration and Designer metadata for canonical FlowContent inspection over host-owned codec catalogs and clocks. workflow;dataflow;components;payloads;composition README.md diff --git a/src/FluxFlow.Components.Projections.Composition/FluxFlow.Components.Projections.Composition.csproj b/src/FluxFlow.Components.Projections.Composition/FluxFlow.Components.Projections.Composition.csproj index 4bcb7c1d..c430f14d 100644 --- a/src/FluxFlow.Components.Projections.Composition/FluxFlow.Components.Projections.Composition.csproj +++ b/src/FluxFlow.Components.Projections.Composition/FluxFlow.Components.Projections.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Projections.Composition FluxFlow.Components.Projections.Composition FluxFlow.Components.Projections.Composition - 5.0.0 + 6.0.0-rc.1 Canonical event-projection result registration and Designer metadata over host-owned clocks. workflow;dataflow;components;events;projections;composition README.md diff --git a/src/FluxFlow.Components.Resilience.Composition/FluxFlow.Components.Resilience.Composition.csproj b/src/FluxFlow.Components.Resilience.Composition/FluxFlow.Components.Resilience.Composition.csproj index 6cc9e29d..f7dc389d 100644 --- a/src/FluxFlow.Components.Resilience.Composition/FluxFlow.Components.Resilience.Composition.csproj +++ b/src/FluxFlow.Components.Resilience.Composition/FluxFlow.Components.Resilience.Composition.csproj @@ -4,7 +4,7 @@ FluxFlow.Components.Resilience.Composition FluxFlow.Components.Resilience.Composition FluxFlow.Components.Resilience.Composition - 4.0.0 + 5.0.0-rc.1 Composition registration and Designer metadata for the flow retry component. workflow;dataflow;components;resilience;retry;composition README.md diff --git a/src/FluxFlow.Components.Routing.Composition/FluxFlow.Components.Routing.Composition.csproj b/src/FluxFlow.Components.Routing.Composition/FluxFlow.Components.Routing.Composition.csproj index 9ee5ae0a..60cf2761 100644 --- a/src/FluxFlow.Components.Routing.Composition/FluxFlow.Components.Routing.Composition.csproj +++ b/src/FluxFlow.Components.Routing.Composition/FluxFlow.Components.Routing.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Routing.Composition FluxFlow.Components.Routing.Composition FluxFlow.Components.Routing.Composition - 6.0.0 + 7.0.0-rc.1 Typed JSON routing registration and Designer metadata over host-owned selectors and clocks. workflow;dataflow;components;routing;composition README.md diff --git a/src/FluxFlow.Components.Serialization.Composition/FluxFlow.Components.Serialization.Composition.csproj b/src/FluxFlow.Components.Serialization.Composition/FluxFlow.Components.Serialization.Composition.csproj index 395e8dbf..7433f489 100644 --- a/src/FluxFlow.Components.Serialization.Composition/FluxFlow.Components.Serialization.Composition.csproj +++ b/src/FluxFlow.Components.Serialization.Composition/FluxFlow.Components.Serialization.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Serialization.Composition FluxFlow.Components.Serialization.Composition FluxFlow.Components.Serialization.Composition - 5.0.0 + 6.0.0-rc.1 FluxFlow.Composition registration and Designer metadata for explicit FlowContent, JSON, text, and Base64 conversions. workflow;dataflow;components;serialization;composition README.md diff --git a/src/FluxFlow.Components.Sessions.Composition/FluxFlow.Components.Sessions.Composition.csproj b/src/FluxFlow.Components.Sessions.Composition/FluxFlow.Components.Sessions.Composition.csproj index fdf76e99..0d5096ba 100644 --- a/src/FluxFlow.Components.Sessions.Composition/FluxFlow.Components.Sessions.Composition.csproj +++ b/src/FluxFlow.Components.Sessions.Composition/FluxFlow.Components.Sessions.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Sessions.Composition FluxFlow.Components.Sessions.Composition FluxFlow.Components.Sessions.Composition - 6.0.0 + 7.0.0-rc.1 Canonical session Composition registrations with exact FlowContent results, fixed ports, Designer metadata, and host-owned store resources. workflow;dataflow;components;sessions;composition README.md diff --git a/src/FluxFlow.Components.Sources.Composition/FluxFlow.Components.Sources.Composition.csproj b/src/FluxFlow.Components.Sources.Composition/FluxFlow.Components.Sources.Composition.csproj index a7a2d09e..5fafbc48 100644 --- a/src/FluxFlow.Components.Sources.Composition/FluxFlow.Components.Sources.Composition.csproj +++ b/src/FluxFlow.Components.Sources.Composition/FluxFlow.Components.Sources.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Sources.Composition FluxFlow.Components.Sources.Composition FluxFlow.Components.Sources.Composition - 6.0.0 + 7.0.0-rc.1 Typed generated and sequence source registration and Designer metadata over host-owned clocks. workflow;dataflow;components;sources;composition README.md diff --git a/src/FluxFlow.Components.State.Composition/FluxFlow.Components.State.Composition.csproj b/src/FluxFlow.Components.State.Composition/FluxFlow.Components.State.Composition.csproj index 15e8bd4e..e0687a9b 100644 --- a/src/FluxFlow.Components.State.Composition/FluxFlow.Components.State.Composition.csproj +++ b/src/FluxFlow.Components.State.Composition/FluxFlow.Components.State.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.State.Composition FluxFlow.Components.State.Composition FluxFlow.Components.State.Composition - 6.0.0 + 7.0.0-rc.1 Typed JSON state-reducer registration and Designer metadata over host-owned expression and clock resources. workflow;dataflow;components;state;composition README.md diff --git a/src/FluxFlow.Components.Storage.Composition/FluxFlow.Components.Storage.Composition.csproj b/src/FluxFlow.Components.Storage.Composition/FluxFlow.Components.Storage.Composition.csproj index b4bcb37e..eeed0b9b 100644 --- a/src/FluxFlow.Components.Storage.Composition/FluxFlow.Components.Storage.Composition.csproj +++ b/src/FluxFlow.Components.Storage.Composition/FluxFlow.Components.Storage.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Storage.Composition FluxFlow.Components.Storage.Composition FluxFlow.Components.Storage.Composition - 6.0.0 + 7.0.0-rc.1 Optional canonical exact-content storage registrations over host-owned keyed stores or factories. workflow;dataflow;components;storage;composition README.md diff --git a/src/FluxFlow.Components.Timers.Composition/FluxFlow.Components.Timers.Composition.csproj b/src/FluxFlow.Components.Timers.Composition/FluxFlow.Components.Timers.Composition.csproj index b810cd9b..6a90cd9d 100644 --- a/src/FluxFlow.Components.Timers.Composition/FluxFlow.Components.Timers.Composition.csproj +++ b/src/FluxFlow.Components.Timers.Composition/FluxFlow.Components.Timers.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Timers.Composition FluxFlow.Components.Timers.Composition FluxFlow.Components.Timers.Composition - 6.0.0 + 7.0.0-rc.1 Optional FluxFlow.Composition registrations and Designer metadata for typed timer sources and transforms over host-owned keyed clocks. workflow;dataflow;components;timers;composition README.md diff --git a/src/FluxFlow.Components.Validation.Composition/FluxFlow.Components.Validation.Composition.csproj b/src/FluxFlow.Components.Validation.Composition/FluxFlow.Components.Validation.Composition.csproj index 439b6429..9c5778f5 100644 --- a/src/FluxFlow.Components.Validation.Composition/FluxFlow.Components.Validation.Composition.csproj +++ b/src/FluxFlow.Components.Validation.Composition/FluxFlow.Components.Validation.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Validation.Composition FluxFlow.Components.Validation.Composition FluxFlow.Components.Validation.Composition - 6.0.0 + 7.0.0-rc.1 Optional FluxFlow.Composition registration and Designer metadata for explicit JsonElement JSON Schema validation. workflow;dataflow;components;validation;json-schema;composition README.md diff --git a/src/FluxFlow.Composition/CompatibilitySuppressions.xml b/src/FluxFlow.Composition/CompatibilitySuppressions.xml new file mode 100644 index 00000000..7468c3a1 --- /dev/null +++ b/src/FluxFlow.Composition/CompatibilitySuppressions.xml @@ -0,0 +1,204 @@ + + + + + CP0001 + T:FluxFlow.Composition.ComponentEvents + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0001 + T:FluxFlow.Composition.ComponentEvents + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.Authoring.DualInputOutputComponentHandle`3.#ctor(FluxFlow.Composition.Authoring.ComponentHandle,System.String,System.String,System.String) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.Authoring.InputComponentHandle`1.#ctor(FluxFlow.Composition.Authoring.ComponentHandle,System.String) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.Authoring.InputOutputComponentHandle`2.#ctor(FluxFlow.Composition.Authoring.ComponentHandle,System.String,System.String) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.Authoring.OutputComponentHandle`1.#ctor(FluxFlow.Composition.Authoring.ComponentHandle,System.String) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.ComponentInstance.#ctor(FluxFlow.Nodes.IFlowNode,System.Collections.Generic.IEnumerable{FluxFlow.Composition.ComponentInputPort},System.Collections.Generic.IEnumerable{FluxFlow.Composition.ComponentOutputPort},System.Threading.Tasks.Dataflow.ISourceBlock{FluxFlow.Nodes.FlowEvent},System.Threading.Tasks.Task,System.Func{System.Threading.Tasks.ValueTask}) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.ComponentInstance.Create(FluxFlow.Nodes.IFlowNode,System.Collections.Generic.IEnumerable{FluxFlow.Composition.ComponentInputPort},System.Collections.Generic.IEnumerable{FluxFlow.Composition.ComponentOutputPort},System.Threading.Tasks.Dataflow.ISourceBlock{FluxFlow.Nodes.FlowEvent},System.Threading.Tasks.Task,System.Func{System.Threading.Tasks.ValueTask}) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.FluxFlowRegistrationExtensions.AddRuntimeComponent(FluxFlow.Composition.FluxFlowRegistrationBuilder,System.String,System.Action{FluxFlow.Composition.RuntimeComponentRegistrationBuilder}) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.RuntimeComponentRegistrationBuilder.AddInput``1(System.String,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.RuntimeComponentRegistrationBuilder.AddOutput``1(System.String,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.RuntimeComponentRegistrationBuilder.AddSignalInput(System.String,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.RuntimeComponentRegistrationBuilder.UseFactory(FluxFlow.Composition.ComponentFactory) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.Authoring.DualInputOutputComponentHandle`3.#ctor(FluxFlow.Composition.Authoring.ComponentHandle,System.String,System.String,System.String) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.Authoring.InputComponentHandle`1.#ctor(FluxFlow.Composition.Authoring.ComponentHandle,System.String) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.Authoring.InputOutputComponentHandle`2.#ctor(FluxFlow.Composition.Authoring.ComponentHandle,System.String,System.String) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.Authoring.OutputComponentHandle`1.#ctor(FluxFlow.Composition.Authoring.ComponentHandle,System.String) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.ComponentInstance.#ctor(FluxFlow.Nodes.IFlowNode,System.Collections.Generic.IEnumerable{FluxFlow.Composition.ComponentInputPort},System.Collections.Generic.IEnumerable{FluxFlow.Composition.ComponentOutputPort},System.Threading.Tasks.Dataflow.ISourceBlock{FluxFlow.Nodes.FlowEvent},System.Threading.Tasks.Task,System.Func{System.Threading.Tasks.ValueTask}) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.ComponentInstance.Create(FluxFlow.Nodes.IFlowNode,System.Collections.Generic.IEnumerable{FluxFlow.Composition.ComponentInputPort},System.Collections.Generic.IEnumerable{FluxFlow.Composition.ComponentOutputPort},System.Threading.Tasks.Dataflow.ISourceBlock{FluxFlow.Nodes.FlowEvent},System.Threading.Tasks.Task,System.Func{System.Threading.Tasks.ValueTask}) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.FluxFlowRegistrationExtensions.AddRuntimeComponent(FluxFlow.Composition.FluxFlowRegistrationBuilder,System.String,System.Action{FluxFlow.Composition.RuntimeComponentRegistrationBuilder}) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.RuntimeComponentRegistrationBuilder.AddInput``1(System.String,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.RuntimeComponentRegistrationBuilder.AddOutput``1(System.String,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.RuntimeComponentRegistrationBuilder.AddSignalInput(System.String,FluxFlow.Composition.ComponentPortLinkCardinality) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0002 + M:FluxFlow.Composition.RuntimeComponentRegistrationBuilder.UseFactory(FluxFlow.Composition.ComponentFactory) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0006 + M:FluxFlow.Composition.Authoring.IResourceDefinitionContainerBuilder.AddResource``1(System.String,FluxFlow.Composition.Authoring.ApplicationResourceContract{``0}) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0006 + M:FluxFlow.Composition.Authoring.IResourceDefinitionContainerBuilder.AddResource``2(System.String,FluxFlow.Composition.Authoring.ApplicationResourceContract{``0,``1},System.Action{``0}) + lib/net10.0/FluxFlow.Composition.dll + lib/net10.0/FluxFlow.Composition.dll + true + + + CP0006 + M:FluxFlow.Composition.Authoring.IResourceDefinitionContainerBuilder.AddResource``1(System.String,FluxFlow.Composition.Authoring.ApplicationResourceContract{``0}) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + + CP0006 + M:FluxFlow.Composition.Authoring.IResourceDefinitionContainerBuilder.AddResource``2(System.String,FluxFlow.Composition.Authoring.ApplicationResourceContract{``0,``1},System.Action{``0}) + lib/net8.0/FluxFlow.Composition.dll + lib/net8.0/FluxFlow.Composition.dll + true + + diff --git a/src/FluxFlow.Composition/FluxFlow.Composition.csproj b/src/FluxFlow.Composition/FluxFlow.Composition.csproj index a1689c83..5016d640 100644 --- a/src/FluxFlow.Composition/FluxFlow.Composition.csproj +++ b/src/FluxFlow.Composition/FluxFlow.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Composition FluxFlow.Composition FluxFlow.Composition - 6.0.0 + 7.0.0-rc.1 Canonical FluxFlow application definitions, addressing, link compilation, component registration contracts, and keyed resource registration without depending on FluxFlow.Engine. workflow;dataflow;composition;nodes README.md diff --git a/src/FluxFlow.Engine.DurableInput.SqlFile/FluxFlow.Engine.DurableInput.SqlFile.csproj b/src/FluxFlow.Engine.DurableInput.SqlFile/FluxFlow.Engine.DurableInput.SqlFile.csproj index c8de14b2..6f5bdc9d 100644 --- a/src/FluxFlow.Engine.DurableInput.SqlFile/FluxFlow.Engine.DurableInput.SqlFile.csproj +++ b/src/FluxFlow.Engine.DurableInput.SqlFile/FluxFlow.Engine.DurableInput.SqlFile.csproj @@ -5,7 +5,7 @@ FluxFlow.Engine.DurableInput.SqlFile FluxFlow.Engine.DurableInput.SqlFile FluxFlow.Engine.DurableInput.SqlFile - 1.3.0 + 2.0.0-rc.1 SQLite single-file durable input store for FluxFlow.Engine.DurableInput. workflow;dataflow;durability;inbox;sqlite;at-least-once README.md diff --git a/src/FluxFlow.Engine.DurableInput.TSql/FluxFlow.Engine.DurableInput.TSql.csproj b/src/FluxFlow.Engine.DurableInput.TSql/FluxFlow.Engine.DurableInput.TSql.csproj index b094d884..aa8d35a2 100644 --- a/src/FluxFlow.Engine.DurableInput.TSql/FluxFlow.Engine.DurableInput.TSql.csproj +++ b/src/FluxFlow.Engine.DurableInput.TSql/FluxFlow.Engine.DurableInput.TSql.csproj @@ -5,7 +5,7 @@ FluxFlow.Engine.DurableInput.TSql FluxFlow.Engine.DurableInput.TSql FluxFlow.Engine.DurableInput.TSql - 1.2.0 + 2.0.0-rc.1 Production networked T-SQL durable-input, lease-renewal, dead-letter inspection, and generation-protected replay provider. workflow;dataflow;durability;inbox;tsql;at-least-once;dead-letter README.md diff --git a/src/FluxFlow.Engine.DurableInput/FluxFlow.Engine.DurableInput.csproj b/src/FluxFlow.Engine.DurableInput/FluxFlow.Engine.DurableInput.csproj index 75dff884..b9865f2f 100644 --- a/src/FluxFlow.Engine.DurableInput/FluxFlow.Engine.DurableInput.csproj +++ b/src/FluxFlow.Engine.DurableInput/FluxFlow.Engine.DurableInput.csproj @@ -5,7 +5,7 @@ FluxFlow.Engine.DurableInput FluxFlow.Engine.DurableInput FluxFlow.Engine.DurableInput - 1.3.0 + 2.0.0-rc.1 Optional provider-neutral durable input delivery for FluxFlow.Engine with leased at-least-once dispatch. workflow;dataflow;durability;inbox;at-least-once README.md diff --git a/src/FluxFlow.Engine.DurableOutput.SqlFile/FluxFlow.Engine.DurableOutput.SqlFile.csproj b/src/FluxFlow.Engine.DurableOutput.SqlFile/FluxFlow.Engine.DurableOutput.SqlFile.csproj index b762fa7a..028d6201 100644 --- a/src/FluxFlow.Engine.DurableOutput.SqlFile/FluxFlow.Engine.DurableOutput.SqlFile.csproj +++ b/src/FluxFlow.Engine.DurableOutput.SqlFile/FluxFlow.Engine.DurableOutput.SqlFile.csproj @@ -5,7 +5,7 @@ FluxFlow.Engine.DurableOutput.SqlFile FluxFlow.Engine.DurableOutput.SqlFile FluxFlow.Engine.DurableOutput.SqlFile - 3.0.0 + 4.0.0-rc.1 Production SQLite single-file durable-output capture, renewable leased delivery, dead-letter, and replay store for local FluxFlow hosts. workflow;dataflow;durability;outbox;sqlite;at-least-once;lease-renewal;dead-letter;replay README.md diff --git a/src/FluxFlow.Engine.DurableOutput.TSql/FluxFlow.Engine.DurableOutput.TSql.csproj b/src/FluxFlow.Engine.DurableOutput.TSql/FluxFlow.Engine.DurableOutput.TSql.csproj index d1302ce0..c44146a1 100644 --- a/src/FluxFlow.Engine.DurableOutput.TSql/FluxFlow.Engine.DurableOutput.TSql.csproj +++ b/src/FluxFlow.Engine.DurableOutput.TSql/FluxFlow.Engine.DurableOutput.TSql.csproj @@ -5,7 +5,7 @@ FluxFlow.Engine.DurableOutput.TSql FluxFlow.Engine.DurableOutput.TSql FluxFlow.Engine.DurableOutput.TSql - 2.0.0 + 3.0.0-rc.1 Production networked T-SQL durable-output capture, renewable leased delivery, dead-letter inspection, and generation-protected replay provider. workflow;dataflow;durability;outbox;tsql;at-least-once;lease-renewal;dead-letter README.md diff --git a/src/FluxFlow.Engine.DurableOutput/FluxFlow.Engine.DurableOutput.csproj b/src/FluxFlow.Engine.DurableOutput/FluxFlow.Engine.DurableOutput.csproj index 728062bd..5176f5ea 100644 --- a/src/FluxFlow.Engine.DurableOutput/FluxFlow.Engine.DurableOutput.csproj +++ b/src/FluxFlow.Engine.DurableOutput/FluxFlow.Engine.DurableOutput.csproj @@ -5,7 +5,7 @@ FluxFlow.Engine.DurableOutput FluxFlow.Engine.DurableOutput FluxFlow.Engine.DurableOutput - 3.0.0 + 4.0.0-rc.1 Optional provider-neutral durable output capture, renewable leased at-least-once delivery, and dead-letter operations for FluxFlow.Engine. workflow;dataflow;durability;outbox;capture;at-least-once;lease-renewal;dead-letter;replay README.md diff --git a/src/FluxFlow.Engine.HealthChecks/FluxFlow.Engine.HealthChecks.csproj b/src/FluxFlow.Engine.HealthChecks/FluxFlow.Engine.HealthChecks.csproj index e9550c90..f61de627 100644 --- a/src/FluxFlow.Engine.HealthChecks/FluxFlow.Engine.HealthChecks.csproj +++ b/src/FluxFlow.Engine.HealthChecks/FluxFlow.Engine.HealthChecks.csproj @@ -5,7 +5,7 @@ FluxFlow.Engine.HealthChecks FluxFlow.Engine.HealthChecks FluxFlow.Engine.HealthChecks - 1.0.0 + 1.0.0-rc.1 Optional standard .NET readiness health check for FluxFlow application lifecycle and revision state. workflow;dataflow;health-checks;readiness;hosting;operations README.md diff --git a/src/FluxFlow.Engine/FluxFlow.Engine.csproj b/src/FluxFlow.Engine/FluxFlow.Engine.csproj index 85b1f477..92b65c5b 100644 --- a/src/FluxFlow.Engine/FluxFlow.Engine.csproj +++ b/src/FluxFlow.Engine/FluxFlow.Engine.csproj @@ -5,7 +5,7 @@ FluxFlow.Engine FluxFlow.Engine FluxFlow.Engine - 7.0.0 + 8.0.0-rc.1 Canonical FluxFlow application runtime assembler with transactional revisions, stable addressable ports, conditional routing, system events, and diagnostics. workflow;dataflow;pipeline;flow-engine;tpl Loads only canonical definitions, owns configuration-tree reconstruction, and consumes public Composition link and resource-registration boundaries. diff --git a/src/FluxFlow.Fluent.Hosting/FluxFlow.Fluent.Hosting.csproj b/src/FluxFlow.Fluent.Hosting/FluxFlow.Fluent.Hosting.csproj index 791947da..30b17be1 100644 --- a/src/FluxFlow.Fluent.Hosting/FluxFlow.Fluent.Hosting.csproj +++ b/src/FluxFlow.Fluent.Hosting/FluxFlow.Fluent.Hosting.csproj @@ -5,7 +5,7 @@ FluxFlow.Fluent.Hosting FluxFlow.Fluent.Hosting FluxFlow.Fluent.Hosting - 4.0.0 + 5.0.0-rc.1 Optional hosting bridge for FluxFlow.Fluent: register a FlowGraph with AddFlowGraph and run it as an IHostedService — built and started on host start, stopped and disposed on shutdown. The factory delegate resolves nodes from DI. workflow;dataflow;fluent;dsl;hosting README.md diff --git a/src/FluxFlow.Fluent/CompatibilitySuppressions.xml b/src/FluxFlow.Fluent/CompatibilitySuppressions.xml new file mode 100644 index 00000000..43a9e845 --- /dev/null +++ b/src/FluxFlow.Fluent/CompatibilitySuppressions.xml @@ -0,0 +1,21 @@ + + + + + CP0002 + M:FluxFlow.Fluent.FlowGraph.get_Runtime + lib/net10.0/FluxFlow.Fluent.dll + lib/net10.0/FluxFlow.Fluent.dll + true + + + CP0002 + M:FluxFlow.Fluent.FlowGraph.get_Runtime + lib/net8.0/FluxFlow.Fluent.dll + lib/net8.0/FluxFlow.Fluent.dll + true + + diff --git a/src/FluxFlow.Fluent/FluxFlow.Fluent.csproj b/src/FluxFlow.Fluent/FluxFlow.Fluent.csproj index 5e723e92..fcefe1e1 100644 --- a/src/FluxFlow.Fluent/FluxFlow.Fluent.csproj +++ b/src/FluxFlow.Fluent/FluxFlow.Fluent.csproj @@ -5,7 +5,7 @@ FluxFlow.Fluent FluxFlow.Fluent FluxFlow.Fluent - 4.0.0 + 5.0.0-rc.1 Type-safe, code-first fluent DSL for composing FluxFlow standalone nodes into a runnable graph — Flow.From(source).Then(node).To(sink) with compile-time-checked wiring, branching, and fan-in. Reuses the FluxFlow.Composition runtime. workflow;dataflow;composition;nodes;fluent;dsl README.md diff --git a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/FluxFlow.Components.Mqtt.Composition.csproj b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/FluxFlow.Components.Mqtt.Composition.csproj index f8a0b9f0..5f0a09a6 100644 --- a/src/Mqtt/FluxFlow.Components.Mqtt.Composition/FluxFlow.Components.Mqtt.Composition.csproj +++ b/src/Mqtt/FluxFlow.Components.Mqtt.Composition/FluxFlow.Components.Mqtt.Composition.csproj @@ -5,7 +5,7 @@ FluxFlow.Components.Mqtt.Composition FluxFlow.Components.Mqtt.Composition FluxFlow.Components.Mqtt.Composition - 6.0.0 + 7.0.0-rc.1 Canonical FluxFlow Composition resources and nodes for provider-neutral MQTT client control, publication, subscriptions, and client events. workflow;dataflow;components;mqtt;composition README.md diff --git a/tests/FluxFlow.Release.Tests/DurabilityPackageVersionTests.cs b/tests/FluxFlow.Release.Tests/DurabilityPackageVersionTests.cs index df2df618..3f79c555 100644 --- a/tests/FluxFlow.Release.Tests/DurabilityPackageVersionTests.cs +++ b/tests/FluxFlow.Release.Tests/DurabilityPackageVersionTests.cs @@ -8,12 +8,12 @@ public sealed class DurabilityPackageVersionTests { public static TheoryData ExpectedVersions => new() { - { "src/FluxFlow.Engine.DurableInput/FluxFlow.Engine.DurableInput.csproj", "1.3.0" }, - { "src/FluxFlow.Engine.DurableInput.SqlFile/FluxFlow.Engine.DurableInput.SqlFile.csproj", "1.3.0" }, - { "src/FluxFlow.Engine.DurableInput.TSql/FluxFlow.Engine.DurableInput.TSql.csproj", "1.2.0" }, - { "src/FluxFlow.Engine.DurableOutput/FluxFlow.Engine.DurableOutput.csproj", "3.0.0" }, - { "src/FluxFlow.Engine.DurableOutput.SqlFile/FluxFlow.Engine.DurableOutput.SqlFile.csproj", "3.0.0" }, - { "src/FluxFlow.Engine.DurableOutput.TSql/FluxFlow.Engine.DurableOutput.TSql.csproj", "2.0.0" } + { "src/FluxFlow.Engine.DurableInput/FluxFlow.Engine.DurableInput.csproj", "2.0.0-rc.1" }, + { "src/FluxFlow.Engine.DurableInput.SqlFile/FluxFlow.Engine.DurableInput.SqlFile.csproj", "2.0.0-rc.1" }, + { "src/FluxFlow.Engine.DurableInput.TSql/FluxFlow.Engine.DurableInput.TSql.csproj", "2.0.0-rc.1" }, + { "src/FluxFlow.Engine.DurableOutput/FluxFlow.Engine.DurableOutput.csproj", "4.0.0-rc.1" }, + { "src/FluxFlow.Engine.DurableOutput.SqlFile/FluxFlow.Engine.DurableOutput.SqlFile.csproj", "4.0.0-rc.1" }, + { "src/FluxFlow.Engine.DurableOutput.TSql/FluxFlow.Engine.DurableOutput.TSql.csproj", "3.0.0-rc.1" } }; [Theory] diff --git a/tests/FluxFlow.Release.Tests/HealthReadinessConventionTests.cs b/tests/FluxFlow.Release.Tests/HealthReadinessConventionTests.cs index 9eda629d..c2523a71 100644 --- a/tests/FluxFlow.Release.Tests/HealthReadinessConventionTests.cs +++ b/tests/FluxFlow.Release.Tests/HealthReadinessConventionTests.cs @@ -23,7 +23,7 @@ public void Health_integration_package_is_optional_standard_only_and_manifested( ReadProperty(project, "PackageId").ShouldBe("FluxFlow.Engine.HealthChecks"); ReadProperty(project, "AssemblyName").ShouldBe("FluxFlow.Engine.HealthChecks"); ReadProperty(project, "RootNamespace").ShouldBe("FluxFlow.Engine.HealthChecks"); - ReadProperty(project, "Version").ShouldBe("1.0.0"); + ReadProperty(project, "Version").ShouldBe("1.0.0-rc.1"); ReadIncludes(project, "PackageReference") .ShouldBe(new[] { "Microsoft.Extensions.Diagnostics.HealthChecks" }); ReadIncludes(project, "ProjectReference") diff --git a/tests/FluxFlow.Release.Tests/PackagePublishWorkflowTests.cs b/tests/FluxFlow.Release.Tests/PackagePublishWorkflowTests.cs index 983486e4..235e67ce 100644 --- a/tests/FluxFlow.Release.Tests/PackagePublishWorkflowTests.cs +++ b/tests/FluxFlow.Release.Tests/PackagePublishWorkflowTests.cs @@ -40,6 +40,62 @@ public void Publish_workflow_orders_build_compatibility_integrity_and_publicatio releaseIndex.ShouldBeGreaterThan(verificationIndex); } + [Fact] + public void Publish_workflow_uses_exact_release_environment_and_trusted_publishing_permissions() + { + var workflow = NormalizeLineEndings(ReadWorkflow()); + var permissionsIndex = RequiredIndexOf(workflow, "permissions:\n"); + var jobsIndex = RequiredIndexOf(workflow, "jobs:\n"); + var stepsIndex = RequiredIndexOf(workflow, "\n steps:\n"); + var permissions = workflow[permissionsIndex..jobsIndex]; + var releaseJobHeader = workflow[jobsIndex..stepsIndex]; + + CountOccurrences(workflow, "permissions:").ShouldBe(1); + CountOccurrences(workflow, "contents: write").ShouldBe(1); + CountOccurrences(workflow, "id-token: write").ShouldBe(1); + CountOccurrences(permissions, "\n contents: write\n").ShouldBe(1); + CountOccurrences(permissions, "\n id-token: write\n").ShouldBe(1); + CountOccurrences(workflow, "environment:").ShouldBe(1); + CountOccurrences(releaseJobHeader, "\n environment: release\n").ShouldBe(1); + } + + [Fact] + public void Publish_workflow_logs_into_package_feed_immediately_before_publication_without_static_api_key_secret() + { + var workflow = NormalizeLineEndings(ReadWorkflow()); + const string loginName = "- name: Package feed login"; + const string publishName = "- name: Publish package"; + var loginIndex = RequiredIndexOf(workflow, loginName); + var publishIndex = RequiredIndexOf(workflow, publishName); + var verificationIndex = RequiredIndexOf(workflow, "- name: Verify package feed"); + var nextNamedStepIndex = workflow.IndexOf( + "- name:", + loginIndex + loginName.Length, + StringComparison.Ordinal); + var loginStep = workflow[loginIndex..publishIndex]; + var publishStep = workflow[publishIndex..verificationIndex]; + + CountOccurrences(workflow, loginName).ShouldBe(1); + CountOccurrences(workflow, publishName).ShouldBe(1); + CountOccurrences(workflow, "uses: NuGet/login@v1").ShouldBe(1); + nextNamedStepIndex.ShouldBe(publishIndex); + CountOccurrences(loginStep, "\n - ").ShouldBe(0); + CountOccurrences(loginStep, "id: nuget-login").ShouldBe(1); + CountOccurrences(loginStep, "uses: NuGet/login@v1").ShouldBe(1); + CountOccurrences(loginStep, "user: ${{ secrets.NUGET_USER }}").ShouldBe(1); + CountOccurrences( + publishStep, + "--api-key \"${{ steps.nuget-login.outputs.NUGET_API_KEY }}\"").ShouldBe(1); + CountOccurrences( + workflow, + "secrets.NUGET_API_KEY", + StringComparison.OrdinalIgnoreCase).ShouldBe(0); + CountOccurrences( + workflow, + "$env:NUGET_API_KEY", + StringComparison.OrdinalIgnoreCase).ShouldBe(0); + } + [Fact] public void Publish_workflow_uses_resolved_binary_compatibility_gate_as_sole_pack_path() { @@ -77,6 +133,9 @@ private static string ReadWorkflow() return File.ReadAllText(workflowPath); } + private static string NormalizeLineEndings(string value) => + value.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n'); + private static int RequiredIndexOf(string text, string value) { var index = text.IndexOf(value, StringComparison.Ordinal); From 243cde05ebd06b0154cbb03bfe7220aab13b85ea Mon Sep 17 00:00:00 2001 From: meisa Date: Sun, 9 Aug 2026 00:25:34 +0200 Subject: [PATCH 5/6] Normalize release diagnostic assertions --- .../PackageConsumerAcceptanceScriptTests.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs b/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs index 00b42f1a..cef12818 100644 --- a/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs +++ b/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs @@ -1,5 +1,6 @@ using System.Runtime.InteropServices; using System.Text.Json; +using System.Text.RegularExpressions; using System.Xml.Linq; using Shouldly; using Xunit; @@ -700,7 +701,7 @@ public async Task Acceptance_script_cleans_owned_workdir_after_invalid_recovery_ result.ExitCode.ShouldNotBe(0); result.ToString().ShouldContain("Package consumer restart recovery must emit"); result.ToString().ShouldContain(invalidMarker); - result.ToString().ShouldContain($"observed {observedCount}"); + NormalizeDiagnosticText(result.ToString()).ShouldContain($"observed {observedCount}"); result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_RESTART_COMPLETE=True"); result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); File.ReadAllLines(fixture.DotnetArgumentsPath).Length.ShouldBe(5); @@ -819,6 +820,20 @@ private static string ReadOutputValue(string output, string prefix) return line[prefix.Length..]; } + private static string NormalizeDiagnosticText(string value) + { + var withoutControlSequences = Regex.Replace( + value, + @"\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007]*(?:\u0007|\x1B\\))", + string.Empty, + RegexOptions.CultureInvariant); + return Regex.Replace( + withoutControlSequences, + @"\s+", + " ", + RegexOptions.CultureInvariant).Trim(); + } + private static string NormalizePath(string path) => path .Replace('/', Path.DirectorySeparatorChar) From d4b239044ebe009c5a665186592d678e38e484e1 Mon Sep 17 00:00:00 2001 From: meisa Date: Sun, 9 Aug 2026 00:39:50 +0200 Subject: [PATCH 6/6] Handle hosted release diagnostics --- .../PackageConsumerAcceptanceScriptTests.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs b/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs index cef12818..d2512748 100644 --- a/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs +++ b/tests/FluxFlow.Release.Tests/PackageConsumerAcceptanceScriptTests.cs @@ -701,7 +701,10 @@ public async Task Acceptance_script_cleans_owned_workdir_after_invalid_recovery_ result.ExitCode.ShouldNotBe(0); result.ToString().ShouldContain("Package consumer restart recovery must emit"); result.ToString().ShouldContain(invalidMarker); - NormalizeDiagnosticText(result.ToString()).ShouldContain($"observed {observedCount}"); + var expectedRecoveryFailure = + $"Package consumer restart recovery must emit '{invalidMarker}' exactly once; observed {observedCount}."; + CountOccurrences(NormalizeDiagnosticText(result.StandardError), expectedRecoveryFailure) + .ShouldBe(1, $"Expected exact recovery clause: \"{expectedRecoveryFailure}\""); result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_RESTART_COMPLETE=True"); result.StandardOutput.ShouldNotContain("PACKAGE_ACCEPTANCE_COMPLETE=True"); File.ReadAllLines(fixture.DotnetArgumentsPath).Length.ShouldBe(5); @@ -827,8 +830,13 @@ private static string NormalizeDiagnosticText(string value) @"\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007]*(?:\u0007|\x1B\\))", string.Empty, RegexOptions.CultureInvariant); - return Regex.Replace( + var withoutPowerShellErrorGutters = Regex.Replace( withoutControlSequences, + @"(?m)^[\t ]*\|[\t ]?", + string.Empty, + RegexOptions.CultureInvariant); + return Regex.Replace( + withoutPowerShellErrorGutters, @"\s+", " ", RegexOptions.CultureInvariant).Trim();