-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeonClient.cs
More file actions
196 lines (173 loc) · 6.05 KB
/
KeonClient.cs
File metadata and controls
196 lines (173 loc) · 6.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
using Keon.Contracts;
using Keon.Contracts.Decision;
using Keon.Contracts.Execution;
using Keon.Contracts.Results;
using Keon.Runtime.Sdk;
using Keon.Sdk.Helpers;
namespace Keon.Sdk;
/// <summary>
/// Safe-by-default client for interacting with Keon Runtime.
/// Automatically handles retries, receipt tracking, and validation.
/// This is the recommended entry point for all SDK usage.
/// </summary>
public sealed class KeonClient : IDisposable
{
private readonly IRuntimeGateway _gateway;
private readonly RetryPolicy _retryPolicy;
private readonly List<DecisionReceipt> _receiptHistory;
private readonly SemaphoreSlim _lock;
private bool _disposed;
/// <summary>
/// Create a new KeonClient with safe defaults.
/// </summary>
/// <param name="gateway">The runtime gateway to use</param>
/// <param name="retryPolicy">Optional retry policy (uses safe default if not provided)</param>
public KeonClient(IRuntimeGateway gateway, RetryPolicy? retryPolicy = null)
{
_gateway = gateway ?? throw new ArgumentNullException(nameof(gateway));
_retryPolicy = retryPolicy ?? RetryPolicy.Default();
_receiptHistory = new List<DecisionReceipt>();
_lock = new SemaphoreSlim(1, 1);
}
/// <summary>
/// All decision receipts processed by this client (read-only).
/// Receipts are automatically tracked for audit purposes.
/// </summary>
public IReadOnlyList<DecisionReceipt> ReceiptHistory
{
get
{
ThrowIfDisposed();
lock (_receiptHistory)
{
return _receiptHistory.AsReadOnly();
}
}
}
/// <summary>
/// Request a decision from the runtime.
/// Automatically retries on transient failures and tracks the receipt.
/// </summary>
public async Task<KeonResult<DecisionReceipt>> DecideAsync(
DecisionRequest request,
CancellationToken ct = default)
{
ThrowIfDisposed();
ValidateDecisionRequest(request);
var result = await _retryPolicy.ExecuteAsync(
ct => _gateway.DecideAsync(request, ct),
ct).ConfigureAwait(false);
// Track successful receipts
if (result.Success && result.Value is not null)
{
await TrackReceiptAsync(result.Value, ct).ConfigureAwait(false);
}
return result;
}
/// <summary>
/// Execute an approved decision.
/// Automatically retries on transient failures.
/// </summary>
public async Task<KeonResult<ExecutionResult>> ExecuteAsync(
ExecutionRequest request,
CancellationToken ct = default)
{
ThrowIfDisposed();
ValidateExecutionRequest(request);
return await _retryPolicy.ExecuteAsync(
ct => _gateway.ExecuteAsync(request, ct),
ct).ConfigureAwait(false);
}
/// <summary>
/// Decide and execute in a single operation (convenience method).
/// Only executes if the decision is approved.
/// </summary>
public async Task<KeonResult<ExecutionResult>> DecideAndExecuteAsync(
DecisionRequest decisionRequest,
Func<DecisionReceipt, ExecutionRequest> buildExecutionRequest,
CancellationToken ct = default)
{
ThrowIfDisposed();
var decisionResult = await DecideAsync(decisionRequest, ct).ConfigureAwait(false);
if (!decisionResult.Success || decisionResult.Value is null)
{
return KeonResult<ExecutionResult>.Fail(
decisionResult.ErrorCode ?? "DECISION_FAILED",
decisionResult.ErrorMessage ?? "Decision failed");
}
var receipt = decisionResult.Value;
// Only execute if approved
if (receipt.Outcome != DecisionOutcome.Approved)
{
return KeonResult<ExecutionResult>.Fail(
"NOT_APPROVED",
$"Decision outcome was {receipt.Outcome}, not Approved");
}
var executionRequest = buildExecutionRequest(receipt);
return await ExecuteAsync(executionRequest, ct).ConfigureAwait(false);
}
/// <summary>
/// Get all receipts for a specific capability.
/// </summary>
public IReadOnlyList<DecisionReceipt> GetReceiptsForCapability(string capability)
{
ThrowIfDisposed();
lock (_receiptHistory)
{
return _receiptHistory
.Where(r => r.Capability == capability)
.ToList()
.AsReadOnly();
}
}
/// <summary>
/// Clear receipt history (use with caution - for testing only).
/// </summary>
public void ClearReceiptHistory()
{
ThrowIfDisposed();
lock (_receiptHistory)
{
_receiptHistory.Clear();
}
}
private async Task TrackReceiptAsync(DecisionReceipt receipt, CancellationToken ct)
{
await _lock.WaitAsync(ct).ConfigureAwait(false);
try
{
_receiptHistory.Add(receipt);
}
finally
{
_lock.Release();
}
}
private static void ValidateDecisionRequest(DecisionRequest request)
{
if (request is null)
throw new ArgumentNullException(nameof(request));
if (string.IsNullOrWhiteSpace(request.Capability))
throw new ArgumentException("Capability cannot be null or empty", nameof(request));
if (request.RequestId.Value == null)
throw new ArgumentException("RequestId cannot be null", nameof(request));
}
private static void ValidateExecutionRequest(ExecutionRequest request)
{
if (request is null)
throw new ArgumentNullException(nameof(request));
if (request.DecisionReceiptId.Value == null)
throw new ArgumentException("DecisionReceiptId cannot be null", nameof(request));
}
private void ThrowIfDisposed()
{
if (_disposed)
throw new ObjectDisposedException(nameof(KeonClient));
}
public void Dispose()
{
if (_disposed) return;
_lock.Dispose();
_disposed = true;
}
}