Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -473,13 +473,13 @@ var cachedRemoteProxy = Proxy<int, string>.Create(id => remoteProxy.Execute(id))
---

## Patterns Table
PatternKit currently tracks 119 production-readiness patterns. Each catalog pattern is represented in tests, documentation, real-world examples, IoC integration, and the BenchmarkDotNet coverage matrix.
PatternKit currently tracks 120 production-readiness patterns. Each catalog pattern is represented in tests, documentation, real-world examples, IoC integration, and the BenchmarkDotNet coverage matrix.

| Category | Count | Patterns |
| --- | ---: | --- |
| Application Architecture | 28 | Activity Tracker, Aggregate Root, Anti-Corruption Layer, Audit Log, Bounded Context, Context Map, CQRS, Data Mapper, Domain Event, Domain Service, Event Sourcing, Eventual Consistency Monitor, Feature Toggle, Identity Map, Lazy Load, Manual Task Gate, Materialized View, Ports and Adapters, Repository, Service Layer, Snapshot / Checkpoint Management, Specification, Table Data Gateway, Timeout Manager, Transaction Script, Unit of Work, Value Object, Workflow Orchestration |
| Behavioral | 12 | Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Null Object, Observer, State, Strategy, Template Method, Visitor |
| Cloud Architecture | 20 | Ambassador, Backends for Frontends, Bulkhead, Cache-Aside, Cache Stampede Protection, Circuit Breaker, External Configuration Store, Gateway Aggregation, Gateway Routing, Health Endpoint Monitoring, Leader Election, Priority Queue, Queue-Based Load Leveling, Rate Limiting, Read-Through Cache, Retry, Scheduler Agent Supervisor, Sidecar, Strangler Fig, Write-Through Cache |
| Cloud Architecture | 21 | Ambassador, Backends for Frontends, Bulkhead, Cache-Aside, Cache Stampede Protection, Circuit Breaker, Distributed Lock / Lease, External Configuration Store, Gateway Aggregation, Gateway Routing, Health Endpoint Monitoring, Leader Election, Priority Queue, Queue-Based Load Leveling, Rate Limiting, Read-Through Cache, Retry, Scheduler Agent Supervisor, Sidecar, Strangler Fig, Write-Through Cache |
| Creational | 6 | Abstract Factory, Builder, Factory Method, Object Pool, Prototype, Singleton |
| Enterprise Integration | 42 | Aggregator, Canonical Data Model, Change Data Capture, Channel Adapter, Channel Purger, Claim Check, Competing Consumers, Content Enricher, Content-Based Router, Control Bus, Correlation Identifier, Dead Letter Channel, Durable Subscriber, Dynamic Router, Event Notification, Event-Carried State Transfer, Event-Driven Consumer, Guaranteed Delivery, Invalid Message Channel, Mailbox, Message Bus, Message Channel, Message Envelope, Message Expiration, Message Filter, Message History, Message Store, Message Translator, Messaging Bridge, Messaging Gateway, Pipes and Filters, Polling Consumer, Publish-Subscribe, Recipient List, Request-Reply, Resequencer, Routing Slip, Saga / Process Manager, Scatter-Gather, Service Activator, Splitter, Wire Tap |
| Messaging Reliability | 4 | Backpressure, Idempotent Receiver, Inbox, Outbox |
Expand Down Expand Up @@ -623,6 +623,8 @@ BenchmarkDotNet guidance is documented in [docs/guides/benchmarks.md](docs/guide
| Identity Map | Execution | 108.91 ns | 968 B | 94.83 ns | 968 B | Same allocation; generated was faster for scoped identity-map reuse. |
| Leader Election | Construction | 14.28 ns | 104 B | 15.91 ns | 104 B | Same allocation; fluent was slightly faster in this microbenchmark. |
| Leader Election | Execution | 43.62 ns | 360 B | 144.37 ns | 312 B | Generated allocated about 13% less memory, while fluent was faster in this path. |
| Distributed Lock / Lease | Construction | Pending | Pending | Pending | Pending | Covered by the BenchmarkDotNet matrix; publish measured values after the next benchmark refresh. |
| Distributed Lock / Lease | Execution | Pending | Pending | Pending | Pending | Covered by the BenchmarkDotNet matrix; publish measured values after the next benchmark refresh. |
| Materialized View | Construction | 140.9 ns | 1.05 KB | 147.4 ns | 1.05 KB | Same allocation; fluent was slightly faster in this microbenchmark. |
| Materialized View | Execution | 389.5 ns | 2.02 KB | 386.0 ns | 2.02 KB | Effectively equivalent for this scenario. |
| Mailbox | Construction | 17.030 ns | 216 B | 29.867 ns | 360 B | Fluent was faster and allocated less for disposable mailbox construction. |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using BenchmarkDotNet.Attributes;
using PatternKit.Cloud.DistributedLocks;
using PatternKit.Examples.DistributedLockDemo;

namespace PatternKit.Benchmarks.Cloud;

[BenchmarkCategory("Cloud", "DistributedLockLease")]
public class DistributedLockBenchmarks
{
private static readonly OrderAllocationRequest Request = new("ORDER-100", "allocator-a", 4);

[Benchmark(Baseline = true, Description = "Fluent: create distributed lock")]
[BenchmarkCategory("Fluent", "Construction")]
public DistributedLock<string> Fluent_CreateDistributedLock()
=> OrderAllocationDistributedLocks.CreateFluent();

[Benchmark(Description = "Generated: create distributed lock")]
[BenchmarkCategory("Generated", "Construction")]
public DistributedLock<string> Generated_CreateDistributedLock()
=> GeneratedOrderAllocationDistributedLock.Create();

[Benchmark(Description = "Fluent: allocate order under lease")]
[BenchmarkCategory("Fluent", "Execution")]
public OrderAllocationSummary Fluent_AllocateOrder()
{
var workflow = new OrderAllocationLockWorkflow(OrderAllocationDistributedLocks.CreateFluent());
return workflow.Allocate(Request);
}

[Benchmark(Description = "Generated: allocate order under lease")]
[BenchmarkCategory("Generated", "Execution")]
public OrderAllocationSummary Generated_AllocateOrder()
{
var workflow = new OrderAllocationLockWorkflow(GeneratedOrderAllocationDistributedLock.Create());
return workflow.Allocate(Request);
}
}
1 change: 1 addition & 0 deletions docs/examples/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ dotnet test PatternKit.slnx -c Release
* **Commerce Backends for Frontends:** `CommerceBackendsForFrontendsDemo` (+ `CommerceBackendsForFrontendsDemoTests`) — fluent and generated client-specific facade shaping with DI and ASP.NET Core mapping.
* **Inventory Ambassador:** `InventoryAmbassadorDemo` (+ `InventoryAmbassadorDemoTests`) — fluent and generated outbound connectivity wrapper with DI and ASP.NET Core mapping.
* **Warehouse Leader Election:** `WarehouseLeaderElectionDemo` (+ `WarehouseLeaderElectionDemoTests`) — fluent and generated active worker lease coordination with DI and Generic Host mapping.
* **Order Allocation Distributed Lock:** `OrderAllocationDistributedLockDemo` (+ `OrderAllocationDistributedLockDemoTests`) — fluent and generated resource lease coordination with DI and Generic Host mapping.
* **Warehouse Scheduler Agent Supervisor:** `WarehouseSchedulerAgentSupervisorDemo` (+ `WarehouseSchedulerAgentSupervisorDemoTests`) — fluent and generated scheduled worker supervision with DI and Generic Host mapping.
* **Production-Ready Example Catalog:** `PatternKitExampleCatalog` (+ `PatternKitExampleCatalogTests`) — DI registration, generic host validation, ASP.NET Core endpoint mapping, and source/test/docs manifest checks.
* **Tests:** `PatternKit.Examples.Tests/*` use TinyBDD scenarios that read like specs.
Expand Down
12 changes: 12 additions & 0 deletions docs/examples/order-allocation-distributed-lock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Order Allocation Distributed Lock

The order allocation example protects inventory allocation with a resource lease so competing workers cannot mutate the same order concurrently.

```csharp
services.AddOrderAllocationDistributedLockDemo();

var runner = provider.GetRequiredService<OrderAllocationDistributedLockDemoRunner>();
var summary = runner.RunGenerated();
```

The example includes fluent and source-generated construction, a container-owned workflow, and an `IServiceCollection` extension that can be imported into a standard .NET host.
3 changes: 3 additions & 0 deletions docs/examples/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,9 @@
- name: Warehouse Leader Election
href: warehouse-leader-election.md

- name: Order Allocation Distributed Lock
href: order-allocation-distributed-lock.md

- name: Warehouse Scheduler Agent Supervisor
href: warehouse-scheduler-agent-supervisor.md

Expand Down
15 changes: 15 additions & 0 deletions docs/generators/distributed-lock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Distributed Lock Generator

`[GenerateDistributedLock]` creates a typed `DistributedLock<TKey>` factory with configured lock name and lease duration.

```csharp
[GenerateDistributedLock(typeof(string), LockName = "order-allocation-lock", LeaseDurationMilliseconds = 30000)]
public static partial class OrderAllocationLocks;

var mutex = OrderAllocationLocks.Create();
```

Diagnostics:

- `PKDLOCK001`: host type must be partial.
- `PKDLOCK002`: factory name, lock name, and lease duration must be valid.
1 change: 1 addition & 0 deletions docs/generators/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ PatternKit includes a Roslyn incremental generator package (`PatternKit.Generato
| [**Backends for Frontends**](backends-for-frontends.md) | Client-specific facade factories | `[GenerateBackendsForFrontends]` |
| [**Ambassador**](ambassador.md) | Outbound connectivity wrapper factories | `[GenerateAmbassador]` |
| [**Leader Election**](leader-election.md) | Lease-backed active worker factories | `[GenerateLeaderElection]` |
| [**Distributed Lock**](distributed-lock.md) | Resource lease lock factories | `[GenerateDistributedLock]` |
| [**Scheduler Agent Supervisor**](scheduler-agent-supervisor.md) | Scheduled worker supervision factories | `[GenerateSchedulerAgentSupervisor]` |

## Quick Reference
Expand Down
3 changes: 3 additions & 0 deletions docs/generators/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,9 @@
- name: Leader Election
href: leader-election.md

- name: Distributed Lock
href: distributed-lock.md

- name: Scheduler Agent Supervisor
href: scheduler-agent-supervisor.md

Expand Down
18 changes: 11 additions & 7 deletions docs/guides/benchmark-results.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ The latest measured timings below were captured on Windows 11, Intel Core i9-149
| Identity Map | Execution | 108.91 ns | 968 B | 94.83 ns | 968 B | Same allocation; generated was faster for scoped identity-map reuse. |
| Leader Election | Construction | 14.28 ns | 104 B | 15.91 ns | 104 B | Same allocation; fluent was slightly faster in this microbenchmark. |
| Leader Election | Execution | 43.62 ns | 360 B | 144.37 ns | 312 B | Generated allocated about 13% less memory, while fluent was faster in this path. |
| Distributed Lock / Lease | Construction | Pending | Pending | Pending | Pending | Covered by the BenchmarkDotNet matrix; publish measured values after the next benchmark refresh. |
| Distributed Lock / Lease | Execution | Pending | Pending | Pending | Pending | Covered by the BenchmarkDotNet matrix; publish measured values after the next benchmark refresh. |
| Materialized View | Construction | 140.9 ns | 1.05 KB | 147.4 ns | 1.05 KB | Same allocation; fluent was slightly faster in this microbenchmark. |
| Materialized View | Execution | 389.5 ns | 2.02 KB | 386.0 ns | 2.02 KB | Effectively equivalent for this scenario. |
| Mailbox | Construction | 17.030 ns | 216 B | 29.867 ns | 360 B | Fluent was faster and allocated less for disposable mailbox construction. |
Expand Down Expand Up @@ -260,19 +262,19 @@ The latest measured timings below were captured on Windows 11, Intel Core i9-149

## Coverage Matrix Summary

The coverage matrix currently publishes 119 catalog patterns and 476 pattern route results. Each pattern has four BenchmarkDotNet routes: fluent construction, fluent execution, source-generated construction, and source-generated execution. The reusable hosting integration matrix publishes 12 reusable hosting integration route results for package-level `IServiceCollection` registrations.
The coverage matrix currently publishes 120 catalog patterns and 480 pattern route results. Each pattern has four BenchmarkDotNet routes: fluent construction, fluent execution, source-generated construction, and source-generated execution. The reusable hosting integration matrix publishes 12 reusable hosting integration route results for package-level `IServiceCollection` registrations.

| Category | Patterns | Published route results |
| --- | ---: | ---: |
| Application Architecture | 28 | 112 |
| Behavioral | 12 | 48 |
| Cloud Architecture | 20 | 80 |
| Cloud Architecture | 21 | 84 |
| Creational | 6 | 24 |
| Enterprise Integration | 42 | 168 |
| Messaging Reliability | 4 | 16 |
| Structural | 7 | 28 |

The generator matrix currently publishes 114 generator source route results.
The generator matrix currently publishes 115 generator source route results.

## Hosting Integration Matrix Results

Expand Down Expand Up @@ -340,8 +342,9 @@ The generator matrix currently publishes 114 generator source route results.
| Cloud Architecture | Bulkhead | Covered | Covered | Covered | Covered |
| Cloud Architecture | Cache Stampede Protection | Covered | Covered | Covered | Covered |
| Cloud Architecture | Cache-Aside | Covered | Covered | Covered | Covered |
| Cloud Architecture | Circuit Breaker | Covered | Covered | Covered | Covered |
| Cloud Architecture | External Configuration Store | Covered | Covered | Covered | Covered |
| Cloud Architecture | Circuit Breaker | Covered | Covered | Covered | Covered |
| Cloud Architecture | Distributed Lock / Lease | Covered | Covered | Covered | Covered |
| Cloud Architecture | External Configuration Store | Covered | Covered | Covered | Covered |
| Cloud Architecture | Gateway Aggregation | Covered | Covered | Covered | Covered |
| Cloud Architecture | Gateway Routing | Covered | Covered | Covered | Covered |
| Cloud Architecture | Health Endpoint Monitoring | Covered | Covered | Covered | Covered |
Expand Down Expand Up @@ -465,8 +468,9 @@ The generator matrix currently publishes 114 generator source route results.
| IdentityMapGenerator | `src/PatternKit.Generators/IdentityMap/IdentityMapGenerator.cs` | Covered |
| LazyLoadGenerator | `src/PatternKit.Generators/LazyLoading/LazyLoadGenerator.cs` | Covered |
| InterpreterGenerator | `src/PatternKit.Generators/Interpreter/InterpreterGenerator.cs` | Covered |
| IteratorGenerator | `src/PatternKit.Generators/Iterator/IteratorGenerator.cs` | Covered |
| LeaderElectionGenerator | `src/PatternKit.Generators/LeaderElection/LeaderElectionGenerator.cs` | Covered |
| IteratorGenerator | `src/PatternKit.Generators/Iterator/IteratorGenerator.cs` | Covered |
| LeaderElectionGenerator | `src/PatternKit.Generators/LeaderElection/LeaderElectionGenerator.cs` | Covered |
| DistributedLockGenerator | `src/PatternKit.Generators/DistributedLocks/DistributedLockGenerator.cs` | Covered |
| MaterializedViewGenerator | `src/PatternKit.Generators/MaterializedViews/MaterializedViewGenerator.cs` | Covered |
| MementoGenerator | `src/PatternKit.Generators/MementoGenerator.cs` | Covered |
| NullObjectGenerator | `src/PatternKit.Generators/NullObject/NullObjectGenerator.cs` | Covered |
Expand Down
4 changes: 2 additions & 2 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,13 @@ if (parser.Execute("123", out var value))

## 📚 Available Patterns

PatternKit covers 119 production-readiness patterns with fluent APIs, source-generated routes where applicable, IoC integration examples, TinyBDD coverage, and BenchmarkDotNet coverage-matrix validation:
PatternKit covers 120 production-readiness patterns with fluent APIs, source-generated routes where applicable, IoC integration examples, TinyBDD coverage, and BenchmarkDotNet coverage-matrix validation:

| Category | Count | Patterns |
| --- | ---: | --- |
| Application Architecture | 28 | Activity Tracker, Aggregate Root, Anti-Corruption Layer, Audit Log, Bounded Context, Context Map, CQRS, Data Mapper, Domain Event, Domain Service, Event Sourcing, Eventual Consistency Monitor, Feature Toggle, Identity Map, Lazy Load, Manual Task Gate, Materialized View, Ports and Adapters, Repository, Service Layer, Snapshot / Checkpoint Management, Specification, Table Data Gateway, Timeout Manager, Transaction Script, Unit of Work, Value Object, Workflow Orchestration |
| Behavioral | 12 | Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Null Object, Observer, State, Strategy, Template Method, Visitor |
| Cloud Architecture | 20 | Ambassador, Backends for Frontends, Bulkhead, Cache-Aside, Cache Stampede Protection, Circuit Breaker, External Configuration Store, Gateway Aggregation, Gateway Routing, Health Endpoint Monitoring, Leader Election, Priority Queue, Queue-Based Load Leveling, Rate Limiting, Read-Through Cache, Retry, Scheduler Agent Supervisor, Sidecar, Strangler Fig, Write-Through Cache |
| Cloud Architecture | 21 | Ambassador, Backends for Frontends, Bulkhead, Cache-Aside, Cache Stampede Protection, Circuit Breaker, Distributed Lock / Lease, External Configuration Store, Gateway Aggregation, Gateway Routing, Health Endpoint Monitoring, Leader Election, Priority Queue, Queue-Based Load Leveling, Rate Limiting, Read-Through Cache, Retry, Scheduler Agent Supervisor, Sidecar, Strangler Fig, Write-Through Cache |
| Creational | 6 | Abstract Factory, Builder, Factory Method, Object Pool, Prototype, Singleton |
| Enterprise Integration | 42 | Aggregator, Canonical Data Model, Change Data Capture, Channel Adapter, Channel Purger, Claim Check, Competing Consumers, Content Enricher, Content-Based Router, Control Bus, Correlation Identifier, Dead Letter Channel, Durable Subscriber, Dynamic Router, Event Notification, Event-Carried State Transfer, Event-Driven Consumer, Guaranteed Delivery, Invalid Message Channel, Mailbox, Message Bus, Message Channel, Message Envelope, Message Expiration, Message Filter, Message History, Message Store, Message Translator, Messaging Bridge, Messaging Gateway, Pipes and Filters, Polling Consumer, Publish-Subscribe, Recipient List, Request-Reply, Resequencer, Routing Slip, Saga / Process Manager, Scatter-Gather, Service Activator, Splitter, Wire Tap |
| Messaging Reliability | 4 | Backpressure, Idempotent Receiver, Inbox, Outbox |
Expand Down
18 changes: 18 additions & 0 deletions docs/patterns/cloud/distributed-lock-lease.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Distributed Lock / Lease

Distributed Lock / Lease coordinates exclusive ownership of a resource through expiring tokens. Use it when one worker, request, or host should mutate a resource while contenders wait or retry.

```csharp
var mutex = DistributedLock<string>
.Create("order-allocation-lock")
.LeaseDuration(TimeSpan.FromSeconds(30))
.Build();

var acquired = mutex.TryAcquire("ORDER-100", "allocator-a");
var renewed = mutex.Renew(acquired.Lease!);
var released = mutex.Release(renewed.Lease!);
```

The fluent path exposes acquisition, contention, renewal, expiry, release, snapshots, and blocked state without requiring a container. The source-generated path uses `[GenerateDistributedLock]` to create a configured `DistributedLock<TKey>` factory for repeatable application composition.

Import the production-shaped example through `AddOrderAllocationDistributedLockDemo()` or the aggregate `AddPatternKitExamples()` registration.
2 changes: 2 additions & 0 deletions docs/patterns/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,8 @@
href: cloud/ambassador.md
- name: Leader Election
href: cloud/leader-election.md
- name: Distributed Lock / Lease
href: cloud/distributed-lock-lease.md
- name: Scheduler Agent Supervisor
href: cloud/scheduler-agent-supervisor.md
- name: Application Architecture
Expand Down
Loading
Loading