-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceCollectionExtensions.cs
More file actions
281 lines (245 loc) · 12.3 KB
/
Copy pathServiceCollectionExtensions.cs
File metadata and controls
281 lines (245 loc) · 12.3 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
using Azure.Core;
using Azure.Identity;
using CloudEngAgent.Application.Abstractions;
using CloudEngAgent.Application.Runs;
using CloudEngAgent.Infrastructure.Backends;
using CloudEngAgent.Infrastructure.Backends.Options;
using CloudEngAgent.Infrastructure.Mcp;
using CloudEngAgent.Infrastructure.Persistence;
using CloudEngAgent.Infrastructure.Personas;
using CloudEngAgent.Infrastructure.Runs;
using CloudEngAgent.Infrastructure.Secrets;
using CloudEngAgent.Infrastructure.Sse;
using CloudEngAgent.Infrastructure.Workflows;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace CloudEngAgent.Infrastructure;
/// <summary>
/// Composition root for the Infrastructure layer. Registers the in-memory
/// stubs that satisfy the Application abstractions for the API milestone.
/// Real EF Core / LLM / MCP implementations replace these registrations in
/// later plans without changing the API-layer code.
/// </summary>
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddInfrastructure(
this IServiceCollection services,
IConfiguration configuration,
IHostEnvironment? hostEnvironment = null)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configuration);
services.AddSingleton<IClock, SystemClock>();
var cs = configuration.GetConnectionString("Runs");
if (!string.IsNullOrEmpty(cs))
{
services.AddPooledDbContextFactory<RunsDbContext>(opts => opts.UseSqlServer(cs));
services.AddSingleton<IRunStore, EfCoreRunStore>();
services.AddHealthChecks().AddDbContextCheck<RunsDbContext>("runs-db");
}
else if (hostEnvironment is null || hostEnvironment.IsDevelopment())
{
services.AddHealthChecks();
services.AddSingleton<InMemoryRunStore>();
services.AddSingleton<IRunStore>(sp =>
{
sp.GetRequiredService<ILoggerFactory>()
.CreateLogger("CloudEngAgent.Infrastructure.InMemoryRunStore")
.LogWarning(
"ConnectionStrings:Runs is not configured; using InMemoryRunStore " +
"(Development only). Data will not be persisted.");
return sp.GetRequiredService<InMemoryRunStore>();
});
}
else
{
throw new InvalidOperationException(
"ConnectionStrings:Runs is required outside Development.");
}
services.AddSingleton<IRunEventBus, InMemoryRunEventBus>();
RegisterPersonaRepository(services, configuration, hostEnvironment);
services.AddSingleton<IWorkflowRegistry, InMemoryWorkflowRegistry>();
RegisterWorkflowEngine(services, configuration, hostEnvironment);
// ── Backend options ────────────────────────────────────────────────────
services.AddOptions<AzureOpenAiOptions>()
.Bind(configuration.GetSection(AzureOpenAiOptions.SectionName))
.ValidateOnStart();
services.AddSingleton<IValidateOptions<AzureOpenAiOptions>, AzureOpenAiOptionsValidator>();
services.AddOptions<AzureFoundryOptions>()
.Bind(configuration.GetSection(AzureFoundryOptions.SectionName))
.ValidateOnStart();
services.AddSingleton<IValidateOptions<AzureFoundryOptions>, AzureFoundryOptionsValidator>();
services.AddOptions<OpenAiOptions>()
.Bind(configuration.GetSection(OpenAiOptions.SectionName))
.ValidateOnStart();
services.AddSingleton<IValidateOptions<OpenAiOptions>, OpenAiOptionsValidator>();
services.AddOptions<GitHubModelsOptions>()
.Bind(configuration.GetSection(GitHubModelsOptions.SectionName))
.ValidateOnStart();
services.AddSingleton<IValidateOptions<GitHubModelsOptions>, GitHubModelsOptionsValidator>();
services.AddOptions<AnthropicOptions>()
.Bind(configuration.GetSection(AnthropicOptions.SectionName))
.ValidateOnStart();
services.AddSingleton<IValidateOptions<AnthropicOptions>, AnthropicOptionsValidator>();
services.AddOptions<OllamaOptions>()
.Bind(configuration.GetSection(OllamaOptions.SectionName))
.ValidateOnStart();
services.AddSingleton<IValidateOptions<OllamaOptions>, OllamaOptionsValidator>();
// ── Secrets ────────────────────────────────────────────────────────────
var kvUri = configuration["KeyVault:Uri"];
if (!string.IsNullOrEmpty(kvUri))
{
services.AddSingleton<ConfigurationBackendSecretResolver>();
services.AddSingleton<IBackendSecretResolver>(sp =>
new KeyVaultBackendSecretResolver(
new Uri(kvUri),
sp.GetRequiredService<TokenCredential>(),
sp.GetRequiredService<ConfigurationBackendSecretResolver>()));
}
else
{
services.AddSingleton<IBackendSecretResolver, ConfigurationBackendSecretResolver>();
}
// ── Azure credential ───────────────────────────────────────────────────
services.TryAddSingleton<TokenCredential>(_ => new DefaultAzureCredential());
// ── LLM chat client factory ────────────────────────────────────────────
services.AddSingleton<IChatClientFactory, ChatClientFactory>();
RegisterMcpToolRegistry(services, configuration);
// Data Protection is required by the SSE token service. Calling AddDataProtection
// is idempotent (TryAdd semantics inside) and gives us key rotation + ciphertext.
services.AddDataProtection();
var lifetimeSeconds = configuration.GetValue<int?>("Sse:TokenLifetimeSeconds") ?? 120;
services.TryAddSingleton<ISseTokenService>(sp =>
new DataProtectionSseTokenService(
sp.GetRequiredService<Microsoft.AspNetCore.DataProtection.IDataProtectionProvider>(),
sp.GetRequiredService<IClock>(),
TimeSpan.FromSeconds(Math.Clamp(lifetimeSeconds, 30, 600))));
services.AddScoped<StartWorkflowRunHandler>();
return services;
}
/// <summary>
/// Registers <see cref="InMemoryRunStore"/> as <see cref="IRunStore"/> explicitly.
/// Intended for use in tests or local tooling that does not need a real database.
/// </summary>
public static IServiceCollection AddInMemoryRunStore(this IServiceCollection services)
{
ArgumentNullException.ThrowIfNull(services);
services.AddSingleton<InMemoryRunStore>();
services.AddSingleton<IRunStore>(sp => sp.GetRequiredService<InMemoryRunStore>());
return services;
}
private static void RegisterWorkflowEngine(
IServiceCollection services,
IConfiguration configuration,
IHostEnvironment? hostEnvironment)
{
var mode = configuration["WorkflowEngine:Mode"];
var isDevelopment = hostEnvironment is null || hostEnvironment.IsDevelopment();
if (string.Equals(mode, "Stub", StringComparison.OrdinalIgnoreCase))
{
services.AddSingleton<IWorkflowEngine, StubWorkflowEngine>();
return;
}
if (string.Equals(mode, "Real", StringComparison.OrdinalIgnoreCase))
{
services.AddSingleton<IWorkflowEngine, ChatClientWorkflowEngine>();
return;
}
// mode is null/empty/Auto: pick based on whether a backend looks ready.
var anyBackendConfigured = HasAnyBackendConfigured(configuration);
if (anyBackendConfigured)
{
services.AddSingleton<IWorkflowEngine, ChatClientWorkflowEngine>();
return;
}
if (isDevelopment)
{
services.AddSingleton<IWorkflowEngine, StubWorkflowEngine>();
return;
}
throw new InvalidOperationException(
"No LLM backend is configured and 'WorkflowEngine:Mode' is not set. " +
"Set 'Backends:azure-openai:Endpoint' (or another backend's Endpoint) to enable " +
"the real workflow engine, or set 'WorkflowEngine:Mode' to 'Stub' to use the stub.");
}
private static bool HasAnyBackendConfigured(IConfiguration configuration)
{
// Azure backends signal "really configured" via a non-empty Endpoint.
// Key-based backends (openai/github-models/anthropic) cannot be auto-detected
// because seed appsettings.json includes placeholder ApiKeyRef values; users
// opt in via WorkflowEngine:Mode=Real for those.
return !string.IsNullOrWhiteSpace(configuration["Backends:azure-openai:Endpoint"])
|| !string.IsNullOrWhiteSpace(configuration["Backends:azure-foundry:Endpoint"]);
}
private static void RegisterMcpToolRegistry(
IServiceCollection services,
IConfiguration configuration)
{
var section = configuration.GetSection(McpClientOptions.SectionName);
var hasServers = section.GetSection("Servers").GetChildren().Any();
if (!hasServers)
{
// Preserve historical behavior: no MCP servers configured → empty registry.
services.AddSingleton<IMcpToolRegistry, EmptyMcpToolRegistry>();
return;
}
services.AddOptions<McpClientOptions>()
.Bind(section)
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddSingleton<IMcpServerSessionFactory>(sp =>
new SdkMcpServerSessionFactory(
sp.GetRequiredService<IBackendSecretResolver>(),
sp.GetRequiredService<ILoggerFactory>()));
services.AddSingleton<HttpMcpToolRegistry>();
services.AddSingleton<IMcpToolRegistry>(sp => sp.GetRequiredService<HttpMcpToolRegistry>());
// Ensure the host disposes the underlying SDK clients on shutdown.
services.AddSingleton<IAsyncDisposable>(sp => sp.GetRequiredService<HttpMcpToolRegistry>());
}
private static void RegisterPersonaRepository(
IServiceCollection services,
IConfiguration configuration,
IHostEnvironment? hostEnvironment)
{
var configured = configuration["Personas:Directory"];
var contentRoot = hostEnvironment?.ContentRootPath ?? Directory.GetCurrentDirectory();
var directory = string.IsNullOrWhiteSpace(configured)
? Path.Combine(contentRoot, "personas")
: (Path.IsPathFullyQualified(configured)
? configured
: Path.Combine(contentRoot, configured));
var watch = configuration.GetValue<bool?>("Personas:Watch") ?? true;
var isDevelopment = hostEnvironment is null || hostEnvironment.IsDevelopment();
if (Directory.Exists(directory))
{
services.AddSingleton<IPersonaRepository>(sp =>
new YamlPersonaRepository(
directory,
sp.GetRequiredService<ILogger<YamlPersonaRepository>>(),
watch));
return;
}
if (isDevelopment)
{
services.AddSingleton<IPersonaRepository>(sp =>
{
sp.GetRequiredService<ILoggerFactory>()
.CreateLogger("CloudEngAgent.Infrastructure.PersonaRepository")
.LogWarning(
"Personas directory '{Directory}' not found; using InMemoryPersonaRepository " +
"(Development only).",
directory);
return new InMemoryPersonaRepository();
});
return;
}
throw new InvalidOperationException(
$"Personas directory '{directory}' does not exist. Set 'Personas:Directory' or " +
"create the directory with at least one *.yaml file.");
}
}