File size: 12,437 Bytes
c981f27 | 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 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::ExitStatus;
use std::sync::Arc;
use bytes::Bytes;
use forge_app::{
CommandInfra, DirectoryReaderInfra, EnvironmentInfra, FileDirectoryInfra, FileInfoInfra,
FileReaderInfra, FileRemoverInfra, FileWriterInfra, GrpcInfra, HttpInfra, McpServerInfra,
StrategyFactory, UserInfra, WalkerInfra,
};
use forge_domain::{
AuthMethod, CommandOutput, FileInfo as FileInfoData, McpServerConfig, ProviderId, URLParamSpec,
};
use forge_eventsource::EventSource;
use reqwest::header::HeaderMap;
use reqwest::{Response, Url};
use crate::auth::{AnyAuthStrategy, ForgeAuthStrategyFactory};
use crate::console::StdConsoleWriter;
use crate::env::{ForgeEnvironmentInfra, to_environment};
use crate::executor::ForgeCommandExecutorService;
use crate::fs_create_dirs::ForgeCreateDirsService;
use crate::fs_meta::ForgeFileMetaService;
use crate::fs_read::ForgeFileReadService;
use crate::fs_read_dir::ForgeDirectoryReaderService;
use crate::fs_remove::ForgeFileRemoveService;
use crate::fs_write::ForgeFileWriteService;
use crate::grpc::ForgeGrpcClient;
use crate::http::ForgeHttpInfra;
use crate::inquire::ForgeInquire;
use crate::mcp_client::ForgeMcpClient;
use crate::mcp_server::ForgeMcpServer;
use crate::walker::ForgeWalkerService;
#[derive(Clone)]
pub struct ForgeInfra {
// TODO: Drop the "Service" suffix. Use names like ForgeFileReader, ForgeFileWriter,
// ForgeHttpClient etc.
file_read_service: Arc<ForgeFileReadService>,
file_write_service: Arc<ForgeFileWriteService>,
file_remove_service: Arc<ForgeFileRemoveService>,
config_infra: Arc<ForgeEnvironmentInfra>,
file_meta_service: Arc<ForgeFileMetaService>,
create_dirs_service: Arc<ForgeCreateDirsService>,
directory_reader_service: Arc<ForgeDirectoryReaderService>,
command_executor_service: Arc<ForgeCommandExecutorService>,
inquire_service: Arc<ForgeInquire>,
mcp_server: ForgeMcpServer,
walker_service: Arc<ForgeWalkerService>,
http_service: Arc<ForgeHttpInfra<ForgeFileWriteService>>,
strategy_factory: Arc<ForgeAuthStrategyFactory>,
grpc_client: Arc<ForgeGrpcClient>,
output_printer: Arc<StdConsoleWriter>,
}
impl ForgeInfra {
/// Creates a new [`ForgeInfra`] with all infrastructure services
/// initialized.
///
/// # Arguments
/// * `cwd` - The working directory for command execution and environment
/// resolution
/// * `config` - Pre-read application configuration; used only at
/// construction time to initialize infrastructure services
/// * `services_url` - Pre-validated URL for the gRPC workspace server
pub fn new(cwd: PathBuf, config: forge_config::ForgeConfig) -> Self {
let env = to_environment(cwd.clone());
let config_infra = Arc::new(ForgeEnvironmentInfra::new(cwd, config.clone()));
let file_write_service = Arc::new(ForgeFileWriteService::new());
let config = config_infra.cached_config().unwrap_or(config);
let http_service = Arc::new(ForgeHttpInfra::new(
config.clone(),
file_write_service.clone(),
));
let file_read_service = Arc::new(ForgeFileReadService::new());
let file_meta_service = Arc::new(ForgeFileMetaService);
let directory_reader_service = Arc::new(ForgeDirectoryReaderService::new(
config_infra
.cached_config()
.map(|c| c.max_parallel_file_reads)
.unwrap_or(4),
));
let grpc_client = Arc::new(ForgeGrpcClient::new(config.services_url.clone()));
let output_printer = Arc::new(StdConsoleWriter::default());
Self {
file_read_service,
file_write_service,
file_remove_service: Arc::new(ForgeFileRemoveService::new()),
config_infra,
file_meta_service,
create_dirs_service: Arc::new(ForgeCreateDirsService),
directory_reader_service,
command_executor_service: Arc::new(ForgeCommandExecutorService::new(
env.clone(),
output_printer.clone(),
)),
inquire_service: Arc::new(ForgeInquire::new()),
mcp_server: ForgeMcpServer,
walker_service: Arc::new(ForgeWalkerService::new()),
strategy_factory: Arc::new(ForgeAuthStrategyFactory::new(env.clone())),
http_service,
grpc_client,
output_printer,
}
}
}
impl ForgeInfra {
/// Returns the current application configuration, re-reading from disk if
/// the cache was invalidated by a prior `update_environment` call.
///
/// # Errors
///
/// Returns an error if the disk read fails.
pub fn config(&self) -> anyhow::Result<forge_config::ForgeConfig> {
self.config_infra.cached_config()
}
}
impl EnvironmentInfra for ForgeInfra {
type Config = forge_config::ForgeConfig;
fn get_env_var(&self, key: &str) -> Option<String> {
self.config_infra.get_env_var(key)
}
fn get_env_vars(&self) -> BTreeMap<String, String> {
self.config_infra.get_env_vars()
}
fn get_environment(&self) -> forge_domain::Environment {
self.config_infra.get_environment()
}
fn get_config(&self) -> anyhow::Result<forge_config::ForgeConfig> {
self.config_infra.get_config()
}
async fn update_environment(
&self,
ops: Vec<forge_domain::ConfigOperation>,
) -> anyhow::Result<()> {
self.config_infra.update_environment(ops).await
}
}
#[async_trait::async_trait]
impl FileReaderInfra for ForgeInfra {
async fn read_utf8(&self, path: &Path) -> anyhow::Result<String> {
self.file_read_service.read_utf8(path).await
}
fn read_batch_utf8(
&self,
batch_size: usize,
paths: Vec<PathBuf>,
) -> impl futures::Stream<Item = (PathBuf, anyhow::Result<String>)> + Send {
self.file_read_service.read_batch_utf8(batch_size, paths)
}
async fn read(&self, path: &Path) -> anyhow::Result<Vec<u8>> {
self.file_read_service.read(path).await
}
async fn range_read_utf8(
&self,
path: &Path,
start_line: u64,
end_line: u64,
) -> anyhow::Result<(String, FileInfoData)> {
self.file_read_service
.range_read_utf8(path, start_line, end_line)
.await
}
}
#[async_trait::async_trait]
impl FileWriterInfra for ForgeInfra {
async fn write(&self, path: &Path, contents: Bytes) -> anyhow::Result<()> {
self.file_write_service.write(path, contents).await
}
async fn append(&self, path: &Path, contents: Bytes) -> anyhow::Result<()> {
self.file_write_service.append(path, contents).await
}
async fn write_temp(&self, prefix: &str, ext: &str, content: &str) -> anyhow::Result<PathBuf> {
self.file_write_service
.write_temp(prefix, ext, content)
.await
}
}
#[async_trait::async_trait]
impl FileInfoInfra for ForgeInfra {
async fn is_binary(&self, path: &Path) -> anyhow::Result<bool> {
self.file_meta_service.is_binary(path).await
}
async fn is_file(&self, path: &Path) -> anyhow::Result<bool> {
self.file_meta_service.is_file(path).await
}
async fn exists(&self, path: &Path) -> anyhow::Result<bool> {
self.file_meta_service.exists(path).await
}
async fn file_size(&self, path: &Path) -> anyhow::Result<u64> {
self.file_meta_service.file_size(path).await
}
}
#[async_trait::async_trait]
impl FileRemoverInfra for ForgeInfra {
async fn remove(&self, path: &Path) -> anyhow::Result<()> {
self.file_remove_service.remove(path).await
}
}
#[async_trait::async_trait]
impl FileDirectoryInfra for ForgeInfra {
async fn create_dirs(&self, path: &Path) -> anyhow::Result<()> {
self.create_dirs_service.create_dirs(path).await
}
}
#[async_trait::async_trait]
impl CommandInfra for ForgeInfra {
async fn execute_command(
&self,
command: String,
working_dir: PathBuf,
silent: bool,
env_vars: Option<Vec<String>>,
) -> anyhow::Result<CommandOutput> {
self.command_executor_service
.execute_command(command, working_dir, silent, env_vars)
.await
}
async fn execute_command_raw(
&self,
command: &str,
working_dir: PathBuf,
env_vars: Option<Vec<String>>,
) -> anyhow::Result<ExitStatus> {
self.command_executor_service
.execute_command_raw(command, working_dir, env_vars)
.await
}
}
#[async_trait::async_trait]
impl UserInfra for ForgeInfra {
async fn prompt_question(&self, question: &str) -> anyhow::Result<Option<String>> {
self.inquire_service.prompt_question(question).await
}
async fn select_one<T: Clone + std::fmt::Display + Send + 'static>(
&self,
message: &str,
options: Vec<T>,
) -> anyhow::Result<Option<T>> {
self.inquire_service.select_one(message, options).await
}
async fn select_many<T: std::fmt::Display + Clone + Send + 'static>(
&self,
message: &str,
options: Vec<T>,
) -> anyhow::Result<Option<Vec<T>>> {
self.inquire_service.select_many(message, options).await
}
}
#[async_trait::async_trait]
impl McpServerInfra for ForgeInfra {
type Client = ForgeMcpClient;
async fn connect(
&self,
config: McpServerConfig,
env_vars: &BTreeMap<String, String>,
environment: &forge_domain::Environment,
) -> anyhow::Result<Self::Client> {
self.mcp_server.connect(config, env_vars, environment).await
}
}
#[async_trait::async_trait]
impl WalkerInfra for ForgeInfra {
async fn walk(&self, config: forge_app::Walker) -> anyhow::Result<Vec<forge_app::WalkedFile>> {
self.walker_service.walk(config).await
}
}
#[async_trait::async_trait]
impl HttpInfra for ForgeInfra {
async fn http_get(&self, url: &Url, headers: Option<HeaderMap>) -> anyhow::Result<Response> {
self.http_service.http_get(url, headers).await
}
async fn http_post(
&self,
url: &Url,
headers: Option<HeaderMap>,
body: Bytes,
) -> anyhow::Result<Response> {
self.http_service.http_post(url, headers, body).await
}
async fn http_delete(&self, url: &Url) -> anyhow::Result<Response> {
self.http_service.http_delete(url).await
}
async fn http_eventsource(
&self,
url: &Url,
headers: Option<HeaderMap>,
body: Bytes,
) -> anyhow::Result<EventSource> {
self.http_service.http_eventsource(url, headers, body).await
}
}
#[async_trait::async_trait]
impl DirectoryReaderInfra for ForgeInfra {
async fn list_directory_entries(
&self,
directory: &Path,
) -> anyhow::Result<Vec<(PathBuf, bool)>> {
self.directory_reader_service
.list_directory_entries(directory)
.await
}
async fn read_directory_files(
&self,
directory: &Path,
pattern: Option<&str>,
) -> anyhow::Result<Vec<(PathBuf, String)>> {
self.directory_reader_service
.read_directory_files(directory, pattern)
.await
}
}
impl StrategyFactory for ForgeInfra {
type Strategy = AnyAuthStrategy;
fn create_auth_strategy(
&self,
provider_id: ProviderId,
method: AuthMethod,
required_params: Vec<URLParamSpec>,
) -> anyhow::Result<Self::Strategy> {
self.strategy_factory
.create_auth_strategy(provider_id, method, required_params)
}
}
impl GrpcInfra for ForgeInfra {
fn channel(&self) -> anyhow::Result<tonic::transport::Channel> {
self.grpc_client.channel()
}
fn hydrate(&self) {
self.grpc_client.hydrate();
}
}
impl forge_domain::ConsoleWriter for ForgeInfra {
fn write(&self, buf: &[u8]) -> std::io::Result<usize> {
self.output_printer.write(buf)
}
fn write_err(&self, buf: &[u8]) -> std::io::Result<usize> {
self.output_printer.write_err(buf)
}
fn flush(&self) -> std::io::Result<()> {
self.output_printer.flush()
}
fn flush_err(&self) -> std::io::Result<()> {
self.output_printer.flush_err()
}
}
|