diff --git a/workflows/csharp/.gitignore b/workflows/csharp/.gitignore new file mode 100644 index 000000000..ed0d0a43a --- /dev/null +++ b/workflows/csharp/.gitignore @@ -0,0 +1,483 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +# but not Directory.Build.rsp, as it configures directory-level build defaults +!Directory.Build.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp +*.lscache diff --git a/workflows/csharp/sdk-context-propagation/README.md b/workflows/csharp/sdk-context-propagation/README.md new file mode 100644 index 000000000..bfcb22843 --- /dev/null +++ b/workflows/csharp/sdk-context-propagation/README.md @@ -0,0 +1,212 @@ +# Dapr Workflow History Propagation — Patient Intake (.NET SDK) + +This quickstart demonstrates **workflow history propagation**, a Dapr 1.18 +feature that lets a workflow propagate its execution history to child workflows +so downstream consumers can inspect the full (or partial) execution context of +their caller — without any external state store or custom messaging. + +The scenario is a patient intake / e-prescribing pipeline: a compliance audit +and a pharmacy dispense step refuse to act unless they can see proof — in the +propagated history — that the required upstream checks (insurance, allergies, +drug interactions) actually ran. + +> **Runtime requirement**: Dapr 1.18+ ([dapr/dapr#9810](https://github.com/dapr/dapr/pull/9810)) +> **SDK requirement**: `Dapr.Workflow >= 1.18.0-rc01` ([dapr/dotnet-sdk#1802](https://github.com/dapr/dotnet-sdk/pull/1802)) +> **Proposal**: [dapr/proposals#102](https://github.com/dapr/proposals/issues/102) + +## Workflow architecture + +``` +PatientIntake (workflow) +├── VerifyInsurance (activity, no propagation) +└── PrescribeMedication (child workflow, Lineage) + ├── CheckAllergies (activity, no propagation) + ├── ScreenDrugInteractions (activity, no propagation) + ├── ComplianceAudit (child workflow, Lineage) + │ → sees PatientIntake + PrescribeMedication events + └── DispenseMedicationWorkflow (child workflow, OwnHistory) + → sees PrescribeMedication events only + → refuses to dispense if the screening lineage is missing +``` + +### Propagation scope + +| Mode | Enum value | What it sends | Use case | +|------|-----------|---------------|----------| +| **Lineage** | `HistoryPropagationScope.Lineage` | Caller's own events + any ancestor events it received | Full chain-of-custody verification (compliance audits) | +| **Own history** | `HistoryPropagationScope.OwnHistory` | Caller's own events only (no ancestor chain) | Trust boundary — downstream only sees the immediate caller (pharmacy dispense) | + +### Key demonstration + +- **ComplianceAudit** receives the full lineage via `HistoryPropagationScope.Lineage` — + it verifies that `VerifyInsurance` ran in the grandparent workflow + (PatientIntake), plus `CheckAllergies` and `ScreenDrugInteractions` ran in + PrescribeMedication. + +- **DispenseMedicationWorkflow** receives only PrescribeMedication's history via + `HistoryPropagationScope.OwnHistory`. The PatientIntake ancestral history is + excluded — the pharmacy system doesn't need (or get to see) the upstream + chain. Before dispensing, the pharmacy verifies that `CheckAllergies` and + `ScreenDrugInteractions` completed in the propagated history. + +### Scenarios + +The demo runs two scenarios back-to-back to show both the happy path and the +pharmacy's safety check: + +1. **Lineage forwarded → pharmacy dispenses.** `PrescribeMedication` calls the + dispense step with `HistoryPropagationScope.OwnHistory`. The pharmacy sees + the completed allergy and interaction screens in the propagated history and + fills the prescription. + +2. **Lineage withheld → pharmacy refuses.** `PrescribeMedication` calls the + dispense step **without** history propagation (simulating an upstream system + that fails to forward its lineage). With no propagated history to prove the + prescription was screened, the pharmacy refuses to dispense and returns a + `refused` result explaining what was missing. + +## .NET note: dispense is a child workflow + +The Python sibling ([dapr/quickstarts#1309](https://github.com/dapr/quickstarts/pull/1309)) +and the Go reference call the final dispense step as a bare **activity** with an +`OwnHistory` propagation argument. In the .NET SDK (v1.18) +`HistoryPropagationScope` is only available on `ChildWorkflowTaskOptions` — +activity calls do not carry a propagation scope. To demonstrate the identical +trust-boundary semantics, this sample wraps the `DispenseMedicationActivity` +inside `DispenseMedicationWorkflow` (a child workflow) which inspects the +propagated history and only calls the activity once it has verified the +screening lineage. + +## .NET API surface + +```csharp +// Parent workflow — propagate Lineage when calling a child workflow +var result = await ctx.CallChildWorkflowAsync( + nameof(ComplianceAuditWorkflow), + input, + new ChildWorkflowTaskOptions(PropagationScope: HistoryPropagationScope.Lineage)); + +// Parent workflow — propagate OwnHistory when calling a child workflow +var dispense = await ctx.CallChildWorkflowAsync( + nameof(DispenseMedicationWorkflow), + input, + new ChildWorkflowTaskOptions(PropagationScope: HistoryPropagationScope.OwnHistory)); + +// Child workflow — read the propagated history +var history = ctx.GetPropagatedHistory(); // returns PropagatedHistory? + +if (history is not null) +{ + // Filter to a specific ancestor workflow by name + var prescribeEntries = history.FilterByWorkflowName(nameof(PrescribeMedicationWorkflow)); + + // Inspect events within that ancestor's segment + var completedCount = prescribeEntries.Entries[0].Events + .Count(e => e.Kind == HistoryEventKind.TaskCompleted); +} +``` + +Key types in `Dapr.Workflow`: +- `HistoryPropagationScope` — enum: `None`, `OwnHistory`, `Lineage` +- `ChildWorkflowTaskOptions` — pass `PropagationScope` here +- `PropagatedHistory` — call `.FilterByWorkflowName(name)`, `.FilterByAppId(id)`, `.FilterByInstanceId(id)` +- `PropagatedHistoryEntry` — has `WorkflowName`, `AppId`, `InstanceId`, `Events` +- `PropagatedHistoryEvent` — has `EventId`, `Kind` (`HistoryEventKind`), `Timestamp` +- `HistoryEventKind` — enum including `TaskScheduled`, `TaskCompleted`, `TaskFailed`, etc. + +> **Replay safety**: workflow code runs many times during durable execution. +> Guard side-effecting calls — including `Console.WriteLine` — with +> `if (!ctx.IsReplaying)` so they only fire on the live execution, not on each +> replay. + +## Running this example + +Requires Dapr `1.18.0+` (workflow history propagation), +`Dapr.Workflow 1.18.0-rc01+`, and the [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) +(or newer). Redis is started automatically by `dapr init`. + +Build the example: + +```bash +dotnet build ./order-processor +``` + +Run the demo: + + + +```bash +dapr run -f . +``` + + + +The app runs both scenarios once and exits on its own — no Ctrl+C needed. + +In scenario 1 (lineage forwarded) you'll see the pharmacy dispense: + +``` +[ComplianceAudit] Received propagated history with 2 segment(s): +[ComplianceAudit] APPROVED (risk=0.10, total events inspected=...) +[DispenseMedication] Dispense request: amoxicillin 500mg for P-1042 (propagated history: ... events) +[DispenseMedication] DISPENSED: rx-P-1042-... +``` + +In scenario 2 (lineage withheld) the pharmacy refuses: + +``` +[PrescribeMedication] Step 4: DispenseMedicationWorkflow child wf + -> NO history propagation (negative scenario) +[DispenseMedication] Dispense request: penicillin 500mg for P-2087 (propagated history: none) +[DispenseMedication] REFUSED — no propagated history; cannot verify screening for P-2087 +[PrescribeMedication] Step 4 BLOCKED: pharmacy refused to dispense (missing lineage: no propagated history received from prescriber) +``` + +## Standalone-mode note + +In standalone mode the sidecar will log `propagating unsigned workflow history +to ...` warnings — these are expected. Without `WorkflowHistorySigning` enabled, +propagated history chunks aren't cryptographically signed, which is fine for a +local `dapr run` demo. Signing the chunks within an mTLS trust boundary is a +production concern handled at the cluster/control-plane level and is out of +scope for this quickstart. + +## Files + +``` +sdk-context-propagation/ +├── README.md # this file +├── dapr.yaml # `dapr run -f .` config (appID, resources, command) +└── order-processor/ + ├── Program.cs # host setup; schedules both scenarios + ├── Models.cs # PatientRecord, ComplianceResult, DispenseResult + ├── Activities.cs # VerifyInsurance, CheckAllergies, ScreenDrugInteractions, DispenseMedication + ├── Workflows.cs # workflow definitions + history inspection + └── OrderProcessor.csproj # project + Dapr.Workflow dependency +``` + +## References + +- Sibling Python quickstart: [dapr/quickstarts#1309](https://github.com/dapr/quickstarts/pull/1309) +- Canonical Go SDK reference: [dapr/go-sdk#823](https://github.com/dapr/go-sdk/pull/823) +- Sibling Go quickstart: [dapr/quickstarts#1315](https://github.com/dapr/quickstarts/pull/1315) +- .NET SDK implementation: [dapr/dotnet-sdk#1802](https://github.com/dapr/dotnet-sdk/pull/1802) +- Runtime support: [dapr/dapr#9810](https://github.com/dapr/dapr/pull/9810) +- Docs (.NET): [dapr/docs#5174](https://github.com/dapr/docs/pull/5174) +- Proposal: [dapr/proposals#102](https://github.com/dapr/proposals/issues/102) +- 1.18 endgame: [dapr/dapr#9856](https://github.com/dapr/dapr/issues/9856) +``` diff --git a/workflows/csharp/sdk-context-propagation/dapr.yaml b/workflows/csharp/sdk-context-propagation/dapr.yaml new file mode 100644 index 000000000..a97cac6e5 --- /dev/null +++ b/workflows/csharp/sdk-context-propagation/dapr.yaml @@ -0,0 +1,7 @@ +version: 1 +common: + resourcesPath: ../../components +apps: + - appID: order-processor + appDirPath: ./order-processor/ + command: ["dotnet", "run"] diff --git a/workflows/csharp/sdk-context-propagation/order-processor/Activities.cs b/workflows/csharp/sdk-context-propagation/order-processor/Activities.cs new file mode 100644 index 000000000..cf3c7adf5 --- /dev/null +++ b/workflows/csharp/sdk-context-propagation/order-processor/Activities.cs @@ -0,0 +1,72 @@ +// ------------------------------------------------------------------------ +// Copyright 2026 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + +namespace OrderProcessor; + +using Dapr.Workflow; + +/// +/// Verifies the patient's insurance coverage. Called by PatientIntake without +/// propagation. +/// +public sealed class VerifyInsuranceActivity : WorkflowActivity +{ + public override Task RunAsync(WorkflowActivityContext ctx, PatientRecord rec) + { + Console.WriteLine($" [VerifyInsurance] Checking coverage for patient {rec.PatientId}"); + return Task.FromResult(true); + } +} + +/// +/// Screens the patient against their allergy list for the candidate drug. +/// Called by PrescribeMedication without propagation. +/// +public sealed class CheckAllergiesActivity : WorkflowActivity +{ + public override Task RunAsync(WorkflowActivityContext ctx, PatientRecord rec) + { + Console.WriteLine($" [CheckAllergies] Screening {rec.PatientId} for {rec.Medication}"); + return Task.FromResult(true); + } +} + +/// +/// Screens the candidate prescription against the patient's active medication +/// list. Called by PrescribeMedication without propagation. +/// +public sealed class ScreenDrugInteractionsActivity : WorkflowActivity +{ + public override Task RunAsync(WorkflowActivityContext ctx, PatientRecord rec) + { + Console.WriteLine($" [ScreenDrugInteractions] Screening {rec.Medication} {rec.Dosage:F0}mg for {rec.PatientId}"); + return Task.FromResult(true); + } +} + +/// +/// Fills the prescription. Called by DispenseMedicationWorkflow only after it +/// has verified the prescribing pipeline in the propagated history. +/// +public sealed class DispenseMedicationActivity : WorkflowActivity +{ + public override Task RunAsync(WorkflowActivityContext ctx, PatientRecord rec) + { + var dispenseId = $"rx-{rec.PatientId}-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}"; + Console.WriteLine($" [DispenseMedication] DISPENSED: {dispenseId}"); + return Task.FromResult(new DispenseResult( + DispenseId: dispenseId, + Status: "dispensed", + EventCount: 0)); // EventCount populated by DispenseMedicationWorkflow + } +} diff --git a/workflows/csharp/sdk-context-propagation/order-processor/Models.cs b/workflows/csharp/sdk-context-propagation/order-processor/Models.cs new file mode 100644 index 000000000..eaa591178 --- /dev/null +++ b/workflows/csharp/sdk-context-propagation/order-processor/Models.cs @@ -0,0 +1,67 @@ +// ------------------------------------------------------------------------ +// Copyright 2026 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + +namespace OrderProcessor; + +/// +/// Patient record propagated through the workflow hierarchy. In a real +/// deployment the Name / DOB / MRN fields are protected health info and +/// would be candidates for redaction when the record is propagated downstream. +/// +/// Patient identifier. +/// Patient name. +/// Date of birth (YYYY-MM-DD). +/// Medical record number. +/// Diagnosis / indication. +/// Prescribed drug name. +/// Dosage in milligrams. +/// +/// Controls whether PrescribeMedication propagates its own history to the +/// dispense step. When true (happy path) the pharmacy can verify the +/// upstream screening and dispenses. When false (negative scenario) +/// the pharmacy receives no lineage and refuses. +/// +public sealed record PatientRecord( + string PatientId, + string Name, + string Dob, + string Mrn, + string Condition, + string Medication, + double Dosage, + bool ForwardLineage = true); + +/// Result produced by the ComplianceAudit workflow. +/// Whether the prescription cleared compliance. +/// Risk score in the range [0, 1]. +/// Human-readable decision rationale. +/// Number of propagated history segments inspected. +public sealed record ComplianceResult( + bool Compliant, + double RiskScore, + string Reason, + int EventCount); + +/// Result produced by the dispense step. +/// Pharmacy dispense identifier (empty when refused). +/// "dispensed" when the pharmacy filled the +/// prescription, or "refused" when it could not verify the prescribing +/// pipeline in the propagated history. +/// Number of propagated history events inspected. +/// Explains what was missing when is +/// "refused"; empty otherwise. +public sealed record DispenseResult( + string DispenseId, + string Status, + int EventCount, + string Reason = ""); diff --git a/workflows/csharp/sdk-context-propagation/order-processor/OrderProcessor.csproj b/workflows/csharp/sdk-context-propagation/order-processor/OrderProcessor.csproj new file mode 100644 index 000000000..322a10fc0 --- /dev/null +++ b/workflows/csharp/sdk-context-propagation/order-processor/OrderProcessor.csproj @@ -0,0 +1,17 @@ + + + + Exe + enable + net10.0 + enable + latest + + + + + + + + + diff --git a/workflows/csharp/sdk-context-propagation/order-processor/Program.cs b/workflows/csharp/sdk-context-propagation/order-processor/Program.cs new file mode 100644 index 000000000..03deaf72c --- /dev/null +++ b/workflows/csharp/sdk-context-propagation/order-processor/Program.cs @@ -0,0 +1,154 @@ +// ------------------------------------------------------------------------ +// Copyright 2026 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + +// Workflow History Propagation Quickstart (.NET SDK) +// +// Scenario: patient intake / e-prescribing pipeline. +// +// Flow: +// PatientIntake (root) +// └─ VerifyInsurance (activity, no propagation) +// └─ PrescribeMedication (child wf, HistoryPropagationScope.Lineage) +// └─ CheckAllergies (activity, no propagation) +// └─ ScreenDrugInteractions (activity, no propagation) +// └─ ComplianceAudit (grandchild wf, HistoryPropagationScope.Lineage) +// | reads: PatientIntake + PrescribeMedication events +// └─ DispenseMedicationWorkflow (grandchild wf, HistoryPropagationScope.OwnHistory) +// reads: PrescribeMedication events only +// └─ DispenseMedication (activity) +// +// The demo runs two scenarios back-to-back: +// 1. Lineage forwarded — PrescribeMedication propagates its own history to the +// pharmacy, which verifies the upstream screening and dispenses. +// 2. Lineage withheld — PrescribeMedication omits propagation, so the pharmacy +// receives no lineage and refuses to dispense. +// +// Requires Dapr 1.18+ (dapr/dapr#9810) and Dapr.Workflow 1.18+ (dapr/dotnet-sdk#1802). +// Against an older sidecar GetPropagatedHistory() returns null and the sample +// exits gracefully. + +using Dapr.Workflow; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using OrderProcessor; + +// --------------------------------------------------------------------------- +// Host setup — register workflows and activities +// --------------------------------------------------------------------------- + +var builder = Host.CreateDefaultBuilder(args) + .ConfigureServices(services => + { + services.AddDaprClient(); + services.AddDaprWorkflow(options => + { + options.RegisterWorkflow(); + options.RegisterWorkflow(); + options.RegisterWorkflow(); + options.RegisterWorkflow(); + + options.RegisterActivity(); + options.RegisterActivity(); + options.RegisterActivity(); + options.RegisterActivity(); + }); + }); + +using var host = builder.Build(); + +await host.StartAsync(); + +var workflowClient = host.Services.GetRequiredService(); + +// --------------------------------------------------------------------------- +// Run two scenarios back-to-back +// --------------------------------------------------------------------------- + +Console.WriteLine(Banner("WORKFLOW HISTORY PROPAGATION DEMO — PATIENT INTAKE (.NET)")); +Console.WriteLine(); +Console.WriteLine(" Flow: PatientIntake -> VerifyInsurance"); +Console.WriteLine(" -> PrescribeMedication (child wf, Lineage)"); +Console.WriteLine(" -> CheckAllergies -> ScreenDrugInteractions"); +Console.WriteLine(" -> ComplianceAudit (child wf, Lineage) <-- sees PatientIntake + PrescribeMedication events"); +Console.WriteLine(" -> DispenseMedicationWorkflow (child wf, OwnHistory) <-- sees only PrescribeMedication events"); + +// Scenario 1 (happy path): PrescribeMedication forwards its own history to the +// pharmacy, which verifies the upstream screening and dispenses. +await RunScenario( + "SCENARIO 1: lineage forwarded — pharmacy dispenses", + "intake-ok", + new PatientRecord( + PatientId: "P-1042", + Name: "Jane Doe", + Dob: "1985-06-12", + Mrn: "MRN-77231", + Condition: "bacterial sinusitis", + Medication: "amoxicillin", + Dosage: 500, + ForwardLineage: true)); + +// Scenario 2 (negative): PrescribeMedication dispenses WITHOUT propagating its +// history, so the pharmacy receives no lineage and refuses to dispense. +await RunScenario( + "SCENARIO 2: lineage withheld — pharmacy refuses", + "intake-missing-lineage", + new PatientRecord( + PatientId: "P-2087", + Name: "John Roe", + Dob: "1979-03-04", + Mrn: "MRN-55810", + Condition: "strep throat", + Medication: "penicillin", + Dosage: 500, + ForwardLineage: false)); + +Console.WriteLine(); +Console.WriteLine(Banner("COMPLETE")); + +await host.StopAsync(); + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +// Schedules one PatientIntake run, waits for it to finish, prints the final +// result, and purges its state so the demo can exit cleanly. +async Task RunScenario(string title, string instanceId, PatientRecord rec) +{ + Console.WriteLine(); + Console.WriteLine(Banner(title)); + Console.WriteLine($" [main] Scheduling workflow instance: {instanceId}"); + + await workflowClient.ScheduleNewWorkflowAsync( + name: nameof(PatientIntakeWorkflow), + instanceId: instanceId, + input: rec); + + var state = await workflowClient.WaitForWorkflowCompletionAsync(instanceId: instanceId); + + if (state is null) + Console.WriteLine(" [main] Workflow not found!"); + else if (state.RuntimeStatus == WorkflowRuntimeStatus.Completed) + Console.WriteLine($" [main] Result: {state.ReadOutputAs()}"); + else + Console.WriteLine($" [main] Workflow ended with status: {state.RuntimeStatus}"); + + await workflowClient.PurgeInstanceAsync(instanceId); +} + +// Renders a "= TITLE =" box sized to the title, matching the Go reference. +static string Banner(string msg) +{ + var line = new string('=', msg.Length + 4); + return $"{line}\n= {msg} =\n{line}"; +} diff --git a/workflows/csharp/sdk-context-propagation/order-processor/Workflows.cs b/workflows/csharp/sdk-context-propagation/order-processor/Workflows.cs new file mode 100644 index 000000000..02156f5e1 --- /dev/null +++ b/workflows/csharp/sdk-context-propagation/order-processor/Workflows.cs @@ -0,0 +1,347 @@ +// ------------------------------------------------------------------------ +// Copyright 2026 The Dapr Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ------------------------------------------------------------------------ + +namespace OrderProcessor; + +using Dapr.Workflow; + +// --------------------------------------------------------------------------- +// PatientIntake (root workflow) +// --------------------------------------------------------------------------- + +/// +/// Root workflow — verifies the patient's insurance then delegates the +/// prescription to a child workflow with full +/// propagation so the grandchild +/// ComplianceAudit can inspect the complete ancestor chain. +/// +public sealed class PatientIntakeWorkflow : Workflow +{ + public override async Task RunAsync(WorkflowContext ctx, PatientRecord rec) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [PatientIntake] Starting intake for patient {rec.PatientId}"); + + // Step 1: Verify insurance — no propagation (plain activity). + if (!ctx.IsReplaying) + Console.WriteLine(" [PatientIntake] Step 1: VerifyInsurance (no propagation)"); + var insured = await ctx.CallActivityAsync( + nameof(VerifyInsuranceActivity), + rec); + if (!insured) + return "intake declined: insurance not on file"; + if (!ctx.IsReplaying) + Console.WriteLine(" [PatientIntake] Step 1 complete: insurance verified"); + + // Step 2: Delegate to PrescribeMedication with Lineage propagation. + // PrescribeMedication inherits this workflow's full history so its own + // grandchild ComplianceAudit can verify the complete ancestor chain. + if (!ctx.IsReplaying) + Console.WriteLine(" [PatientIntake] Step 2: PrescribeMedication child wf (HistoryPropagationScope.Lineage)"); + var result = await ctx.CallChildWorkflowAsync( + nameof(PrescribeMedicationWorkflow), + rec, + new ChildWorkflowTaskOptions(PropagationScope: HistoryPropagationScope.Lineage)); + + if (!ctx.IsReplaying) + Console.WriteLine($" [PatientIntake] COMPLETE: {result}"); + return result; + } +} + +// --------------------------------------------------------------------------- +// PrescribeMedication (child workflow, level 2) +// --------------------------------------------------------------------------- + +/// +/// Child workflow — orchestrates allergy + interaction screening, compliance +/// audit, and dispensing. Receives +/// from PatientIntake, so it holds the full ancestor chain when calling its +/// own children. Calls ComplianceAudit with Lineage (audit needs to see the +/// grandparent) and DispenseMedicationWorkflow with OwnHistory (pharmacy only +/// sees the prescribing step, not the intake). +/// +public sealed class PrescribeMedicationWorkflow : Workflow +{ + public override async Task RunAsync(WorkflowContext ctx, PatientRecord rec) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [PrescribeMedication] Starting prescription: {rec.Medication} {rec.Dosage:F0}mg for {rec.Condition}"); + + // Step 1: Allergy check (no propagation). + if (!ctx.IsReplaying) + Console.WriteLine(" [PrescribeMedication] Step 1: CheckAllergies (no propagation)"); + var allergyClear = await ctx.CallActivityAsync( + nameof(CheckAllergiesActivity), + rec); + if (!allergyClear) + return "prescription declined: known allergy"; + if (!ctx.IsReplaying) + Console.WriteLine(" [PrescribeMedication] Step 1 complete: allergy clear"); + + // Step 2: Drug interaction screen (no propagation). + if (!ctx.IsReplaying) + Console.WriteLine(" [PrescribeMedication] Step 2: ScreenDrugInteractions (no propagation)"); + var interactionsClear = await ctx.CallActivityAsync( + nameof(ScreenDrugInteractionsActivity), + rec); + if (!interactionsClear) + return "prescription declined: drug interaction risk"; + if (!ctx.IsReplaying) + Console.WriteLine(" [PrescribeMedication] Step 2 complete: no interactions"); + + // Step 3: Compliance audit grandchild workflow with Lineage propagation. + // ComplianceAudit will see both PatientIntake AND PrescribeMedication events. + if (!ctx.IsReplaying) + Console.WriteLine(" [PrescribeMedication] Step 3: ComplianceAudit child wf (HistoryPropagationScope.Lineage)"); + var audit = await ctx.CallChildWorkflowAsync( + nameof(ComplianceAuditWorkflow), + rec, + new ChildWorkflowTaskOptions(PropagationScope: HistoryPropagationScope.Lineage)); + if (!audit.Compliant) + return $"prescription blocked: compliance audit failed (risk={audit.RiskScore:F2}, reason={audit.Reason})"; + if (!ctx.IsReplaying) + Console.WriteLine($" [PrescribeMedication] Step 3 complete: compliance audit passed (risk={audit.RiskScore:F2})"); + + // Step 4: Dispense the medication via a child workflow. + // In the happy path we attach OwnHistory propagation — the pharmacy + // receives PrescribeMedication's own events only (no ancestral chain) + // and can verify that the allergy and interaction screens ran. In the + // negative scenario (rec.ForwardLineage == false) we deliberately omit + // propagation, so the pharmacy receives no lineage and refuses. + // + // Note: the .NET SDK propagation support is on ChildWorkflowTaskOptions + // only. For a trust-boundary demo equivalent to PropagateOwnHistory() on + // the activity call in Python/Go, the dispense step is implemented as a + // child workflow (not a bare activity). + if (!ctx.IsReplaying) + { + Console.WriteLine(" [PrescribeMedication] Step 4: DispenseMedicationWorkflow child wf"); + Console.WriteLine(rec.ForwardLineage + ? " -> HistoryPropagationScope.OwnHistory" + : " -> NO history propagation (negative scenario)"); + } + var dispense = await (rec.ForwardLineage + ? ctx.CallChildWorkflowAsync( + nameof(DispenseMedicationWorkflow), + rec, + new ChildWorkflowTaskOptions(PropagationScope: HistoryPropagationScope.OwnHistory)) + : ctx.CallChildWorkflowAsync( + nameof(DispenseMedicationWorkflow), + rec)); + + if (dispense.Status != "dispensed") + { + if (!ctx.IsReplaying) + Console.WriteLine($" [PrescribeMedication] Step 4 BLOCKED: pharmacy refused to dispense ({dispense.Reason})"); + return $"prescription not dispensed: pharmacy refused ({dispense.Reason})"; + } + if (!ctx.IsReplaying) + Console.WriteLine($" [PrescribeMedication] Step 4 complete: dispensed (id={dispense.DispenseId}, {dispense.EventCount} events verified)"); + + var summary = $"dispensed: id={dispense.DispenseId}, patient={rec.PatientId}, drug={rec.Medication} {rec.Dosage:F0}mg"; + if (!ctx.IsReplaying) + Console.WriteLine($" [PrescribeMedication] COMPLETE: {summary}"); + return summary; + } +} + +// --------------------------------------------------------------------------- +// ComplianceAudit (grandchild workflow, level 3) +// --------------------------------------------------------------------------- + +/// +/// Grandchild workflow that inspects the full ancestor chain to make a +/// trust-aware compliance decision. Receives +/// from PrescribeMedication, so +/// returns entries for both PatientIntake and PrescribeMedication. Refuses to +/// approve dispensing unless the required upstream steps (insurance, allergies, +/// drug interactions) are all present and completed in the propagated history. +/// +public sealed class ComplianceAuditWorkflow : Workflow +{ + public override Task RunAsync(WorkflowContext ctx, PatientRecord rec) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [ComplianceAudit] Auditing prescription for patient {rec.PatientId}"); + + var history = ctx.GetPropagatedHistory(); + if (history is null) + { + if (!ctx.IsReplaying) + { + Console.WriteLine(" [ComplianceAudit] WARNING: no propagated history — sidecar may not support 1.18+"); + Console.WriteLine(" [ComplianceAudit] BLOCKED — cannot verify upstream pipeline without history"); + } + return Task.FromResult(new ComplianceResult( + Compliant: false, + RiskScore: 1.0, + Reason: "no execution history provided — cannot verify caller pipeline", + EventCount: 0)); + } + + if (!ctx.IsReplaying) + { + Console.WriteLine($" [ComplianceAudit] Received propagated history with {history.Entries.Count} segment(s):"); + foreach (var entry in history.Entries) + Console.WriteLine($" [ComplianceAudit] workflow: name={entry.WorkflowName} app={entry.AppId} events={entry.Events.Count}"); + } + + // Verify PatientIntake is present in the ancestor chain. + var intakeEntries = history.FilterByWorkflowName(nameof(PatientIntakeWorkflow)); + if (intakeEntries.Entries.Count == 0) + { + return Task.FromResult(new ComplianceResult( + Compliant: false, + RiskScore: 0.9, + Reason: $"{nameof(PatientIntakeWorkflow)} missing from propagated history", + EventCount: history.Entries.Count)); + } + + // Verify PrescribeMedication is present in the ancestor chain. + var prescribeEntries = history.FilterByWorkflowName(nameof(PrescribeMedicationWorkflow)); + if (prescribeEntries.Entries.Count == 0) + { + return Task.FromResult(new ComplianceResult( + Compliant: false, + RiskScore: 0.9, + Reason: $"{nameof(PrescribeMedicationWorkflow)} missing from propagated history", + EventCount: history.Entries.Count)); + } + + // Verify the required activity completions are recorded in history events. + var intakeEntry = intakeEntries.Entries[0]; + var prescribeEntry = prescribeEntries.Entries[0]; + + int intakeCompletedCount = intakeEntry.Events.Count(e => e.Kind == HistoryEventKind.TaskCompleted); + int prescribeCompletedCount = prescribeEntry.Events.Count(e => e.Kind == HistoryEventKind.TaskCompleted); + + if (!ctx.IsReplaying) + { + Console.WriteLine(" [ComplianceAudit] Verification:"); + Console.WriteLine($" PatientIntake TaskCompleted events: {intakeCompletedCount} (expect >= 1: VerifyInsurance)"); + Console.WriteLine($" PrescribeMedication TaskCompleted events: {prescribeCompletedCount} (expect >= 2: CheckAllergies, ScreenDrugInteractions)"); + } + + if (intakeCompletedCount == 0 || prescribeCompletedCount < 2) + { + if (!ctx.IsReplaying) + Console.WriteLine(" [ComplianceAudit] BLOCKED — required upstream checks not completed"); + return Task.FromResult(new ComplianceResult( + Compliant: false, + RiskScore: 0.9, + Reason: "required upstream checks not completed in propagated history", + EventCount: history.Entries.Count)); + } + + int totalEventCount = history.Entries.Sum(e => e.Events.Count); + double riskScore = rec.Dosage > 1000 ? 0.3 : 0.1; + if (!ctx.IsReplaying) + Console.WriteLine($" [ComplianceAudit] APPROVED (risk={riskScore:F2}, total events inspected={totalEventCount})"); + + return Task.FromResult(new ComplianceResult( + Compliant: true, + RiskScore: riskScore, + Reason: "all upstream checks verified in propagated history", + EventCount: totalEventCount)); + } +} + +// --------------------------------------------------------------------------- +// DispenseMedicationWorkflow (grandchild workflow, level 3) +// --------------------------------------------------------------------------- + +/// +/// Dispense workflow — the pharmacy. In the happy path it receives +/// from PrescribeMedication, so +/// it can only see PrescribeMedication's own events (the PatientIntake ancestor +/// history is intentionally excluded — the pharmacy doesn't need, or get to see, +/// the upstream patient-intake chain). It refuses to dispense unless the +/// propagated history proves the prescriber ran the required allergy and +/// drug-interaction screens. In the negative scenario PrescribeMedication omits +/// propagation entirely, so this workflow sees no history and refuses. +/// +/// +/// In the Python sibling and the Go reference the pharmacy is a bare activity +/// because those SDKs support a propagation argument on activity calls. The +/// .NET SDK's is currently scoped to child +/// workflows only (), so the dispense step +/// is a child workflow here to demonstrate the identical OwnHistory boundary. +/// +public sealed class DispenseMedicationWorkflow : Workflow +{ + public override async Task RunAsync(WorkflowContext ctx, PatientRecord rec) + { + var history = ctx.GetPropagatedHistory(); + + if (!ctx.IsReplaying) + Console.WriteLine($" [DispenseMedication] Dispense request: {rec.Medication} {rec.Dosage:F0}mg for {rec.PatientId} (propagated history: {DescribeHistory(history)})"); + + // Pharmacy policy: no lineage, no dispense. Without propagated history the + // pharmacy cannot prove the prescription was screened, so it refuses. + if (history is null) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [DispenseMedication] REFUSED — no propagated history; cannot verify screening for {rec.PatientId}"); + return new DispenseResult( + DispenseId: "", + Status: "refused", + EventCount: 0, + Reason: "missing lineage: no propagated history received from prescriber"); + } + + int eventCount = history.Entries.Sum(e => e.Events.Count); + + if (!ctx.IsReplaying) + { + // With OwnHistory only PrescribeMedication appears here — not PatientIntake. + foreach (var entry in history.Entries) + Console.WriteLine($" [DispenseMedication] workflow: name={entry.WorkflowName} app={entry.AppId} events={entry.Events.Count}"); + } + + // Verify the prescriber's own history is present and shows both screens + // completed (CheckAllergies + ScreenDrugInteractions == 2 TaskCompleted). + var prescribeEntries = history.FilterByWorkflowName(nameof(PrescribeMedicationWorkflow)); + if (prescribeEntries.Entries.Count == 0) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [DispenseMedication] REFUSED — propagated history is missing the PrescribeMedication lineage for {rec.PatientId}"); + return new DispenseResult( + DispenseId: "", + Status: "refused", + EventCount: eventCount, + Reason: "missing lineage: PrescribeMedication not present in propagated history"); + } + + int screensCompleted = prescribeEntries.Entries[0].Events.Count(e => e.Kind == HistoryEventKind.TaskCompleted); + if (screensCompleted < 2) + { + if (!ctx.IsReplaying) + Console.WriteLine($" [DispenseMedication] REFUSED — required screening not verified in propagated history for {rec.PatientId}"); + return new DispenseResult( + DispenseId: "", + Status: "refused", + EventCount: eventCount, + Reason: "missing lineage: allergy/interaction screening not verified in propagated history"); + } + + var result = await ctx.CallActivityAsync( + nameof(DispenseMedicationActivity), + rec); + + return result with { EventCount = eventCount }; + } + + private static string DescribeHistory(PropagatedHistory? history) => + history is null ? "none" : $"{history.Entries.Sum(e => e.Events.Count)} events"; +}