DependencyInjection.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. using Application.Abstractions.Authentication;
  2. using Application.Abstractions.Cache;
  3. using Application.Abstractions.Chat;
  4. using Application.Abstractions.Crypto;
  5. using Application.Abstractions.Data;
  6. using Application.Abstractions.Hub;
  7. using Application.Abstractions.Identity;
  8. using Application.Abstractions.Forum;
  9. using Application.Abstractions.Kyc;
  10. using Application.Abstractions.Messaging.Email;
  11. using Application.Abstractions.Notification;
  12. using Application.Abstractions.Payment;
  13. using Application.Abstractions.RateLimit;
  14. using Application.Abstractions.YouTube;
  15. using Infrastructure.Authentication;
  16. using Infrastructure.RateLimit;
  17. using Infrastructure.Crypto;
  18. using Infrastructure.Payment;
  19. using Infrastructure.Forum;
  20. using Infrastructure.Kyc.Nice;
  21. using Infrastructure.Cache;
  22. using Infrastructure.Chat;
  23. using Infrastructure.Messaging.Email;
  24. using Infrastructure.Persistence;
  25. using Infrastructure.Persistence.Identity;
  26. using Infrastructure.Ranking;
  27. using Infrastructure.Storage;
  28. using Infrastructure.YouTube;
  29. using Microsoft.AspNetCore.Authentication;
  30. using Microsoft.AspNetCore.Authentication.JwtBearer;
  31. using Microsoft.AspNetCore.DataProtection;
  32. using Microsoft.AspNetCore.Identity;
  33. using Microsoft.AspNetCore.Identity.UI.Services;
  34. using Microsoft.EntityFrameworkCore;
  35. using Microsoft.EntityFrameworkCore.Diagnostics;
  36. using Microsoft.Extensions.Configuration;
  37. using Microsoft.Extensions.DependencyInjection;
  38. using Microsoft.Extensions.Options;
  39. using Microsoft.IdentityModel.Tokens;
  40. using SharedKernel;
  41. using SharedKernel.Storage;
  42. using StackExchange.Redis;
  43. using System.Text;
  44. namespace Infrastructure;
  45. public static class DependencyInjection
  46. {
  47. // SQL Server
  48. private static IServiceCollection AddDatabase(this IServiceCollection services, IConfiguration configuration)
  49. {
  50. var dbConn = configuration.GetConnectionString("DefaultConnection");
  51. if (string.IsNullOrWhiteSpace(dbConn))
  52. {
  53. throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured.");
  54. }
  55. // Pooling: 매 request 마다 새 DbContext 생성 비용 제거. ChangeTracker 등 내부 상태는 풀 반환 시 자동 reset
  56. // ConfigureWarnings: EF 9+의 PendingModelChangesWarning을 무시 (snapshot 일관성 문제로 false-positive 발생, 마이그레이션은 별도 관리)
  57. services.AddDbContextPool<AppDbContext>(options => options
  58. .UseSqlServer(dbConn)
  59. .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning)), poolSize: 128);
  60. services.AddDbContextPool<IdentityDbContext>(options => options
  61. .UseSqlServer(dbConn)
  62. .ConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning)), poolSize: 64);
  63. services.AddScoped<IAppDbContext>(sp => sp.GetRequiredService<AppDbContext>());
  64. return services;
  65. }
  66. // Redis Server
  67. public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
  68. {
  69. var settings = configuration.Get<AppSettings>()!;
  70. var redis = ConnectionMultiplexer.Connect(settings.Redis.DefaultConnection);
  71. services.AddSingleton<IConnectionMultiplexer>(redis);
  72. services.AddDataProtection()
  73. .SetApplicationName(settings.App.Name)
  74. .PersistKeysToStackExchangeRedis(redis, settings.Redis.DataProtectionKey)
  75. .ProtectKeysWithDpapi(protectToLocalMachine: true) // key를 암호화하여 저장 (로컬 머신에서만 복호화 가능, 서버간 공유 불가)
  76. .SetDefaultKeyLifetime(settings.Redis.DefaultKeyLifetime); // 기본 90일 주기
  77. // Distributed Cache 설정
  78. services.AddStackExchangeRedisCache(options =>
  79. {
  80. options.Configuration = settings.Redis.DefaultConnection;
  81. options.InstanceName = settings.Redis.CachePrefix;
  82. });
  83. return services;
  84. }
  85. private static IServiceCollection AddHealthChecks(this IServiceCollection services, IConfiguration configuration)
  86. {
  87. var settings = configuration.Get<AppSettings>()!;
  88. services.AddHealthChecks().AddSqlServer(settings.ConnectionStrings.DefaultConnection).AddRedis(settings.Redis.DefaultConnection);
  89. return services;
  90. }
  91. // Admin/Api 둘 다 필요한 공용 서비스 (singleton/transient/scoped, HttpClient)
  92. private static IServiceCollection AddCommonServices(this IServiceCollection services, IConfiguration configuration)
  93. {
  94. // 파일 저장 위치 옵션 (deploy 영향 받지 않는 외부 경로 권장)
  95. services.Configure<StorageOptions>(configuration.GetSection(StorageOptions.SectionName));
  96. // NICE 통합인증 (본인인증)
  97. services.Configure<NiceAuthOptions>(configuration.GetSection("Nice:Auth"));
  98. services.AddSingleton<IJwtTokenProvider, JwtTokenProvider>();
  99. services.AddSingleton<ILegacyPasswordVerifier, BcryptLegacyPasswordVerifier>();
  100. services.AddSingleton<ICacheService, RedisCacheService>();
  101. services.AddSingleton<IRateLimiter, RedisSlidingWindowLimiter>();
  102. services.AddSingleton<IFieldEncryptor, AesGcmFieldEncryptor>();
  103. services.AddTransient<IEmailSender, IdentityEmailSender>();
  104. services.AddScoped<IFileStorage, LocalFileStorage>();
  105. services.AddScoped<IEditorImageService, EditorImageService>();
  106. services.AddScoped<IIdentityUserReader, IdentityUserReader>();
  107. services.AddScoped<IIdentityUserWriter, IdentityUserWriter>();
  108. services.AddScoped<IIdentityRoleReader, IdentityRoleReader>();
  109. services.AddScoped<IIdentityRoleWriter, IdentityRoleWriter>();
  110. services.AddSingleton<IChatMessageStore, RedisChatMessageStore>();
  111. services.AddSingleton<IChatConnectionTracker, RedisChatConnectionTracker>();
  112. services.AddSingleton<IChatLeaderboard, RedisChatLeaderboard>();
  113. services.AddSingleton<IPresenceTracker, Hubs.PresenceTracker>();
  114. services.AddSingleton<IVisitorTracker, Hubs.RedisVisitorTracker>();
  115. services.AddScoped<IBoardPermissionService, BoardPermissionService>();
  116. services.AddHttpClient<IGoogleTokenValidator, GoogleTokenValidator>();
  117. // YouTube & Google OAuth (HttpClients + singletons — Admin에서도 "API 키 테스트" 등에 쓰므로 공용)
  118. services.AddSingleton<IYouTubeApiKeyProvider, YouTubeApiKeyProvider>();
  119. services.AddTransient<YouTubeApiKeyHandler>();
  120. services.AddTransient<IYouTubeApiConnectionTester, YouTubeApiConnectionTester>();
  121. services.AddHttpClient("YouTubeApi", client =>
  122. {
  123. client.Timeout = TimeSpan.FromSeconds(15);
  124. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  125. })
  126. .AddHttpMessageHandler<YouTubeApiKeyHandler>();
  127. services.AddHttpClient("PubSubHub", client =>
  128. {
  129. client.Timeout = TimeSpan.FromSeconds(15);
  130. });
  131. services.AddHttpClient("YouTubeFeed", client =>
  132. {
  133. client.Timeout = TimeSpan.FromSeconds(10);
  134. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/atom+xml"));
  135. });
  136. services.AddHttpClient<IGoogleOAuthService, GoogleOAuthService>();
  137. services.AddHttpClient<IDanalPayService, DanalPayService>();
  138. services.AddHttpClient<INiceAuthClient, NiceAuthClient>((sp, client) =>
  139. {
  140. var opt = sp.GetRequiredService<IOptions<NiceAuthOptions>>().Value;
  141. if (!string.IsNullOrWhiteSpace(opt.BaseUrl))
  142. {
  143. client.BaseAddress = new Uri(opt.BaseUrl);
  144. }
  145. client.Timeout = TimeSpan.FromSeconds(opt.HttpTimeoutSeconds);
  146. });
  147. services.AddSingleton<IYouTubeApiService, YouTubeApiService>();
  148. services.AddSingleton<IYouTubeChannelCache, YouTubeChannelCache>();
  149. services.AddSingleton<IYouTubeLiveStateStore, YouTubeLiveStateStore>();
  150. services.AddSingleton<YouTubeLiveChatService>();
  151. services.AddSingleton<IYouTubeLiveChatService>(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  152. services.AddSingleton<YouTubePubSubService>();
  153. services.AddSingleton<IYouTubePubSubService>(sp => sp.GetRequiredService<YouTubePubSubService>());
  154. services.AddSingleton<IYouTubeFeedPoller, YouTubeFeedPoller>();
  155. // Notification
  156. services.AddScoped<INotificationService, Notification.NotificationService>();
  157. // Nextcloud Talk 운영 알림 (결제 보고 활동/이상 징후) — singleton + fire-and-forget
  158. services.AddHttpClient("NextcloudTalk", client => {
  159. client.Timeout = TimeSpan.FromSeconds(10);
  160. });
  161. services.AddSingleton<IAdminAlertService, Notification.NextcloudTalkAlertService>();
  162. // Feed broadcaster (SignalR)
  163. services.AddScoped<IFeedBroadcaster, Hubs.FeedBroadcaster>();
  164. // Crew member change broadcaster (크루원 추가/수정/삭제/응답 → AppHub crew:{crewID} 그룹 브로드캐스트)
  165. services.AddScoped<ICrewHubBroadcaster, Hubs.CrewHubBroadcaster>();
  166. // Channel status broadcaster (라이브 시작/종료/시청자 수 → AppHub 브로드캐스트)
  167. services.AddSingleton<IChannelStatusBroadcaster, Hubs.ChannelStatusBroadcaster>();
  168. return services;
  169. }
  170. // Web.Api 전용 백그라운드 서비스 (Admin에서 중복 실행되면 quota 2배/폴링 2번 문제)
  171. // appsettings.json BackgroundJobs 섹션으로 개별 토글 (기본 모두 true). 진단용 A/B 테스트에 사용
  172. private static IServiceCollection AddBackgroundServices(this IServiceCollection services, IConfiguration configuration)
  173. {
  174. var bg = configuration.GetSection("BackgroundJobs").Get<AppSettings.BackgroundJobsSection>() ?? new AppSettings.BackgroundJobsSection();
  175. if (bg.LiveChat)
  176. {
  177. services.AddHostedService(sp => sp.GetRequiredService<YouTubeLiveChatService>());
  178. }
  179. if (bg.PubSubRenewal)
  180. {
  181. services.AddHostedService<YouTubePubSubRenewalService>();
  182. }
  183. if (bg.FeedPolling)
  184. {
  185. services.AddHostedService<YouTubeFeedPollingService>();
  186. }
  187. if (bg.LiveViewerPoller)
  188. {
  189. services.AddHostedService<YouTubeLiveViewerPoller>();
  190. }
  191. if (bg.ChannelCacheRefresh)
  192. {
  193. services.AddHostedService<YouTubeChannelCacheRefreshService>();
  194. }
  195. if (bg.YouTubeDailyAggregator)
  196. {
  197. services.AddHostedService<YouTubeDailyAggregatorService>();
  198. }
  199. if (bg.RankingDailyAggregator)
  200. {
  201. services.AddHostedService<RankingDailyAggregatorService>();
  202. }
  203. if (bg.YouTubeStaleDataPurge)
  204. {
  205. services.AddHostedService<YouTubeStaleDataPurgeService>();
  206. }
  207. if (bg.ApiPurchaseConfirm)
  208. {
  209. services.AddHostedService<Developers.ApiPurchaseConfirmService>();
  210. }
  211. return services;
  212. }
  213. /**
  214. * ========================================================================================================================================================================================================
  215. * ========================================================================================================================================================================================================
  216. */
  217. // Admin 전용 — 백그라운드 서비스는 포함하지 않음 (Web.Api에서만 돌아야 함)
  218. // 메일은 즉시 SMTP 발송 (DirectMailService)
  219. public static IServiceCollection AddAdminInfrastructure(this IServiceCollection services, IConfiguration configuration)
  220. {
  221. services.AddScoped<IMailService, DirectMailService>();
  222. return services.AddDatabase(configuration).AddRedis(configuration).AddCommonServices(configuration).AddHealthChecks(configuration);
  223. }
  224. /**
  225. * ========================================================================================================================================================================================================
  226. * ========================================================================================================================================================================================================
  227. */
  228. // API 전용 — 공용 서비스 + 백그라운드 서비스 모두 포함
  229. // 메일은 EmailLog 큐에 적재 (QueuedMailService) — MailWorker가 별도로 폴링하여 SMTP 송신
  230. public static IServiceCollection AddApiInfrastructure(this IServiceCollection services, IConfiguration configuration)
  231. {
  232. services.AddScoped<IMailService, QueuedMailService>();
  233. return services.AddDatabase(configuration).AddRedis(configuration).AddApiAuthentication(configuration).AddCommonServices(configuration).AddBackgroundServices(configuration).AddHealthChecks(configuration);
  234. }
  235. private static IServiceCollection AddApiAuthentication(this IServiceCollection services, IConfiguration configuration)
  236. {
  237. var settings = configuration.Get<AppSettings>()!;
  238. // 인증 정책- JWT Bearer
  239. services.AddAuthentication(options =>
  240. {
  241. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  242. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  243. })
  244. .AddJwtBearer(options =>
  245. {
  246. options.RequireHttpsMetadata = false;
  247. options.MapInboundClaims = false;
  248. options.TokenValidationParameters = new TokenValidationParameters
  249. {
  250. ValidateIssuer = true,
  251. ValidateAudience = true,
  252. ValidateLifetime = true,
  253. ValidateIssuerSigningKey = true,
  254. ValidIssuer = settings.JWT.Issuer,
  255. ValidAudience = settings.JWT.Audience,
  256. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.JWT.SecretKey)),
  257. ClockSkew = TimeSpan.Zero
  258. };
  259. options.Events = new JwtBearerEvents
  260. {
  261. OnMessageReceived = context =>
  262. {
  263. var accessToken = context.Request.Query["access_token"];
  264. var path = context.HttpContext.Request.Path;
  265. if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
  266. {
  267. context.Token = accessToken;
  268. }
  269. return Task.CompletedTask;
  270. }
  271. };
  272. })
  273. // OAuth2 Client Credentials 로 발급된 access_token (공개 API /v1/* 용, audience 분리)
  274. .AddJwtBearer("OAuth2Bearer", options =>
  275. {
  276. options.RequireHttpsMetadata = false;
  277. options.MapInboundClaims = false;
  278. options.TokenValidationParameters = new TokenValidationParameters
  279. {
  280. ValidateIssuer = true,
  281. ValidateAudience = true,
  282. ValidateLifetime = true,
  283. ValidateIssuerSigningKey = true,
  284. ValidIssuer = settings.JWT.Issuer,
  285. ValidAudience = "dpot-public-api",
  286. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.JWT.SecretKey)),
  287. ClockSkew = TimeSpan.Zero
  288. };
  289. })
  290. // PAT (Personal Access Token) Bearer scheme
  291. .AddScheme<AuthenticationSchemeOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthenticationHandler.SchemeName, null);
  292. services.AddAuthorization();
  293. // Identity Core (Admin Handler의 UserManager/RoleManager 의존 해소용)
  294. services.AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
  295. return services;
  296. }
  297. }